File: sj-main.c

package info (click to toggle)
sound-juicer 3.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,264 kB
  • ctags: 1,014
  • sloc: sh: 11,456; ansic: 8,534; xml: 805; makefile: 229
file content (2490 lines) | stat: -rw-r--r-- 85,313 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
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
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
/*
 * Copyright (C) 2003 Ross Burton <ross@burtonini.com>
 *
 * Sound Juicer - sj-main.c
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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 for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: Ross Burton <ross@burtonini.com>
 *          Mike Hearn  <mike@theoretic.com>
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "sound-juicer.h"

#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include <glib/gi18n.h>
#include <gdk/gdkkeysyms.h>
#include <gio/gio.h>
#include <gtk/gtk.h>
#include <brasero-medium-selection.h>
#include <brasero-volume.h>
#include <gst/gst.h>
#include <gst/pbutils/encoding-profile.h>

#include "sj-cell-renderer-text.h"
#include "rb-gst-media-types.h"
#include "sj-about.h"
#include "sj-metadata.h"
#include "sj-metadata-getter.h"
#include "sj-extractor.h"
#include "sj-structures.h"
#include "sj-error.h"
#include "sj-util.h"
#include "sj-main.h"
#include "sj-prefs.h"
#include "sj-play.h"
#include "sj-genres.h"
#include "sj-window-state.h"

gboolean on_delete_event (GtkWidget *widget, GdkEvent *event, gpointer user_data);

static void reread_cd (gboolean ignore_no_media);
static void update_ui_for_album (AlbumDetails *album);
static gboolean get_action_state_bool (const char *name);
static void set_action_state (const char *detailed_name);

/* Prototypes for the signal blocking/unblocking in update_ui_for_album */
G_MODULE_EXPORT void on_title_edit_changed(GtkEditable *widget, gpointer user_data);
G_MODULE_EXPORT void on_person_edit_changed(GtkEditable *widget, gpointer user_data);
G_MODULE_EXPORT void on_year_edit_changed(GtkEditable *widget, gpointer user_data);
G_MODULE_EXPORT void on_disc_number_edit_changed(GtkEditable *widget, gpointer user_data);
G_MODULE_EXPORT void submit_bar_response_cb (GtkInfoBar *infobar, int response_id, gpointer user_data);
G_MODULE_EXPORT void on_activate_move_focus (GtkWidget *widget, gpointer data);

GtkBuilder *builder;

SjMetadataGetter *metadata;
SjExtractor *extractor;

GSettings *sj_settings;

GtkWidget *main_window;
static GtkWidget *submit_bar, *submit_label;
static GtkWidget *title_entry, *artist_entry, *composer_label, *composer_entry, *duration_label, *genre_entry, *year_entry, *disc_number_entry;
static GtkWidget *entry_table; /* GtkTable containing composer_entry */
static GtkTreeViewColumn *composer_column; /* Treeview column containing composers */
static GtkWidget *track_listview, *extract_button, *play_button, *select_button;
static GtkWidget *status_bar;
GtkListStore *track_store;
GtkCellRenderer *toggle_renderer, *title_renderer, *artist_renderer, *composer_renderer;

char *path_pattern, *file_pattern;
GFile *base_uri;
BraseroDrive *drive = NULL;
gboolean strip_chars;
gboolean eject_finished;
gboolean open_finished;
gboolean extracting = FALSE;
static gboolean duplication_enabled;

static gint total_no_of_tracks;
static gint no_of_tracks_selected;
static AlbumDetails *current_album;
static char *current_submit_url = NULL;

gboolean autostart = FALSE, autoplay = FALSE;
static char *device = NULL, **uris = NULL;

static guint debug_flags = 0;

/**
 * Shared state for cell editing callbacks
 */
typedef struct {
  GtkTreePath* editable_path;
  char* text;
  ViewColumn column;
} CellCbContext;

static CellCbContext cell_editing_context;

#define DEFAULT_PARANOIA 15
#define RAISE_WINDOW "raise-window"
#define SOURCE_BUILDER "../data/sound-juicer.ui"
#define INSTALLED_BUILDER DATADIR"/sound-juicer/sound-juicer.ui"
#define SOURCE_MENU_BUILDER "../data/sound-juicer-menu.ui"
#define INSTALLED_MENU_BUILDER DATADIR"/sound-juicer/sound-juicer-menu.ui"
#define COMPOSER_ROW 2 /* Row of entry_table containing composer_entry */

void
sj_main_set_title (const char* detail)
{
  if (detail == NULL) {
    gtk_window_set_title (GTK_WINDOW (main_window), _("Sound Juicer"));
  } else {
    char *s = g_strdup_printf ("%s - %s", detail, _("Sound Juicer"));
    gtk_window_set_title (GTK_WINDOW (main_window), s);
    g_free (s);
  }
}

void sj_debug (SjDebugDomain domain, const gchar* format, ...)
{
  va_list args;
  gchar *string;

  if (debug_flags & domain) {
    va_start (args, format);
    string = g_strdup_vprintf (format, args);
    va_end (args);
    g_printerr ("%s", string);
    g_free (string);
  }
}

static void sj_debug_init (void)
{
  const char *str;
  const GDebugKey debug_keys[] = {
    { "cd", DEBUG_CD },
    { "metadata", DEBUG_METADATA },
    { "playing", DEBUG_PLAYING },
    { "extracting", DEBUG_EXTRACTING }
  };

  str = g_getenv ("SJ_DEBUG");
  if (str) {
    debug_flags = g_parse_debug_string (str, debug_keys, G_N_ELEMENTS (debug_keys));
  }
}

static void error_on_start (GError *error)
{
  GtkWidget *dialog;
  dialog = gtk_message_dialog_new_with_markup (NULL, 0,
                                               GTK_MESSAGE_ERROR,
                                               GTK_BUTTONS_CLOSE,
                                               "<b>%s</b>\n\n%s: %s.\n%s",
                                               _("Could not start Sound Juicer"),
                                               _("Reason"),
                                               error->message,
                                               _("Please consult the documentation for assistance."));
  gtk_dialog_run (GTK_DIALOG (dialog));
}

/**
 * Clicked Quit
 */
static void on_quit_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  if (on_delete_event (NULL, NULL, NULL) == FALSE) {
    gtk_widget_destroy (GTK_WIDGET (main_window));
  }
}

/**
 * Clicked Eject
 */
static void on_eject_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  /* first make sure we're not playing */
  stop_playback ();
  set_action_state ("re-read(false)");
  brasero_drive_eject (drive, FALSE, NULL);
}

G_MODULE_EXPORT gboolean on_delete_event (GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
  if (extracting) {
    GtkWidget *dialog;
    int response;

    dialog = gtk_message_dialog_new (GTK_WINDOW (main_window), GTK_DIALOG_MODAL,
                                     GTK_MESSAGE_QUESTION,
                                     GTK_BUTTONS_NONE,
                                     _("You are currently extracting a CD. Do you want to quit now or continue?"));
    gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Quit"), GTK_RESPONSE_ACCEPT);
    gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Continue"), GTK_RESPONSE_REJECT);
    gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_REJECT);
    response = gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);

    if (response == GTK_RESPONSE_ACCEPT) {
      return FALSE;
    }
    return TRUE;
  }
  return FALSE;
}

static gboolean select_all_foreach_cb (GtkTreeModel *model,
                                      GtkTreePath *path,
                                      GtkTreeIter *iter,
                                      gpointer data)
{
  gboolean b = (gboolean)GPOINTER_TO_INT (data);
  gtk_list_store_set (track_store, iter, COLUMN_EXTRACT, b, -1);
  return FALSE;
}

static void on_play_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  toggle_play ();
}

static void on_next_track_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  play_next_track ();
}

static void on_previous_track_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  play_previous_track ();
}

static void on_select_all_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  gtk_tree_model_foreach (GTK_TREE_MODEL (track_store), select_all_foreach_cb, GINT_TO_POINTER (TRUE));
  gtk_widget_set_sensitive (extract_button, TRUE);

  set_action_enabled ("select-all", FALSE);
  set_action_enabled ("deselect-all", TRUE);

  gtk_actionable_set_action_name(GTK_ACTIONABLE(select_button), "win.deselect-all");
  gtk_button_set_label(GTK_BUTTON(select_button), _("Select None"));

  no_of_tracks_selected = total_no_of_tracks;
}

static void on_deselect_all_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  gtk_tree_model_foreach (GTK_TREE_MODEL (track_store), select_all_foreach_cb, GINT_TO_POINTER (FALSE));
  gtk_widget_set_sensitive (extract_button, FALSE);

  set_action_enabled ("deselect-all", FALSE);
  set_action_enabled ("select-all", TRUE);

  gtk_actionable_set_action_name(GTK_ACTIONABLE(select_button), "win.select-all");
  gtk_button_set_label(GTK_BUTTON(select_button), _("Select All"));

  no_of_tracks_selected = 0;
}

/**
 * GtkTreeView cell renderer callback to render durations
 */
static void duration_cell_data_cb (GtkTreeViewColumn *tree_column,
                                GtkCellRenderer *cell,
                                GtkTreeModel *tree_model,
                                GtkTreeIter *iter,
                                gpointer data)
{
  int duration;
  char *string;

  gtk_tree_model_get (tree_model, iter, COLUMN_DURATION, &duration, -1);
  if (duration != 0) {
    string = g_strdup_printf("%d:%02d", duration / 60, duration % 60);
  } else {
    string = g_strdup(_("(unknown)"));
  }
  g_object_set (G_OBJECT (cell), "text", string, NULL);
  g_free (string);
}

static void number_cell_icon_data_cb (GtkTreeViewColumn *tree_column,
                                      GtkCellRenderer *cell,
                                      GtkTreeModel *tree_model,
                                      GtkTreeIter *iter,
                                      gpointer data)
{
  TrackState state;
  gtk_tree_model_get (tree_model, iter, COLUMN_STATE, &state, -1);
  switch (state) {
  case STATE_IDLE:
    g_object_set (G_OBJECT (cell), "icon-name", NULL, NULL);
    break;
  case STATE_PLAYING:
    {
      gboolean rtl = gtk_widget_get_direction (track_listview) == GTK_TEXT_DIR_RTL;
      gchar *name = rtl ? "media-playback-start-rtl" : "media-playback-start";
      g_object_set (G_OBJECT (cell), "icon-name", name, NULL);
    }
    break;
  case STATE_PAUSED:
    g_object_set (G_OBJECT (cell), "icon-name", "media-playback-pause", NULL);
    break;
  case STATE_EXTRACTING:
    g_object_set (G_OBJECT (cell), "icon-name", "media-record", NULL);
    break;
  default:
    g_warning("Unhandled track state %d\n", state);
  }
}

static void
set_submit_text (const AlbumDetails *album)
{
  gchar *text;

  if (g_str_equal (album->title, _("Unknown Title"))) {
    text = g_strdup (_("This album is not in the MusicBrainz database."));
  } else {
    text = g_strdup_printf (_("Could not find %s by %s on MusicBrainz."),
                                    album->title, album->artist);
  }
  gtk_label_set_text (GTK_LABEL (submit_label), text);
  g_free (text);
}

static void
submit_tracks_enabled_changed_cb (GActionGroup *action_group,
                                  gchar        *action_name,
                                  gboolean      enabled,
                                  gpointer      user_data)
{
  if (!enabled)
    gtk_widget_hide (submit_bar);
}

G_MODULE_EXPORT void
submit_bar_response_cb (GtkInfoBar *infobar,
                        int         response_id,
                        gpointer    user_data)
{
  gtk_widget_hide (GTK_WIDGET (infobar));
}

/**
 * Clicked the Submit menu item in the UI
 */
static void on_submit_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  GError *error = NULL;

  if (current_submit_url) {
      if (!gtk_show_uri (NULL, current_submit_url, GDK_CURRENT_TIME, &error)) {
      GtkWidget *dialog;

      dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (main_window),
                                                   GTK_DIALOG_DESTROY_WITH_PARENT,
                                                   GTK_MESSAGE_ERROR,
                                                   GTK_BUTTONS_CLOSE,
                                                   "<b>%s</b>\n\n%s\n%s: %s",
                                                   _("Could not open URL"),
                                                   _("Sound Juicer could not open the submission URL"),
                                                   _("Reason"),
                                                   error->message);
      gtk_dialog_run (GTK_DIALOG (dialog));
      gtk_widget_destroy (dialog);
      g_error_free (error);
    }
  }
  gtk_widget_hide (GTK_WIDGET (submit_bar));
}

static void on_preferences_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  show_preferences_dialog ();
}

static void on_about_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  show_about_dialog ();
}

/**
 * Clicked on duplicate in the UI (button/menu)
 */
static void on_duplicate_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  GError *error = NULL;
  const gchar* device;

  device = brasero_drive_get_device (drive);
  if (!g_spawn_command_line_async (g_strconcat ("brasero -c ", device, NULL), &error)) {
      GtkWidget *dialog;

      dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (main_window),
                                                   GTK_DIALOG_DESTROY_WITH_PARENT,
                                                   GTK_MESSAGE_ERROR,
                                                   GTK_BUTTONS_CLOSE,
                                                   "<b>%s</b>\n\n%s\n%s: %s",
                                                   _("Could not duplicate disc"),
                                                   _("Sound Juicer could not duplicate the disc"),
                                                   _("Reason"),
                                                   error->message);
      gtk_dialog_run (GTK_DIALOG (dialog));
      gtk_widget_destroy (dialog);
      g_error_free (error);
  }
}

#define TABLE_ROW_SPACING 6 /* spacing of rows in entry_table */

/*
 * Show composer entry and composer column in track listview
 */
static void
show_composer_fields (void)
{
  if (!gtk_widget_get_visible (GTK_WIDGET (composer_label))) {
    gtk_table_set_row_spacing (GTK_TABLE (entry_table), COMPOSER_ROW,
                               TABLE_ROW_SPACING);
    gtk_widget_show (GTK_WIDGET (composer_entry));
    gtk_widget_show (GTK_WIDGET (composer_label));
    gtk_tree_view_column_set_visible (composer_column, TRUE);
  }
}

#undef TABLE_ROW_SPACING

/*
 * Hide composer entry and composer column in track listview
 */
static void
hide_composer_fields (void)
{
  if (gtk_widget_get_visible (GTK_WIDGET (composer_label))) {
    gtk_table_set_row_spacing (GTK_TABLE (entry_table), COMPOSER_ROW, 0);
    gtk_widget_hide (GTK_WIDGET (composer_entry));
    gtk_widget_hide (GTK_WIDGET (composer_label));
    gtk_tree_view_column_set_visible (composer_column, FALSE);
  }
}

/*
 * Determine if the composer fields should be shown based on genre,
 * always show composer fields if they are non-empty.
 */
static void
composer_show_hide (const char* genre)
{
  const static char *composer_genres[] = {
    N_("Classical"), N_("Lieder"), N_("Opera"), N_("Chamber"), N_("Musical")
  };  /* Genres for which the composer fields should be shown. */
#define COUNT (G_N_ELEMENTS (composer_genres))
  static char *genres[COUNT]; /* store localized genre names */
  static gboolean init = FALSE; /* TRUE if localized genre names initalized*/
  gboolean composer_show = FALSE;
  int i;
  GList* l;
  char *folded_genre;

  if (composer_column == NULL)
    return;

  if (!init) {
    for (i = 0; i < COUNT; i++)
      genres[i] = g_utf8_casefold (gettext (composer_genres[i]), -1);

    init = TRUE;
  }

  composer_show = !sj_str_is_empty (current_album->composer);
  for (l = current_album->tracks; l; l = g_list_next (l)) {
    if (!sj_str_is_empty (((TrackDetails*) (l->data))->composer) == TRUE) {
      composer_show = TRUE;
      break;
    }
  }

  folded_genre = g_utf8_casefold (genre, -1);
  for (i = 0; i < COUNT; i++) {
    if (g_str_equal (folded_genre, genres[i])) {
      composer_show = TRUE;
      break;
    }
  }
  g_free (folded_genre);

  if (composer_show)
    show_composer_fields ();
  else
    hide_composer_fields ();
  return;
}
#undef COUNT

/**
 * Utility function to update the UI for a given Album
 */
static void update_ui_for_album (AlbumDetails *album)
{
  GList *l;
  int album_duration = 0;
  char* duration_text;
  total_no_of_tracks=0;

  /* Really really make sure we don't have a playing title */
  sj_main_set_title (NULL);

  hide_composer_fields ();

  if (album == NULL) {
    gtk_list_store_clear (track_store);
    gtk_entry_set_text (GTK_ENTRY (title_entry), "");
    gtk_entry_set_text (GTK_ENTRY (artist_entry), "");
    gtk_entry_set_text (GTK_ENTRY (composer_entry), "");
    gtk_entry_set_text (GTK_ENTRY (genre_entry), "");
    gtk_entry_set_text (GTK_ENTRY (year_entry), "");
    gtk_entry_set_text (GTK_ENTRY (disc_number_entry), "");
    gtk_label_set_text (GTK_LABEL (duration_label), "");
    gtk_widget_set_sensitive (title_entry, FALSE);
    gtk_widget_set_sensitive (artist_entry, FALSE);
    gtk_widget_set_sensitive (composer_entry, FALSE);
    gtk_widget_set_sensitive (genre_entry, FALSE);
    gtk_widget_set_sensitive (year_entry, FALSE);
    gtk_widget_set_sensitive (disc_number_entry, FALSE);
    gtk_widget_set_sensitive (play_button, FALSE);
    gtk_widget_set_sensitive (extract_button, FALSE);
    set_action_enabled ("play", FALSE);
    set_action_enabled ("select-all", FALSE);
    set_action_enabled ("deselect-all", FALSE);
    set_action_enabled ("previous-track", FALSE);
    set_action_enabled ("next-track", FALSE);
    set_action_enabled ("duplicate", FALSE);
  } else {
    gtk_list_store_clear (track_store);

    g_signal_handlers_block_by_func (title_entry, on_title_edit_changed, NULL);
    g_signal_handlers_block_by_func (artist_entry, on_person_edit_changed, NULL);
    g_signal_handlers_block_by_func (composer_entry, on_person_edit_changed, NULL);
    g_signal_handlers_block_by_func (year_entry, on_year_edit_changed, NULL);
    g_signal_handlers_block_by_func (disc_number_entry, on_disc_number_edit_changed, NULL);
    gtk_entry_set_text (GTK_ENTRY (title_entry), album->title);
    gtk_entry_set_text (GTK_ENTRY (artist_entry), album->artist);
    if (!sj_str_is_empty (album->composer)) {
      gtk_entry_set_text (GTK_ENTRY (composer_entry), album->composer);
      show_composer_fields ();
    } else {
      gtk_entry_set_text (GTK_ENTRY (composer_entry), "");
    }
    if (album->disc_number) {
      gchar *disc_number = g_strdup_printf ("%d", album->disc_number);
      gtk_entry_set_text (GTK_ENTRY (disc_number_entry), disc_number);
      g_free (disc_number);
    }
    if (album->release_date && gst_date_time_has_year (album->release_date)) {
      gchar *release_date =  g_strdup_printf ("%d", gst_date_time_get_year (album->release_date));
      gtk_entry_set_text (GTK_ENTRY (year_entry), release_date);
      g_free (release_date);
    }
    g_signal_handlers_unblock_by_func (title_entry, on_title_edit_changed, NULL);
    g_signal_handlers_unblock_by_func (artist_entry, on_person_edit_changed, NULL);
    g_signal_handlers_unblock_by_func (composer_entry, on_person_edit_changed, NULL);
    g_signal_handlers_unblock_by_func (year_entry, on_year_edit_changed, NULL);
    g_signal_handlers_unblock_by_func (disc_number_entry, on_disc_number_edit_changed, NULL);
    /* Clear the genre field, it's from the user */
    gtk_entry_set_text (GTK_ENTRY (genre_entry), "");

    gtk_widget_set_sensitive (title_entry, TRUE);
    gtk_widget_set_sensitive (artist_entry, TRUE);
    gtk_widget_set_sensitive (composer_entry, TRUE);
    gtk_widget_set_sensitive (genre_entry, TRUE);
    gtk_widget_set_sensitive (year_entry, TRUE);
    gtk_widget_set_sensitive (disc_number_entry, TRUE);
    gtk_widget_set_sensitive (play_button, TRUE);
    gtk_widget_set_sensitive (extract_button, TRUE);
    set_action_enabled ("play", TRUE);
    set_action_enabled ("select-all", FALSE);
    set_action_enabled ("deselect-all", TRUE);
    set_action_enabled ("previous-track", FALSE);
    set_action_enabled ("next-track", FALSE);
    set_action_enabled ("duplicate", TRUE);

    for (l = album->tracks; l; l=g_list_next (l)) {
      GtkTreeIter iter;
      TrackDetails *track = (TrackDetails*)l->data;
      album_duration += track->duration;
      gtk_list_store_append (track_store, &iter);
      gtk_list_store_set (track_store, &iter,
                          COLUMN_STATE, STATE_IDLE,
                          COLUMN_EXTRACT, TRUE,
                          COLUMN_NUMBER, track->number,
                          COLUMN_TITLE, track->title,
                          COLUMN_ARTIST, track->artist,
                          COLUMN_COMPOSER, track->composer,
                          COLUMN_DURATION, track->duration,
                          COLUMN_DETAILS, track,
                          -1);
      if (!sj_str_is_empty (track->composer))
        show_composer_fields ();
      total_no_of_tracks++;
    }
    no_of_tracks_selected=total_no_of_tracks;

    /* Some albums don't have track durations :( */
    if (album_duration) {
      duration_text = g_strdup_printf("%d:%02d", album_duration / 60, album_duration % 60);
      gtk_label_set_text (GTK_LABEL (duration_label), duration_text);
      g_free (duration_text);
    } else {
      gtk_label_set_text (GTK_LABEL (duration_label), _("(unknown)"));
    }
    /* If album details don't come from MusicBrainz ask user to add them */
    if (album->metadata_source != SOURCE_MUSICBRAINZ) {
      set_submit_text (album);
      gtk_widget_show (submit_bar);
    }
  }
}

/**
 * Callback that gets fired when a user double clicks on a row
 */
static void album_row_activated (GtkTreeView *treeview,
                                 GtkTreePath *arg1,
                                 GtkTreeViewColumn *arg2,
                                 gpointer user_data)
{
  GtkDialog *dialog = GTK_DIALOG (user_data);
  gtk_dialog_response (dialog, GTK_RESPONSE_OK);
}

/**
 * Callback that gets fired when an the selection changes. We use this to
 * change the sensitivity of the continue button
 */
static void selected_album_changed (GtkTreeSelection *selection,
                                    gpointer *user_data)
{
  GtkWidget *ok_button = GTK_WIDGET (user_data);

  if (gtk_tree_selection_get_selected (selection, NULL, NULL)) {
    gtk_widget_set_sensitive (ok_button, TRUE);
  } else {
    gtk_widget_set_sensitive (ok_button, FALSE);
  }
}


/**
 * NULL safe utility to collate utf8 strings
 */
static gint collate (const char *a, const char *b)
{
  gint ret_val = 0;

  if (a) {
    if (b) {
      ret_val = g_utf8_collate (a, b);
    } else {
      ret_val = 1;
    }
  } else if (b) {
    ret_val = -1;
  }
  return ret_val;
}

static gint sj_gst_date_time_compare_field (GstDateTime *lhs, GstDateTime *rhs,
                                            gboolean (*has_field) (const GstDateTime *datetime),
                                            gint (*get_field) (const GstDateTime *datetime))
{
  gint field_lhs = -1;
  gint field_rhs = -1;

  if (has_field (lhs)) {
    field_lhs = get_field (lhs);
  }
  if (has_field (rhs)) {
    field_rhs = get_field (rhs);
  }

  return (field_lhs - field_rhs);
}

static gint sj_gst_date_time_compare (gpointer lhs, gpointer rhs)
{
  GstDateTime *date_lhs = (GstDateTime *)lhs;
  GstDateTime *date_rhs = (GstDateTime *)rhs;

  int comparison;

  comparison = sj_gst_date_time_compare_field (date_lhs, date_rhs,
                                               gst_date_time_has_year,
                                               gst_date_time_get_year);
  if (comparison != 0) {
      return comparison;
  }

  comparison = sj_gst_date_time_compare_field (date_lhs, date_rhs,
                                               gst_date_time_has_month,
                                               gst_date_time_get_month);
  if (comparison != 0) {
      return comparison;
  }

  comparison = sj_gst_date_time_compare_field (date_lhs, date_rhs,
                                               gst_date_time_has_day,
                                               gst_date_time_get_day);

  return comparison;
}

/**
 * Utility function to sort albums in multiple_album_dialog
 */
static gint sort_release_info (GtkTreeModel *model, GtkTreeIter *a,
                               GtkTreeIter *b, gpointer user_data)
{
  AlbumDetails *album_a, *album_b;
  GList *label_a, *label_b;
  gint ret_val = 0;
  const gint column = GPOINTER_TO_INT (user_data);

  gtk_tree_model_get (model, a, column, &album_a, -1);
  gtk_tree_model_get (model, b, column, &album_b, -1);

  ret_val = collate (album_a->title, album_b->title);
  if (ret_val)
    return ret_val;

  ret_val = collate (album_a->artist_sortname, album_b->artist_sortname);
  if (ret_val)
    return ret_val;

  ret_val = collate (album_a->country, album_b->country);
  if (ret_val)
    return ret_val;

  if (album_a->release_date) {
    if (album_b->release_date) {
      ret_val = sj_gst_date_time_compare (album_a->release_date, album_b->release_date);
      if (ret_val)
        return ret_val;
    } else {
      return -1;
    }
  } else if (album_b->release_date) {
    return 1;
  }

  label_a = album_a->labels;
  label_b = album_b->labels;
  while (label_a && label_b) {
    LabelDetails *a = label_a->data;
    LabelDetails *b = label_b->data;
    ret_val = collate (a->sortname,b->sortname);
    if (ret_val)
      return ret_val;

    label_a = label_a->next;
    label_b = label_b->next;
  }
  if (label_a && !label_b)
    return -1;
  if (!label_a && label_b)
    return 1;

  ret_val = (album_a->disc_number < album_b->disc_number) ? -1 :
    ((album_a->disc_number > album_b->disc_number) ? 1 : 0);
  if (ret_val)
    return ret_val;

  return (album_a->disc_count < album_b->disc_count) ? -1 :
    ((album_a->disc_count > album_b->disc_count) ? 1 : 0);
}


/**
 * Utility function to format label string for multiple_album_dialog
 */
static GString* format_label_text (GList* labels)
{
  int count;
  GString *label_text;

  if (labels == NULL)
    return NULL;

  label_text = g_string_new (NULL);
  count = g_list_length (labels);
  while (count > 2) {
    g_string_append (label_text, ((LabelDetails*)labels->data)->name);
    g_string_append (label_text, ", ");
    labels = labels->next;
    count--;
  }

  if (count > 1) {
    g_string_append (label_text, ((LabelDetails*)labels->data)->name);
    g_string_append (label_text, " & ");
    labels = labels->next;
  }

  g_string_append (label_text, ((LabelDetails*)labels->data)->name);

  return label_text;
}

/**
 * Utility function for multiple_album_dialog to format the
 * release label, date and country.
 */
static char *format_release_details (AlbumDetails *album)
{
  gchar *details;
  GString *label_text = NULL;

  if (album->labels)
    label_text = format_label_text (album->labels);

  if (!sj_str_is_empty (album->country)) {
    if (album->labels) {
      if (album->release_date && gst_date_time_has_year (album->release_date)) {
        /* Translators: this string appears when multiple CDs were
         * found in musicbrainz online database, it corresponds to
         * "Released: <country> in <year> on <label>" */
        details = g_strdup_printf (_("Released: %s in %d on %s"),
                                   album->country,
                                   gst_date_time_get_year (album->release_date),
                                   label_text->str);
      } else {
        /* Translators: this string appears when multiple CDs were
         * found in musicbrainz online database, it corresponds to
         * "Released: <country> on <label>" */
        details = g_strdup_printf (_("Released: %s on %s"), album->country, label_text->str);
      }
    } else if (album->release_date && gst_date_time_has_year (album->release_date)) {
      /* Translators: this string appears when multiple CDs were
       * found in musicbrainz online database, it corresponds to
       * "Released: <country> in <year>" */
      details = g_strdup_printf (_("Released: %s in %d"), album->country,
                                 gst_date_time_get_year (album->release_date));
    } else {
      /* Translators: this string appears when multiple CDs were
       * found in musicbrainz online database, it corresponds to
       * "Released: <country>" */
      details = g_strdup_printf (_("Released: %s"), album->country);
    }
  } else if (album->release_date && gst_date_time_has_year (album->release_date)) {
    if (album->labels) {
        /* Translators: this string appears when multiple CDs were
         * found in musicbrainz online database, it corresponds to
         * "Released in <year> on <label>" */
        details = g_strdup_printf (_("Released in %d on %s"),
                                   gst_date_time_get_year (album->release_date),
                                   label_text->str);
    } else {
        /* Translators: this string appears when multiple CDs were
         * found in musicbrainz online database, it corresponds to
         * "Released in <year>" */
        details = g_strdup_printf(_("Released in %d"),
                                  gst_date_time_get_year (album->release_date));
    }
  } else if (album->labels) {
    /* Translators: this string appears when multiple CDs were
     * found in musicbrainz online database, it corresponds to
     * "Released on <label>" */
    details = g_strdup_printf (_("Released on %s"), label_text->str);
  } else {
    details = _("Release label, year & country unknown");
  }

  if (label_text)
    g_string_free (label_text, TRUE);

  return details;
}

/**
 * Utility function for when there are more than one albums available
 */
AlbumDetails* multiple_album_dialog(GList *albums)
{
  static GtkWidget *dialog = NULL, *albums_listview;
  static GtkListStore *albums_store;
  static GtkTreeSelection *selection;
  AlbumDetails *album;
  GtkTreeIter iter;
  int response;
  GtkWidget *ok_button = NULL;
  enum COLUMNS
  {
    COLUMN_RELEASE,
    COLUMN_DETAILS,
    COLUMN_COUNT
  };

  if (dialog == NULL) {
    GtkTreeViewColumn *column = gtk_tree_view_column_new ();
    GtkCellRenderer *renderer = gtk_cell_renderer_text_new ();

    dialog = GET_WIDGET ("multiple_dialog");
    g_assert (dialog != NULL);
    gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (main_window));
    albums_listview = GET_WIDGET ("albums_listview");
    ok_button       = GET_WIDGET ("ok_button");

    gtk_tree_view_column_set_title (column, _("Albums"));
    gtk_tree_view_column_pack_start (column, renderer, TRUE);
    gtk_tree_view_column_add_attribute (column, renderer,
                                        "markup", COLUMN_RELEASE);

    g_signal_connect (albums_listview, "row-activated",
                      G_CALLBACK (album_row_activated), dialog);

    albums_store = gtk_list_store_new (COLUMN_COUNT,
                                       G_TYPE_STRING,
                                       G_TYPE_POINTER);
    gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (albums_store),
                                     COLUMN_DETAILS, sort_release_info,
                                     GINT_TO_POINTER (COLUMN_DETAILS), NULL);
    gtk_tree_view_append_column (GTK_TREE_VIEW (albums_listview), column);

    gtk_tree_view_set_model (GTK_TREE_VIEW (albums_listview),
                             GTK_TREE_MODEL (albums_store));
    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW (albums_listview));
    gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE);
    gtk_widget_set_sensitive (ok_button, FALSE);
    g_signal_connect (selection, "changed", (GCallback)selected_album_changed,
                      ok_button);
  }

  gtk_list_store_clear (albums_store);
  for (; albums ; albums = g_list_next (albums)) {
    GtkTreeIter iter;
    AlbumDetails *album = (AlbumDetails*)(albums->data);
    GString *album_title = g_string_new (album->title);
    gchar *release_details = format_release_details (album);
    gchar *markup;

    if (album->disc_number > 0 && album->disc_count > 1)
      g_string_append_printf (album_title,_(" (Disc %d/%d)"),
                              album->disc_number, album->disc_count);

    markup = g_markup_printf_escaped ("<b>%s</b>\n<i>%s</i>\n%s", album_title->str,
                                                                  album->artist,
                                                                  release_details);

    gtk_list_store_append (albums_store, &iter);
    gtk_list_store_set (albums_store, &iter,
                        COLUMN_RELEASE, markup,
                        COLUMN_DETAILS, album,
                        -1);
    g_free (markup);
    g_string_free (album_title, TRUE);
    g_free (release_details);
  }

  /* Sort the model */
  gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (albums_store),
                                        COLUMN_DETAILS, GTK_SORT_ASCENDING);

  /* Select the first album */
  if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (albums_store), &iter))
  {
    gtk_tree_selection_select_iter (selection, &iter);
  }

  gtk_widget_show_all (dialog);
  response = gtk_dialog_run (GTK_DIALOG (dialog));
  gtk_widget_hide (dialog);

  if (response == GTK_RESPONSE_DELETE_EVENT) {
    return NULL;
  }

  if (gtk_tree_selection_get_selected (selection, NULL, &iter)) {
    gtk_tree_model_get (GTK_TREE_MODEL (albums_store), &iter, COLUMN_DETAILS,
                        &album, -1);
    return album;
  } else {
    return NULL;
  }
}

/**
 * The GSettings key for the base path changed
 */
static void baseuri_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  gchar *value;
  g_assert (strcmp (key, SJ_SETTINGS_BASEURI) == 0);
  if (base_uri) {
    g_object_unref (base_uri);
  }
  value = g_settings_get_string (settings, key);
  if (sj_str_is_empty (value)) {
    base_uri = sj_get_default_music_directory ();
  } else {
    GFileType file_type;
    base_uri = g_file_new_for_uri (value);
    file_type = g_file_query_file_type (base_uri, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL);
    if (file_type != G_FILE_TYPE_DIRECTORY) {
      g_object_unref (base_uri);
      base_uri = sj_get_default_music_directory ();
    }
  }
  g_free (value);
}

/**
 * The GSettings key for the directory pattern changed
 */
static void path_pattern_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_PATH_PATTERN) == 0);
  g_free (path_pattern);
  path_pattern = g_settings_get_string (settings, key);
  if (sj_str_is_empty (path_pattern)) {
    g_free (path_pattern);
    path_pattern = g_strdup (sj_get_default_path_pattern ());
  }
  /* TODO: sanity check the pattern */
}

/**
 * The GSettings key for the filename pattern changed
 */
static void file_pattern_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_FILE_PATTERN) == 0);
  g_free (file_pattern);
  file_pattern = g_settings_get_string (settings, key);
  if (sj_str_is_empty (file_pattern)) {
    g_free (file_pattern);
    file_pattern = g_strdup (sj_get_default_file_pattern ());
  }
  /* TODO: sanity check the pattern */
}

/**
 * The GSettings key for the paranoia mode has changed
 */
static void paranoia_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  int value;
  g_assert (strcmp (key, SJ_SETTINGS_PARANOIA) == 0);
  value = g_settings_get_flags (settings, key);
  if (value >= 0) {
    if (value < 32) {
      sj_extractor_set_paranoia (extractor, value);
    } else {
      sj_extractor_set_paranoia (extractor, DEFAULT_PARANOIA);
    }
  }
}

/**
 * The GSettings key for the strip characters option changed
 */
static void strip_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_STRIP) == 0);
  strip_chars = g_settings_get_boolean (settings, key);
}

/**
 * The GSettings key for the eject when finished option changed
 */
static void eject_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_EJECT) == 0);
  eject_finished = g_settings_get_boolean (settings, key);
}

/**
 * The GSettings key for the open when finished option changed
 */
static void open_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_OPEN) == 0);
  open_finished = g_settings_get_boolean (settings, key);
}

/**
 * The GSettings key for audio volume changes
 */
static void audio_volume_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  g_assert (strcmp (key, SJ_SETTINGS_AUDIO_VOLUME) == 0);

  GtkWidget *volb = GET_WIDGET ("volume_button");
  gtk_scale_button_set_value (GTK_SCALE_BUTTON (volb), g_settings_get_double (settings, key));
}

static void
metadata_cb (SjMetadataGetter *m, GList *albums, GError *error)
{
  gboolean realized = gtk_widget_get_realized (main_window);

  set_action_state ("re-read(false)");

  if (realized)
    gdk_window_set_cursor (gtk_widget_get_window (main_window), NULL);
    /* Clear the statusbar message */
    gtk_statusbar_pop(GTK_STATUSBAR(status_bar), 0);

  if (error && !(error->code == SJ_ERROR_CD_NO_MEDIA)) {
    GtkWidget *dialog;

    dialog = gtk_message_dialog_new_with_markup (realized ? GTK_WINDOW (main_window) : NULL, 0,
                                                 GTK_MESSAGE_ERROR,
                                                 GTK_BUTTONS_CLOSE,
                                                 "<b>%s</b>\n\n%s\n%s: %s",
                                                 _("Could not read the CD"),
                                                 _("Sound Juicer could not read the track listing on this CD."),
                                                 _("Reason"),
                                                 error->message);
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    update_ui_for_album (NULL);
    return;
  }

  g_free (current_submit_url);
  current_submit_url = sj_metadata_getter_get_submit_url (metadata);
  if (current_submit_url) {
    set_action_enabled ("submit-tracks", TRUE);
  }
  set_action_enabled ("re-read", TRUE);

  /* Free old album details */
  if (current_album != NULL) {
    album_details_free (current_album);
    current_album = NULL;
  }
  /* Set the new current album pointer */
  if (albums == NULL) {
    current_album = NULL;
  } else if (g_list_next (albums)) {
    current_album = multiple_album_dialog (albums);
    /* Concentrate here. We remove the album we want from the list, and then
       deep-free the list. */
    albums = g_list_remove (albums, current_album);
    g_list_free_full (albums, (GDestroyNotify)album_details_free);
    albums = NULL;
  } else {
    current_album = albums->data;
    /* current_album now owns ->data, so just free the list */
    g_list_free (albums);
    albums = NULL;
  }
  update_ui_for_album (current_album);

  if (autostart) {
    g_signal_emit_by_name (extract_button, "activate", NULL);
    autostart = FALSE;
  }
  if (autoplay) {
    g_signal_emit_by_name (play_button, "activate", NULL);
    autoplay = FALSE;
  }
}

static gboolean
is_audio_cd (BraseroDrive *drive)
{
  BraseroMedium *medium;
  BraseroMedia type;

  medium = brasero_drive_get_medium (drive);
  if (medium == NULL) return FALSE;
  type = brasero_medium_get_status (medium);
  if (type == BRASERO_MEDIUM_UNSUPPORTED) {
    g_warning ("Error getting media type\n");
  }
  if (type == BRASERO_MEDIUM_BUSY) {
    g_warning ("BUSY getting media type, should re-check\n");
  }
  return BRASERO_MEDIUM_IS (type, BRASERO_MEDIUM_HAS_AUDIO|BRASERO_MEDIUM_CD);
}

/**
 * Utility function to reread a CD
 */
static void reread_cd (gboolean ignore_no_media)
{
  /* TODO: remove ignore_no_media? */
  GError *error = NULL;
  GdkCursor *cursor;
  GdkWindow *window;
  gboolean realized = gtk_widget_get_realized (main_window);

  window = gtk_widget_get_window (main_window);

  set_action_state ("re-read(true)");
  set_action_enabled ("re-read", FALSE);

  /* Make sure nothing is playing */
  stop_playback ();

  /* Set watch cursor */
  if (realized) {
    cursor = gdk_cursor_new_for_display (gtk_widget_get_display (GTK_WIDGET (main_window)), GDK_WATCH);
    gdk_window_set_cursor (window, cursor);
    g_object_unref (cursor);
    gdk_display_sync (gtk_widget_get_display (GTK_WIDGET (main_window)));
  }

  /* Set statusbar message */
  gtk_statusbar_push(GTK_STATUSBAR(status_bar), 0, _("Retrieving track listing...please wait."));

  if (!drive)
    sj_debug (DEBUG_CD, "Attempting to re-read NULL drive\n");

  g_free (current_submit_url);
  current_submit_url = NULL;
  set_action_enabled ("submit-tracks", FALSE);

  if (!is_audio_cd (drive)) {
    sj_debug (DEBUG_CD, "Media is not an audio CD\n");
    set_action_state ("re-read(false)");
    update_ui_for_album (NULL);
    gtk_statusbar_pop(GTK_STATUSBAR(status_bar), 0);
    if (realized)
      gdk_window_set_cursor (window, NULL);
    return;
  }

  sj_metadata_getter_list_albums (metadata, &error);

  if (error && !(error->code == SJ_ERROR_CD_NO_MEDIA && ignore_no_media)) {
    GtkWidget *dialog;

    dialog = gtk_message_dialog_new (realized ? GTK_WINDOW (main_window) : NULL, 0,
                                     GTK_MESSAGE_ERROR,
                                     GTK_BUTTONS_CLOSE,
                                     "%s", _("Could not read the CD"));
    gtk_message_dialog_format_secondary_markup (GTK_MESSAGE_DIALOG (dialog),
                                                "%s\n%s: %s",
                                                _("Sound Juicer could not read the track listing on this CD."),
                                                _("Reason"),
                                                error->message);

    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    g_error_free (error);
    update_ui_for_album (NULL);
    return;
  }
}

static void
media_added_cb (BraseroMediumMonitor	*drive,
		BraseroMedium		*medium,
                gpointer           	 data)
{
  if (extracting == TRUE) {
    /* FIXME: recover? */
  }

  sj_debug (DEBUG_CD, "Media added to device %s\n", brasero_drive_get_device (brasero_medium_get_drive (medium)));
  /* Don't call re-read if metadata is already being retreived */
  if (!get_action_state_bool ("re-read"))
    reread_cd (TRUE);
}

static void
media_removed_cb (BraseroMediumMonitor	*drive,
		  BraseroMedium		*medium,
                  gpointer           data)
{
  if (extracting == TRUE) {
    /* FIXME: recover? */
  }

  /* first make sure we're not playing */
  stop_playback ();

  sj_debug (DEBUG_CD, "Media removed from device %s\n", brasero_drive_get_device (brasero_medium_get_drive (medium)));
  stop_ui_hack ();
  update_ui_for_album (NULL);
  set_action_enabled ("submit-tracks", FALSE);
}

static void
set_drive_from_device (const char *device)
{
  BraseroMediumMonitor *monitor;

  if (drive) {
    g_object_unref (drive);
    drive = NULL;
  }

  if (! device)
    return;

  monitor = brasero_medium_monitor_get_default ();
  drive = brasero_medium_monitor_get_drive (monitor, device);
  if (! drive) {
    GtkWidget *dialog;
    char *message;
    message = g_strdup_printf (_("Sound Juicer could not use the CD-ROM device '%s'"), device);
    dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (main_window),
                                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                                                 GTK_MESSAGE_ERROR,
                                                 GTK_BUTTONS_CLOSE,
                                                 "<b>%s</b>\n\n%s",
                                                 message,
                                                 _("HAL daemon may not be running."));
    g_free (message);
    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);
    return;
  }

  g_signal_connect (monitor, "medium-added", G_CALLBACK (media_added_cb), NULL);
  g_signal_connect (monitor, "medium-removed", G_CALLBACK (media_removed_cb), NULL);
}

static void
set_device (const char* device, gboolean ignore_no_media)
{
  gboolean tray_opened;

  if (device == NULL) {
    set_drive_from_device (device);
  } else if (access (device, R_OK) != 0) {
    GtkWidget *dialog;
    char *message;
    const char *error;

    error = g_strerror (errno);
    message = g_strdup_printf (_("Sound Juicer could not access the CD-ROM device '%s'"), device);

    dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (main_window),
                                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                                                 GTK_MESSAGE_ERROR,
                                                 GTK_BUTTONS_CLOSE,
                                                 "<b>%s</b>\n\n%s\n%s: %s",
                                                 _("Could not read the CD"),
                                                 message,
                                                 _("Reason"),
                                                 error);
    g_free (message);

    gtk_dialog_run (GTK_DIALOG (dialog));
    gtk_widget_destroy (dialog);

    /* Set a null device */
    set_drive_from_device (NULL);
  } else {
    set_drive_from_device (device);
  }

  sj_metadata_getter_set_cdrom (metadata, device);
  sj_extractor_set_device (extractor, device);

  if (drive != NULL) {
    tray_opened = brasero_drive_is_door_open (drive);
    if (tray_opened == FALSE) {
      reread_cd (ignore_no_media);
    }

    /* Enable/disable the eject options based on wether the drive supports ejection */
    set_action_enabled ("eject", brasero_drive_can_eject (drive));
  }
}

gboolean cd_drive_exists (const char *device)
{
  BraseroMediumMonitor *monitor;
  BraseroDrive *drive;
  gboolean exists;

  if (device == NULL)
    return FALSE;

  monitor = brasero_medium_monitor_get_default ();
  drive = brasero_medium_monitor_get_drive (monitor, device);
  exists = (drive != NULL);
  if (exists)
    g_object_unref (drive);

  return exists;
}

const char *
prefs_get_default_device (void)
{
  static const char * default_device = NULL;

  if (default_device == NULL) {
    BraseroMediumMonitor *monitor;

    BraseroDrive *drive;
    GSList *drives;

    monitor = brasero_medium_monitor_get_default ();
    drives = brasero_medium_monitor_get_drives (monitor, BRASERO_DRIVE_TYPE_ALL);
    if (drives == NULL)
      return NULL;

    drive = drives->data;
    default_device = brasero_drive_get_device (drive);

    g_slist_free_full (drives, g_object_unref);
  }
  return default_device;
}

/**
 * The GSettings key for the device changed
 */
static void device_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  const char *device;
  char *value;
  gboolean ignore_no_media = GPOINTER_TO_INT (user_data);
  g_assert (strcmp (key, SJ_SETTINGS_DEVICE) == 0);

  value = g_settings_get_string (settings, key);
  if (!cd_drive_exists (value)) {
    device = prefs_get_default_device();
    if (device == NULL) {
#ifndef IGNORE_MISSING_CD
      GtkWidget *dialog;
      dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (main_window),
                                                   GTK_DIALOG_DESTROY_WITH_PARENT,
                                                   GTK_MESSAGE_ERROR,
                                                   GTK_BUTTONS_CLOSE,
                                                   "<b>%s</b>\n\n%s",
                                                   _("No CD-ROM drives found"),
                                                   _("Sound Juicer could not find any CD-ROM drives to read."));
      gtk_dialog_run (GTK_DIALOG (dialog));
      gtk_widget_destroy (dialog);
      exit (1);
#endif
    }
  } else {
    device = value;
  }
  set_device (device, ignore_no_media);
  g_free (value);
}

static void profile_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
  GstEncodingProfile *profile;
  char *media_type;

  g_assert (strcmp (key, SJ_SETTINGS_AUDIO_PROFILE) == 0);
  media_type = g_settings_get_string (settings, key);
  profile = rb_gst_get_encoding_profile (media_type);
  g_free (media_type);
  if (profile != NULL)
    g_object_set (extractor, "profile", profile, NULL);

  if (profile == NULL || !sj_extractor_supports_profile(profile)) {
    GtkWidget *dialog;
    int response;

    dialog = gtk_message_dialog_new (GTK_WINDOW (main_window),
                                     GTK_DIALOG_MODAL,
                                     GTK_MESSAGE_QUESTION,
                                     GTK_BUTTONS_NONE,
                                     _("The currently selected audio profile is not available on your installation."));
    gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Quit"), GTK_RESPONSE_REJECT);
    gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Change Profile"), GTK_RESPONSE_ACCEPT);
    gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
    response = gtk_dialog_run (GTK_DIALOG (dialog));
    if (response != GTK_RESPONSE_REJECT) {
      gtk_widget_destroy (dialog);
      show_preferences_dialog ();
    } else {
      /* Can't use gtk_main_quit here, we may be outside the main loop */
      exit(0);
    }
  }

  if (profile != NULL)
    gst_encoding_profile_unref (profile);
}

/**
 * Clicked on Reread in the UI (button/menu)
 */
static void on_reread_activate (GSimpleAction *action, GVariant *parameter, gpointer data)
{
  reread_cd (FALSE);
}

/**
 * Move focus to next widget when GtkEntry is activated
 */
G_MODULE_EXPORT void on_activate_move_focus (GtkWidget *widget,
                                             gpointer   data)
{
  gboolean ret_val;

  g_signal_emit_by_name (widget, "move-focus", GTK_DIR_TAB_FORWARD, &ret_val);
}

/**
 * If path is selected call func on all selected rows, if not call
 * func only on path.
 */
static void
tree_path_or_selection_foreach (GtkTreeView                 *tree_view,
                                GtkTreePath                 *path,
                                GtkTreeSelectionForeachFunc  func,
                                gpointer                     data)
{
  GtkTreeSelection *selection;

  selection = gtk_tree_view_get_selection (tree_view);
  if (gtk_tree_selection_path_is_selected (selection, path)) {
    gtk_tree_selection_selected_foreach (selection,
                                         func,
                                         data);
  } else {
    GtkTreeModel *model;
    GtkTreeIter iter;
    model = gtk_tree_view_get_model (tree_view);
    if (gtk_tree_model_get_iter (model, &iter, path))
      func (model, path, &iter, data);
  }
}

/**
 * Called by on_extract_toggled to update the Extract column for all
 * the selected rows
 */
static void
on_extract_toggled_foreach (GtkTreeModel *model,
                            GtkTreePath  *path,
                            GtkTreeIter  *iter,
                            gpointer      data)
{
  gboolean extract = GPOINTER_TO_INT (data);
  gboolean old_extract;

  gtk_tree_model_get (model, iter,
                      COLUMN_EXTRACT, &old_extract,
                      -1);
  if (extract != old_extract) {
    gtk_list_store_set (GTK_LIST_STORE (model), iter,
                        COLUMN_EXTRACT, extract,
                        -1);
    /* Update number of selected tracks */
    if (extract) {
      no_of_tracks_selected++;
    } else {
      no_of_tracks_selected--;
    }
  }
}

/**
 * Called when the user clicked on the Extract column check boxes
 */
static void
on_extract_toggled (GtkCellRendererToggle *cellrenderertoggle,
                    gchar                 *path_str,
                    gpointer               user_data)
{
  gboolean extract;
  GtkTreePath *path;
  GtkTreeIter iter;

  if (!gtk_tree_model_get_iter_from_string (GTK_TREE_MODEL (track_store),
                                            &iter,
                                            path_str))
      return;
  gtk_tree_model_get (GTK_TREE_MODEL (track_store), &iter,
                      COLUMN_EXTRACT, &extract,
                      -1);
  /* extract is the old state here, so toggle */
  extract = !extract;
  path = gtk_tree_path_new_from_string (path_str);
  tree_path_or_selection_foreach (GTK_TREE_VIEW (track_listview),
                                  path,
                                  on_extract_toggled_foreach,
                                  GINT_TO_POINTER (extract));
  gtk_tree_path_free (path);
  /* Update the Extract button */
  gtk_widget_set_sensitive (extract_button, no_of_tracks_selected > 0);
  /* Enable and disable the Select/Deselect All buttons */
  if (no_of_tracks_selected == total_no_of_tracks) {
    set_action_enabled ("deselect-all", TRUE);
    set_action_enabled ("select-all", FALSE);
  } else if (no_of_tracks_selected == 0) {
    set_action_enabled ("deselect-all", FALSE);
    set_action_enabled ("select-all", TRUE);
  } else {
    set_action_enabled ("select-all", TRUE);
    set_action_enabled ("deselect-all", TRUE);
  }
}

static void
on_cell_changed_foreach (GtkTreeModel *model,
                         GtkTreePath  *path,
                         GtkTreeIter  *iter,
                         gpointer      user_data)
{
  CellCbContext *context = user_data;

  /* Updating the model for the cell being edited aborts the edit so
     avoid it and set it in on_cell_editing_done instead */
  if (gtk_tree_path_compare (path, context->editable_path) != 0)
    gtk_list_store_set (GTK_LIST_STORE (model), iter,
                        context->column, context->text,
                        -1);
}

/**
 * Update the selected rows as the user types
 */
static void
on_cell_changed (GtkEditable *editable,
                 gpointer     user_data)
{
  CellCbContext *context = user_data;

  context->text = gtk_editable_get_chars (editable, 0, -1);
  tree_path_or_selection_foreach (GTK_TREE_VIEW (track_listview),
                                  context->editable_path,
                                  on_cell_changed_foreach,
                                  context);
  g_free (context->text);
}

static void
on_cell_editing_done_foreach (GtkTreeModel *model,
                              GtkTreePath  *path,
                              GtkTreeIter  *iter,
                              gpointer      user_data)
{
  CellCbContext *context = user_data;
  TrackDetails *track;

  /* COLUMN_DETAILS isn't updated during editing so update it now */
  gtk_tree_model_get (GTK_TREE_MODEL (track_store), iter,
                      COLUMN_DETAILS, &track,
                      -1);
  switch (context->column) {
  case COLUMN_TITLE:
    g_free (track->title);
    track->title = g_strdup (context->text);
    break;
  case COLUMN_ARTIST:
    g_free (track->artist);
    track->artist = g_strdup (context->text);
    if (track->artist_sortname) {
      g_free (track->artist_sortname);
      track->artist_sortname = NULL;
    }
    if (track->artist_id) {
      g_free (track->artist_id);
      track->artist_id = NULL;
    }
    break;
  case COLUMN_COMPOSER:
    g_free (track->composer);
    track->composer = g_strdup (context->text);
    if (track->composer_sortname) {
      g_free (track->composer_sortname);
      track->composer_sortname = NULL;
    }
    break;
  default:
    g_warning ("Unknown column %d in on_cell_editing_done_foreach",
               context->column);
  }
}

static void
on_cell_editing_canceled_foreach (GtkTreeModel *model,
                                  GtkTreePath  *path,
                                  GtkTreeIter  *iter,
                                  gpointer      user_data)
{
  CellCbContext *context = user_data;
  TrackDetails *track;
  char *text;

  /* COLUMN_DETAILS isn't updated during editing so get original
     values back from it. */
  gtk_tree_model_get (model, iter, COLUMN_DETAILS, &track, -1);
  switch (context->column) {
  case COLUMN_TITLE:
    text = track->title;
    break;
  case COLUMN_ARTIST:
    text = track->artist;
    break;
  case COLUMN_COMPOSER:
    text = track->composer;
    break;
  default:
    g_warning ("Unknown column %d in on_cell_editing_canceled_foreach",
               context->column);
    return;
  }
  gtk_list_store_set (track_store, iter, context->column, text, -1);
}

/**
 *  Called when the user finishes or cancels editing a track. Store
 *  changes/restore original values & disconnect callbacks on the
 *  GtkCellEditable.
 */
static void
on_cell_editing_done (GtkCellEditable *cell_editable,
                      gpointer         user_data)
{
  gboolean canceled;
  CellCbContext *context = user_data;

  g_signal_handlers_disconnect_by_data (cell_editable, context);
  g_object_get (G_OBJECT (cell_editable), "editing-canceled", &canceled, NULL);
  if (canceled) {
    tree_path_or_selection_foreach (GTK_TREE_VIEW (track_listview),
                                    context->editable_path,
                                    on_cell_editing_canceled_foreach,
                                    context);
  } else { /* We need to update the track details in COLUMN_DETAILS */
    GtkTreeIter iter;
    context->text = gtk_editable_get_chars (GTK_EDITABLE (cell_editable), 0, -1);
    /* Update the model for the cell that has been edited */
    gtk_tree_model_get_iter (GTK_TREE_MODEL (track_store),
                             &iter, context->editable_path);
    gtk_list_store_set (track_store, &iter, context->column, context->text, -1);
    /* Update COLUMN_DETAILS */
    tree_path_or_selection_foreach (GTK_TREE_VIEW (track_listview),
                                    context->editable_path,
                                    on_cell_editing_done_foreach,
                                    context);
    g_free (context->text);
  }
  gtk_tree_path_free (context->editable_path);
}

/**
 * Called when the user starts editing a track. Setup callbacks on the
 * GtkCellEditable to support editing multiple rows at once.
 */
static void
on_cell_editing_started (GtkCellRenderer *renderer,
                         GtkCellEditable *cell_editable,
                         gchar           *path,
                         gpointer         user_data)
{
  cell_editing_context.editable_path = gtk_tree_path_new_from_string (path);
  cell_editing_context.column = GPOINTER_TO_UINT (user_data);
  g_signal_connect (cell_editable, "changed",
                    G_CALLBACK (on_cell_changed), &cell_editing_context);
  g_signal_connect (cell_editable, "editing-done",
                    G_CALLBACK (on_cell_editing_done), &cell_editing_context);
}

/*
 * Remove all of the data which is intrinsic to the album being correctly
 * detected, such as MusicBrainz IDs, ASIN, and Wikipedia links.
 */
static void
remove_musicbrainz_ids (AlbumDetails *album)
{
  GList *l;
#define UNSET(id) g_free (album->id);           \
  album->id = NULL;

  UNSET (album_id);
  UNSET (artist_id);
  UNSET (asin);
  UNSET (discogs);
  UNSET (wikipedia);
#undef UNSET

#define UNSET(id) g_free (track->id);           \
  track->id = NULL;

  for (l = album->tracks; l; l = l->next) {
    TrackDetails *track = l->data;
    UNSET (track_id);
    UNSET (artist_id);
  }
#undef UNSET
}

G_MODULE_EXPORT void on_title_edit_changed(GtkEditable *widget, gpointer user_data) {
  g_return_if_fail (current_album != NULL);

  remove_musicbrainz_ids (current_album);

  if (current_album->title) {
    g_free (current_album->title);
  }
  current_album->title = gtk_editable_get_chars (widget, 0, -1); /* get all the characters */
}

/**
 * Return TRUE if s1 and s2 are equal according to g_utf8_casefold or
 * if they are NULL, NUL or just ascii space. NULL, NUL and space are
 * considered equal
 */
static gboolean str_case_equal (const char*s1, const char *s2)
{
  gboolean retval;
  char *t1, *t2;

  if (sj_str_is_empty (s1) && sj_str_is_empty (s2))
    return TRUE;

  /* is_empty can handle NULL pointers but g_utf8_casefold cannot */
  if (!s1 || !s2)
    return FALSE;

  t1 = g_utf8_casefold (s1, -1);
  t2 = g_utf8_casefold (s2, -1);
  retval = g_str_equal (t1, t2);
  g_free (t1);
  g_free (t2);
  return retval;
}

G_MODULE_EXPORT void on_person_edit_changed(GtkEditable *widget,
                                            gpointer user_data) {
  GtkTreeIter iter;
  gboolean ok; /* TRUE if iter is valid */
  TrackDetails *track;
  gchar *former_album_person = NULL;
  /* Album person name and sortname */
  gchar **album_person_name, **album_person_sortname;
  /* Offsets for track person name and sortname */
  int off_person_name, off_person_sortname;
  int column; /* column for person in listview */

  g_return_if_fail (current_album != NULL);

  if (widget == GTK_EDITABLE (artist_entry)) {
    column = COLUMN_ARTIST;
    album_person_name = &current_album->artist;
    album_person_sortname = &current_album->artist_sortname;
    off_person_name = G_STRUCT_OFFSET (TrackDetails, artist);
    off_person_sortname = G_STRUCT_OFFSET (TrackDetails,
                                           artist_sortname);
  } else if (widget == GTK_EDITABLE (composer_entry)) {
    column = COLUMN_COMPOSER;
    album_person_name = &current_album->composer;
    album_person_sortname = &current_album->composer_sortname;
    off_person_name = G_STRUCT_OFFSET (TrackDetails, composer);
    off_person_sortname = G_STRUCT_OFFSET (TrackDetails,
                                           composer_sortname);
  } else {
    g_warning (_("Unknown widget calling on_person_edit_changed."));
    return;
  }

  remove_musicbrainz_ids (current_album);

  /* Unset the sortname field, as we can't change it automatically */
  if (*album_person_sortname) {
    g_free (*album_person_sortname);
    *album_person_sortname = NULL;
  }

  if (*album_person_name) {
    former_album_person = *album_person_name;
  }

  /* get all the characters */
  *album_person_name = gtk_editable_get_chars (widget, 0, -1);

  /* Set the person field in each tree row */
  for (ok = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (track_store), &iter);
       ok;
       ok = gtk_tree_model_iter_next (GTK_TREE_MODEL (track_store), &iter)) {
    gchar *current_track_person;
    gchar **track_person_name, **track_person_sortname;

    gtk_tree_model_get (GTK_TREE_MODEL (track_store), &iter, column,
                        &current_track_person, -1);

    /* Change track person if it matched album person before the change */
    if (!str_case_equal (current_track_person, former_album_person) &&
        !str_case_equal (current_track_person, *album_person_name))
      continue;

    gtk_tree_model_get (GTK_TREE_MODEL (track_store), &iter, COLUMN_DETAILS,
                        &track, -1);
    track_person_name     = G_STRUCT_MEMBER_P (track, off_person_name);
    track_person_sortname = G_STRUCT_MEMBER_P (track, off_person_sortname);

    g_free (*track_person_name);
    *track_person_name = g_strdup (*album_person_name);

    /* Unset the sortname field, as we can't change it automatically */
    if (*track_person_sortname) {
      g_free (*track_person_sortname);
      *track_person_sortname = NULL;
    }

    gtk_list_store_set (track_store, &iter, column, *track_person_name, -1);
  }
  g_free (former_album_person);
}

G_MODULE_EXPORT void on_genre_edit_changed(GtkEditable *widget, gpointer user_data) {
  g_return_if_fail (current_album != NULL);
  if (current_album->genre) {
    g_free (current_album->genre);
  }
  current_album->genre = gtk_editable_get_chars (widget, 0, -1); /* get all the characters */
  /* Toggle visibility of composer fields based on genre */
  composer_show_hide (current_album->genre);
}

G_MODULE_EXPORT void on_year_edit_changed(GtkEditable *widget, gpointer user_data) {
  const gchar* yearstr;
  int year;

  g_return_if_fail (current_album != NULL);

  yearstr = gtk_entry_get_text (GTK_ENTRY (widget));
  year = atoi (yearstr);
  if (year > 0) {
    if (current_album->release_date) {
      gst_date_time_unref (current_album->release_date);
    }
    current_album->release_date = gst_date_time_new_y (year);
  }
}

G_MODULE_EXPORT void on_disc_number_edit_changed(GtkEditable *widget, gpointer user_data) {
    const gchar* discstr;
    int disc_number;

    g_return_if_fail (current_album != NULL);
    discstr = gtk_entry_get_text (GTK_ENTRY (widget));
    disc_number = atoi(discstr);
    current_album->disc_number = disc_number;
}

static void on_contents_activate(GSimpleAction *action, GVariant *parameter, gpointer data) {
  GError *error = NULL;

  gtk_show_uri (NULL, "help:sound-juicer", GDK_CURRENT_TIME, &error);
  if (error) {
    GtkWidget *dialog;

    dialog = gtk_message_dialog_new (GTK_WINDOW (main_window),
                                     GTK_DIALOG_DESTROY_WITH_PARENT,
                                     GTK_MESSAGE_ERROR,
                                     GTK_BUTTONS_CLOSE,
                                     _("Could not display help for Sound Juicer\n"
                                       "%s"),
                                     error->message);
    g_signal_connect_swapped (dialog, "response",
                              G_CALLBACK (gtk_widget_destroy),
                              dialog);
    gtk_widget_show (dialog);
    g_error_free (error);
  }
}

/**
 * Performs various checks to ensure CD duplication is available.
 * If this is found TRUE is returned, otherwise FALSE is returned.
 */
static gboolean
is_cd_duplication_available(void)
{
  /* First check the brasero tool is available in the path */
  gchar* brasero_cd_burner = g_find_program_in_path ("brasero");
  if (brasero_cd_burner == NULL) {
    return FALSE;
  }
  g_free(brasero_cd_burner);

  /* Second check the cdrdao tool is available in the path */
  gchar* cdrdao = g_find_program_in_path ("cdrdao");
  if (cdrdao == NULL) {
    return FALSE;
  }
  g_free(cdrdao);

  /* Now check that there is at least one cd recorder available */
  BraseroMediumMonitor     *monitor;
  GSList		   *drives;
  GSList		   *iter;

  monitor = brasero_medium_monitor_get_default ();
  drives = brasero_medium_monitor_get_drives (monitor, BRASERO_DRIVE_TYPE_ALL);

  for (iter = drives; iter; iter = iter->next) {
    BraseroDrive *drive;

    drive = iter->data;
    if (brasero_drive_can_write (drive)) {
      g_slist_free_full (drives, g_object_unref);
      return TRUE;
    }
  }

  g_slist_free_full (drives, g_object_unref);
  return FALSE;
}

GActionEntry app_entries[] = {
  { "re-read", on_reread_activate, NULL, "false", NULL },
  { "duplicate", on_duplicate_activate, NULL, NULL, NULL },
  { "eject", on_eject_activate, NULL, NULL, NULL },
  { "submit-tracks", on_submit_activate, NULL, NULL, NULL },
  { "preferences", on_preferences_activate, NULL, NULL, NULL },
  { "about", on_about_activate, NULL, NULL, NULL },
  { "help", on_contents_activate, NULL, NULL, NULL },
  { "quit", on_quit_activate, NULL, NULL, NULL }
};

GActionEntry win_entries[] = {
  { "play", on_play_activate, NULL, NULL, NULL },
  { "next-track", on_next_track_activate, NULL, NULL, NULL },
  { "previous-track", on_previous_track_activate, NULL, NULL, NULL },
  { "select-all", on_select_all_activate, NULL, NULL, NULL },
  { "deselect-all", on_deselect_all_activate, NULL, NULL, NULL }
};

static GtkCellRenderer*
add_editable_listview_column (const char       *title,
                              const ViewColumn  model_column)
{
  GtkCellRenderer *renderer;
  GtkTreeViewColumn *column;

  renderer = sj_cell_renderer_text_new ();
  g_signal_connect (renderer,
                    "editing-started",
                    G_CALLBACK (on_cell_editing_started),
                    GUINT_TO_POINTER (model_column));
  g_object_set (G_OBJECT (renderer), "editable", TRUE, NULL);
  column = gtk_tree_view_column_new_with_attributes (title, renderer,
                                                     "text", model_column,
                                                     NULL);
  gtk_tree_view_column_set_resizable (column, TRUE);
  gtk_tree_view_column_set_expand (column, TRUE);
  gtk_tree_view_append_column (GTK_TREE_VIEW (track_listview), column);
  return renderer;
}

static void
startup_cb (GApplication *app, gpointer user_data)
{
  GtkTreeSelection *selection;
  GError *error = NULL;

  brasero_media_library_start ();

  metadata = sj_metadata_getter_new ();
  g_signal_connect (metadata, "metadata", G_CALLBACK (metadata_cb), NULL);

  sj_settings = g_settings_new ("org.gnome.sound-juicer");

  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_DEVICE,
                    (GCallback)device_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_EJECT,
                    (GCallback)eject_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_OPEN,
                    (GCallback)open_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_BASEURI,
                    (GCallback)baseuri_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_STRIP,
                    (GCallback)strip_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_AUDIO_PROFILE,
                    (GCallback)profile_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_PARANOIA,
                    (GCallback)paranoia_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_PATH_PATTERN,
                    (GCallback)path_pattern_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_FILE_PATTERN,
                    (GCallback)file_pattern_changed_cb, NULL);
  g_signal_connect (sj_settings, "changed::"SJ_SETTINGS_AUDIO_VOLUME,
                    (GCallback)audio_volume_changed_cb, NULL);

  g_action_map_add_action_entries (G_ACTION_MAP (app),
                                   app_entries, G_N_ELEMENTS (app_entries),
                                   NULL);

  builder = gtk_builder_new ();
  if (g_file_test (SOURCE_BUILDER, G_FILE_TEST_EXISTS) != FALSE) {
    gtk_builder_add_from_file (builder, SOURCE_BUILDER, &error);
  } else {
    gtk_builder_add_from_file (builder, INSTALLED_BUILDER, &error);
  }

  if (g_file_test (SOURCE_MENU_BUILDER, G_FILE_TEST_EXISTS) != FALSE) {
    gtk_builder_add_from_file (builder, SOURCE_MENU_BUILDER, &error);
  } else {
    gtk_builder_add_from_file (builder, INSTALLED_MENU_BUILDER, &error);
  }

  gtk_application_set_app_menu (GTK_APPLICATION (app),
                                G_MENU_MODEL (gtk_builder_get_object (builder, "app-menu")));

  if (error != NULL) {
    error_on_start (error);
    g_error_free (error);
    exit (1);
  }

  gtk_builder_connect_signals (builder, NULL);

  main_window           = GET_WIDGET ("main_window");
  submit_bar            = GET_WIDGET ("submit_bar");
  submit_label          = GET_WIDGET ("submit_label");
  title_entry           = GET_WIDGET ("title_entry");
  artist_entry          = GET_WIDGET ("artist_entry");
  composer_label        = GET_WIDGET ("composer_label");
  composer_entry        = GET_WIDGET ("composer_entry");
  duration_label        = GET_WIDGET ("duration_label");
  genre_entry           = GET_WIDGET ("genre_entry");
  year_entry            = GET_WIDGET ("year_entry");
  disc_number_entry     = GET_WIDGET ("disc_number_entry");
  track_listview        = GET_WIDGET ("track_listview");
  extract_button        = GET_WIDGET ("extract_button");
  play_button           = GET_WIDGET ("play_button");
  select_button         = GET_WIDGET ("select_button");
  status_bar            = GET_WIDGET ("status_bar");
  entry_table           = GET_WIDGET ("entry_table");

  sj_main_window_init (GTK_WINDOW (main_window));

  g_action_map_add_action_entries (G_ACTION_MAP (main_window),
                                   win_entries, G_N_ELEMENTS (win_entries),
                                   NULL);

  g_signal_connect (app, "action-enabled-changed::submit-tracks",
                    G_CALLBACK (submit_tracks_enabled_changed_cb), NULL);

  gtk_button_set_label(GTK_BUTTON(select_button), _("Select None"));
  gtk_actionable_set_action_name(GTK_ACTIONABLE(select_button), "win.deselect-all");
  gtk_actionable_set_action_name(GTK_ACTIONABLE(play_button), "win.play");

  /* window actions are only available via shortcuts */
  gtk_application_add_accelerator (GTK_APPLICATION (app),
                                   "<Primary>p", "win.play", NULL);
  gtk_application_add_accelerator (GTK_APPLICATION (app),
                                   "<Primary>n", "win.next-track", NULL);
  gtk_application_add_accelerator (GTK_APPLICATION (app),
                                   "<Primary>b", "win.previous-track", NULL);
  gtk_application_add_accelerator (GTK_APPLICATION (app),
                                   "<Primary>a", "win.select-all", NULL);
  gtk_application_add_accelerator (GTK_APPLICATION (app),
                                   "<Primary><Shift>a", "win.deselect-all", NULL);

  { /* ensure that the play/pause button's size is constant */
    GtkWidget *fake_button1, *fake_button2;
    GtkSizeGroup *size_group;

    size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);

    fake_button1 = gtk_button_new_with_label (_("_Play"));
    gtk_button_set_use_underline (GTK_BUTTON (fake_button1), TRUE);
    gtk_size_group_add_widget (size_group, fake_button1);
    g_signal_connect_swapped (play_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button1);

    fake_button2 = gtk_button_new_with_label (_("_Pause"));
    gtk_button_set_use_underline (GTK_BUTTON (fake_button2), TRUE);
    gtk_size_group_add_widget (size_group, fake_button2);
    g_signal_connect_swapped (play_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button2);

    gtk_size_group_add_widget (size_group, play_button);
    g_object_unref (G_OBJECT (size_group));
  }

  { /* ensure that the extract/play button's size is constant */
    GtkWidget *fake_button1, *fake_button2;
    GtkSizeGroup *size_group;

    size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);

    fake_button1 = gtk_button_new_with_label (_("E_xtract"));
    gtk_button_set_use_underline (GTK_BUTTON (fake_button1), TRUE);
    gtk_size_group_add_widget (size_group, fake_button1);
    g_signal_connect_swapped (extract_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button1);

    fake_button2 = gtk_button_new_with_label (_("_Stop"));
    gtk_button_set_use_underline (GTK_BUTTON (fake_button2), TRUE);
    gtk_size_group_add_widget (size_group, fake_button2);
    g_signal_connect_swapped (extract_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button2);

    gtk_size_group_add_widget (size_group, extract_button);
    g_object_unref (G_OBJECT (size_group));
  }

  { /* ensure that the select/unselect button's size is constant */
    GtkWidget *fake_button1, *fake_button2;
    GtkSizeGroup *size_group;

    size_group = gtk_size_group_new (GTK_SIZE_GROUP_HORIZONTAL);

    fake_button1 = gtk_button_new_with_label (_("Select All"));
    gtk_size_group_add_widget (size_group, fake_button1);
    g_signal_connect_swapped (select_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button1);

    fake_button2 = gtk_button_new_with_label (_("Select None"));
    gtk_size_group_add_widget (size_group, fake_button2);
    g_signal_connect_swapped (select_button, "destroy",
                              G_CALLBACK (gtk_widget_destroy),
                              fake_button2);

    gtk_size_group_add_widget (size_group, select_button);
    g_object_unref (G_OBJECT (size_group));
  }

  setup_genre_entry (genre_entry);

  /* Remove row spacing from hidden row containing composer_entry */
  gtk_table_set_row_spacing (GTK_TABLE (entry_table), COMPOSER_ROW, 0);

  track_store = gtk_list_store_new (COLUMN_TOTAL, G_TYPE_INT, G_TYPE_BOOLEAN, G_TYPE_INT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_POINTER);
  gtk_tree_view_set_model (GTK_TREE_VIEW (track_listview), GTK_TREE_MODEL (track_store));
  {
    GtkTreeViewColumn *column;
    GtkCellRenderer *renderer;

    toggle_renderer = gtk_cell_renderer_toggle_new ();
    g_signal_connect (toggle_renderer, "toggled", G_CALLBACK (on_extract_toggled), NULL);
    column = gtk_tree_view_column_new_with_attributes ("",
                                                       toggle_renderer,
                                                       "active", COLUMN_EXTRACT,
                                                       NULL);
    gtk_tree_view_column_set_resizable (column, FALSE);
    gtk_tree_view_append_column (GTK_TREE_VIEW (track_listview), column);

    column = gtk_tree_view_column_new ();
    gtk_tree_view_column_set_title (column, _("Track"));
    gtk_tree_view_column_set_expand (column, FALSE);
    gtk_tree_view_column_set_resizable (column, FALSE);
    renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_column_pack_start (column, renderer, FALSE);
    gtk_tree_view_column_add_attribute (column, renderer, "text", COLUMN_NUMBER);
    renderer = gtk_cell_renderer_pixbuf_new ();
    g_object_set (renderer, "stock-size", GTK_ICON_SIZE_MENU, "xalign", 0.0, NULL);
    gtk_tree_view_column_pack_start (column, renderer, TRUE);
    gtk_tree_view_column_set_cell_data_func (column, renderer, number_cell_icon_data_cb, NULL, NULL);
    gtk_tree_view_append_column (GTK_TREE_VIEW (track_listview), column);

    title_renderer = add_editable_listview_column (_("Title"), COLUMN_TITLE);
    artist_renderer = add_editable_listview_column (_("Artist"), COLUMN_ARTIST);
    composer_renderer = add_editable_listview_column (_("Composer"), COLUMN_COMPOSER);
    composer_column = gtk_tree_view_get_column (GTK_TREE_VIEW (track_listview),
                                                gtk_tree_view_get_n_columns (GTK_TREE_VIEW (track_listview)) - 1);
    gtk_tree_view_column_set_visible (composer_column, FALSE);

    renderer = gtk_cell_renderer_text_new ();
    column = gtk_tree_view_column_new_with_attributes (_("Duration"),
                                                       renderer,
                                                       NULL);
    gtk_tree_view_column_set_resizable (column, FALSE);
    gtk_tree_view_column_set_cell_data_func (column, renderer, duration_cell_data_cb, NULL, NULL);
    gtk_tree_view_append_column (GTK_TREE_VIEW (track_listview), column);
  }

  extractor = SJ_EXTRACTOR (sj_extractor_new());
  error = sj_extractor_get_new_error (extractor);
  if (error) {
    error_on_start (error);
    exit (1);
  }

  update_ui_for_album (NULL);

  sj_play_init ();

  selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (track_listview));
  gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);

  baseuri_changed_cb (sj_settings, SJ_SETTINGS_BASEURI, NULL);
  path_pattern_changed_cb (sj_settings, SJ_SETTINGS_PATH_PATTERN, NULL);
  file_pattern_changed_cb (sj_settings, SJ_SETTINGS_FILE_PATTERN, NULL);
  profile_changed_cb (sj_settings, SJ_SETTINGS_AUDIO_PROFILE, NULL);
  paranoia_changed_cb (sj_settings, SJ_SETTINGS_PARANOIA, NULL);
  strip_changed_cb (sj_settings, SJ_SETTINGS_STRIP, NULL);
  eject_changed_cb (sj_settings, SJ_SETTINGS_EJECT, NULL);
  open_changed_cb (sj_settings, SJ_SETTINGS_OPEN, NULL);
  audio_volume_changed_cb (sj_settings, SJ_SETTINGS_AUDIO_VOLUME, NULL);
  if (device == NULL && uris == NULL) {
    /* FIXME: this should set the device gsettings key to a meaningful
     * value if it's empty (which is the case until the user changes it in
     * the prefs)
     */
    device_changed_cb (sj_settings, SJ_SETTINGS_DEVICE, NULL);
  } else {
    if (device)
      set_device (device, TRUE);
    else {
      char *d;

      /* Mash up the CDDA URIs into a device path */
      if (g_str_has_prefix (uris[0], "cdda://")) {
        gint len;
        d = g_strdup_printf ("/dev/%s%c", uris[0] + strlen ("cdda://"), '\0');
        /* Take last '/' out of path, or set_device thinks it is part of the device name */
      len = strlen (d);
      if (d[len - 1] == '/')
          d [len - 1] = '\0';
      set_device (d, TRUE);
      g_free (d);
      } else {
        device_changed_cb (sj_settings, SJ_SETTINGS_DEVICE, NULL);
      }
    }
  }

  if (sj_extractor_supports_encoding (&error) == FALSE) {
    error_on_start (error);
    return;
  }

  /* Set whether duplication of a cd is available using the brasero tool */
  set_action_enabled ("duplicate", FALSE);
  duplication_enabled = is_cd_duplication_available();

  gtk_application_add_window (GTK_APPLICATION (app), GTK_WINDOW (main_window));
  gtk_widget_show (main_window);
}

static void
activate_cb (GApplication *app, gpointer user_data)
{
  gtk_window_present (GTK_WINDOW (main_window));
}

static GAction*
lookup_action (const gchar* name)
{
  GActionMap *map;
  GAction *action;

  map = G_ACTION_MAP (g_application_get_default ());
  action = g_action_map_lookup_action (map, name);
  if (action == NULL)
    action = g_action_map_lookup_action (G_ACTION_MAP (main_window), name);
  if (action == NULL)
    g_warning ("Action '%s' not found", name);

  return action;
}

static gboolean
get_action_state_bool (const gchar* name)
{
  gboolean state = FALSE;
  GAction *action;

  action = lookup_action (name);
  if (action != NULL) {
    GVariant *value = g_action_get_state (action);
    state = g_variant_get_boolean (value);
    g_variant_unref (value);
  }

  return state;
}

static void
set_action_state (const gchar *detailed_name)
{
  gchar *name;
  GVariant *value;
  GError *error = NULL;

  if (g_action_parse_detailed_name (detailed_name, &name, &value, &error)) {
    GSimpleAction *action;

    action = G_SIMPLE_ACTION (lookup_action (name));
    if (action != NULL)
      g_simple_action_set_state (action, value);

    g_free (name);
    g_variant_unref (value);
  } else {
    g_warning ("Error parsing detailed action name '%s' - %s",
               detailed_name, error->message);
    g_error_free (error);
  }
}

void set_action_enabled (const char *name, gboolean enabled)
{
  GAction *action;

  action = lookup_action (name);
  if (action != NULL)
    g_simple_action_set_enabled (G_SIMPLE_ACTION (action), enabled);
}

int main (int argc, char **argv)
{
  GError *error = NULL;
  GtkApplication *app;
  GOptionContext *ctx;
  const GOptionEntry entries[] = {
    { "auto-start", 'a', 0, G_OPTION_ARG_NONE, &autostart, N_("Start extracting immediately"), NULL },
    { "play", 'p', 0, G_OPTION_ARG_NONE, &autoplay, N_("Start playing immediately"), NULL},
    { "device", 'd', 0, G_OPTION_ARG_FILENAME, &device, N_("What CD device to read"), N_("DEVICE") },
    { G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &uris, N_("URI to the CD device to read"), NULL },
    { NULL }
  };
  guint status = 0;

  bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  g_set_application_name (_("Sound Juicer"));
  g_setenv ("PULSE_PROP_media.role", "music", TRUE);

  ctx = g_option_context_new (N_("- Extract music from your CDs"));
  g_option_context_add_main_entries (ctx, entries, GETTEXT_PACKAGE);
  g_option_context_set_translation_domain(ctx, GETTEXT_PACKAGE);
  g_option_context_add_group (ctx, gtk_get_option_group (TRUE));
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  g_option_context_add_group (ctx, brasero_media_get_option_group ());
  g_option_context_set_ignore_unknown_options (ctx, TRUE);

  g_option_context_parse (ctx, &argc, &argv, &error);
  if (error != NULL) {
      g_printerr ("Error parsing options: %s", error->message);
      exit (1);
  }
  g_option_context_free (ctx);

  sj_debug_init ();

  gtk_window_set_default_icon_name ("sound-juicer");

  app = gtk_application_new ("org.gnome.sound-juicer",
                             G_APPLICATION_FLAGS_NONE);

  g_signal_connect (app, "startup", G_CALLBACK (startup_cb), NULL);
  g_signal_connect (app, "activate", G_CALLBACK (activate_cb), NULL);

  status = g_application_run (G_APPLICATION (app), argc, argv);

  g_object_unref (app);

  sj_metadata_helper_cleanup ();
  g_object_unref (base_uri);
  g_object_unref (metadata);
  g_object_unref (extractor);
  g_object_unref (sj_settings);
  brasero_media_library_stop ();

  return status;
}