Source

delQuery / delquery.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
{ delQuery v0.1 - jQuery like library for Delphi VCL.
  http://bitbucket.org/utku/delquery/

  (c) 2009-2010 M.Utku Karataş. <m.utku.k@gmail.com>
  This library is freely distributable under the terms of the MIT license.
  Inspired by jQuery by John Resig and the jQuery Team - jquery.com.

  TODO:
  - mouseenter-mouseleave has bugs
  - .prop(array of props)
  - .toggle(array of handlers)
  - insert all doc comments
  - better RTTI intergration with .prop
}
unit delquery;

interface

uses
  Classes, SysUtils, Controls, Windows, Messages, Graphics, Forms, Generics.Collections,
  ExtCtrls, Rtti;

type
  TdelQuery = class;

  { All delQuery event handlers are passed this construct as parameter. }
  dqevent = packed record
  private
    function GetThis: TdelQuery;
  public
    sender: TControl;                      { Reference to the original Sender parameter of events. }
    prevent: boolean;                      { Set this to true to prevent the default event handlers trigger }
    property this: TdelQuery read GetThis; { So that you can use "event.this" instead of
                                             "dq(event.sender)" every time. }
    case Integer of
      0: ( { mouse events }
        button: TMouseButton;
        shift: TShiftState;
        x, y: Integer;
        wheeldelta: Integer; mousepos: TPoint; handled: Boolean);
      1: ( { key events }
        {shift}
        key: Word;);
      2: ( {resize events }
        NewWidth: integer;
        NewHeight: integer;
        Resize: boolean;);
  end;

  TdqEachCallback = reference to procedure(obj: TControl);
  TdqEventHandler = reference to procedure(event: dqevent);
  TdqAnimationDoneCallback = reference to procedure(event: dqevent);
  TdqEasingFunc = function(x, t, b, c, d: double): double;

  { The all-mighty class providing every thing. Basically it is a list that holds control references }
  TdelQuery = class(TComponent)
  private
    fList: TList<TControl>;
    procedure AddControl(aControl: TControl);
    { event stubs }
    procedure OnClickStub(Sender: TObject);
    procedure OnDblClickStub(Sender: TObject);
    procedure OnEnterStub(Sender: TObject);
    procedure OnExitStub(Sender: TObject);
    procedure OnMouseDownStub(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure OnMouseUpStub(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure OnMouseMoveStub(Sender: TObject; Shift: TShiftState; X, Y: Integer);
    procedure OnMouseWheelStub(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
    procedure OnMouseWheelUpStub(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
    procedure OnMouseWheelDownStub(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
    procedure OnKeyDownStub(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure OnKeyUpStub(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure OnKeyPressStub(Sender: TObject; var Key: Char);
    procedure OnResizeStub(Sender: TObject);
    procedure OnCanResizeStub(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean);
    function GetCount: integer;
    function GetItems(Index: integer): TControl;
  protected
    fFxTimer: TTimer;
    function GetFx: TTimer;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    property FxTimer: TTimer read GetFx;
    function DoAnimate(obj: TControl; props: array of string; duration: string;
      easing: TdqEasingFunc = nil; callback: TdqAnimationDoneCallback = nil): TdelQuery;
  public
    constructor Create; reintroduce;
    destructor Destroy; override;

    { core }
    function each(callback: TdqEachCallback): TdelQuery;
    property count: integer read GetCount; // jQuery equivalent: size
    property get[Index: integer]: TControl read GetItems; default;

    { properties }
    function prop(const key: string): TValue; overload; // jQuery equivalent: jQuery.attr
    function prop(const key: string; value: TValue): TdelQuery; overload;

    { events }
    function enter(fn: TdqEventHandler): TdelQuery;
    function exit_(fn: TdqEventHandler): TdelQuery;
    function click(fn: TdqEventHandler): TdelQuery;
    function dblclick(fn: TdqEventHandler): TdelQuery;
    function mouseover(fn: TdqEventHandler): TdelQuery;
    function mouseout(fn: TdqEventHandler): TdelQuery;
    function mouseenter(fn: TdqEventHandler): TdelQuery;
    function mouseleave(fn: TdqEventHandler): TdelQuery;
    function mouseup(fn: TdqEventHandler): TdelQuery;
    function mousedown(fn: TdqEventHandler): TdelQuery;
    function mousemove(fn: TdqEventHandler): TdelQuery;
    function mousewheel(fn: TdqEventHandler): TdelQuery;
    function mousewheelup(fn: TdqEventHandler): TdelQuery;
    function mousewheeldown(fn: TdqEventHandler): TdelQuery;
    function keydown(fn: TdqEventHandler): TdelQuery;
    function keyup(fn: TdqEventHandler): TdelQuery;
    function keypress(fn: TdqEventHandler): TdelQuery;
    function oncanresize(fn: TdqEventHandler): TdelQuery;
    function onresize(fn: TdqEventHandler): TdelQuery;

    // xxx more to come...
    // function dragdrop
    // function dragover
    // function startdock
    // function startdrag
    // function contextpopup

    { utils }
    function toggle(fn, fn2: TdqEventHandler): TdelQuery;

    { effects }
    function animate(props: array of const;
                     duration: string;
                     easing: TdqEasingFunc = nil;
                     callback: TdqAnimationDoneCallback = nil): TdelQuery;
    function stop(clearQueue: boolean = False; gotoEnd: boolean = False): TdelQuery;
  end;

{ delQuery contructors }
function dq(aClass: TClass; Parent: TWinControl; Greedy: boolean = False): TdelQuery; overload;
function dq(aControl: TControl): TdelQuery; overload;
function dq(Controls: array of TControl): TdelQuery; overload;

{ Easing effects }
function ease_lineer(x, t, b, c, d: double): double;
function ease_swing(x, t, b, c, d: double): double;
function ease_outbounce(x, t, b, c, d: double): double;
function ease_inelastic(x, t, b, c, d: double): double;
function ease_inback(x, t, b, c, d: double): double;
function ease_outback(x, t, b, c, d: double): double;

implementation

uses
  Types, Math, Dialogs, DateUtils;

{ -------------------------------------------------------------------------------------------------------------------- }
{ Internal structs of use }

type
  TWinControlAccessHack = class(TWinControl);

  TAnimationData = class;

  { Too bad class helpers can't attach fields to a class, this is gonna be a weird way
    but every control needs to be attached a copy of ExtraData }
  ExtraData = class
  private
    fSelf: TControl;
    fDQ: TdelQuery;
    fThis: TdelQuery;
    fOldWindowProc: TWndMethod;
    AlreadyInElement: boolean;
    AnimationQueue: TObjectQueue<TAnimationData>;
    InAnimation: Boolean;
    procedure OnWindowProc(var Message: TMessage);
  private
    { New event to trrigger }           { The old event before assignment }
    EnterFn: TdqEventHandler;           OldOnEnter: TNotifyEvent;
    ExitFn: TdqEventHandler;            OldOnExit: TNotifyEvent;
    ClickFn: TdqEventHandler;           OldOnClick: TNotifyEvent;
    DblClickFn: TdqEventHandler;        OldOnDblClick: TNotifyEvent;
    MouseEnterFn: TdqEventHandler;      //OldOnMouseEnter: TNotifyEvent;
    MouseLeaveFn: TdqEventHandler;      //OldOnMouseLeave: TNotifyEvent;
    MouseUpFn: TdqEventHandler;         OldOnMouseUp: TMouseEvent;
    MouseDownFn: TdqEventHandler;       OldOnMouseDown: TMouseEvent;
    MouseMoveFn: TdqEventHandler;       OldOnMouseMove: TMouseMoveEvent;
    MouseWheelFn: TdqEventHandler;      OldOnMouseWheel: TMouseWheelEvent;
    MouseWheelUpFn: TdqEventHandler;    OldOnMouseWheelUp: TMouseWheelUpDownEvent;
    MouseWheelDownFn: TdqEventHandler;  OldOnMouseWheelDown: TMouseWheelUpDownEvent;
    KeyDownFn: TdqEventHandler;         OldOnKeyDown: TKeyEvent;
    KeyUpFn: TdqEventHandler;           OldOnKeyUp: TKeyEvent;
    KeyPressFn: TdqEventHandler;        OldOnKeyPress: TKeyPressEvent;
    CanResizeFn: TdqEventHandler;       OldOnCanResize: Controls.TCanResizeEvent;
    ResizeFn: TdqEventHandler;          OldOnResize: TNotifyEvent;
  public
    destructor Destroy; override;
    class function for_(obj: TObject): ExtraData;
  end;

  TAnimationData = class
  public
    props: array of string;
    duration: string;
    easing: TdqEasingFunc;
    callback: TdqAnimationDoneCallback;
    destructor Destroy; override;
  end;

  { easy to use timer }
  TFxOnStop = reference to procedure;
  TFxOnStep = reference to procedure(var stop: boolean);

  TFxTimer = class(TTimer)
  protected
    fOnStep: TFxOnStep;
    fOnStop: TFxOnStop;
    procedure OnTimerStub(Sender: TObject);
  public
    procedure FireUp(OnStep: TFxOnStep; OnStop: TFxOnStop);
  end;

var
  ExtraDataRegistry: TDictionary<TObject, ExtraData>;

destructor ExtraData.Destroy;
begin
  FreeAndNil(AnimationQueue);
  inherited;
end;

class function ExtraData.for_(obj: TObject): ExtraData;
begin
  if not ExtraDataRegistry.TryGetValue(obj, Result) then
  begin
    Result := ExtraData.Create;
    Result.fSelf := obj as TControl;
    Result.AnimationQueue := TObjectQueue<TAnimationData>.Create;
    Result.AnimationQueue.OwnsObjects := False;
    ExtraDataRegistry.Add(obj, Result);
  end;
end;

procedure TFxTimer.FireUp(OnStep: TFxOnStep; OnStop: TFxOnStop);
begin
  Self.fOnStep := OnStep;
  Self.fOnStop := OnStop;
  Self.OnTimer := OnTimerStub;
  Self.Interval := 13;
  Self.Enabled := True;
end;

procedure TFxTimer.OnTimerStub;
var
  stop: boolean;
begin
  stop := false;
  Self.fOnStep(stop);
  if stop then
  begin
    Self.Enabled := false;
    Self.fOnStop();
  end;
end;

function dqEvent.GetThis: TdelQuery;
var data: ExtraData;
begin
  data := ExtraData.for_(sender);
  if data.fThis = nil then
  begin
    Result := TdelQuery.Create;
    Result.AddControl(sender);
  end
  else
    Result := data.fThis;
end;

procedure log(const S: string);
begin
  OutputDebugString(PWideChar(S));
end;

function ObjGetInitialValue(Obj: TObject; const Prop: string): integer;
begin
  Result := TRttiContext.Create.GetType(Obj.ClassType).GetProperty(Prop).GetValue(obj).AsInteger;
end;

procedure ObjSetValue(Obj: TObject; const Prop: string; Value: TValue); overload;
var
  dotPos: integer;
  curProp, curProp2: string;
  curRProp: TRttiProperty;
begin
  dotPos := Pos('.', Prop);
  if dotPos = 0 then
    TRttiContext.Create.GetType(Obj.ClassType).GetProperty(Prop).SetValue(Obj, Value)
  else
  begin
    { support calls like 'font.color' }
    // todo: support more depth
    curProp := Copy(Prop, 1, dotPos - 1);
    curRProp := TRttiContext.Create.GetType(Obj.ClassType).GetProperty(curProp);
    curProp2 := Copy(Prop, dotPos + 1, MaxInt);
    if curRProp.PropertyType is TRttiInstanceType then
      TRttiContext.Create.GetType(curRProp.GetValue(Obj).AsObject.ClassType).
        GetProperty(curProp2).SetValue(curRProp.GetValue(Obj).AsObject, Value);
  end;
end;

function ObjGetTargetValue(const S: string; InitialValue: integer): integer;
begin
  try
    if Copy(S, 1, 2) = '+=' then
      Result := StrToInt(Copy(S, 3, Maxint)) + InitialValue
    else if Copy(S, 1, 2) = '-=' then
      Result := InitialValue - StrToInt(Copy(S, 3, Maxint))
    else
      Result := StrToInt(S);
  except
    raise Exception.CreateFmt('Unrecognized param value "%s"', [S]);
  end;
end;

{ Delphi doesn't let you use open arrays out of function context but we need
  to store given values. This function converts an open array to a string array
  for further use.}
type TStringArray = array of string;

function StrArrayFromOpenArray(openArr: array of const): TStringArray;
var
  i: integer;
  v: PVarRec;
begin
  SetLength(Result, Length(openArr));
  for i := low(openArr) to high(openArr) do
  begin
    v := @openArr[i];
    case v.VType of
      vtString: Result[i] := string(v.VString);
      vtUnicodeString: Result[i] := string(v.VString);
      vtInteger: Result[i] := IntToStr(v.VInteger);
    else
      raise Exception.Create('xxx unsupported property type to use in animations!');
    end;
  end;
end;

{ -------------------------------------------------------------------------------------------------------------------- }
{ Functions for easing effects

  See http://jquery-ui.googlecode.com/svn/trunk/demos/effect/easing.html for the effects in use.
  Can add more functions from http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js }

function ease_lineer(x, t, b, c, d: double): double;
begin
  Result := b + c * x;
end;

function ease_swing(x, t, b, c, d: double): double;
begin
  Result := ((-cos(x * PI) / 2) + 0.5) * c + b;
end;

function ease_outbounce(x, t, b, c, d: double): double;
begin
  t := t / d;
  if (t < (1 / 2.75)) then
    Result := c * (7.5625 * t * t) + b
  else
  if (t < (2 / 2.75)) then
  begin
    t := t - (1.5 / 2.75);
    Result := c * (7.5625 * t * t + 0.75) + b;
  end
  else if (t < (2.5 / 2.75)) then
  begin
    t := t - (2.25 / 2.75);
    Result := c * (7.5625 * t * t + 0.9375) + b;
  end
  else
  begin
    t := t - (2.625 / 2.75);
    Result := c * (7.5625 * t * t + 0.984375) + b;
  end;
end;

function ease_inelastic(x, t, b, c, d: double): double;
var
  a,s,p: double;
begin
  p := 0;
  a := c;
  if (t = 0) then EXIT(b);
  t := t / d;
  if (t = 1) then EXIT(b+c);
  if p = 0 then
    p := d * 0.3;
  if (a < abs(c)) then
  begin
    a := c;
    s := p/4;
  end
  else
    s := p / (2 * PI) * ArcSin(c / a);
  t := t - 1;
  Result := -(a * Power(2, 10 * t) * sin((t * d - s) * (2 * PI) / p)) + b;
end;

function ease_inback(x, t, b, c, d: double): double;
const s = 1.70158;
begin
  t := t / d;
  Result := c * t * t * ((s + 1) * t - s) + b;
end;

function ease_outback(x, t, b, c, d: double): double;
const s = 1.70158;
begin
  t := t / d-1;
  Result := c * (t * t * ((s + 1) * t + s) + 1) + b;
end;

{ -------------------------------------------------------------------------------------------------------------------- }
{ TdelQuery }

constructor TdelQuery.Create;
begin
  fList := TList<TControl>.Create;
end;

destructor TdelQuery.Destroy;
begin
  FreeAndNil(fFxTimer);
  FreeAndNil(fList);
end;

procedure TdelQuery.AddControl(aControl: TControl);
begin
  fList.Add(aControl);
  aControl.FreeNotification(self);
end;

function TdelQuery.GetCount: integer;
begin
  Result := fList.Count
end;

function TdelQuery.GetFx: TTimer;
begin
  if fFxTimer = nil then
    fFxTimer := TFxTimer.Create(nil);
  Result := TFxTimer(fFxTimer);
end;

function TdelQuery.GetItems(Index: integer): TControl;
begin
  Result := fList[Index];
end;

procedure TdelQuery.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if (Operation = opRemove) then
  begin
    // cleanup ExtraData
    ExtraData.for_(AComponent).Free;
    ExtraDataRegistry.Remove(AComponent);

    // remove control from the internal list
    fList.Delete(fList.IndexOf(TControl(AComponent)));

    // cleanup delQuery instance if not needed
    if fList.Count = 0 then
      Destroy; // log('all controls of delQuery are gone and so is the delQuery object..');
  end;
end;

function TdelQuery.each(callback: TdqEachCallback): TdelQuery;

  { }

var
  i: integer;
begin
  Result := Self;
  for i := 0 to fList.Count - 1 do
    callback(fList[i]);
end;

function TdelQuery.prop(const key: string): TValue;

  { Access a property on the first element (first control in delQuery instance). }

begin
  if count = 0 then
    result := TValue.Empty
  else
    Result := TRttiContext.Create.GetType(get[0].ClassType).GetProperty(key).GetValue(get[0]);
end;

function TdelQuery.prop(const key: string; value: TValue): TdelQuery;

  { Set the property given by "key" to the "value" on all controls.
    Using TValue gives us implicit conversion for most of the types }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ObjSetValue(obj, key, value);
            end);
end;

{??? function TdelQuery.prop(const props: array of const): TdelQuery;
var i: integer;
begin
  if Odd(Length(props)) then raise Exception.Create('Every property must match a value!');
  Result := Self;
  for i := 1 to (Length(props) div 2) do
  begin
    prop(string(props[i*2-1].VUnicodeString), '');
  end;
end; ???}

type TStepFunc = reference to procedure;

function TdelQuery.DoAnimate(obj: TControl; props: array of string; duration: string;
  easing: TdqEasingFunc; callback: TdqAnimationDoneCallback): TdelQuery;
var
  state, pos: double;
  durationMS, i: integer;
  startTime: TDateTime;
  callback_: TdqAnimationDoneCallback; // clone for capturing
  props_: array of string; // clone for capturing
  step, lastStep: TStepFunc;
  currentValues, startValues, endValues: TArray<integer>;

  procedure FixUpDuration;
  begin
    durationMS := StrToIntDef(duration, -1);
    if durationMS = -1 then
      if duration = 'slow' then
        durationMS := 600
      else if duration = 'default' then
        durationMS := 400
      else if duration = 'fast' then
        durationMS := 200;
  end;

  function PushToQueue: boolean;
  var
    data: TAnimationData;
    i: integer;
  begin
    Result := False;
    if ExtraData.for_(obj).InAnimation then // there's already an animation
    begin
      data := TAnimationData.Create;
      SetLength(data.props, Length(props)); // silly pascal now letting array of strings autocopy
      for i := 0 to Length(props) - 1 do
        data.props[i] := props[i];
      data.duration := duration;
      data.easing := easing;
      data.callback := callback;
      Extradata.for_(obj).AnimationQueue.Enqueue(data);
      //log(Format('PUSH animation with %s, %s', [props[0], props[1]]));
      Result := True;
    end;
  end;

  procedure InitFxVars;
  var i: integer;
  begin
    SetLength(currentValues, Length(props_) div 2);
    SetLength(startValues, Length(props_) div 2);
    SetLength(endValues, Length(props_) div 2);
    for i := 0 to (Length(props_) div 2) - 1 do
    begin
      startValues[i] := ObjGetInitialValue(obj, props_[i*2]);
      endValues[i] := ObjGetTargetValue(props[i*2+1], startValues[i]);
    end;
  end;

begin
  //log(Format('REQUEST animation with %s, %s', [props[0], props[1]]));
  Result := Self;
  if PushToQueue then EXIT;
  ExtraData.for_(obj).InAnimation := True;
  //log(Format('IN animation with %s, %s', [props[0], props[1]]));

  SetLength(props_, Length(props));
  for i := 0 to High(props) do props_[i] := props[i];
  callback_ := callback;

  FixUpDuration;
  if @easing = nil then
    easing := ease_lineer;
  InitFxVars;
  startTime := Now;

  step := procedure
          var i: integer;
          begin
            for i := 0 to (Length(props_) div 2) - 1 do
            begin
              currentValues[i] := trunc(startValues[i] + ((endValues[i] - startValues[i]) * pos));
              ObjSetValue(obj, props_[i*2], currentValues[i]);
            end;
          end;

  lastStep := procedure
              var i: integer;
              begin
                for i := 0 to (Length(props_) div 2) - 1 do
                begin
                  ObjSetValue(obj, props_[i*2], endValues[i]);
                end;
              end;

  FxTimer.Tag := 0;
  TFxTimer(FxTimer).FireUp(
    procedure(var stop: boolean) // OnStep
    var n: integer;
    begin
      if durationMS <= MilliSecondsBetween(startTime, Now) then
      begin
        stop := True;
      end
      else
      begin
        n := MilliSecondsBetween(startTime, Now);
        state := n / durationMS;

        // Perform the easing function
        pos := easing(state, n, 0, 1, durationMS);

        // next step in the animation
        step;
      end;

      if FxTimer.Tag = $BABE then // .stop called with gotoEnd true
      begin
        lastStep;
        FxTimer.Tag := 0;
        FxTimer.Enabled := False;
        log('was deadbeef');
      end
      else
      if FxTimer.Tag = $DEAD then // .stop called
      begin
        FxTimer.Tag := 0;
        FxTimer.Enabled := False;
        log('was dead');
      end;
      log('onstep '+IntToStr(FxTimer.Tag));
    end
    ,
    procedure // OnStop
    var
      event: dqevent;
      q: TAnimationData;
    begin
      try
        ExtraData.for_(obj).InAnimation := False;

        // last step in the animation. (easing funcs don't complete till last bit, so force it)
        lastStep;

        // xxx DELPHI INTERNAL ERROR? I guess this is a compiler bug.
        // Finalize(currentValues);
        // Finalize(startValues);
        // Finalize(endValues);
        // Free the array mem.
        // props := nil; AND ANOTHER COMPILER BUG?
        props_ := nil;
        currentValues := nil;
        startValues := nil;
        endValues := nil;

        // trigger done-animation callback
        if assigned(callback_) then
        begin
          event.sender := obj;
          callback_(event);
        end;
      finally
        // call the next effect in queue
        if Extradata.for_(obj).AnimationQueue.Count > 0 then
        begin
          q := Extradata.for_(obj).AnimationQueue.Peek;
          Extradata.for_(obj).AnimationQueue.Dequeue;
          DoAnimate(obj, q.props, q.duration, q.easing, q.callback);
          q.Free;
        end;
      end;
    end
    );
end;

{ event redirections }

function TdelQuery.click(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnClick event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnClick := TWinControlAccessHack(obj).OnClick;
               TWinControlAccessHack(obj).OnClick := OnClickStub;
               ExtraData.for_(obj).ClickFn := fn;
             end );
end;

procedure TdelQuery.OnClickStub(Sender: TObject);
var event: dqevent;
begin
  event.prevent := False;
  event.sender := Sender as TControl;
  ExtraData.for_(Sender).ClickFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnClick <> nil then
      ExtraData.for_(Sender).OldOnClick(Sender);
end;

function TdelQuery.dblclick(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnDblClick event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnDblClick := TWinControlAccessHack(obj).OnDblClick;
               TWinControlAccessHack(obj).OnDblClick := OnDblClickStub;
               ExtraData.for_(obj).DblClickFn := fn;
             end );
end;

procedure TdelQuery.OnDblClickStub(Sender: TObject);
var event: dqevent;
begin
  event.prevent := False;
  event.sender := Sender as TControl;
  ExtraData.for_(Sender).DblClickFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnDblClick <> nil then
      ExtraData.for_(Sender).OldOnDblClick(Sender);
end;

function TdelQuery.enter(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnEnter event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnEnter := TWinControlAccessHack(obj).OnEnter;
               TWinControlAccessHack(obj).OnEnter := OnEnterStub;
               ExtraData.for_(obj).EnterFn := fn;
             end );
end;

procedure TdelQuery.OnEnterStub(Sender: TObject);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  ExtraData.for_(Sender).EnterFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnEnter <> nil then
      ExtraData.for_(Sender).OldOnEnter(Sender);
end;

function TdelQuery.exit_(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnExit event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnExit := TWinControlAccessHack(obj).OnExit;
               TWinControlAccessHack(obj).OnExit := OnExitStub;
               ExtraData.for_(obj).ExitFn := fn;
             end );
end;

procedure TdelQuery.OnExitStub(Sender: TObject);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  ExtraData.for_(Sender).ExitFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnExit <> nil then
      ExtraData.for_(Sender).OldOnExit(Sender);
end;

function TdelQuery.mousedown(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnMouseDown event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnMouseDown := TWinControlAccessHack(obj).OnMouseDown;
               TWinControlAccessHack(obj).OnMouseDown := OnMouseDownStub;
               ExtraData.for_(obj).MouseDownFn := fn;
             end );
end;

procedure TdelQuery.OnMouseDownStub(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.button := Button;
  event.shift := Shift;
  event.x := X;
  event.y := Y;
  ExtraData.for_(Sender).MouseDownFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseDown <> nil then
      ExtraData.for_(Sender).OldOnMouseDown(Sender, Button, Shift, X, Y);
end;

function TdelQuery.mouseup(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnMouseUp event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnMouseUp := TWinControlAccessHack(obj).OnMouseUp;
               TWinControlAccessHack(obj).OnMouseUp := OnMouseUpStub;
               ExtraData.for_(obj).MouseUpFn := fn;
             end );
end;

procedure TdelQuery.OnMouseUpStub(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.button := Button;
  event.shift := Shift;
  event.x := X;
  event.y := Y;
  ExtraData.for_(Sender).MouseUpFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseUp <> nil then
      ExtraData.for_(Sender).OldOnMouseUp(Sender, Button, Shift, X, Y);
end;

function TdelQuery.mousewheel(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnMouseWheel event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnMouseWheel := TWinControlAccessHack(obj).OnMouseWheel;
               TWinControlAccessHack(obj).OnMouseWheel := OnMouseWheelStub;
               ExtraData.for_(obj).MouseWheelFn := fn;
             end );
end;

procedure TdelQuery.OnMouseWheelStub(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.wheeldelta := WheelDelta;
  event.mousepos := MousePos;
  event.handled := Handled;
  ExtraData.for_(Sender).MouseWheelFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseWheel <> nil then
      ExtraData.for_(Sender).OldOnMouseWheel(Sender, Shift, WheelDelta, MousePos, Handled);
end;

function TdelQuery.mousewheeldown(fn: TdqEventHandler): TdelQuery;

   { fn will be triggered when the control gets OnMouseWheelDown event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnMouseWheelDown := TWinControlAccessHack(obj).OnMouseWheelDown;
               TWinControlAccessHack(obj).OnMouseWheelDown := OnMouseWheelDownStub;
               ExtraData.for_(obj).MouseWheelDownFn := fn;
             end );
end;

procedure TdelQuery.OnMouseWheelDownStub(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.mousepos := MousePos;
  event.handled := Handled;
  ExtraData.for_(Sender).MouseWheelDownFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseWheelDown <> nil then
      ExtraData.for_(Sender).OldOnMouseWheelDown(Sender, Shift, MousePos, Handled);
end;

function TdelQuery.mousewheelup(fn: TdqEventHandler): TdelQuery;

   { fn will be triggered when the control gets OnMouseWheelUp event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             begin
               ExtraData.for_(obj).OldOnMouseWheelUp := TWinControlAccessHack(obj).OnMouseWheelUp;
               TWinControlAccessHack(obj).OnMouseWheelUp := OnMouseWheelUpStub;
               ExtraData.for_(obj).MouseWheelUpFn := fn;
             end );
end;

procedure TdelQuery.OnMouseWheelUpStub(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.mousepos := MousePos;
  event.handled := Handled;
  ExtraData.for_(Sender).MouseWheelUpFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseWheelUp <> nil then
      ExtraData.for_(Sender).OldOnMouseWheelUp(Sender, Shift, MousePos, Handled);
end;

function TdelQuery.mousemove(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnMouseMove event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ExtraData.for_(obj).OldOnMouseMove := TWinControlAccessHack(obj).OnMouseMove;
              TWinControlAccessHack(obj).OnMouseMove := OnMouseMoveStub;
              ExtraData.for_(obj).MouseMoveFn := fn;
            end);
end;

procedure TdelQuery.OnMouseMoveStub(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.x := X;
  event.y := Y;
  ExtraData.for_(Sender).MouseMoveFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnMouseDown <> nil then
      ExtraData.for_(Sender).OldOnMouseMove(Sender, Shift, X, Y);
end;

procedure ExtraData.OnWindowProc(var Message: TMessage);

  function WithinElement: boolean;
  var
    c: TControl;
  begin
    c := TControl(Message.LParam);
    while c <> nil do
    begin
      if c.Parent = fSelf then EXIT(True);
      c := c.Parent;
    end;
    Result := False;
  end;

  function WithinBoundaries: boolean;
  var p: TPoint;
  begin
    p := fSelf.ScreenToClient(Mouse.CursorPos);
    Result := not (((p.X <= 0) or (p.X >= fSelf.Width)) or
                   ((p.Y <= 0) or (p.Y >= fSelf.Height)));
  end;

  procedure DoEnter;
  var event: dqevent;
  begin
    AlreadyInElement := True;
    event.Sender := fSelf as TControl;
    if assigned(MouseEnterFn) then
      MouseEnterFn(event);
  end;

  procedure DoLeave;
  var event: dqevent;
  begin
    event.Sender := fSelf as Tcontrol;
    if assigned(MouseEnterFn) then
      MouseLeaveFn(event);
    AlreadyInElement := False;
  end;

begin
  // todo: refactor this shit completely - there're some subtle bugs anyway
  // Message.LParam is 0 when the message is about fSelf, the message is about children if not.
  if Message.Msg = CM_MOUSEENTER then
  begin
    if ((Message.LParam = 0) or (WithinElement)) and not AlreadyInElement then
      DoEnter;
  end
  else
  if Message.Msg = CM_MOUSELEAVE then
  begin
    if (Message.LParam = 0) and not WithinBoundaries {xxx and not EatNextLeaveWithLparam0} then
      DoLeave;
  end;

  if assigned(fOldWindowProc) then
    fOldWindowProc(Message);
end;

function TdelQuery.mouseenter(fn: TdqEventHandler): TdelQuery;

  { xxx VCL OnMouseEnter/Leave is not enough }

begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             var data: ExtraData;
             begin
               data := ExtraData.for_(obj);
//               data.OldOnMouseEnter := TWinControlAccessHack(obj).OnMouseEnter;
//               TWinControlAccessHack(obj).OnMouseEnter := OnMouseEnterStub;
               data.MouseEnterFn := fn;

               { hook the wndproc for proper mouseenter/mouseleave dispatching }
//               if @data.fOldWindowProc <> @obj.WindowProc then
//               begin
//                 data.fOldWindowProc:= obj.WindowProc;
//                 obj.WindowProc := data.OnWindowProc;
//               end;
             end );
end;

//procedure TdelQuery.OnMouseEnterStub(Sender: TObject);
//var event: dqevent;
//begin
//  event.Sender := Sender as TControl;
//  ExtraData.for_(Sender).MouseEnterFn(event);
//  if not event.prevent then
//    if @ExtraData.for_(Sender).OldOnMouseEnter <> nil then
//      ExtraData.for_(Sender).OldOnMouseEnter(Sender);
//end;

function TdelQuery.mouseleave(fn: TdqEventHandler): TdelQuery;

  { xxx VCL OnMouseEnter/Leave is not enough }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            var data: ExtraData;
            begin
              data := ExtraData.for_(obj);
              //ExtraData.for_(obj).OldOnMouseLeave := TWinControlAccessHack(obj).OnMouseLeave;
              //TWinControlAccessHack(obj).OnMouseLeave := OnMouseLeaveStub;
              data.MouseLeaveFn := fn;

               { hook the wndproc for proper mouseenter/mouseleave dispatching }
               if @data.fOldWindowProc <> @obj.WindowProc then
               begin
                 data.fOldWindowProc:= obj.WindowProc;
                 obj.WindowProc := data.OnWindowProc;
               end;
            end);
end;

//procedure TdelQuery.OnMouseLeaveStub(Sender: TObject);
//var event: dqevent;
//begin
//  event.sender := Sender as TControl;
//  if not event.prevent then
//    if @ExtraData.for_(Sender).OldOnMouseLeave <> nil then
//      ExtraData.for_(Sender).OldOnMouseLeave(Sender);
//end;

function TdelQuery.mouseover(fn: TdqEventHandler): TdelQuery;
begin
  Result := Self;
  Self.each( procedure(obj: TControl)
             var data: ExtraData;
             begin
               data := ExtraData.for_(obj);
//               data.OldOnMouseEnter := TWinControlAccessHack(obj).OnMouseEnter;
//               TWinControlAccessHack(obj).OnMouseEnter := OnMouseEnterStub;
               data.MouseEnterFn := fn;

               { hook the wndproc for proper mouseenter/mouseleave dispatching }
//               if @data.fOldWindowProc <> @obj.WindowProc then
//               begin
//                 data.fOldWindowProc:= obj.WindowProc;
//                 obj.WindowProc := data.OnWindowProc;
//               end;
             end );
end;

function TdelQuery.mouseout(fn: TdqEventHandler): TdelQuery;
begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            var data: ExtraData;
            begin
              data := ExtraData.for_(obj);
              //ExtraData.for_(obj).OldOnMouseLeave := TWinControlAccessHack(obj).OnMouseLeave;
              //TWinControlAccessHack(obj).OnMouseLeave := OnMouseLeaveStub;
              data.MouseLeaveFn := fn;

               { hook the wndproc for proper mouseenter/mouseleave dispatching }
               if @data.fOldWindowProc <> @obj.WindowProc then
               begin
                 data.fOldWindowProc:= obj.WindowProc;
                 obj.WindowProc := data.OnWindowProc;
               end;
            end);
end;


function TdelQuery.keydown(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnKeyDown event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ExtraData.for_(obj).OldOnKeyDown := TWinControlAccessHack(obj).OnKeyDown;
              TWinControlAccessHack(obj).OnKeyDown := OnKeydownStub;
              ExtraData.for_(obj).KeyDownFn := fn;
            end);
end;

procedure TdelQuery.OnKeyDownStub(Sender: TObject; var Key: Word; Shift: TShiftState);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.key := Key;
  ExtraData.for_(Sender).KeyDownFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnKeyDown <> nil then
      ExtraData.for_(Sender).OldOnKeyDown(Sender, Key, Shift);
end;

function TdelQuery.keyup(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnKeyUp event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ExtraData.for_(obj).OldOnKeyUp := TWinControlAccessHack(obj).OnKeyUp;
              TWinControlAccessHack(obj).OnKeyUp := OnKeyUpStub;
              ExtraData.for_(obj).KeyUpFn := fn;
            end);
end;

procedure TdelQuery.OnKeyUpStub(Sender: TObject; var Key: Word; Shift: TShiftState);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.shift := Shift;
  event.key := Key;
  ExtraData.for_(Sender).KeyUpFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnKeyUp <> nil then
      ExtraData.for_(Sender).OldOnKeyUp(Sender, Key, Shift);
end;

function TdelQuery.keypress(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control gets OnKeyPress event. Check dqevent struct for
    extra event parameters. }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ExtraData.for_(obj).OldOnKeyPress := TWinControlAccessHack(obj).OnKeyPress;
              TWinControlAccessHack(obj).OnKeyPress := OnKeyPressStub;
              ExtraData.for_(obj).KeyPressFn := fn;
            end);
end;

procedure TdelQuery.OnKeyPressStub(Sender: TObject; var Key: Char);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.key := Word(Key);
  ExtraData.for_(Sender).KeyPressFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnKeyPress <> nil then
      ExtraData.for_(Sender).OldOnKeyPress(Sender, Key);
end;

function TdelQuery.oncanresize(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control is about to be resized. Check dqevent struct
    for extra event parameters. }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              //ExtraData.for_(obj).OldOnCanResize := TWinControlAccessHack(obj).OnCanResize;
              TWinControlAccessHack(obj).OnCanResize := OnCanResizeStub;
              ExtraData.for_(obj).CanResizeFn := fn;
            end);
end;

procedure TdelQuery.OnCanResizeStub(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  event.NewWidth := NewWidth;
  event.NewHeight := NewHeight;
  event.Resize := Resize;
  ExtraData.for_(Sender).CanResizeFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnCanResize <> nil then
      ExtraData.for_(Sender).OldOnCanResize(Sender, NewWidth, NewHeight, Resize);
end;

function TdelQuery.onresize(fn: TdqEventHandler): TdelQuery;

  { fn will be triggered when the control is resized }

begin
  Result := Self;
  Self.each(procedure(obj: TControl)
            begin
              ExtraData.for_(obj).OldOnResize := TWinControlAccessHack(obj).OnResize;
              TWinControlAccessHack(obj).OnResize := OnResizeStub;
              ExtraData.for_(obj).ResizeFn := fn;
            end);
end;

procedure TdelQuery.OnResizeStub(Sender: TObject);
var event: dqevent;
begin
  event.Sender := Sender as TControl;
  ExtraData.for_(Sender).ResizeFn(event);
  if not event.prevent then
    if @ExtraData.for_(Sender).OldOnResize <> nil then
      ExtraData.for_(Sender).OldOnResize(Sender);
end;

function TdelQuery.toggle(fn, fn2: TdqEventHandler): TdelQuery;

  { Toggle among fn and fn2 calls every other click. }

var i: integer;
begin
  Result := self;
  i := 0;
  self.click(procedure(event: dqevent)
             begin
               if i mod 2 = 0 then
                 fn(event)
               else
                 fn2(event);
               inc(i);
             end);
end;

function TdelQuery.animate(props: array of const;
                           duration: string;
                           easing: TdqEasingFunc = nil;
                           callback: TdqAnimationDoneCallback = nil): TdelQuery;

  { props: The parameters of the control that will be affected by the effect.

      Examples:
      ['height', '+=200'] -> increases the height property by 200px, relative to its current value.
      ['height', '+=200'] -> decreases the height property by 200px, relative to its current value.
      ['height', '200']   -> increases or decreases the height until it reaches 200px exactly.
      ['height', '-=200',
      'width', '+=100']    -> decrease control width by 200 px while incresing width by 100.

    duration: Total time that animation effect occurs. in milliseconds.
              pass 'slow' for 600ms; 'default' for 400ms; 'fast' for 200ms; (inherited from jQuery)
    easing: The easing effect function.
    callback: Called when the animation is completed.

  * Further ref. http://docs.jquery.com/Effects/animate#paramsdurationeasingcallback }

var
  props_: TStringArray;
begin
  Result := Self;
  props_ := StrArrayFromOpenArray(props);
  Self.each( procedure(obj: TControl)
             begin
               DoAnimate(obj, props_, duration, easing, callback);
             end );
end;

function TdelQuery.stop(clearQueue: boolean = False; gotoEnd: boolean = False): TdelQuery;

  { see http://docs.jquery.com/Effects/stop }

begin
  Result := Self;

  if clearQueue then
  begin
    Self.each( procedure(obj: TControl)
               begin
                 ExtraData.for_(obj).AnimationQueue.Clear;
               end );
  end;

  if gotoEnd then
    FxTimer.Tag := $BABE
  else
    FxTimer.Tag := $DEAD;

  log('stop '+IntToStr(FxTimer.Tag));
end;

{ -------------------------------------------------------------------------------------------------------------------- }
{ The selectors..

  dq(TButton, form1) -> selects all TButton instances in form1 (the immediate children).
  dq(TButton, form1, True) -> selects all TButton instances in form1 recursively.
  dq(button1) -> selects the given "button1" control only.
  dq([button1, button2, button3]) -> selects the controls given in the array.

  jQuery equivalent: $(...), jQuery(...) }

function dq(aClass: TClass; Parent: TWinControl; Greedy: boolean): TdelQuery;

  { Selects all instances of control class "aClass" in "Parent".
    Unless "Greedy" is True only direct children are selected. }

  procedure Recurse(aControl: TWinControl);
  var
    i: integer;
    control: TWinControl;
  begin // todo: refactor
    for i := 0 to aControl.ControlCount - 1 do
    begin
      if (aControl.Controls[i] is aClass) then
      begin
        control := (aControl.Controls[i] as aClass) as TWinControl;
        Result.AddControl(control);
      end;
      if (aControl.Controls[i] is TWinControl) and ((aControl.Controls[i] as TWinControl).ControlCount > 0) then
        Recurse(aControl.Controls[i] as TWinControl);
    end;
  end;

var
  control: TControl;
  i: integer;
begin
  Result := TdelQuery.Create;
  if not Greedy then
    for i := 0 to Parent.ControlCount - 1 do
    begin
      if not(Parent.Controls[i] is aClass) then CONTINUE;
      control := (Parent.Controls[i] as aClass) as TControl;
      Result.AddControl(control);
    end
  else
    Recurse(Parent);
end;

function dq(aControl: TControl): TdelQuery;

  { Select given control }

begin
  assert(aControl <> nil);
  Result := dq([aControl]);
end;

function dq(Controls: array of TControl): TdelQuery; overload;

  { Select given controls }

var
  c: TControl;
begin
  Result := TdelQuery.Create;
  for c in Controls do
  begin
    assert(c <> nil);
    Result.AddControl(c);
    ExtraData.for_(c).fDQ := Result;
  end;
end;

{ TAnimationData }

destructor TAnimationData.Destroy;
begin
  inherited;
end;

initialization
  ExtraDataRegistry := TDictionary<TObject, ExtraData>.Create;
finalization
  FreeAndNil(ExtraDataRegistry);
end.