src/trackergrid.pas39.5 KB · ObjectPascal
Raw
   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
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
unit TrackerGrid;

{$mode delphi}

interface

uses
  Classes, SysUtils, Controls, Graphics, Constants, LCLType, math, LCLIntf,
  LMessages, HugeDatatypes, ClipboardUtils, gdeque, gstack, utils, effecteditor,
  Keymap, LazLoggerBase, hUGESettings;

const
  UNDO_STACK_SIZE = 100;

type
  TPatternGrid = array of PPattern;

  { TSavedPattern }

  TSavedPattern = record
    PatternNumber: Integer;
    Pattern: TPattern;
  end;

  TSavedPatternSet = array of TSavedPattern;
  TUndoRedoAction = record
    Before, After: TSavedPatternSet;
  end;
  TUndoDeque = TDeque<TUndoRedoAction>;
  TRedoStack = TStack<TUndoRedoAction>;

  { TSelectionEnumerator }

  TSelectionEnumerator = record
  private
    function GetCurrent: TSelectionRow;
  public
    Grid: TPatternGrid;
    Row: Integer;
    Cursor, Other: TSelectionPos;

    constructor Create(Grid: TPatternGrid; Cursor, Other: TSelectionPos);
    function MoveNext: Boolean;
    property Current: TSelectionRow read GetCurrent;
    function GetEnumerator: TSelectionEnumerator;
  end;

  { TTrackerGrid }

  TTrackerGrid = class(TCustomControl)
    procedure Paint; override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure DblClick; override;
    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
  private
    function GetSelection: TSelection;
    procedure PerformPaste(Paste: TSelection; Mix: Boolean = False); overload;
    procedure PerformPaste(Paste: TSelection; Where: TSelectionPos; Mix: Boolean = False); overload;
    procedure PerformCopy;
    procedure DoPaste(var Msg: TLMessage); message LM_PASTE;
    procedure DoCopy(var Msg: TLMessage); message LM_COPY;
    procedure DoCut(var Msg: TLMessage); message LM_CUT;
    procedure BeginUndoAction;
    procedure EndUndoAction;
    procedure RevertUndoAction;

    procedure RenderSelectedArea;
    procedure ClampCursors;
    procedure EnsureCursorVisible;
    procedure NormalizeCursors;

    procedure InputNote(Key: Word);
    procedure InputInstrument(Key: Word);
    procedure InputVolume(Key: Word); virtual;
    procedure InputEffectCode(Key: Word);
    procedure InputEffectParams(Key: Word);

    procedure RenderRow(Row: Integer);
    procedure RenderCell(const Cell: TCell); virtual;

    procedure SetHighlightedRow(Row: Integer);
    procedure SetSelectionGridRect(R: TRect);
    function GetSelectionGridRect: TRect;
    function GetEffectColor(EffectCode: Integer): TColor;
    function SelectionsToRect(S1, S2: TSelectionPos): TRect;
    function SelectionToRect(Selection: TSelectionPos): TRect;
    function MousePosToSelection(X, Y: Integer): TSelectionPos;
    function KeycodeToHexNumber(Key: Word; var Num: Nibble): Boolean; overload;
    function KeycodeToHexNumber(Key: Word; var Num: Integer): Boolean; overload;

    procedure ChangeFontSize;
  private
    PatternMap: TPatternMap;
    Patterns: TPatternGrid;
    PatternNumbers: array of Integer;

    CharHeight: Integer;
    CharWidth: Integer;

    MouseButtonDown: Boolean;
    Selecting: Boolean;
    DraggingSelection: Boolean;
    MouseMoveHappened: Boolean;
    ShiftClicking: Boolean;
    DragSelCursor, DragSelOther, ShiftClickOrigin: TSelectionPos;
    DragOffsetY: Integer;

    NestedUndoCount: Integer;
    CurrentUndoAction: TUndoRedoAction;
    Performed: TUndoDeque;
    Recall: TRedoStack;

    LastFxParam: array [0..15] of Byte;

    FHighlightedRow: Integer;
    FFontSize: Integer;
    procedure SetFontSize(AValue: Integer);
  public
    Cursor, Other: TSelectionPos;
    ColumnWidth, RowHeight: Integer;
    NumColumns, NumRows: Integer;

    SelectedInstrument, SelectedOctave, Step: Integer;

    OnCursorOutOfBounds: procedure of object;
    OnDoubleClickedInstrument: procedure of object;

    property HighlightedRow: Integer read FHighlightedRow write SetHighlightedRow;
    property SelectionGridRect: TRect read GetSelectionGridRect write SetSelectionGridRect;
    property FontSize: Integer read FFontSize write SetFontSize;
    procedure LoadPattern(Idx: Integer; PatternNumber: Integer);

    function GetAt(SelectionPos: TSelectionPos): Integer;
    procedure SetAt(SelectionPos: TSelectionPos; Value: Integer);
    procedure IncrementAt(SelectionPos: TSelectionPos; Value: Integer); virtual;
    procedure ClearAt(SelectionPos: TSelectionPos);

    procedure InsertRowInPatternAtCursor(Pattern: Integer);
    procedure InsertRowInAllAtCursor;
    procedure DeleteRowInPatternAtCursor(Pattern: Integer);
    procedure DeleteRowInAllAtCursor;

    procedure InputNoteValue(Note: Integer);

    procedure SelectAll;
    procedure SelectColumn;
    procedure EraseSelection;
    procedure DoUndo;
    procedure DoRedo;
    procedure DoRepeatPaste;
    procedure DoMixPaste;
    procedure TransposeSelection(Semitones: Integer);
    procedure IncrementSelection(Note, Instrument, Volume, EffectCode, EffectParam: Integer);
    procedure InterpolateSelection;
    procedure ChangeSelectionInstrument;
    procedure OpenEffectEditor;

    constructor Create(
      AOwner: TComponent;
      Parent: TWinControl;
      PatternMap: TPatternMap;
      NumColumns: Integer;
      NumRows: Integer = 64); reintroduce;
    destructor Destroy; override;
  end;

  { TTableGrid }

  TTableGrid = class(TTrackerGrid)
    procedure RenderCell(const Cell: TCell); override;
    procedure InputVolume(Key: Word); override;
    procedure IncrementAt(SelectionPos: TSelectionPos; Value: Integer); override;
  end;

var
  clNote: TColor = TColor($7F4A00);
  clInstrument: TColor = TColor($7F7F00);

  clFxMisc: TColor = TColor($3F3F7C);
  clFxPitch: TColor = TColor($006262);
  clFxVolume: TColor = TColor($007F26);
  clFxPan: TColor = TColor($7F7F00);
  clFxSong: TColor = TColor($00007F);

  clTblJump: TColor = TColor($72004E);

  clBackground: TColor = TColor($D0DBE1);
  clHighlighted: TColor = TColor($7A99A9);
  clSelected: TColor = TColor($9EB4C0);

  clLineFour: TColor = TColor($C3D1D8);
  clLineSixteen: TColor = TColor($B5C5CE);

  clDots: TColor = clGray;
  clDividers: TColor = TColor($ABB7BC);

implementation

uses Forms;

{ TTableGrid }

procedure TTableGrid.RenderCell(const Cell: TCell);
begin
  with Canvas do begin
    Font.Color := clNote;

    if (Cell.Note = NO_NOTE) then begin
      Font.Color := clDots;
      TextOut(PenPos.X, PenPos.Y, '...')
    end
    else if Cell.Note >= MIDDLE_NOTE then
      TextOut(PenPos.X, PenPos.Y, '+'+FormatFloat('00', Cell.Note - MIDDLE_NOTE))
    else if Cell.Note < MIDDLE_NOTE then
      TextOut(PenPos.X, PenPos.Y, '-'+FormatFloat('00', MIDDLE_NOTE - Cell.Note));

    TextOut(PenPos.X, PenPos.Y, ' ');

    // Instrument column empty
    Font.Color := clDots;
    TextOut(PenPos.X, PenPos.Y, '..');

    if Cell.Volume <> 0 then begin
      Font.Color := clTblJump;
      if TrackerSettings.DisplayRowNumbersAsHex then
        TextOut(PenPos.X, PenPos.Y, 'J'+IntToHex(Cell.Volume, 2))
      else
        TextOut(PenPos.X, PenPos.Y, 'J'+FormatFloat('00', Cell.Volume));
    end
    else begin
      Font.Color := clDots;
      TextOut(PenPos.X, PenPos.Y, '...');
    end;

    if (Cell.EffectCode <> 0) or (Cell.EffectParams.Value <> 0) then begin
      Font.Color := GetEffectColor(Cell.EffectCode);
      TextOut(
        PenPos.X,
        PenPos.Y,
        IntToHex(Cell.EffectCode, 1)
          + IntToHex(Cell.EffectParams.Param1, 1)
          + IntToHex(Cell.EffectParams.Param2, 1)
      );
    end
    else begin
      Font.Color := clDots;
      TextOut(PenPos.X, PenPos.Y, '...');
    end;

    TextOut(PenPos.X, PenPos.Y, ' ');
  end;
end;

procedure TTableGrid.InputVolume(Key: Word);
var
  Temp: Nibble;
begin
  BeginUndoAction;
  with Patterns[Cursor.X]^[Cursor.Y] do begin
    if Key = VK_DELETE then Volume := 0
    else if KeycodeToHexNumber(Key, Temp) then begin
      if TrackerSettings.DisplayRowNumbersAsHex then begin
        Volume := ((Volume mod 16) * 16) + Temp;
        if Volume > 99 then Volume := Temp;
      end
      else if InRange(Temp, 0, 9) then
        Volume := ((Volume mod 10) * 10) + Temp;
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTableGrid.IncrementAt(SelectionPos: TSelectionPos; Value: Integer);
begin
  with Patterns[SelectionPos.X]^[SelectionPos.Y] do
    if (Note = NO_NOTE) and (SelectionPos.SelectedPart = cpNote) then
      Note := MIDDLE_NOTE;

  inherited;
end;

{ TSelectionEnumerator }

constructor TSelectionEnumerator.Create(Grid: TPatternGrid; Cursor,
  Other: TSelectionPos);
begin
  Self.Grid := Grid;
  Self.Row := Cursor.Y-1;
  Self.Cursor := Cursor;
  Self.Other := Other;
end;

function TSelectionEnumerator.GetCurrent: TSelectionRow;
var
  X, I: Integer;
begin
  // Very ugly function
  SetLength(Result, (Other.X-Cursor.X)+1);

  Result[0].Cell := Grid[Cursor.X]^[Row];
  if Cursor.X <> Other.X then
    Result[0].Parts := [Cursor.SelectedPart..High(TCellPart)]
  else
    Result[0].Parts := [Cursor.SelectedPart..Other.SelectedPart];

  I := 1;
  for X := Cursor.X+1 to Other.X - 1 do begin
    Result[I].Cell := Grid[X]^[Row];
    Result[I].Parts := [Low(TCellPart)..High(TCellPart)];
    Inc(I);
  end;

  if Cursor.X <> Other.X then begin
    Result[High(Result)].Cell := Grid[Other.X]^[Row];
    Result[High(Result)].Parts := [Low(TCellPart)..Other.SelectedPart];
  end;
end;

function TSelectionEnumerator.MoveNext: Boolean;
begin
  Result := True;
  Inc(Row);
  if Row > Other.Y then Result := False;
end;

function TSelectionEnumerator.GetEnumerator: TSelectionEnumerator;
begin
  Result := Self;
end;

{ TTrackerGrid }

constructor TTrackerGrid.Create(
  AOwner: TComponent;
  Parent: TWinControl;
  PatternMap: TPatternMap;
  NumColumns: Integer;
  NumRows: Integer);
var
  I: Integer;
begin
  inherited Create(AOwner);

  // The LCL only populates the screen's font list once. Since we're
  // dynamically adding fonts at startup, we need to refresh this list.

  Screen.Fonts.Clear;

  FFontSize := 12;

  Self.PatternMap := PatternMap;
  Self.NumColumns := NumColumns;
  Self.NumRows := NumRows;

  SetLength(Patterns, NumColumns);
  SetLength(PatternNumbers, NumColumns);

  NestedUndoCount := 0;
  Performed := TUndoDeque.Create;
  Recall := TRedoStack.Create;

  for I := Low(LastFxParam) to High(LastFxParam) do
    LastFxParam[I] := Byte(0);

  DoubleBuffered := True;
  ControlStyle := ControlStyle + [csCaptureMouse, csClickEvents, csDoubleClicks];
  Self.Parent := Parent;

  ChangeFontSize;

  SelectedInstrument := 0;
  SelectedOctave := 0;
  Step := 0;
end;

destructor TTrackerGrid.Destroy;
var
  Q: TUndoRedoAction;
begin
  // There's an FPC version which includes a bugged destructor for TDeque, in
  // which it will segfault when freeing an empty TDeque. To avoid this, we put
  // an element in it first. TODO: Remove this ridiculous hack once the fix gets
  // released to the stable channel.
  Q.After := nil;
  Q.Before := nil;
  Performed.PushFront(Q);

  Performed.Free;
  Recall.Free;

  inherited;
end;

procedure TTrackerGrid.Paint;
var
  I: Integer;
  R: TRect;
begin
  inherited Paint;

  with Canvas do begin
    Brush.Color := clBackground;
    Clear;

    for I := 0 to NumRows-1 do begin
      if (I mod 4) = 0 then
        Brush.Color := clLineFour;
      if (I mod 16) = 0 then
        Brush.Color := clLineSixteen;
      if I = Cursor.Y then
        Brush.Color := clSelected;
      if I = FHighlightedRow then
        Brush.Color := clHighlighted;

      FillRect(0, I*RowHeight, Width, (I+1)*RowHeight);
      MoveTo(0, I*RowHeight);
      RenderRow(I);
    end;
  end;

  // Draw borders between columns
  Canvas.Pen.Color := clDividers;
  Canvas.Pen.Width := 2;

  for I := 0 to NumColumns do
    Canvas.Line((ColumnWidth*I) - 1, 0, (ColumnWidth*I) - 1, Height);

  if DraggingSelection then
    Canvas.DrawFocusRect(SelectionsToRect(DragSelCursor, DragSelOther));
  RenderSelectedArea;
end;

procedure TTrackerGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  Clicked: TSelectionPos;
begin
  inherited MouseDown(Button, Shift, X, Y);

  if (Button = mbRight) and (Cursor <> Other) then Exit;

  if (Button = mbLeft) and not (ssShift in Shift) then
    MouseButtonDown := True;

  if CanFocus then SetFocus;

  Clicked := MousePosToSelection(X, Y);

  if ssShift in Shift then begin
    if not ShiftClicking then begin
      ShiftClickOrigin := Cursor;
      ShiftClicking :=  True;
    end;
    Cursor := ShiftClickOrigin;
    Other := Clicked
  end
  else begin
    if not SelectionsToRect(Cursor, Other).IntersectsWith(SelectionToRect(Clicked)) then begin
      Cursor := Clicked;
      Other := Cursor;
      Selecting := False;
    end
  end;

  MouseMoveHappened := False;

  NormalizeCursors;
  Invalidate;
end;

procedure TTrackerGrid.MouseMove(Shift: TShiftState; X, Y: Integer);
var
  Click, Drag: TSelectionPos;
  SelectionRect: TRect;
begin
  inherited MouseMove(Shift, X, Y);

  Click := MousePosToSelection(X, Y);
  if  MouseButtonDown
  and ((Cursor <> Other) or (Cursor.Y <> Other.Y)) // <> is overridden
  and (not Selecting)
  and (not MouseMoveHappened)
  and SelectionsToRect(Cursor, Other).IntersectsWith(SelectionToRect(Click)) then begin
    DraggingSelection := True;
    SelectionRect := SelectionsToRect(Cursor, Other);
    DragOffsetY := Y - SelectionRect.Top;
  end;

  if MouseButtonDown then begin
    if DraggingSelection then begin
      Drag := MousePosToSelection(X, Y - DragOffsetY);
      DragSelCursor := Cursor;
      DragSelOther := Other;

      DragSelCursor.X := Drag.X;
      DragSelCursor.Y := Drag.Y;

      DragSelOther.X := DragSelCursor.X + (Other.X - Cursor.X);
      DragSelOther.Y := DragSelCursor.Y + (Other.Y - Cursor.Y);

      Invalidate;
    end
    else begin
      Selecting := True;
      Other := Click;

      ClampCursors;
      Invalidate;
    end;
  end;

  MouseMoveHappened := True;
end;

procedure TTrackerGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  Selection: TSelection;
begin
  inherited MouseUp(Button, Shift, X, Y);

  if (not Selecting) and (not MouseMoveHappened) and (not (ssShift in Shift)) then begin
    Cursor := MousePosToSelection(X, Y);
    Other := Cursor;
  end;

  Selecting := False;
  MouseMoveHappened := False;
  MouseButtonDown := False;

  if DraggingSelection then begin
    BeginUndoAction;

    Selection := GetSelection;
    EraseSelection;
    PerformPaste(Selection, DragSelCursor);
    Cursor := DragSelCursor;
    Other := DragSelOther;

    DraggingSelection := False;

    EndUndoAction;
  end;

  NormalizeCursors;
  Invalidate;
end;

procedure TTrackerGrid.DblClick;
begin
  if (Cursor.SelectedPart = cpInstrument) and Assigned(OnDoubleClickedInstrument) then
    OnDoubleClickedInstrument
  else
    OpenEffectEditor;

  NormalizeCursors;
  MouseButtonDown := False;
  Invalidate;
end;

procedure TTrackerGrid.KeyDown(var Key: Word; Shift: TShiftState);
begin
  inherited KeyDown(Key, Shift);

  if Key in [VK_CONTROL, VK_SHIFT, VK_DELETE] then Exit;

  case Key of
    VK_UP: Dec(Cursor.Y);
    VK_DOWN: Inc(Cursor.Y);
    VK_PRIOR: Dec(Cursor.Y, 16);
    VK_NEXT: Inc(Cursor.Y, 16);
    VK_LEFT: DecSelectionPos(Cursor);
    VK_RIGHT: IncSelectionPos(Cursor);
    VK_HOME: Cursor.Y := 0;
    VK_END: Cursor.Y := NumRows-1;
    VK_TAB: begin
      if ssShift in Shift then begin
        Dec(Cursor.X);
        Exclude(Shift, ssShift)
      end
      else
        Inc(Cursor.X);

      if Cursor.X > (NumColumns-1) then
        Cursor.X := 0;
      if Cursor.X < 0 then
        Cursor.X := (NumColumns-1);

      Key := 0;
    end
    else
      if (not (ssCtrl in Shift)) and (not (ssShift in Shift)) then
        case Cursor.SelectedPart of
          cpNote:         InputNote(Key);
          cpInstrument:   InputInstrument(Key);
          cpVolume:       InputVolume(Key);
          cpEffectCode:   InputEffectCode(Key);
          cpEffectParams: InputEffectParams(Key);
        end;
  end;

  if (Cursor.Y > NumRows-1) or (Cursor.Y < 0) then
    if Assigned(OnCursorOutOfBounds) then OnCursorOutOfBounds;

  if Shift = [] then
    Other := Cursor;

  ClampCursors;
  EnsureCursorVisible;
  Invalidate;
end;

procedure TTrackerGrid.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited KeyUp(Key, Shift);

  if key = VK_SHIFT then
    ShiftClicking := False;
end;

function TTrackerGrid.GetSelection: TSelection;
var
  R: Integer;
  Rect: TRect;
  SelRow: TSelectionRow;
begin
  NormalizeCursors;

  Rect := SelectionGridRect;
  SetLength(Result, Rect.Height+1);
  R := 0;
  for SelRow in TSelectionEnumerator.Create(Patterns, Cursor, Other) do begin
    Result[R] := SelRow;
    Inc(R)
  end;
end;

procedure TTrackerGrid.PerformPaste(Paste: TSelection; Where: TSelectionPos; Mix: Boolean = False);
  procedure OverlayCell(var Cell1: TCell; const Cell2: TSelectedCell);
  begin
    if cpNote in Cell2.Parts then
      if (not Mix) or (Cell2.Cell.Note <> NO_NOTE) then
        Cell1.Note := Cell2.Cell.Note;

    if cpInstrument in Cell2.Parts then
      if (not Mix) or (Cell2.Cell.Instrument <> 0) then
        Cell1.Instrument := Cell2.Cell.Instrument;

     if cpVolume in Cell2.Parts then
        if (not Mix) or (Cell2.Cell.Volume <> 0) then
           Cell1.Volume := Cell2.Cell.Volume;

    if cpEffectCode in Cell2.Parts then
      if (not Mix) or (Cell2.Cell.EffectCode <> 0) then
        Cell1.EffectCode := Cell2.Cell.EffectCode;

    if cpEffectParams in Cell2.Parts then
      if (not Mix) or (Cell2.Cell.EffectParams.Value <> 0) then
        Cell1.EffectParams.Value := Cell2.Cell.EffectParams.Value;
  end;
var
  X, Y: Integer;
begin
  try
    for Y := 0 to High(Paste) do begin
      if not InRange(Where.Y+Y, 0, NumRows-1) then Continue;
      for X := 0 to High(Paste[Y]) do begin
        if not InRange(Where.X+X, Low(Patterns), High(Patterns)) then Continue;
        OverlayCell(Patterns[Where.X + X]^[Where.Y + Y], Paste[Y, X]);
      end;
    end;
    Other := Where;
    Cursor.X := Other.X + X;
    Cursor.Y := Other.Y + Y;
    Other.SelectedPart := Low(TCellPart);
    Cursor.SelectedPart := High(TCellPart);
  except
    on E: Exception do
      DebugLn('[DEBUG] Clipboard did not contain valid note data!');
  end;
end;

procedure TTrackerGrid.PerformPaste(Paste: TSelection; Mix: Boolean = False);
begin
  PerformPaste(Paste, Cursor, Mix);
end;

procedure TTrackerGrid.PerformCopy;
begin

end;

procedure TTrackerGrid.DoRepeatPaste;
var
  Selection: TSelection;
  I: Integer;
begin
  BeginUndoAction;

  try
    Selection := GetPastedCells;
    I := Cursor.Y;
    while I < NumRows do begin
      Cursor.Y := I;
      PerformPaste(Selection);
      Inc(I, High(Selection)+1);
    end;
  except
    on E: EClipboardFormatException do begin
      DebugLn('[WARNING] ', E.Message);
      RevertUndoAction;
      Exit
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.DoMixPaste;
begin
  BeginUndoAction;

  try
    PerformPaste(GetPastedCells, True);
  except
    on E: EClipboardFormatException do begin
      DebugLn('[WARNING] ', E.Message);
      RevertUndoAction;
      Exit
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.DoPaste(var Msg: TLMessage);
begin
  BeginUndoAction;

  try
    PerformPaste(GetPastedCells);
  except
    on E: EClipboardFormatException do begin
      DebugLn('[WARNING] ', E.Message);
      RevertUndoAction;
      Exit
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.DoCopy(var Msg: TLMessage);
begin
  CopyCells(GetSelection);
end;

procedure TTrackerGrid.DoCut(var Msg: TLMessage);
begin
  DoCopy(Msg);
  EraseSelection;
end;

procedure TTrackerGrid.BeginUndoAction;
var
  I: Integer;
begin
  if NestedUndoCount = 0 then begin
    // Save the "before" to our current undo action, so that EndUndoAction
    // can save the "after" and commit it to the Performed stack.
    CurrentUndoAction := Default(TUndoRedoAction);
    for I := Low(Patterns) to High(Patterns) do begin
      SetLength(CurrentUndoAction.Before, NumColumns);
      SetLength(CurrentUndoAction.After, NumColumns);
      with CurrentUndoAction.Before[I] do begin
        Pattern := Patterns[I]^;
        PatternNumber := PatternNumbers[I];
      end;
    end;
  end;

  Inc(NestedUndoCount);
end;

procedure TTrackerGrid.EndUndoAction;
var
  I: Integer;
begin
  if NestedUndoCount = 1 then begin
    // First, clear out the recall stack
    while not Recall.IsEmpty do
      Recall.Pop;

    // Save the "after" to our current undo action
    for I := Low(Patterns) to High(Patterns) do
      with CurrentUndoAction.After[I] do begin
        Pattern := Patterns[I]^;
        PatternNumber := PatternNumbers[I];
      end;

    // Commit the action to the Performed stack
    Performed.PushFront(CurrentUndoAction);

    // Keep the stack size, at maximum, UNDO_STACK_SIZE
    while Performed.Size > UNDO_STACK_SIZE do
      Performed.PopBack;
  end;

  Dec(NestedUndoCount);
end;

procedure TTrackerGrid.RevertUndoAction;
begin
  // Don't save the undo action, just decrement the nested undo count.
  Dec(NestedUndoCount);
end;

procedure TTrackerGrid.DoUndo;
var
  State: TUndoRedoAction;
  I: Integer;
begin
  if Performed.IsEmpty then Exit;

  State := Performed.Front;
  Performed.PopFront;

  Recall.Push(State);

  for I := Low(State.Before) to High(State.Before) do begin
    LoadPattern(I, State.Before[I].PatternNumber);
    Patterns[I]^ := State.Before[I].Pattern;
  end;

  Invalidate;
end;

procedure TTrackerGrid.DoRedo;
var
  State: TUndoRedoAction;
  I: Integer;
begin
  if Recall.IsEmpty then Exit;

  State := Recall.Top;
  Recall.Pop;

  Performed.PushFront(State);

  for I := Low(State.After) to High(State.After) do begin
    LoadPattern(I, State.After[I].PatternNumber);
    Patterns[I]^ := State.After[I].Pattern;
  end;

  Invalidate;
end;

procedure TTrackerGrid.RenderSelectedArea;
begin
    Canvas.Pen.Width := 1;
    Canvas.Pen.Color := clBlack;

    // TODO: Seems like the Cocoa backend doesn't support pmXOR.
    // For now, just don't set it, and draw a black box around the thing.
    {$ifndef DARWIN}
    Canvas.Brush.Color := clWhite;
    Canvas.Pen.Mode := pmXOR;
    {$endif}

    Canvas.Rectangle(SelectionsToRect(Cursor, Other));
    Canvas.Pen.Mode := pmCopy;
end;

procedure TTrackerGrid.ClampCursors;
begin
  if Cursor.X < 0 then
    Cursor.SelectedPart := Low(TCellPart);
  if Cursor.X > (NumColumns-1) then
    Cursor.SelectedPart := High(TCellPart);

  if Other.X < 0 then
    Other.SelectedPart := Low(TCellPart);
  if Other.X > (NumColumns-1) then
    Other.SelectedPart := High(TCellPart);

  Cursor.Y := EnsureRange(Cursor.Y, 0, NumRows-1);
  Cursor.X := EnsureRange(Cursor.X, Low(TPatternGrid), (NumColumns-1));
  Other.Y := EnsureRange(Other.Y, 0, NumRows-1);
  Other.X := EnsureRange(Other.X, Low(TPatternGrid), (NumColumns-1));
end;

procedure TTrackerGrid.EnsureCursorVisible;
var
  SB: TScrollBox;
  CursorRect, SelRect: TRect;
  VLeft, VRight, VTop, VBottom: Integer;
  CLeft, CRight, CTop, CBottom: Integer;
  PadLeft, PadRight, PadTop, PadBottom, I: Integer;
  P, ClientW, ClientH: Integer;
  Ctrl: TControl;
begin
  if not (Parent is TScrollBox) then Exit;
  SB := TScrollBox(Parent);

  PadLeft := 0; PadRight := 0; PadTop := 0; PadBottom := 0;
  for I := 0 to SB.ControlCount - 1 do begin
    Ctrl := SB.Controls[I];
    if Ctrl = Self then Continue;
    case Ctrl.Align of
      alLeft:   Inc(PadLeft, Ctrl.Width);
      alRight:  Inc(PadRight, Ctrl.Width);
      alTop:    Inc(PadTop, Ctrl.Height);
      alBottom: Inc(PadBottom, Ctrl.Height);
    end;
  end;

  CursorRect := SelectionToRect(Cursor);
  SelRect := SelectionsToRect(Cursor, Other);

  // Convert grid-local coords to scrollbox virtual coords by adding Self.Left/Top.
  VLeft := SelRect.Left + Self.Left;
  VRight := SelRect.Right + Self.Left;
  VTop := SelRect.Top + Self.Top;
  VBottom := SelRect.Bottom + Self.Top;
  CLeft := CursorRect.Left + Self.Left;
  CRight := CursorRect.Right + Self.Left;
  CTop := CursorRect.Top + Self.Top;
  CBottom := CursorRect.Bottom + Self.Top;

  ClientH := SB.ClientHeight;
  if VBottom - VTop > ClientH - PadTop - PadBottom then begin
    VTop := CTop;
    VBottom := CBottom;
  end;
  P := SB.VertScrollBar.Position;
  if VTop < P + PadTop then
    SB.VertScrollBar.Position := VTop - PadTop
  else if VBottom > P + ClientH - PadBottom then
    SB.VertScrollBar.Position := VBottom - ClientH + PadBottom;

  ClientW := SB.ClientWidth;
  if VRight - VLeft > ClientW - PadLeft - PadRight then begin
    VLeft := CLeft;
    VRight := CRight;
  end;
  P := SB.HorzScrollBar.Position;
  if VLeft < P + PadLeft then
    SB.HorzScrollBar.Position := VLeft - PadLeft
  else if VRight > P + ClientW - PadRight then
    SB.HorzScrollBar.Position := VRight - ClientW + PadRight;
end;

procedure TTrackerGrid.NormalizeCursors;
var
  TempI: Integer;
  TempS: TCellPart;
begin
  ClampCursors;

  // Normalize the cursor positions such that cursor is always in the top left
  if (Cursor > Other) then begin
    TempI := Other.X;
    Other.X := Cursor.X;
    Cursor.X := TempI;

    TempS := Other.SelectedPart;
    Other.SelectedPart := Cursor.SelectedPart;
    Cursor.SelectedPart := TempS;
  end;
  if (Cursor.Y > Other.Y) then begin
    TempI := Other.Y;
    Other.Y := Cursor.Y;
    Cursor.Y := TempI;
  end;
end;

procedure TTrackerGrid.TransposeSelection(Semitones: Integer);
begin
  IncrementSelection(Semitones, 0, 0, 0, 0);
end;

procedure TTrackerGrid.IncrementSelection(Note, Instrument, Volume, EffectCode,
  EffectParam: Integer);
var
  Pos: TSelectionPos;
begin
  BeginUndoAction;

  NormalizeCursors;

  Pos := Cursor;

  while Pos.Y <= Other.Y do begin
    while Pos <= Other do begin
      case Pos.SelectedPart of
        cpNote: IncrementAt(Pos, Note);
        cpInstrument: IncrementAt(Pos, Instrument);
        cpVolume: IncrementAt(Pos, Volume);
        cpEffectCode: IncrementAt(Pos, EffectCode);
        cpEffectParams: IncrementAt(Pos, EffectParam);
      end;
      IncSelectionPos(Pos);
    end;
    Inc(Pos.Y);
    Pos.X := Cursor.X;
    Pos.SelectedPart := Cursor.SelectedPart;
  end;

  Invalidate;
  EndUndoAction
end;

procedure TTrackerGrid.InterpolateSelection;
var
  S, E, Len: Integer;
  Pos: TSelectionPos;
  StartCell: TCell;
begin
  BeginUndoAction;

  NormalizeCursors;

  if Cursor.Y = Other.Y then Exit;

  if Cursor.SelectedPart = cpEffectCode then begin
    Cursor.SelectedPart := cpEffectParams;
    Other.SelectedPart := cpEffectParams;
  end;

  StartCell := Patterns[Cursor.x]^[Cursor.Y];

  S := GetAt(Cursor);
  E := GetAt(Other);
  Len := Other.Y - Cursor.Y;

  Pos := Cursor;
  while Pos.Y <= Other.Y do begin
    SetAt(Pos, Trunc(Lerp(S, E, ((Pos.Y - Cursor.Y) / Len))));

    if Pos.SelectedPart = cpEffectParams then
      Patterns[Pos.X]^[Pos.Y].EffectCode := StartCell.EffectCode;

    Inc(Pos.Y)
  end;

  Invalidate;
  EndUndoAction
end;

procedure TTrackerGrid.ChangeSelectionInstrument;
var
  Pos: TSelectionPos;
  R: Integer;
begin
  BeginUndoAction;

  NormalizeCursors;

  for R := Cursor.Y to Other.Y do begin
    Pos := Cursor;
    Pos.Y := R;
    while Pos <= Other do begin
      with Patterns[Pos.X]^[Pos.Y] do
        if Note <> NO_NOTE then
          Instrument := SelectedInstrument;

      IncSelectionPos(Pos);
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.OpenEffectEditor;
begin
  BeginUndoAction;

  frmEffectEditor.Cell := @Patterns[Cursor.X]^[Cursor.Y];
  frmEffectEditor.ShowModal;

  Invalidate;
  EndUndoAction
end;

procedure TTrackerGrid.EraseSelection;
var
  X: TSelectionPos;
  R: Integer;
begin
  BeginUndoAction;

  NormalizeCursors;

  for R := Cursor.Y to Other.Y do begin
    X := Cursor;
    X.Y := R;
    while X <= Other do begin
      ClearAt(X);
      IncSelectionPos(X);
    end;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.InputNoteValue(Note: Integer);
var
  Cell: PCell;
begin
  if (Note < LOWEST_NOTE) or (Note > HIGHEST_NOTE) then Exit;
  if Cursor.SelectedPart <> cpNote then Exit;

  BeginUndoAction;
  Cell := @Patterns[Cursor.X]^[Cursor.Y];
  Cell^.Note := Note;
  if SelectedInstrument <> 0 then
    Cell^.Instrument := SelectedInstrument;

  Inc(Cursor.Y, Step);
  ClampCursors;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.InputNote(Key: Word);
var
  Temp: Integer;
begin
  if Keybindings.TryGetData(Key, Temp) then
    InputNoteValue(Min(HIGHEST_NOTE, Temp + (SelectedOctave * 12)));
end;

procedure TTrackerGrid.InputInstrument(Key: Word);
var
  Temp: Nibble;
begin
  BeginUndoAction;
  with Patterns[Cursor.X]^[Cursor.Y] do begin
    if Key = VK_DELETE then Instrument := 0
    else if KeycodeToHexNumber(Key, Temp) and InRange(Temp, 0, 9) then
      Instrument := ((Instrument mod 10) * 10) + Temp;
  end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.InputVolume(Key: Word);
begin

end;

procedure TTrackerGrid.InputEffectCode(Key: Word);
begin
  BeginUndoAction;
  with Patterns[Cursor.X]^[Cursor.Y] do
    if Key = VK_DELETE then begin
      EffectCode := 0;
      EffectParams.Value := 0;
    end
    else begin
      KeycodeToHexNumber(Key, EffectCode);
      if EffectParams.Value = 0 then
        EffectParams.Value := LastFxParam[EffectCode];
    end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.InputEffectParams(Key: Word);
var
  Temp: Nibble;
begin
  BeginUndoAction;
  with Patterns[Cursor.X]^[Cursor.Y] do
    if Key = VK_DELETE then begin
      EffectCode := 0;
      EffectParams.Value := 0;
    end
    else if KeycodeToHexNumber(Key, Temp) then begin
      EffectParams.Value := ((EffectParams.Value mod $10) * $10) + Temp;
      LastFxParam[EffectCode] := EffectParams.Value;
    end;

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.RenderRow(Row: Integer);
var
  I: Integer;
begin
  with Canvas do begin
    Brush.Style := bsClear;
    Pen.Color := RGBToColor(58, 52, 39);

    for I := 0 to High(Patterns) do
      if Assigned(Patterns[I]) then
        RenderCell(Patterns[I]^[Row]);
  end;
end;

procedure TTrackerGrid.RenderCell(const Cell: TCell);
var
  NoteString: ShortString;
begin
  with Canvas do begin
    if NoteMap.TryGetData(Cell.Note, NoteString) then begin
      Font.Color := clNote;
      TextOut(PenPos.X, PenPos.Y, NoteString);
    end
    else begin
      Font.Color := clDots;
      if Cell.Note = NO_NOTE then
        TextOut(PenPos.X, PenPos.Y, '...')
      else
        TextOut(PenPos.X, PenPos.Y, '???');
    end;

    TextOut(PenPos.X, PenPos.Y, ' ');

    if Cell.Instrument <> 0 then begin
      Font.Color := clInstrument;
      TextOut(PenPos.X, PenPos.Y, FormatFloat('00', Cell.Instrument));
    end
    else begin
      Font.Color := clDots;
      TextOut(PenPos.X, PenPos.Y, '..');
    end;

    //Font.Color := clDark; //clGreen;
    Font.Color := clDots;
    TextOut(PenPos.X, PenPos.Y, '...');

    if (Cell.EffectCode <> 0) or (Cell.EffectParams.Value <> 0) then begin
      Font.Color := GetEffectColor(Cell.EffectCode);
      TextOut(
        PenPos.X,
        PenPos.Y,
        IntToHex(Cell.EffectCode, 1)
          + IntToHex(Cell.EffectParams.Param1, 1)
          + IntToHex(Cell.EffectParams.Param2, 1)
      );
    end
    else begin
      Font.Color := clDots;
      TextOut(PenPos.X, PenPos.Y, '...');
    end;

    TextOut(PenPos.X, PenPos.Y, ' ');
  end;
end;

procedure TTrackerGrid.SetHighlightedRow(Row: Integer);
//var
  //R: TRect;
  //OldRow: Integer;
begin
  //OldRow := FHighlightedRow;
  FHighlightedRow := Row;

  Invalidate

  // An optimization to redraw the pattern faster. This function gets called
  // a lot (every time the FD callback happens) so it needs to be fast. It can
  // sort of lag out the main thread if it just does a full invalidate.

  // For some reason it's flakey whether or not it works, so we're just doing
  // a full invalidate right now...

  {R.Left:=0;
  R.Width:=ColumnWidth*4;
  R.Height:=RowHeight*2;

  if InRange(OldRow, Low(TPattern), High(TPattern)) then begin
    RenderRow(OldRow);
    R.Top:=(OldRow-1)*RowHeight;
    InvalidateRect(Self.Handle, @R, True);
  end;

  R.Left:=0;
  R.Width:=ColumnWidth*4;
  R.Height:=RowHeight*2;

  if InRange(Row, Low(TPattern), High(TPattern)) then begin
    RenderRow(Row);
    R.Top:=(Row-1)*RowHeight;
    InvalidateRect(Self.Handle, @R, True);
  end;}
end;

procedure TTrackerGrid.SetSelectionGridRect(R: TRect);
begin
  Cursor.X := R.Left;
  Other.X := R.Right;
  Cursor.Y := R.Top;
  Other.Y := R.Bottom;
end;

function TTrackerGrid.GetSelectionGridRect: TRect;
begin
  Result := TRect.Create(
    TPoint.Create(Cursor.X, Cursor.Y),
    TPoint.Create(Other.X, Other.Y),
    True
  );
end;

function TTrackerGrid.GetEffectColor(EffectCode: Integer): TColor;
begin
  Result := clBlack;
  case EffectCode of
    $0: Result := clFxMisc;
    $1: Result := clFxPitch;
    $2: Result := clFxPitch;
    $3: Result := clFxPitch;
    $4: Result := clFxPitch;
    $5: Result := clFxSong;
    $6: Result := clFxMisc;
    $7: Result := clFxMisc;
    $8: Result := clFxPan;
    $9: Result := clFxSong;
    $A: Result := clFxVolume;
    $B: Result := clFxSong;
    $C: Result := clFxVolume;
    $D: Result := clFxSong;
    $E: Result := clFxMisc;
    $F: Result := clFxSong;
  end;
end;

function TTrackerGrid.SelectionsToRect(S1, S2: TSelectionPos): TRect;
begin
  Result := SelectionToRect(S1);
  Result.Union(SelectionToRect(S2));
end;

function TTrackerGrid.SelectionToRect(Selection: TSelectionPos): TRect;
var
  CharLeft, CharRight: Integer;
begin
  case Selection.SelectedPart of
    cpNote: begin
      CharLeft := 0;
      CharRight := 3;
    end;
    cpInstrument: begin
      CharLeft := 4;
      CharRight := 6
    end;
    cpVolume: begin
      CharLeft := 6;
      CharRight := 9;
    end;
    cpEffectCode: begin
      CharLeft := 9;
      CharRight := 10;
    end;
    cpEffectParams: begin
      CharLeft := 10;
      CharRight := 12;
    end;
  end;

  Result.Left := (Selection.X*ColumnWidth) + (CharLeft*CharWidth);
  Result.Right := (Selection.X*ColumnWidth) + (CharRight*CharWidth);
  Result.Top := (Selection.Y*RowHeight);
  Result.Bottom := (Selection.Y*RowHeight) + RowHeight;
end;

function TTrackerGrid.MousePosToSelection(X, Y: Integer): TSelectionPos;
var
  OrigX: Integer;
begin
  OrigX := X;
  X := EnsureRange(Width-1, 0, X);
  Y := EnsureRange(Height-1, 0, Y);

  Result.X := Trunc((X/Width)*NumColumns);
  Result.Y := Trunc((Y/Height)*NumRows);

  if OrigX <= 0 then
    Result.SelectedPart := cpNote
  else begin
    X := X mod ColumnWidth;
    X := Trunc((X/ColumnWidth)*13);
    case X of
      0..3: Result.SelectedPart := cpNote;
      4..5: Result.SelectedPart := cpInstrument;
      6..8: Result.SelectedPart := cpVolume;
      9:   Result.SelectedPart := cpEffectCode;
      10..12: Result.SelectedPart := cpEffectParams;
    end;
  end;
end;

function TTrackerGrid.KeycodeToHexNumber(Key: Word; var Num: Nibble): Boolean;
begin
  Result := True;

  case Key of
    VK_0: Num := $0;
    VK_1: Num := $1;
    VK_2: Num := $2;
    VK_3: Num := $3;
    VK_4: Num := $4;
    VK_5: Num := $5;
    VK_6: Num := $6;
    VK_7: Num := $7;
    VK_8: Num := $8;
    VK_9: Num := $9;
    VK_NUMPAD0: Num := $0;
    VK_NUMPAD1: Num := $1;
    VK_NUMPAD2: Num := $2;
    VK_NUMPAD3: Num := $3;
    VK_NUMPAD4: Num := $4;
    VK_NUMPAD5: Num := $5;
    VK_NUMPAD6: Num := $6;
    VK_NUMPAD7: Num := $7;
    VK_NUMPAD8: Num := $8;
    VK_NUMPAD9: Num := $9;
    VK_A: Num := $A;
    VK_B: Num := $B;
    VK_C: Num := $C;
    VK_D: Num := $D;
    VK_E: Num := $E;
    VK_F: Num := $F;
    else Result := False;
  end;
end;

function TTrackerGrid.KeycodeToHexNumber(Key: Word; var Num: Integer): Boolean;
var
  X: Nibble;
begin
  Result := KeycodeToHexNumber(Key, X);
  if Result then Num := X;
end;

procedure TTrackerGrid.ChangeFontSize;
begin
  // Kind of a hack
  with Canvas.Font do begin
    if Screen.Fonts.IndexOf('PixeliteTTF') >= 0 then begin
       Name := 'PixeliteTTF';
       Style := [];
    end
    else
    begin
       Name := 'Courier New';
       Style := [fsBold];
    end;
    Size := FontSize;
    ColumnWidth := GetTextWidth('C-5 01v64C01 ');
    RowHeight := GetTextHeight('C-5 01v64C01 ');

    CharHeight := RowHeight;
    CharWidth := GetTextWidth('C');
  end;

  Width := ColumnWidth*NumColumns;
  Height := RowHeight*NumRows;
end;

procedure TTrackerGrid.SetFontSize(AValue: Integer);
begin
  if FFontSize=AValue then Exit;
  FFontSize:=AValue;

  ChangeFontSize;
  Invalidate;
end;

function TTrackerGrid.GetAt(SelectionPos: TSelectionPos): Integer;
begin
  Result := 0;

  with Patterns[SelectionPos.X]^[SelectionPos.Y] do
    case SelectionPos.SelectedPart of
      cpNote: Result := Note;
      cpInstrument: Result := Instrument;
      cpVolume:;
      cpEffectCode: Result := EffectCode;
      cpEffectParams: Result := EffectParams.Value;
    end;
end;

procedure TTrackerGrid.SetAt(SelectionPos: TSelectionPos; Value: Integer);
begin
  with Patterns[SelectionPos.X]^[SelectionPos.Y] do
    case SelectionPos.SelectedPart of
      cpNote: Note := Value;
      cpInstrument: Instrument := Value;
      cpVolume:;
      cpEffectCode: EffectCode := Value;
      cpEffectParams: EffectParams.Value := Value;
    end;
end;

procedure TTrackerGrid.IncrementAt(SelectionPos: TSelectionPos; Value: Integer);
begin
  with Patterns[SelectionPos.X]^[SelectionPos.Y] do
    case SelectionPos.SelectedPart of
      cpNote:
        if Note <> NO_NOTE then
          Note := EnsureRange(Note+Value, LOWEST_NOTE, HIGHEST_NOTE);

      cpInstrument:
        if Instrument <> 0 then
          Instrument := EnsureRange(Instrument+Value, 1, 15);

      cpVolume:;

      cpEffectCode:
        EffectCode := EnsureRange(EffectCode+Value, $0, $F);

      cpEffectParams:
        if EffectCode = $0 then begin
          if EffectParams.Value <> $00 then
            EffectParams.Value := EnsureRange(EffectParams.Value+Value, Low(Byte)+1, High(Byte));
        end
        else
          EffectParams.Value := EnsureRange(EffectParams.Value+Value, Low(Byte), High(Byte));
    end;
end;

procedure TTrackerGrid.ClearAt(SelectionPos: TSelectionPos);
begin
  with Patterns[SelectionPos.X]^[SelectionPos.Y] do
    case SelectionPos.SelectedPart of
      cpNote: Note := NO_NOTE;
      cpInstrument: Instrument := 0;
      cpVolume: Volume := 0;
      cpEffectCode: begin
        EffectCode := 0;
        EffectParams.Value := 0;
      end;
      cpEffectParams: EffectParams.Value := 0;
    end;
end;

procedure TTrackerGrid.InsertRowInPatternAtCursor(Pattern: Integer);
var
  I: Integer;
begin
  BeginUndoAction;
  NormalizeCursors;

  for I := NumRows-1 downto Cursor.Y do
    Patterns[Pattern]^[I] := Patterns[Pattern]^[I-1];

  BlankCell(Patterns[Pattern]^[Cursor.Y]);

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.InsertRowInAllAtCursor;
var
  I: Integer;
begin
  BeginUndoAction;

  for I := Low(Patterns) to High(Patterns) do
    InsertRowInPatternAtCursor(I);

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.DeleteRowInPatternAtCursor(Pattern: Integer);
var
  I: Integer;
begin
  BeginUndoAction;
  NormalizeCursors;

  for I := Cursor.Y to NumRows-2 do
    Patterns[Pattern]^[I] := Patterns[Pattern]^[I+1];

  BlankCell(Patterns[Pattern]^[NumRows-1]);

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.DeleteRowInAllAtCursor;
var
  I: Integer;
begin
  BeginUndoAction;

  for I := Low(Patterns) to High(Patterns) do
    DeleteRowInPatternAtCursor(I);

  Invalidate;
  EndUndoAction;
end;

procedure TTrackerGrid.SelectAll;
begin
  Cursor.X := 0;
  Cursor.Y := 0;
  Cursor.SelectedPart := cpNote;
  Other.X := High(Patterns);
  Other.Y := NumRows-1;
  Other.SelectedPart := cpEffectParams;

  Invalidate;
end;

procedure TTrackerGrid.SelectColumn;
begin
  Cursor.Y := 0;
  Other.Y := NumRows-1;
  Cursor.SelectedPart := Low(TCellPart);
  Other.SelectedPart := High(TCellPart);

  Invalidate;
end;

procedure TTrackerGrid.LoadPattern(Idx: Integer; PatternNumber: Integer);
begin
  Patterns[Idx] := PatternMap.GetOrCreateNew(PatternNumber);
  PatternNumbers[Idx] := PatternNumber; // Ugh
  Invalidate;
end;

end.