forked from farshadmohajeri/extpascal
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ExtPascal.pas
2109 lines (1975 loc) · 75.5 KB
/
ExtPascal.pas
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Classes to JavaScript and Ext JS translating from Object Pascal.
Associates semantic concepts of JavaScript and Ext JS for Object Pascal, such as: Function, Object, List of Objects and Ajax Method.
It's the heart of the automatic translation method from Object Pascal to JavaScript, that I call "Self-translating".
It takes advantage of the fact that JavaScript and Object Pascal are structurally similar languages,
where there is almost one to one parity between its syntax and semantic structures.
-ExtPascal is composed of four main components:-
1. The <color red>Parser</color> (<link ExtToPascal.dpr>) able to scan Ext JS documentation in HTML format and to create the <color red>Wrapper</color>.
2. The <color red>Wrapper</color> programmatically created by Parser. It's in fact a set of units (twelve in Ext JS 2.1), which has the definition of all Ext JS classes, properties, methods and events.
3. The <color red>Self-translating</color> engine, <link ExtPascal.pas, ExtPascal unit>. It's triggered when using the <color red>Wrapper</color>, ie by creating objects, assigning properties and events, and invoking methods.
4. The <link FCGIApp.pas, FastCGI> multithread environment. It implements FastCGI protocol using TCP/IP Sockets and statefull, keep-alive, multithread web application behavior.
<image extpascal>
1. The <color red>Parser</color> reads the HTML documentation of Ext JS,
2. Reads ExtFixes.txt file to fix documentation faults and omissions, and
3. Generates the <color red>Wrapper</color>.
4. With the application running, a browser session does a HTTP request to the Web Server.
5. The Web Server does a FastCGI request to the application that creates a <color red>thread</color> to handle the request.
6. The <color red>thread</color> creates ExtObjects, set properties and call methods from <color red>Wrapper</color> Units.
7. For each these tasks the <color red>Self-translating</color> is invoked
8. Generating JavaScript code that uses Ext JS classes.
9. At end of request processing, the <color red>thread</color> reads and formats all JS generated
10. And sends the response to browser session. New requests can be done begining from step 4.
So the translating is not focused on JavaScript language, but to access widget frameworks made in JavaScript.
In this way the use of (X)HTML, JavaScript and CSS is minimum.
Indeed the <color red>Parser</color> can be adapted to read the documentation of another JavaScript framework, Dojo for example.
ExtPascal has one optional fifth component the <link CGIGateway.dpr>.
Author: Wanderlan Santos dos Anjos, wanderlan.anjos@gmail.com
Date: jun-2008
License: <extlink http://www.opensource.org/licenses/bsd-license.php>BSD</extlink>
}
unit ExtPascal;
// @@Overview
// <copy ExtPascal.pas>
// Enabling SERVICE directive ExtPascal application can be used as a Windows Service,
// In command line use -INSTALL to install the service and - UNINSTALL to uninstall the service
{$IFDEF MSWINDOWS}
{ .$DEFINE SERVICE }
{$ENDIF}
// Enabling WebServer directive ExtPascal can be used within an embedded Indy based WebServer
{$IFNDEF SERVICE}
{ .$DEFINE WebServer }
{$ENDIF}
// Uses ext-all-debug.js, format all JS/CSS source code to facilitate debugging on browser and locates line error if using Firefox on AJAX responses
{ .$DEFINE DEBUGJS }
// Uses CacheFly for performance boost see: http://extjs.com/blog/2008/11/18/ext-cdn-custom-builds-compression-and-fast-performance/
{ .$DEFINE CacheFly }
// Uses DebugExtJS to load ext-all-debug.js library instead ext-all.js to debugging purposes
{ .$DEFINE DebugExtJS }
interface
uses
{$IFNDEF WebServer}FCGIApp{$ELSE}IdExtHTTPServer{$ENDIF},
Classes, ExtPascalUtils;
type
TArrayOfString = array of string;
TArrayOfInteger = array of Integer;
TExtObjectList = class;
TExtFunction = class;
{
Defines an user session opened in a browser. Each session is a FastCGI thread that owns additional JavaScript and Ext JS resources
as: theme, charset, language, Ajax, error messages using Ext look, JS libraries and CSS.
The <color red>"Self-translating"</color> is implemented in this class in <link TExtObject.JSCode, JSCode> method.
}
TExtThread = class(TWebSession)
private
Style, Libraries, CustomJS, FLanguage: string;
JSReturns: TStringList;
Sequence: cardinal;
procedure RelocateVar(JS, JSName: string; I: Integer);
function GetStyle: string;
protected
procedure RemoveJS(const JS: string);
function BeforeHandleRequest: boolean; override;
procedure AfterHandleRequest; override;
procedure AfterNewSession; override;
{$IFDEF HAS_CONFIG}
procedure DoReconfig; override;
procedure ReadConfig;
{$ENDIF}
function GarbageFixName(const Name: string): string; override;
procedure OnError(const Msg, Method, Params: string); override;
function GetSequence: string;
function GetUrlHandlerObject: TObject; override;
function JSConcat(PrevCommand, NextCommand: string): string;
public
HTMLQuirksMode: boolean;
// Defines the (X)HTML DocType. True to Transitional (Quirks mode) or false to Strict. Default is false.
Theme: string; // Sets or gets Ext JS installed theme, default '' that is Ext Blue theme
ExtPath: string;
// Installation path of Ext JS framework, below the your Web server document root. Default value is '/ext'
ImagePath: string;
// Image path below ExtPath, used by <link TExtThread.SetIconCls, SetIconCls> method. Default value is '/images'
ExtBuild: string;
// Custom <extlink http://www.extjs.com/products/extjs/build/>ExtJS build</extlink>. Default is ext-all.
Charset: string; // Charset for html contenttype default utf-8, another option iso-8859-1
property Language: string read FLanguage write FLanguage;
// Actual language for this session, reads HTTP_ACCEPT_LANGUAGE header
constructor Create(AOwner: TObject); override;
procedure InitDefaultValues; override;
procedure JSCode(JS: string; JSClassName: string = ''; JSName: string = ''; Owner: string = '');
procedure JSSleep(MiliSeconds: Integer);
procedure SetStyle(pStyle: string = '');
procedure SetLibrary(pLibrary: string = ''; CSS: boolean = false);
procedure SetCSS(pCSS: string; Check: boolean = true);
procedure SetIconCls(Cls: array of string);
procedure SetCustomJS(JS: string = '');
procedure ErrorMessage(Msg: string; Action: string = ''); overload;
procedure ErrorMessage(Msg: string; Action: TExtFunction); overload;
procedure Alert(const Msg: string); override;
published
procedure HandleEvent; virtual;
end;
{$M+}
{
Ancestor of all classes and components of Ext JS framework.
Each TExtObject has the capability to self-translate to JavaScript during the program execution.
When a property is assigned or a method is called the <link TExtThread.JSCode, Self-translating> enter in action
translating these Object Pascal commands to JavaScript.
}
TExtObject = class
private
function WriteFunction(Command: string): string;
function GetJSCommand: string;
procedure SetJSCommand(const Value: string);
function PopJSCommand: string;
function FormatParams(MethodName: string; Params: array of const): string;
procedure AjaxCode(MethodName, RawParams: string; Params: array of const);
function Ajax(Method: TExtProcedure; Params: string): TExtFunction; overload;
function AddJSReturn(Expression: string; MethodsValues: array of const): string;
function FindMethod(Method: TExtProcedure; var PascalName, ObjName: string): TExtFunction;
protected
FJSName: string; // Internal JavaScript name generated automatically by <link TExtObject.CreateJSName, CreateJSName>
Created: boolean; // Tests if object already created
FJSCommand: string;
function ConfigAvailable(JSName: string): boolean;
function ExtractJSCommand: string;
function IsParent(CName: string): boolean;
function VarToJSON(A: array of const): string; overload;
function VarToJSON(Exts: TExtObjectList): string; overload;
function ArrayToJSON(Strs:
{$IF Defined(FPC) or (RTLVersion < 20)}TArrayOfString{$ELSE} array of string{$IFEND}): string; overload;
function ArrayToJSON(Ints:
{$IF Defined(FPC) or (RTLVersion < 20)}TArrayOfInteger{$ELSE} array of Integer{$IFEND}): string; overload;
function ParamAsInteger(ParamName: string): Integer;
function ParamAsDouble(ParamName: string): double;
function ParamAsBoolean(ParamName: string): boolean;
function ParamAsString(ParamName: string): string;
function ParamAsTDateTime(ParamName: string): TDateTime;
function ParamAsObject(ParamName: string): TExtObject;
procedure CreateVar(JS: string);
procedure CreateVarAlt(JS: string);
procedure CreateJSName;
procedure InitDefaults; virtual;
procedure HandleEvent(const AEvtName: string); virtual;
property JSCommand: string read GetJSCommand write SetJSCommand; // Last commands written in Response
public
IsChild: boolean;
constructor CreateInternal(Owner: TExtObject; Attribute: string);
constructor Create(Owner: TExtObject = nil);
constructor CreateSingleton(Attribute: string = '');
constructor AddTo(List: TExtObjectList);
constructor Init(Method: TExtFunction); overload;
constructor Init(Command: string); overload;
destructor Destroy; override;
function DestroyJS: TExtFunction; virtual;
procedure Free(CallDestroyJS: boolean = false);
procedure Delete;
procedure DeleteFromGarbage;
function JSClassName: string; virtual;
function JSArray(JSON: string; SquareBracket: boolean = true): TExtObjectList;
function JSObject(JSON: string; ObjectConstructor: string = ''; CurlyBracket: boolean = true): TExtObject;
function JSFunction(Params, Body: string): TExtFunction; overload;
procedure JSFunction(Name, Params, Body: string); overload;
function JSFunction(Body: string): TExtFunction; overload;
function JSFunction(Method: TExtProcedure; Silent: boolean = false): TExtFunction; overload;
function JSExpression(Expression: string; MethodsValues: array of const): Integer; overload;
function JSExpression(Method: TExtFunction): Integer; overload;
function JSString(Expression: string; MethodsValues: array of const): string; overload;
function JSString(Method: TExtFunction): string; overload;
function JSMethod(Method: TExtFunction): string;
procedure JSCode(JS: string; pJSName: string = ''; pOwner: string = '');
procedure JSSleep(MiliSeconds: Integer);
function Ajax(MethodName: string; Params: array of const; IsEvent: boolean = false): TExtFunction; overload;
function Ajax(Method: TExtProcedure): TExtFunction; overload;
function Ajax(Method: TExtProcedure; Params: array of const): TExtFunction; overload;
function AjaxExtFunction(Method: TExtProcedure; Params: array of TExtFunction): TExtFunction; overload;
function AjaxSelection(Method: TExtProcedure; SelectionModel: TExtObject; Attribute, TargetQuery: string;
Params: array of const): TExtFunction;
function AjaxForms(Method: TExtProcedure; Forms: array of TExtObject): TExtFunction;
function RequestDownload(Method: TExtProcedure): TExtFunction; overload;
function RequestDownload(Method: TExtProcedure; Params: array of const): TExtFunction; overload;
function MethodURI(Method: TExtProcedure; Params: array of const): string; overload;
function MethodURI(Method: TExtProcedure): string; overload;
function MethodURI(MethodName: string; Params: array of const): string; overload;
function MethodURI(MethodName: string): string; overload;
function CharsToPixels(Chars: Integer): Integer;
function LinesToPixels(Lines: Integer): Integer;
property JSName: string read FJSName;
// JS variable name to this object, it's created automatically when the object is created
end;
{$M-}
{
Basic class descending of TExtObject that defines a JavaScript function. All functions and procedures of Ext JS framework are converted to Pascal functions
where its return is this class. With this all converted functions by <link ExtPascal.pas, Wrapper> could be assigned to event handlers.
}
TExtFunction = class(TExtObject);
// List of TExtObjects. The <link ExtPascal.pas, Wrapper> convey the JavaScript Array type to this class
TExtObjectList = class(TExtFunction)
private
FObjects: array of TExtObject;
Attribute, JSName: string;
Owner: TExtObject;
function GetFObjects(I: Integer): TExtObject;
public
property Objects[I: Integer]: TExtObject read GetFObjects; default;
// Returns the Ith object in the list, start with 0.
constructor CreateSingleton(pAttribute: string);
constructor Create(pOwner: TExtObject = nil; pAttribute: string = '');
destructor Destroy; override;
procedure Add(Obj: TExtObject);
function Count: Integer;
end;
// (*DOM-IGNORE-BEGIN
{
Classes that can not be documented.
They are usually JS basic classes without reference in Ext JS documentation by omission or fault.
}
THTMLElement = class(TExtObject);
TRegExp = type string;
TEvent = class(TExtObject);
TCSSStyleSheet = type string;
TTextNode = class(TExtObject);
TXMLHttpRequest = type string;
TWindow = type string;
TNodeList = type string;
TMixed = TExtObjectList;
// DOM-IGNORE-END*)
const
DeclareJS = '/*var*/ '; // Declare JS objects as global
CommandDelim = #3; // Internal JS command delimiter
IdentDelim = #4; // Internal JS identifier delimiter
JSDelim = #5; // Internal JSCommand delimiter
implementation
uses
SysUtils, StrUtils, Math, Ext; // , ExtUtil, ExtGrid, ExtForm;
threadvar InJSFunction: boolean;
var
ExtUtilTextMetrics: TExtUtilTextMetrics;
{ TExtThread }
{
Removes identificated JS commands from response.
Used internally by Self-Translating mechanism to repositioning JS commands.
@param JS JS command with sequence identifier.
@see TExtObject.ExtractJSCommand
}
procedure TExtThread.RemoveJS(const JS: string);
var
I: Integer;
begin
I := ExtPascalUtils.RPosEx(JS, Response, 1);
if I <> 0 then
Delete(Response, I, length(JS))
end;
{
Adds/Removes an user JS library to be used in current response.
If the WebServer is Apache tests if the library exists.
Repeated libraries are ignored.
@param pLibrary JS library without extension (.js), but with Path based on Web server document root.
@param CSS pLibrary has a companion stylesheet (.css) with same path and name.
If defined DebugJS then uses Library with debug (non minified version).
If pLibrary is '' then all user JS libraries to this session will be removed from response.
@example <code>SetLibrary('');</code>
@example <code>SetLibrary(<link ExtPath> + '/examples/tabs/TabCloseMenu');</code>
}
procedure TExtThread.SetLibrary(pLibrary: string = ''; CSS: boolean = false);
var
Root: string;
begin
if pos(pLibrary, Libraries) = 0 then
if pLibrary = '' then
Libraries := '' // Clear Libraries
else
begin
Root := RequestHeader['DOCUMENT_ROOT'];
if (Root = '') or ((Root <> '') and FileExists(Root + pLibrary + '.js')) then
begin
Libraries := Libraries + '<script src="' + pLibrary{$IFDEF DEBUGJS} + '-debug'{$ENDIF} + '.js"></script>'^M^J;
if CSS then
begin
if not FileExists(Root + pLibrary + '.css') then // Assume in /css like ux
pLibrary := ExtractFilePath(pLibrary) + 'css/' + ExtractFileName(pLibrary);
Libraries := Libraries + '<link rel=stylesheet href="' + pLibrary + '.css" />';
end;
end
else
raise Exception.Create('Library: ' + Root + pLibrary + '.js not found');
end;
end;
{
Adds/Removes an user CSS (cascade style sheet) to be used in current response.
If the WebServer is Apache tests if the CSS file exists.
Repeated CSS's are ignored.
@param pCSS CSS file name without extension (.css), but with Path based on Web server document root.
@param Check Checks if the CSS file exists, default is true.
If pCSS is '' then all user CSS AND JS libraries to this session will be removed from response.
}
procedure TExtThread.SetCSS(pCSS: string; Check: boolean = true);
var
Root: string;
begin
if pos(pCSS, Libraries) = 0 then
if pCSS = '' then
Libraries := '' // Clear Libraries
else
begin
Root := RequestHeader['DOCUMENT_ROOT'];
if Check and (Root <> '') and not FileExists(Root + pCSS + '.css') then
raise Exception.Create('Library: ' + Root + pCSS + '.js not found')
else
Libraries := Libraries + '<link rel=stylesheet href="' + pCSS + '.css" />';
end;
end;
{
Adds/Removes an user JS code to be used in current response.
Repeated code is ignored.
@param JS JS code to inject in response. If JS is '' then all user JS code to this session will be removed from response.
}
procedure TExtThread.SetCustomJS(JS: string = '');
begin
if pos(JS, CustomJS) = 0 then
if JS = '' then
CustomJS := ''
else
CustomJS := CustomJS + JS;
end;
{
Creates CSS classes to use with IconCls properties in Buttons. The images are .png files in 16x16 format.
Set <link ImagePath> variable to appropriate value before to use this method. Default is /images.
If the WebServer is Apache tests if each image exists.
Repeated images are ignored.
@param Cls String array with the names of .png files.
@example <code>
SetIconCls(['task', 'objects', 'commit', 'cancel', 'refresh', 'info', 'help', 'pitinnu', 'exit']);
with TExtToolbarButton.AddTo(Items) do begin
Text := 'Tasks';
IconCls := 'task';
Menu := TaskMenu;
end;</code>
}
procedure TExtThread.SetIconCls(Cls: array of string);
var
I: Integer;
Root: string;
begin
Root := RequestHeader['Document_Root'];
for I := 0 to high(Cls) do
if (Root = '') or ((Root <> '') and FileExists(Root + ImagePath + '/' + Cls[I] + '.png')) then
SetStyle('.' + Cls[I] + '{background-image:url("' + ImagePath + '/' + Cls[I] + '.png") !important}')
else
raise Exception.Create('Image file: ' + Root + ImagePath + '/' + Cls[I] + '.png not found');
end;
(*
Adds/Removes a user stylesheet to be used in current response.
Repeated style is ignored.
@param pStyle Styles to apply upon HTML or Ext elements in this response using CSS notation.
If pStyle is '' then all user styles to this session will be removed from response.
@example <code>SetStyle('');</code>
@example <code>SetStyle('img:hover{border:1px solid blue}');</code>
*)
procedure TExtThread.SetStyle(pStyle: string);
begin
if pos(pStyle, Style) = 0 then
if pStyle = '' then
Style := ''
else
Style := Style + pStyle
end;
// Returns all styles in use in current response
function TExtThread.GetStyle: string;
begin
if Style = '' then
Result := ''
else
Result := '<style>' + {$IFDEF DEBUGJS}BeautifyCSS(Style){$ELSE}Style{$ENDIF} + '</style>'^M^J;
end;
// Returns a object which will be used to handle the page method. We will call it's published method based on PathInfo.
function TExtThread.GetUrlHandlerObject: TObject;
begin
if (Query['Obj'] = '') or (Query['IsEvent'] = '1') then
Result := inherited GetUrlHandlerObject
else
Result := GarbageFind(Query['Obj']);
end;
{
Shows an error message in browser session using Ext JS style.
@param Msg Message text, can to use HTML to formating text.
@param Action Optional action that will be executed after user to click Ok button. Could be JavaScript or ExtPascal commands
@example <code>ErrorMessage('User not found.');</code>
@example <code>ErrorMessage('Context not found.<br/>This Window will be reloaded to fix this issue.', 'window.location.reload()');</code>
}
procedure TExtThread.ErrorMessage(Msg: string; Action: string = '');
begin
JSCode('Ext.Msg.show({title:"Error",msg:' + StrToJS(Msg, true) + ',icon:Ext.Msg.ERROR,buttons:Ext.Msg.OK' +
IfThen(Action = '', '', ',fn:function(){' + Action + '}') + '});');
end;
{
Shows an error message in browser session using Ext JS style.
@param Msg Message text, can to use HTML to formating text.
@param Action Optional action that will be executed after user to click Ok button. Could be JavaScript or ExtPascal commands
@example <code>ErrorMessage('Illegal operation.<br/>Click OK to Shutdown.', Ajax(Shutdown));</code>
}
procedure TExtThread.ErrorMessage(Msg: string; Action: TExtFunction);
begin
ErrorMessage(Msg, Action.ExtractJSCommand);
end;
function TExtThread.GarbageFixName(const Name: string): string;
begin
Result := AnsiReplaceStr(Name, IdentDelim, '');
end;
{
Occurs when an exception is raised during the execution of method that handles the request (PATH_INFO).
Display error message with exception message, method name and method params.
@param Msg Exception message
@param Method Method name invoked by Browser (PATH_INFO) or thru AJAX request
@param Params Method params list
@exception TAccessViolation If current request is AJAX the session can be fixed reloading the page.
}
procedure TExtThread.OnError(const Msg, Method, Params: string);
var
FMsg: string;
begin
Response := '';
FMsg := Msg;
if IsAjax and (pos('Access violation', FMsg) <> 0) then
FMsg := FMsg + '<br/><b>Reloading this page (F5) perhaps fix this error.</b>';
ErrorMessage(FMsg + '<br/>Method: ' + IfThen(Method = '', 'Home', Method) + IfThen(Params = '', '',
'<br/>Params:<br/>' + AnsiReplaceStr(Params, '&', '<br/>')));
end;
procedure TExtThread.Alert(const Msg: string);
begin
ErrorMessage(Msg)
end;
{
Self-translating main procedure. Translates Object Pascal code to JavaScript code.
Self-translating (ST) is not a compiler. It's a minimalist (very small, ultra quick and dirty) approach that imitates an online interpreter.
You code in Object Pascal and when the program runs it automatically generates the corresponding JavaScript code.
But there is an essential limitation; it does not create business rules or sophisticated behavior in JavaScript.
So it does not interpret "IF", "WHILE", "CASE", "TRY", etc commands, but "IF", "WHILE", etc realizes a conditional code generation
on Server side as ASP and JSP does it. ST is used to create objects and widgets, to set properties and events and to call methods.
It's analogous to Delphi .dfm file role: to describe a GUI.
There are additional facilities to invoke complex Server side logic using <link TExtObject.Ajax, AJAX>, to define small <link TExtObject.JSFunction, functions> in JavaScript and
to use <link TExtThread.SetLibrary, large JS libraries>. It's enough to create powerful GUIs.
The rest (business rules, database access, etc) should be done in Object Pascal on Server side.
Basic work:
* JS commands are appended to Response.
* JS attributes are found in Response using yours JSName attribute and setted in place.
* If not found, JS attributes are appended to Response.
@param JS JS commands or assigning of attributes or events
@param JSName Optional current JS object name
@param Owner Optional JS object owner for TExtObjectList
}
procedure TExtThread.JSCode(JS: string; JSClassName: string = ''; JSName: string = ''; Owner: string = '');
var
I, J: Integer;
begin
if (JS <> '') and (JS[length(JS)] = ';') then
begin // Command
I := pos('.', JS);
J := pos(IdentDelim, JS);
if (pos('Singleton', JSClassName) = 0) and (J > 0) and (J < I) and (pos(DeclareJS, JS) = 0) and
not GarbageExists(copy(JS, J - 1, I - J + 1)) then
raise Exception.Create('Public property or Method: ''' + JSClassName + '.' + copy(JS, I + 1,
FirstDelimiter('=(', JS, I) - I - 1) + ''' requires explicit ''var'' declaration.');
I := length(Response) + 1
end
else // set attribute
if JSName = '' then
raise Exception.Create('Missing '';'' in command: ' + JS)
else
begin
I := pos('/*' + JSName + '*/', Response);
if I = 0 then
raise Exception.Create('Config Option: ' + JS + '<br/>is refering a previous request,' +
'<br/>it''s not allowed in AJAX request or JS handler.<br/>Use equivalent Public Property or Method instead.');
if not(Response[I - 1] in ['{', '[', '(', ';']) then
JS := ',' + JS;
end;
insert(JS, Response, I);
if (pos('O' + IdentDelim, JS) <> 0) and (pos('O' + IdentDelim, JSName) <> 0) then
begin
if Owner <> '' then
JSName := Owner;
RelocateVar(JS, JSName, I + length(JS));
end;
end;
{
Forces that the JS Object declaration (var) occurs before of its use: method call, get/set attributes, etc,
relocating the declaration to a previous position in Response.
@param JS Command or attribute that uses the JS Object.
@param JSName Current JS Object.
@param I Position in Response string where the JS command ends.
}
procedure TExtThread.RelocateVar(JS, JSName: string; I: Integer);
var
VarName, VarBody: string;
J, K: Integer;
begin
J := LastDelimiter(':,', JS);
if J <> 0 then
VarName := copy(JS, J + 1, posex(IdentDelim, JS, J + 3) - J)
else
VarName := JS;
J := posex('/*' + VarName + '*/', Response, I);
if J > I then
begin
K := pos('/*' + JSName + '*/', Response);
K := posex(';', Response, K) + 1;
J := posex(';', Response, J);
VarBody := copy(Response, K, J - K + 1);
J := LastDelimiter(CommandDelim, VarBody) + 1;
VarBody := copy(VarBody, J, length(VarBody));
Delete(Response, K + J - 1, length(VarBody));
insert(VarBody, Response, pos(DeclareJS + JSName + '=new', Response));
end;
end;
{
Concats two JS commands only to translate nested Object Pascal typecasts as:
@param PrevCommand Command already present in Response that will be concatenated with NextCommand
@param NextCommand Command that will be concatenated with PrevCommand.
@return The JS commands concatenated
@example <code>
TExtGridRowSelectionModel(GetSelectionModel).SelectFirstRow;
// It's usually could be translated to:
O1.getSelectionModel;
O1.selectFirstRow;
// instead of:
O1.getSelectionModel.selectFirstRow;</code>
}
function TExtThread.JSConcat(PrevCommand, NextCommand: string): string;
var
I, J: Integer;
begin
J := ExtPascalUtils.RPosEx(PrevCommand, Response, 1);
I := pos('.', NextCommand);
if (I <> 0) and (J <> 0) then
begin
NextCommand := copy(NextCommand, I, length(NextCommand));
Result := copy(PrevCommand, 1, length(PrevCommand) - 1) + NextCommand;
Delete(Response, J + length(PrevCommand) - 1, 1);
insert(NextCommand, Response, J + length(PrevCommand))
end
else
Result := PrevCommand;
end;
procedure TExtThread.JSSleep(MiliSeconds: Integer);
begin
JSCode('sleep(' + IntToStr(MiliSeconds) + ');')
end;
procedure TExtObject.JSSleep(MiliSeconds: Integer);
begin
JSCode('sleep(' + IntToStr(MiliSeconds) + ');')
end;
function TExtObject.MethodURI(Method: TExtProcedure; Params: array of const): string;
begin
Result := MethodURI(Method);
if length(Params) <> 0 then
begin
if pos('?', Result) = 0 then
Result := Result + '?';
Result := Result + FormatParams('TExtObject.MethodURI', Params)
end;
end;
function TExtObject.MethodURI(Method: TExtProcedure): string;
var
MetName, ObjName: string;
begin
FindMethod(Method, MetName, ObjName);
Result := CurrentWebSession.MethodURI(MetName) + IfThen(ObjName = '', '', '?Obj=' + ObjName);
end;
function TExtObject.MethodURI(MethodName: string; Params: array of const): string;
begin
Result := CurrentWebSession.MethodURI(MethodName) + IfThen(length(Params) = 0, '',
'?' + FormatParams(MethodName, Params))
end;
function TExtObject.MethodURI(MethodName: string): string;
begin
Result := CurrentWebSession.MethodURI(MethodName)
end;
{
Does tasks related to the Request that occur before the method call invoked by Browser (PATH-INFO)
1. Detects the browser language.
2. If that language has corresponding JS resource file in framework uses it, for example: '/ext/source/locale/ext-lang-?????.js',
3. Else uses the default language (English).
4. Identify the browser.
5. Tests if is an AJAX request.
6. Tests if cookies are enabled.
@return False if Cookies are disable or if is Ajax executing the first thread request else returns true.
}
function TExtThread.BeforeHandleRequest: boolean;
var
I: Integer;
begin
Result := true;
if FLanguage = '' then
begin // Set language
FLanguage := RequestHeader['HTTP_ACCEPT_LANGUAGE'];
I := pos('-', FLanguage);
if I <> 0 then
begin
FLanguage := copy(FLanguage, I - 2, 2) + '_' + Uppercase(copy(FLanguage, I + 1, 2));
if not FileExists(RequestHeader['DOCUMENT_ROOT'] + ExtPath + SourcePath + '/locale/ext-lang-' + FLanguage + '.js')
then
FLanguage := copy(FLanguage, 1, 2)
end;
end;
IsAjax := (RequestHeader['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest') or IsUpload;
if IsAjax then
begin
if Cookie['FCGIThread'] = '' then
begin
ErrorMessage('This web application requires Cookies enabled to AJAX works.');
Result := false;
end
else if NewThread or RequiresReload then
begin
ErrorMessage('Session expired or lost.<br/>A new session will be created now.', 'window.location.reload()');
RequiresReload := true;
Result := false;
end
end
else
RequiresReload := false;
JSReturns := TStringList.Create;
end;
// Override this method to change ExtPath, ImagePath, ExtBuild and Charset default values
procedure TExtThread.InitDefaultValues;
begin
inherited;
{$IFDEF CacheFly}
ExtPath := 'http://extjs.cachefly.net/ext-4.0.2';
{$ELSE}
ExtPath := '/ext';
{$ENDIF}
ImagePath := '/images';
ExtBuild := 'ext-all';
Charset := 'utf-8'; // 'iso-8859-1'
UpLoadPath := '/uploads';
end;
{
Creates a session to handle a new requests
@param AOwner You do not need to know this :)
}
constructor TExtThread.Create(AOwner: TObject);
begin
inherited;
end;
// config will be read once, only on new client thread construction
procedure TExtThread.AfterNewSession;
begin
inherited;
{$IFDEF HAS_CONFIG}
ReadConfig;
{$ENDIF}
end;
{$IFDEF HAS_CONFIG}
// Read ExtPath, ImagePath and Theme from configuration file
procedure TExtThread.ReadConfig;
begin
with Application do
if HasConfig then
begin
ExtPath := Config.ReadString('FCGI', 'ExtPath', ExtPath);
if pos('/', ExtPath) <> 1 then
ExtPath := '/' + ExtPath;
ImagePath := Config.ReadString('FCGI', 'ImagePath', ImagePath);
if pos('/', ImagePath) <> 1 then
ImagePath := '/' + ImagePath;
Theme := Config.ReadString('FCGI', 'ExtTheme', Theme);
Charset := Config.ReadString('FCGI', 'Charset', Charset);
end;
end;
// Re-read config file if password is right
procedure TExtThread.DoReconfig;
{$IFDEF DEBUGJS}
var
I: Integer;
{$ENDIF}
begin
ReadConfig;
{$IFDEF DEBUGJS}
// show applied configuration values (only during debugging)
with TStringList.Create do
begin
LoadFromFile(Config.FileName);
Response := 'RECONFIG: Application is reconfigured with the following values:<p>';
for I := 0 to Count - 1 do
Response := Response + Strings[I] + '<br>';
SendResponse(Response);
Free;
end;
{$ENDIF}
end;
{$ENDIF}
// Calls events using Delphi style
procedure TExtThread.HandleEvent;
var
Obj: TExtObject;
begin
if Query['IsEvent'] = '1' then
begin
Obj := TExtObject(GarbageFind(Query['Obj']));
if not Assigned(Obj) then
OnError('Object not found in session list. It could be timed out, refresh page and try again', 'HandleEvent', '')
else
Obj.HandleEvent(Query['Evt']);
end;
end;
{
Does tasks after Request processing.
1. Extracts Comments, auxiliary delimiters, and sets:
2. HTML body,
3. Title,
4. Application icon,
5. Charset,
6. ExtJS CSS,
7. ExtJS libraries,
8. ExtJS theme,
9. ExtJS language,
10. Additional user styles,
11. Additional user libraries,
12. Additional user JavaScript,
13. ExtJS invoke,
14. Handlers for AJAX response and
15. If DEBUGJS conditional-define is active:
15.1. Uses CodePress library with syntax highlight,
15.2. Generates JS code to enhance AJAX debugging, using Firefox, and
15.3. Formats AJAX response code for easy debugging.
}
procedure TExtThread.AfterHandleRequest;
procedure HandleJSReturns;
var
I: Integer;
begin
if (JSReturns <> nil) and (JSReturns.Count <> 0) then
for I := 0 to JSReturns.Count - 1 do
begin
Response := AnsiReplaceStr(Response, JSReturns.Names[I], JSReturns.ValueFromIndex[I]);
Response := AnsiReplaceStr(Response, IntToStr(StrToInt(JSReturns.Names[I])), JSReturns.ValueFromIndex[I]);
end;
FreeAndNil(JSReturns);
end;
var
I, J: Integer;
begin
if IsDownLoad or IsUpload then
exit;
I := pos('/*', Response);
while I <> 0 do
begin // Extracts comments
J := posex('*/', Response, I);
Delete(Response, I, J - I + 2);
I := posex('/*', Response, I);
end;
HandleJSReturns;
Response := AnsiReplaceStr(AnsiReplaceStr(Response, CommandDelim, ''), IdentDelim, ''); // Extracts aux delimiters
if not IsAjax then
begin
Response := IfThen(HTMLQuirksMode, '<!docttype html public><html>',
'<?xml version=1.0?><!doctype html public "-//W3C//DTD XHTML 1.0 Strict//EN">'^M^J'<html xmlns=http://www.w3org/1999/xthml>') + ^M^J + '<head>'^M^J + '<title>' + Application.Title + '</title>'^M^J
+ IfThen(Application.Icon = '', '', '<link rel="shortcut icon" href="' + ImagePath + '/' + Application.Icon +
'"/>'^M^J) + '<meta http-equiv="content-type" content="charset=' + Charset + '" />'^M^J +
IfThen(Browser = brIE, '<meta http-equiv="X-UA-Compatible" content="IE=8" />'^M^J, '') +
'<link rel=stylesheet href="' + ExtPath + '/resources/css/' + ExtBuild + IfThen(Theme = '', '', '-' + Theme) +
'.css" />'^M^J + '<script src="' + ExtPath + '/' + ExtBuild + {$IFDEF DebugExtJS}'-debug' +
{$ENDIF} '.js"></script>'^M^J +
{$IFDEF DEBUGJS}'<script src="/codepress/Ext.ux.CodePress.js"></script>'^M^J + {$ENDIF}
IfThen(FLanguage = 'en', '', '<script src="' + ExtPath + '/locale/ext-lang-' + FLanguage + '.js"></script>'^M^J) +
GetStyle + Libraries + '</head>'^M^J'<p></p>'^M^J + '<body><div id=body>'^M^J +
'<div id=loading style="position:absolute;font-family:verdana;top:40%;left:40%">'^M^J + '<img src="' + ExtPath +
'/resources/images/default/shared/loading-balls.gif"/>' + ' Loading ' + Application.Title + '...</div>'^M^J +
'</div><noscript>This web application requires JavaScript enabled</noscript></body>'^M^J + '<script>'^M^J +
{$IFDEF DEBUGJS}BeautifyJS{$ENDIF}
(IfThen(CustomJS = '', '', CustomJS + ^M^J) + 'Ext.onReady(function(){' + 'Ext.get("loading").remove();' +
'Ext.BLANK_IMAGE_URL="' + ExtPath +
'/resources/images/default/s.gif";TextMetrics=Ext.util.TextMetrics.createInstance("body");' +
'function AjaxError(m){Ext.Msg.show({title:"Ajax Error",multiline:true,msg:m,icon:Ext.Msg.ERROR,buttons:Ext.Msg.OK});};'
+
{$IFDEF DEBUGJS}
'function AjaxSource(t,l,s){var w=new Ext.Window({title:"Ajax error: "+t+", Line: "+' +
IfThen(Browser = brFirefox, '(l-%%)', '"Use Firefox to debug"') +
',width:600,height:400,modal:true,items:[new Ext.ux.CodePress({language:"javascript",readOnly:true,code:s})]});w.show();'
+ 'w.on("resize",function(){w.items.get(0).resize();});};' +
'function AjaxSuccess(response){try{eval(response.responseText);}catch(err){AjaxSource(err.message,err.lineNumber,response.responseText);}};'
+
{$ELSE}
'function AjaxSuccess(response){try{eval(response.responseText);}catch(err){AjaxError(err.message+"<br/>Use DebugJS define to enhance debugging<br/>"+response.responseText);}};'
+
{$ENDIF}
'function sleep(ms){var start=new Date().getTime();for(var i=0;i<1e7;i++)if((new Date().getTime()-start)>ms)break;};'
+ 'function AjaxFailure(){AjaxError("Server unavailable, try later.");};' +
'Download=Ext.DomHelper.append(document.body,{tag:"iframe",cls:"x-hidden"});' + Response) + '});'^M^J +
'</script>'^M^J^M^J'</html>';
{$IFDEF DEBUGJS}
Response := AnsiReplaceStr(Response, '%%', IntToStr(CountStr(^M^J, Response, 'eval('))); // eval() line number
{$ENDIF}
end
{$IFDEF DEBUGJS}
else
Response := BeautifyJS(Response);
{$ENDIF}
end;
{
Returns a unique numeric sequence to identify a JS object, list or attribute in this session.
This sequence will be used by Self-translating process imitating a Symbol table entrance.
}
function TExtThread.GetSequence: string;
begin
Result := IntToHex(Sequence, 1);
inc(Sequence);
end;
{ ExtObjectList }
{
Creates a TExtObjectList instance.
@param pOwner TExtObject that owns this list
@param pAttribute JS attribute name in TExtObject to this list
}
constructor TExtObjectList.Create(pOwner: TExtObject = nil; pAttribute: string = '');
begin
Attribute := pAttribute;
Owner := pOwner;
Created := true;
if CurrentWebSession <> nil then
JSName := 'O' + IdentDelim + TExtThread(CurrentWebSession).GetSequence + IdentDelim;
end;
{
Creates a singleton TExtObjectList instance, used usually by Parser only.
@param pAttribute JS attribute name in TExtObject to this list in the form 'Owner.attribute'
}
constructor TExtObjectList.CreateSingleton(pAttribute: string);
begin
Attribute := pAttribute;
end;
// Frees this list and all objects linked in it
destructor TExtObjectList.Destroy;
var
I: Integer;
begin
for I := high(FObjects) downto 0 do
try
FObjects[I].Free
except
end;
SetLength(FObjects, 0);
inherited;
end;
{
Adds a <link TExtObject> in this list and generates the corresponding JS code in the Response.
@param Obj <link TExtObject> to add in the list
}
procedure TExtObjectList.Add(Obj: TExtObject);
var
ListAdd, Response, OwnerName: string;
begin
if length(FObjects) = 0 then
if Owner <> nil then
begin
if pos('/*' + Owner.JSName + '*/', CurrentWebSession.Response) <> 0 then
Owner.JSCode(Attribute + ':[/*' + JSName + '*/]', Owner.JSName)
end
else
with TExtThread(CurrentWebSession) do
begin
JSCode(DeclareJS + JSName + '=[/*' + JSName + '*/];');
GarbageAdd(JSName, nil);
end;
SetLength(FObjects, length(FObjects) + 1);
FObjects[high(FObjects)] := Obj;
Response := CurrentWebSession.Response;
if Owner <> nil then
OwnerName := Owner.JSName
else
OwnerName := '';
if not Obj.Created or (pos(JSName, Response) = 0) then
begin
if TExtThread(CurrentWebSession).IsAjax and (OwnerName <> '') then
if not Obj.Created then
if pos(JSName, Response) = 0 then
begin
ListAdd := DeclareJS + Obj.JSName + '=' + OwnerName + '.add(%s);';
TExtThread(CurrentWebSession).GarbageAdd(Obj.JSName, nil);
end
else
ListAdd := '%s'
else
ListAdd := OwnerName + '.add(' + Obj.JSName + ');'
else
ListAdd := '%s';
if Attribute = 'items' then // Generalize it more if necessary
ListAdd := Format(ListAdd, ['new ' + Obj.JSClassName + '({/*' + Obj.JSName + '*/})'])
else
ListAdd := Format(ListAdd, ['{/*' + Obj.JSName + '*/}']);
end
else if pos(Obj.JSName + '.clone', Obj.JSCommand) = 1 then
ListAdd := Obj.ExtractJSCommand
else
ListAdd := Obj.JSName;
Obj.Created := true;
Obj.JSCode(ListAdd, JSName, OwnerName);
if Obj.JSClassName = 'Ext.ux.CodePress' then
Owner.JSCode(OwnerName + '.on("resize", function(){' + OwnerName + '.items.get(' + IntToStr(high(FObjects)) +
').resize();});');
end;
{
Returns the Ith object in the list, starts with 0.
@param I Position in list
@return <link TExtObject>
}
function TExtObjectList.GetFObjects(I: Integer): TExtObject;
begin
if (I >= 0) and (I <= high(FObjects)) then
Result := FObjects[I]
else
Result := nil
end;
// Returns the number of Objects in the list
function TExtObjectList.Count: Integer;
begin
Result := length(FObjects)
end;
{ ExtObject }
// Set an unique <link TExtObject.JSName, JSName> using <link TExtThread.GetSequence, GetSequence>
procedure TExtObject.CreateJSName;
begin
if Assigned(CurrentWebSession) then