File: interface.c

package info (click to toggle)
xwax 0.9-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 420 kB
  • sloc: ansic: 4,215; makefile: 263; sh: 124
file content (1546 lines) | stat: -rw-r--r-- 38,443 bytes parent folder | download
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
/*
 * Copyright (C) 2011 Mark Hills <mark@pogo.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2, as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 2 for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

#include <assert.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <SDL.h>
#include <SDL_ttf.h>

#include "interface.h"
#include "listing.h"
#include "player.h"
#include "rig.h"
#include "selector.h"
#include "timecoder.h"
#include "xwax.h"


/* Screen refresh time in milliseconds */

#define REFRESH 10


/* Font definitions */

#define FONT "DejaVuSans.ttf"
#define FONT_SIZE 10
#define FONT_SPACE 15

#define EM_FONT "DejaVuSans-Oblique.ttf"

#define CLOCK_FONT FONT
#define CLOCK_FONT_SIZE 32

#define DECI_FONT FONT
#define DECI_FONT_SIZE 20

#define DETAIL_FONT "DejaVuSansMono.ttf"
#define DETAIL_FONT_SIZE 9


/* Screen dimensions */

#define BORDER 12
#define SPACER 8

#define CURSOR_WIDTH 4

#define PLAYER_HEIGHT 213
#define OVERVIEW_HEIGHT 16

#define LIBRARY_MIN_WIDTH 64
#define LIBRARY_MIN_HEIGHT 64

#define DEFAULT_WIDTH 960
#define DEFAULT_HEIGHT 720
#define DEFAULT_METER_SCALE 8

#define MAX_METER_SCALE 11

#define SEARCH_HEIGHT (FONT_SPACE)
#define STATUS_HEIGHT (FONT_SPACE)

#define RESULTS_ARTIST_WIDTH 200

#define CLOCKS_WIDTH 160

#define SPINNER_SIZE (CLOCK_FONT_SIZE * 2 - 6)
#define SCOPE_SIZE (CLOCK_FONT_SIZE * 2 - 6)

#define SCROLLBAR_SIZE 10

#define METER_WARNING_TIME 20 /* time in seconds for "red waveform" warning */


/* Function key (F1-F12) definitions */

#define FUNC_LOAD 0
#define FUNC_RECUE 1
#define FUNC_TIMECODE 2


/* State variables used to trigger certain actions */

#define UPDATE_NONE 0
#define UPDATE_REDRAW 1


/* Types of SDL_USEREVENT */

#define EVENT_TICKER 0
#define EVENT_QUIT 1


/* Macro functions */

#define MIN(x,y) ((x)<(y)?(x):(y))
#define SQ(x) ((x)*(x))

#define LOCK(sf) if (SDL_MUSTLOCK(sf)) SDL_LockSurface(sf)
#define UNLOCK(sf) if (SDL_MUSTLOCK(sf)) SDL_UnlockSurface(sf)
#define UPDATE(sf, rect) SDL_UpdateRect(sf, (rect)->x, (rect)->y, \
                                        (rect)->w, (rect)->h)


/* List of directories to use as search path for fonts. */

static const char *font_dirs[] = {
    "/usr/X11R6/lib/X11/fonts/TTF",
    "/usr/share/fonts/truetype/ttf-dejavu/", 
    "/usr/share/fonts/ttf-dejavu",
    "/usr/share/fonts/dejavu",
    "/usr/share/fonts/TTF",
    NULL
};


static TTF_Font *clock_font, *deci_font, *detail_font, *font, *em_font;

static SDL_Color background_col = {0, 0, 0, 255},
    text_col = {224, 224, 224, 255},
    warn_col = {192, 64, 0, 255},
    ok_col = {32, 128, 3, 255},
    elapsed_col = {0, 32, 255, 255},
    cursor_col = {192, 0, 0, 255},
    selected_col = {0, 48, 64, 255},
    detail_col = {128, 128, 128, 255},
    needle_col = {255, 255, 255, 255};

static int spinner_angle[SPINNER_SIZE * SPINNER_SIZE];


struct rect_t {
    signed short x, y, w, h;
};


/* Split the given rectangle split v pixels from the top, with a gap
 * of 'space' between the output rectangles */

static void split_top(const struct rect_t *source, struct rect_t *upper,
                      struct rect_t *lower, int v, int space)
{
    int u;

    u = v + space;

    if (upper) {
        upper->x = source->x;
        upper->y = source->y;
        upper->w = source->w;
        upper->h = v;
    }

    if (lower) {
        lower->x = source->x;
        lower->y = source->y + u;
        lower->w = source->w;
        lower->h = source->h - u;
    }
}


/* As above, x pixels from the bottom */

static void split_bottom(const struct rect_t *source, struct rect_t *upper,
                         struct rect_t *lower, int v, int space)
{
    split_top(source, upper, lower, source->h - v - space, space);
}


/* As above, v pixels from the left */

static void split_left(const struct rect_t *source, struct rect_t *left,
                       struct rect_t *right, int v, int space)
{
    int u;

    u = v + space;

    if (left) {
        left->x = source->x;
        left->y = source->y;
        left->w = v;
        left->h = source->h;
    }

    if (right) {
        right->x = source->x + u;
        right->y = source->y;
        right->w = source->w - u;
        right->h = source->h;
    }
}


/* As above, v pixels from the right */

static void split_right(const struct rect_t *source, struct rect_t *left,
                        struct rect_t *right, int v, int space)
{
    split_left(source, left, right, source->w - v - space, space);
}


static void time_to_clock(char *buf, char *deci, int t)
{
    int minutes, seconds, frac, neg;

    if (t < 0) {
        t = abs(t);
        neg = 1;
    } else
        neg = 0;

    minutes = (t / 60 / 1000) % (60*60);
    seconds = (t / 1000) % 60;
    frac = t % 1000;
    
    if (neg)
        *buf++ = '-';

    sprintf(buf, "%02d:%02d.", minutes, seconds);
    sprintf(deci, "%03d", frac);
}


/* Calculate a lookup which maps a position on screen to an angle,
 * relative to the centre of the spinner */

static void calculate_spinner_lookup(int *angle, int *distance, int size)
{
    int r, c, nr, nc;
    float theta, rat;

    for (r = 0; r < size; r++) {
        nr = r - size / 2;

        for (c = 0; c < size; c++) {
            nc = c - size / 2;

            if (nr == 0)
                theta = M_PI_2;

            else if (nc == 0) {
                theta = 0;
                
                if (nr < 0)
                    theta = M_PI;
            
            } else {
                rat = (float)(nc) / -nr;
                theta = atanf(rat);
                
                if (rat < 0)
                    theta += M_PI;
            }
            
            if (nc <= 0)
                theta += M_PI;

            /* The angles stored in the lookup table range from 0 to
             * 1023 (where 1024 is 360 degrees) */

            angle[r * size + c]
                = ((int)(theta * 1024 / (M_PI * 2)) + 1024) % 1024;

            if (distance)
                distance[r * size + c] = sqrt(SQ(nc) + SQ(nr));
        }
    }    
}


/* Open a font, given the leafname. This scans the available font
 * directories for the file, to account for different software
 * distributions. */

static TTF_Font* open_font(const char *name, int size) {
    int r;
    char buf[256];
    const char **dir;
    struct stat st;
    TTF_Font *font;

    dir = &font_dirs[0];

    while (*dir) {
        
        sprintf(buf, "%s/%s", *dir, name);
        
        r = stat(buf, &st);

        if (r != -1) { /* something exists at this path */
            fprintf(stderr, "Loading font '%s', %dpt...\n", buf, size);
            
            font = TTF_OpenFont(buf, size);
            if (!font) {
                fputs("Font error: ", stderr);
                fputs(TTF_GetError(), stderr);
                fputc('\n', stderr);
            }            
            return font; /* or NULL */
        }
        
        if (errno != ENOENT) {
            perror("stat");
            return NULL;
        }
        
        dir++;
        continue;
    }

    fprintf(stderr, "Font '%s' cannot be found in", name);
    
    dir = &font_dirs[0];
    while (*dir) {
        fputc(' ', stderr);
        fputs(*dir, stderr);
        dir++;
    }
    fputc('.', stderr);
    fputc('\n', stderr);

    return NULL;
}


static int load_fonts(void)
{
    clock_font = open_font(CLOCK_FONT, CLOCK_FONT_SIZE);
    if (!clock_font)
        return -1;
    
    deci_font = open_font(DECI_FONT, DECI_FONT_SIZE);
    if (!deci_font)
        return -1;
    
    font = open_font(FONT, FONT_SIZE);
    if (!font)
        return -1;
    
    em_font = open_font(EM_FONT, FONT_SIZE);
    if (!em_font)
        return -1;
    
    detail_font = open_font(DETAIL_FONT, DETAIL_FONT_SIZE);
    if (!detail_font)
        return -1;
    
    return 0;
}


static void clear_fonts(void)
{
    TTF_CloseFont(clock_font);
    TTF_CloseFont(deci_font);
    TTF_CloseFont(font);
    TTF_CloseFont(em_font);
    TTF_CloseFont(detail_font);
}


static Uint32 palette(SDL_Surface *sf, SDL_Color *col)
{
    return SDL_MapRGB(sf->format, col->r, col->g, col->b);
}


static int draw_font(SDL_Surface *sf, int x, int y, int w, int h,
                     const char *buf, TTF_Font *font,
                     SDL_Color fg, SDL_Color bg)
{
    SDL_Surface *rendered;
    SDL_Rect dst, src, fill;

    if (buf == NULL) {
        src.w = 0;
        src.h = 0;

    } else if (buf[0] == '\0') { /* SDL_ttf fails for empty string */
        src.w = 0;
        src.h = 0;

    } else {
        rendered = TTF_RenderText_Shaded(font, buf, fg, bg);
        
        src.x = 0;
        src.y = 0;
        src.w = MIN(w, rendered->w);
        src.h = MIN(h, rendered->h);
        
        dst.x = x;
        dst.y = y;
        
        SDL_BlitSurface(rendered, &src, sf, &dst);
        SDL_FreeSurface(rendered);
    } 

    /* Complete the remaining space with a blank rectangle */

    if (src.w < w) {
        fill.x = x + src.w;
        fill.y = y;
        fill.w = w - src.w;
        fill.h = h;   
        SDL_FillRect(sf, &fill, palette(sf, &bg));
    }

    if (src.h < h) {
        fill.x = x;
        fill.y = y + src.h;
        fill.w = src.w; /* the x-fill rectangle does the corner */
        fill.h = h - src.h;
        SDL_FillRect(sf, &fill, palette(sf, &bg));
    }

    return src.w;
}


static int draw_font_rect(SDL_Surface *surface, const struct rect_t *rect,
                          const char *buf, TTF_Font *font,
                          SDL_Color fg, SDL_Color bg)
{
    return draw_font(surface, rect->x, rect->y, rect->w, rect->h,
                     buf, font, fg, bg);
}


/* Draw the display of artist name and track name */

static void draw_track_summary(SDL_Surface *surface, const struct rect_t *rect,
                               struct track_t *track)
{
    struct rect_t top, bottom;

    split_top(rect, &top, &bottom, FONT_SPACE, 0);

    draw_font_rect(surface, &top, track->artist,
                   font, text_col, background_col);
    draw_font_rect(surface, &bottom, track->title,
                   em_font, text_col, background_col);
}


/* Draw a single clock, in hours:minutes.seconds format */

static void draw_clock(SDL_Surface *surface, const struct rect_t *rect, int t,
                       SDL_Color col)
{
    char hms[8], deci[8];
    short int v;
    int offset;
    struct rect_t sr;

    time_to_clock(hms, deci, t);
    
    v = draw_font_rect(surface, rect, hms, clock_font, col, background_col);
    
    offset = CLOCK_FONT_SIZE - DECI_FONT_SIZE * 1.04;

    sr.x = rect->x + v; 
    sr.y = rect->y + offset;
    sr.w = rect->w - v;
    sr.h = rect->h - offset;
    
    draw_font_rect(surface, &sr, deci, deci_font, col, background_col);
}


/* Draw the visual display of the input audio to the timecoder (the
 * 'scope') */

static void draw_scope(SDL_Surface *surface, const struct rect_t *rect,
                       struct timecoder_t *tc)
{
    int r, c, v, mid;
    Uint8 *p;

    mid = tc->mon_size / 2;

    for (r = 0; r < tc->mon_size; r++) {
        for (c = 0; c < tc->mon_size; c++) {
            p = surface->pixels
                + (rect->y + r) * surface->pitch
                + (rect->x + c) * surface->format->BytesPerPixel;

            v = tc->mon[r * tc->mon_size + c];

            if ((r == mid || c == mid) && v < 64)
                v = 64;

            p[0] = v;
            p[1] = p[0];
            p[2] = p[1];            
        }
    }    
}


/* Draw the spinner which shows the rotational position of the record,
 * and matches the physical rotation of the vinyl record */

static void draw_spinner(SDL_Surface *surface, const struct rect_t *rect,
                         struct player_t *pl)
{
    int x, y, r, c, rangle, pangle;
    double position, rps;
    Uint8 *rp, *p;
    SDL_Color col;

    x = rect->x;
    y = rect->y;

    position = pl->position - pl->offset;
    rps = timecoder_revs_per_sec(pl->timecoder);
    rangle = (int)(pl->position * 1024 * rps) % 1024;

    if (position < 0 || position >= (double)pl->track->length / pl->track->rate)
        col = warn_col;
    else
        col = ok_col;

    for (r = 0; r < SPINNER_SIZE; r++) {

        /* Store a pointer to this row of the framebuffer */

        rp = surface->pixels + (y + r) * surface->pitch;

        for (c = 0; c < SPINNER_SIZE; c++) {

            /* Use the lookup table to provide the angle at each
             * pixel */

            pangle = spinner_angle[r * SPINNER_SIZE + c];

            /* Calculate the final pixel location and set it */

            p = rp + (x + c) * surface->format->BytesPerPixel;

            if ((rangle - pangle + 1024) % 1024 < 512) {
                p[0] = col.b >> 2;
                p[1] = col.g >> 2;
                p[2] = col.r >> 2;
            } else {
                p[0] = col.b;
                p[1] = col.g;
                p[2] = col.r;
            }
        }
    }    
}


/* Draw the clocks which show time elapsed and time remaining */

static void draw_deck_clocks(SDL_Surface *surface, const struct rect_t *rect,
                             struct player_t *pl)
{
    int elapse, remain;
    float pos;
    struct rect_t upper, lower;
    SDL_Color col;

    split_top(rect, &upper, &lower, CLOCK_FONT_SIZE, 0);

    pos = pl->position - pl->offset;

    elapse = pos * 1000;
    remain = (pos - pl->track->length / pl->track->rate) * 1000;

    if (elapse < 0)
        col = warn_col;
    else if (remain <= 0)
        col = ok_col;
    else
        col = text_col;

    draw_clock(surface, &upper, elapse, col);

    if (remain > 0)
        col = warn_col;
    else
        col = text_col;

    if (track_is_importing(pl->track)) {
        col.r >>= 2;
        col.g >>= 2;
        col.b >>= 2;
    }

    draw_clock(surface, &lower, remain, col);
}


/* Draw the high-level overview meter which shows the whole length
 * of the track */

static void draw_overview(SDL_Surface *surface, const struct rect_t *rect,
                          struct track_t *tr, int position)
{
    int x, y, w, h, r, c, sp, fade, bytes_per_pixel, pitch, height,
        current_position;
    Uint8 *pixels, *p;
    SDL_Color col;

    x = rect->x;
    y = rect->y;
    w = rect->w;
    h = rect->h;

    pixels = surface->pixels;
    bytes_per_pixel = surface->format->BytesPerPixel;
    pitch = surface->pitch;

    if (tr->length)
        current_position = (long long)position * w / tr->length;
    else
        current_position = 0;

    for (c = 0; c < w; c++) {

        /* Collect the correct meter value for this column */

        sp = (long long)tr->length * c / w;

        if (sp < tr->length) /* account for rounding */
            height = track_get_overview(tr, sp) * h / 256;
        else
            height = 0;

        /* Choose a base colour to display in */

        if (!tr->length) {
            col = background_col;
            fade = 0;
        } else if (c == current_position) {
            col = needle_col;
            fade = 1;
        } else if (position > tr->length - tr->rate * METER_WARNING_TIME) {
            col = warn_col;
            fade = 3;
        } else {
            col = elapsed_col;
            fade = 3;
        }

        if (track_is_importing(tr)) {
            col.b >>= 1;
            col.g >>= 1;
            col.r >>= 1;
        }

        if (c < current_position) {
            col.b >>= 1;
            col.g >>= 1;
            col.r >>= 1;
        }

        /* Store a pointer to this column of the framebuffer */

        p = pixels + y * pitch + (x + c) * bytes_per_pixel;

        r = h;
        while (r > height) {
            p[0] = col.b >> fade;
            p[1] = col.g >> fade;
            p[2] = col.r >> fade;
            p += pitch;
            r--;
        }
        while (r) {
            p[0] = col.b;
            p[1] = col.g;
            p[2] = col.r;
            p += pitch;
            r--;
        }
    }
}


/* Draw the close-up meter, which can be zoomed to a level set by
 * 'scale' */

static void draw_closeup(SDL_Surface *surface, const struct rect_t *rect,
                         struct track_t *tr, int position, int scale)
{
    int x, y, w, h, r, c, sp, fade, bytes_per_pixel, pitch, height;
    Uint8 *pixels, *p;
    SDL_Color col;

    x = rect->x;
    y = rect->y;
    w = rect->w;
    h = rect->h;

    pixels = surface->pixels;
    bytes_per_pixel = surface->format->BytesPerPixel;
    pitch = surface->pitch;

    for (c = 0; c < w; c++) {

        /* Work out the meter height in pixels for this column */

        sp = position - (position % (1 << scale))
            + ((c - w / 2) << scale);

        if (sp < tr->length && sp > 0)
            height = track_get_ppm(tr, sp) * h / 256;
        else
            height = 0;

        /* Select the appropriate colour */

        if (c == w / 2) {
            col = needle_col;
            fade = 1;
        } else {
            col = elapsed_col;
            fade = 3;
        }

        /* Get a pointer to the top of the column, and increment
         * it for each row */

        p = pixels + y * pitch + (x + c) * bytes_per_pixel;

        r = h;
        while (r > height) {
            p[0] = col.b >> fade;
            p[1] = col.g >> fade;
            p[2] = col.r >> fade;
            p += pitch;
            r--;
        }
        while (r) {
            p[0] = col.b;
            p[1] = col.g;
            p[2] = col.r;
            p += pitch;
            r--;
        }
    }
}


/* Draw the audio meters for a deck */                         

static void draw_meters(SDL_Surface *surface, const struct rect_t *rect,
                        struct track_t *tr, int position, int scale)
{
    struct rect_t overview, closeup;

    split_top(rect, &overview, &closeup, OVERVIEW_HEIGHT, SPACER);

    if (closeup.h > OVERVIEW_HEIGHT)
        draw_overview(surface, &overview, tr, position);
    else
        closeup = *rect;

    draw_closeup(surface, &closeup, tr, position, scale);
}


/* Draw the current playback status -- clocks, spinner and scope */

static void draw_deck_top(SDL_Surface *surface, const struct rect_t *rect,
                          struct player_t *pl)
{
    struct rect_t clocks, left, right, spinner, scope;
    
    split_left(rect, &clocks, &right, CLOCKS_WIDTH, SPACER);

    /* If there is no timecoder to display information on, or not enough 
     * available space, just draw clocks which span the overall space */

    if (!pl->timecode_control || right.w < 0) {
        draw_deck_clocks(surface, rect, pl);
        return;
    }

    draw_deck_clocks(surface, &clocks, pl);    

    split_right(&right, &left, &spinner, SPINNER_SIZE, SPACER);
    if (left.w < 0)
        return;
    split_bottom(&spinner, NULL, &spinner, SPINNER_SIZE, 0);
    draw_spinner(surface, &spinner, pl);

    split_right(&left, &clocks, &scope, SCOPE_SIZE, SPACER);
    if (clocks.w < 0)
        return;
    split_bottom(&scope, NULL, &scope, SCOPE_SIZE, 0);
    draw_scope(surface, &scope, pl->timecoder);
}


/* Draw the textual description of playback status, which includes
 * information on the timecode */

static void draw_deck_status(SDL_Surface *surface,
                                 const struct rect_t *rect,
                                 struct player_t *pl)
{
    char buf[128];
    int tc;

    tc = timecoder_get_position(pl->timecoder, NULL);
    if (pl->timecode_control && tc != -1)
        sprintf(buf, "timecode:%d      ", tc);
    else
        sprintf(buf, "timecode:        ");
    
    sprintf(buf + 17, "pitch:%+0.2f (sync %0.2f %+.5fs = %+0.2f)  %s",
            pl->pitch,
            pl->sync_pitch,
            pl->last_difference,
            pl->pitch * pl->sync_pitch,
            pl->recalibrate ? "RCAL  " : "");
    
    draw_font_rect(surface, rect, buf, detail_font,
                   detail_col, background_col);
}


/* Draw a single deck */

static void draw_deck(SDL_Surface *surface, const struct rect_t *rect,
                      struct player_t *pl, int meter_scale)
{
    int position;
    struct rect_t track, top, meters, status, rest, lower;

    position = (pl->position - pl->offset) * pl->track->rate;

    split_top(rect, &track, &rest, FONT_SPACE * 2, 0);
    if (rest.h < 160)
        rest = *rect;
    else
        draw_track_summary(surface, &track, pl->track);

    split_top(&rest, &top, &lower, CLOCK_FONT_SIZE * 2, SPACER);
    if (lower.h < 64)
        lower = rest;
    else
        draw_deck_top(surface, &top, pl);
    
    split_bottom(&lower, &meters, &status, FONT_SPACE, SPACER); 
    if (meters.h < 64)
        meters = lower;
    else
        draw_deck_status(surface, &status, pl);

    draw_meters(surface, &meters, pl->track, position, meter_scale);
}


/* Draw all the decks in the system */

static void draw_decks(SDL_Surface *surface, const struct rect_t *rect,
                       int ndecks, struct player_t **player,
                       int meter_scale)
{
    int d, deck_width;
    struct rect_t single;

    deck_width = (rect->w - BORDER * (ndecks - 1)) / ndecks;

    single = *rect;
    single.w = deck_width;

    for (d = 0; d < ndecks; d++) {
        single.x = rect->x + (deck_width + BORDER) * d;
        draw_deck(surface, &single, player[d], meter_scale);
    }
}


/* Draw the status bar */

static void draw_status(SDL_Surface *sf, const struct rect_t *rect,
                        const char *text)
{
    draw_font_rect(sf, rect, text, detail_font, detail_col, background_col);
}


/* Draw the search field which the user types into */

static void draw_search(SDL_Surface *surface, const struct rect_t *rect,
                        struct selector_t *sel)
{
    int s;
    const char *buf;
    char cm[32];
    SDL_Rect cursor;
    struct rect_t rtext;

    split_left(rect, NULL, &rtext, SCROLLBAR_SIZE, SPACER);

    if (sel->search[0] != '\0')
        buf = sel->search;
    else
        buf = NULL;

    s = draw_font_rect(surface, &rtext, buf, font, text_col, background_col);

    cursor.x = rtext.x + s;
    cursor.y = rtext.y;
    cursor.w = CURSOR_WIDTH;
    cursor.h = rtext.h;

    SDL_FillRect(surface, &cursor, palette(surface, &cursor_col));

    if (sel->view_listing->entries > 1)
        sprintf(cm, "%zd matches", sel->view_listing->entries);
    else if (sel->view_listing->entries > 0)
        sprintf(cm, "1 match");
    else
        sprintf(cm, "no matches");

    rtext.x += s + CURSOR_WIDTH + SPACER;
    rtext.w -= s + CURSOR_WIDTH + SPACER;

    draw_font_rect(surface, &rtext, cm, em_font, detail_col, background_col);
}


/* Draw a vertical scroll bar representing our view on a list of the
 * given number of entries */

static void draw_scroll_bar(SDL_Surface *surface, const struct rect_t *rect,
                            struct scroll_t *scroll)
{
    SDL_Rect box;
    SDL_Color bg;

    bg = selected_col;
    bg.r >>= 1;
    bg.g >>= 1;
    bg.b >>= 1;

    box.x = rect->x;
    box.y = rect->y;
    box.w = rect->w;
    box.h = rect->h;
    SDL_FillRect(surface, &box, palette(surface, &bg));

    if (scroll->entries > 0) {
        box.x = rect->x;
        box.y = rect->y + rect->h * scroll->offset / scroll->entries;
        box.w = rect->w;
        box.h = rect->h * MIN(scroll->lines, scroll->entries) / scroll->entries;
        SDL_FillRect(surface, &box, palette(surface, &selected_col));
    }
}


/* Display a crate listing, with scrollbar and current
 * selection. Return the number of lines which fit on the display. */

static void draw_crates(SDL_Surface *surface, const struct rect_t *rect,
                        struct selector_t *sel)
{
    int x, y, w, h, r, ox, n;
    struct rect_t rs;
    SDL_Rect box;
    SDL_Color col_bg, col_text;

    x = rect->x;
    y = rect->y;
    w = rect->w;
    h = rect->h;
    ox = x;

    x += SCROLLBAR_SIZE + SPACER;
    w -= SCROLLBAR_SIZE + SPACER;

    for (n = 0; n + sel->crates.offset < sel->library->crates; n++) {

        if ((n + 1) * FONT_SPACE > h)
            break;

        r = y + n * FONT_SPACE;

        if (sel->library->crate[n + sel->crates.offset]->is_fixed)
            col_text = detail_col;
        else
            col_text = text_col;

        if (n + sel->crates.offset == sel->crates.selected)
            col_bg = selected_col;
        else
            col_bg = background_col;

        draw_font(surface, x, r, w, FONT_SPACE,
                  sel->library->crate[n + sel->crates.offset]->name, font,
                  col_text, col_bg);
    }

    /* Blank any remaining space */

    box.x = x;
    box.y = y + n * FONT_SPACE;
    box.w = w;
    box.h = h - (n * FONT_SPACE);

    SDL_FillRect(surface, &box, palette(surface, &background_col));

    rs.x = ox;
    rs.y = y;
    rs.w = SCROLLBAR_SIZE;
    rs.h = h;
    draw_scroll_bar(surface, &rs, &sel->crates);
}


/* Display a record library listing, with scrollbar and current
 * selection. Return the number of lines which fit on the display. */

static void draw_records(SDL_Surface *surface, const struct rect_t *rect,
                         struct selector_t *sel)
{
    int x, y, w, h, n, r, ox;
    struct rect_t rs;
    struct record_t *re;
    SDL_Rect box;
    SDL_Color col;
    
    x = rect->x;
    y = rect->y;
    w = rect->w;
    h = rect->h;

    ox = x;

    x += SCROLLBAR_SIZE + SPACER;
    w -= SCROLLBAR_SIZE + SPACER;

    for (n = 0; n + sel->records.offset < sel->view_listing->entries; n++) {
        re = sel->view_listing->record[n + sel->records.offset];
    
        if ((n + 1) * FONT_SPACE > h)
            break;

        r = y + n * FONT_SPACE;
    
        if (n + sel->records.offset == sel->records.selected)
            col = selected_col;
        else
            col = background_col;

        draw_font(surface, x, r, RESULTS_ARTIST_WIDTH, FONT_SPACE,
                  re->artist, font, text_col, col);

        box.x = x + RESULTS_ARTIST_WIDTH;
        box.y = r;
        box.w = SPACER;
        box.h = FONT_SPACE;

        SDL_FillRect(surface, &box, palette(surface, &col));
            
        draw_font(surface, x + RESULTS_ARTIST_WIDTH + SPACER, r,
                  w - RESULTS_ARTIST_WIDTH - SPACER, FONT_SPACE,
                  re->title, em_font, text_col, col);
    }

    /* Blank any remaining space */
    
    box.x = x;
    box.y = y + n * FONT_SPACE;
    box.w = w;
    box.h = h - (n * FONT_SPACE);
    
    SDL_FillRect(surface, &box, palette(surface, &background_col));
    
    rs.x = ox;
    rs.y = y;
    rs.w = SCROLLBAR_SIZE;
    rs.h = h;
    draw_scroll_bar(surface, &rs, &sel->records);
}


/* Display the music library, which consists of the query, and search
 * results */

static void draw_library(SDL_Surface *surface, const struct rect_t *rect,
                         struct selector_t *sel)
{
    unsigned int lines;
    struct rect_t rsearch, rlists, rcrates, rrecords;

    split_top(rect, &rsearch, &rlists, SEARCH_HEIGHT, SPACER);
    draw_search(surface, &rsearch, sel);

    lines = rlists.h / FONT_SPACE;
    selector_set_lines(sel, lines);

    split_left(&rlists, &rcrates, &rrecords, (rlists.w / 4), SPACER);
    if (rcrates.w > LIBRARY_MIN_WIDTH) {
        draw_records(surface, &rrecords, sel);
        draw_crates(surface, &rcrates, sel);
    } else {
        draw_records(surface, rect, sel);
    }
}


/* Initiate the process of loading a record from the library into a
 * track in memory */

static void do_loading(struct interface_t *interface,
                       struct track_t *track, struct record_t *record)
{
    fprintf(stderr, "Loading '%s'.\n", record->pathname);

    if (track_import(track, record->pathname) == -1)
        return;

    track->artist = record->artist;
    track->title = record->title;

    (void)rig_awaken(interface->rig);
}


/* Handle a single key event. Return true if the selector needs
 * to be redrawn */

static bool handle_key(struct interface_t *in, struct selector_t *sel,
                       int *meter_scale, SDLKey key, SDLMod mod)
{
    struct player_t *pl;
    struct record_t* re;

    if (key >= SDLK_a && key <= SDLK_z) {
        selector_search_refine(sel, (key - SDLK_a) + 'a');
        return true;

    } else if (key >= SDLK_0 && key <= SDLK_9) {
        selector_search_refine(sel, (key - SDLK_0) + '0');
        return true;

    } else if (key == SDLK_SPACE) {
        selector_search_refine(sel, ' ');
        return true;

    } else if (key == SDLK_BACKSPACE) {
        selector_search_expand(sel);
        return true;

    } else if (key == SDLK_PERIOD) {
        selector_search_refine(sel, '.');
        return true;

    } else if (key == SDLK_HOME) {
        selector_top(sel);
        return true;

    } else if (key == SDLK_END) {
        selector_bottom(sel);
        return true;

    } else if (key == SDLK_UP) {
        selector_up(sel);
        return true;

    } else if (key == SDLK_DOWN) {
        selector_down(sel);
        return true;

    } else if (key == SDLK_PAGEUP) {
        selector_page_up(sel);
        return true;

    } else if (key == SDLK_PAGEDOWN) {
        selector_page_down(sel);
        return true;

    } else if (key == SDLK_LEFT) {
        selector_prev(sel);
        return true;

    } else if (key == SDLK_RIGHT) {
        selector_next(sel);
        return true;

    } else if (key == SDLK_TAB) {
        selector_toggle(sel);
        return true;

    } else if ((key == SDLK_EQUALS) || (key == SDLK_PLUS)) {
        (*meter_scale)--;

        if (*meter_scale < 0)
            *meter_scale = 0;

        fprintf(stderr, "Meter scale decreased to %d\n", *meter_scale);

    } else if (key == SDLK_MINUS) {
        (*meter_scale)++;

        if (*meter_scale > MAX_METER_SCALE)
            *meter_scale = MAX_METER_SCALE;

        fprintf(stderr, "Meter scale increased to %d\n", *meter_scale);

    } else if (key >= SDLK_F1 && key <= SDLK_F12) {
        int func, deck;

        /* Handle the function key press in groups of four --
	 * F1-F4 (deck 0), F5-F8 (deck 1) etc. */

        func = (key - SDLK_F1) % 4;
        deck = (key - SDLK_F1) / 4;

        if (deck < in->players) {
            pl = in->player[deck];

            if (mod & KMOD_SHIFT) {
                if (func < in->timecoders)
                    player_connect_timecoder(pl, in->timecoder[func]);

            } else switch(func) {

            case FUNC_LOAD:
                re = selector_current(sel);
                if (re != NULL)
                    do_loading(in, pl->track, re);
                break;

            case FUNC_RECUE:
                player_recue(pl);
                break;

            case FUNC_TIMECODE:
                (void)player_toggle_timecode_control(pl);
                break;
            }
        }
    }

    return false;
}


static SDL_Surface* set_size(int w, int h, struct rect_t *rect)
{
    SDL_Surface *surface;

    surface = SDL_SetVideoMode(w, h, 32, SDL_RESIZABLE);
    if (surface == NULL) {
        fprintf(stderr, "%s\n", SDL_GetError());
        return NULL;
    }
    
    rect->x = BORDER;
    rect->y = BORDER;
    rect->w = w - 2 * BORDER;
    rect->h = h - 2 * BORDER;

    fprintf(stderr, "New interface size is %dx%d.\n", w, h);
    
    return surface;
}


static Uint32 ticker(Uint32 interval, void *p)
{
    SDL_Event event;
    
    if (!SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_EVENTMASK(SDL_USEREVENT)))
    {
        event.type = SDL_USEREVENT;
        event.user.code = EVENT_TICKER;
        SDL_PushEvent(&event);
    }        

    return interval;
}


/*
 * The SDL interface thread
 */

static int interface_main(struct interface_t *in)
{
    int meter_scale, library_update, decks_update, status_update;
    const char *status = banner;

    SDL_Event event;
    SDL_TimerID timer;
    SDL_Surface *surface;

    struct rect_t rworkspace, rplayers, rlibrary, rstatus, rtmp;

    meter_scale = DEFAULT_METER_SCALE;

    surface = set_size(DEFAULT_WIDTH, DEFAULT_HEIGHT, &rworkspace);
    if (!surface)
        return -1;

    decks_update = UPDATE_REDRAW;
    status_update = UPDATE_REDRAW;
    library_update = UPDATE_REDRAW;

    /* The final action is to add the timer which triggers refresh */

    timer = SDL_AddTimer(REFRESH, ticker, (void*)in);

    while (SDL_WaitEvent(&event) >= 0) {

        switch(event.type) {
        case SDL_QUIT: /* user request to quit application; eg. window close */
            if (rig_quit(in->rig) == -1)
                return -1;
            break;

        case SDL_VIDEORESIZE:
            surface = set_size(event.resize.w, event.resize.h, &rworkspace);
            if (!surface)
                return -1;

            if (library_update < UPDATE_REDRAW)
                library_update = UPDATE_REDRAW;

            if (decks_update < UPDATE_REDRAW)
                decks_update = UPDATE_REDRAW;

            if (status_update < UPDATE_REDRAW)
                status_update = UPDATE_REDRAW;

            break;
            
        case SDL_USEREVENT:
            switch (event.user.code) {
            case EVENT_TICKER: /* request to poll the clocks */
                if (decks_update < UPDATE_REDRAW)
                    decks_update = UPDATE_REDRAW;
                break;

            case EVENT_QUIT: /* internal request to finish this thread */
                goto finish;

            default:
                abort();
            }
            break;

        case SDL_KEYDOWN:
            if (handle_key(in, &in->selector, &meter_scale,
                          event.key.keysym.sym, event.key.keysym.mod))
            {
                library_update = UPDATE_REDRAW;
            }

        } /* switch(event.type) */

        /* Split the display into the various areas. If an area is too
         * small, abandon any actions to happen in that area. */

        split_bottom(&rworkspace, &rtmp, &rstatus, STATUS_HEIGHT, SPACER);
        if (rtmp.h < 128 || rtmp.w < 0) {
            rtmp = rworkspace;
            status_update = UPDATE_NONE;
        }

        split_top(&rtmp, &rplayers, &rlibrary, PLAYER_HEIGHT, SPACER);        
        if (rlibrary.h < LIBRARY_MIN_HEIGHT || rlibrary.w < LIBRARY_MIN_WIDTH) {
            rplayers = rtmp;
            library_update = UPDATE_NONE;
        }

        if (rplayers.h < 0 || rplayers.w < 0)
            decks_update = UPDATE_NONE;

        /* If there's been a change to the library search results,
         * check them over and display them. */

        if (library_update >= UPDATE_REDRAW) {

            if (selector_current(&in->selector) != NULL)
                status = selector_current(&in->selector)->pathname;
            else
                status = "No search results found";
            status_update = UPDATE_REDRAW;
          
            LOCK(surface);
            draw_library(surface, &rlibrary, &in->selector);
            UNLOCK(surface);
            UPDATE(surface, &rlibrary);
            library_update = UPDATE_NONE;
        }

        /* If there's been a change to status, redisplay it */

        if (status_update >= UPDATE_REDRAW) {
            LOCK(surface);
            draw_status(surface, &rstatus, status);
            UNLOCK(surface);
            UPDATE(surface, &rstatus);
            status_update = UPDATE_NONE;
        }

        /* If it's due, redraw the players. This is triggered by the
         * timer event. */

        if (decks_update >= UPDATE_REDRAW) {
            LOCK(surface);
            draw_decks(surface, &rplayers, in->players, in->player,
                       meter_scale);
            UNLOCK(surface);
            UPDATE(surface, &rplayers);
            decks_update = UPDATE_NONE;
        }

    } /* main loop */

 finish:
    SDL_RemoveTimer(timer);

    return 0;
}

static void* launch(void *p)
{
    interface_main(p);
    return NULL;
}

/*
 * Start the SDL interface
 *
 * FIXME: There are multiple points where resources are leaked on
 * error
 */

int interface_start(struct interface_t *in, size_t ndeck,
                    struct player_t *pl, struct timecoder_t *tc,
                    struct library_t *lib, struct rig_t *rig)
{
    size_t n;

    assert(ndeck <= MAX_DECKS);

    for (n = 0; n < ndeck; n++) {
        in->player[n] = &pl[n];
        in->timecoder[n] = &tc[n];
        if (timecoder_monitor_init(in->timecoder[n], SCOPE_SIZE) == -1)
            return -1;
    }

    in->players = ndeck;
    in->timecoders = ndeck;

    in->rig = rig;
    selector_init(&in->selector, lib);
    calculate_spinner_lookup(spinner_angle, NULL, SPINNER_SIZE);

    fprintf(stderr, "Initialising SDL...\n");

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) {
        fprintf(stderr, "%s\n", SDL_GetError());
        return -1;
    }
    SDL_WM_SetCaption(banner, NULL);
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    /* Initialise the fonts */

    if (TTF_Init() == -1) {
        fprintf(stderr, "%s\n", TTF_GetError());
        return -1;
    }

    if (load_fonts() == -1)
        return -1;

    fprintf(stderr, "Launching interface thread...\n");

    if (pthread_create(&in->ph, NULL, launch, (void*)in)) {
        perror("pthread_create");
        return -1;
    }

    return 0;
}

/*
 * Synchronise with the SDL interface and exit
 */

void interface_stop(struct interface_t *in)
{
    size_t n;
    SDL_Event quit;

    quit.type = SDL_USEREVENT;
    quit.user.code = EVENT_QUIT;
    if (SDL_PushEvent(&quit) == -1)
        abort();

    if (pthread_join(in->ph, NULL) != 0)
        abort();

    for (n = 0; n < in->timecoders; n++)
        timecoder_monitor_clear(in->timecoder[n]);

    selector_clear(&in->selector);

    clear_fonts();

    TTF_Quit();
    SDL_Quit();
}