File: nbrowserwindow.cpp

package info (click to toggle)
nixnote2 2.0~beta11-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,448 kB
  • ctags: 7,058
  • sloc: cpp: 68,338; java: 1,096; sh: 834; makefile: 27
file content (3683 lines) | stat: -rw-r--r-- 130,111 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
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
/*********************************************************************************
NixNote - An open-source client for the Evernote service.
Copyright (C) 2013 Randy Baumgarte

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
***********************************************************************************/

#include "nbrowserwindow.h"
#include "sql/notetable.h"
#include "sql/notebooktable.h"
#include "gui/browserWidgets/urleditor.h"
#include "sql/tagtable.h"
#include "html/noteformatter.h"
#include "html/enmlformatter.h"
#include "sql/usertable.h"
#include "sql/resourcetable.h"
#include "sql/linkednotebooktable.h"
#include "email/smtpclient.h"
#include "email/mimehtml.h"
#include "email/mimemessage.h"
#include "email/mimeinlinefile.h"
#include "global.h"
#include "gui/browserWidgets/colormenu.h"
#include "gui/plugins/pluginfactory.h"
#include "dialog/insertlinkdialog.h"
#include "html/thumbnailer.h"
#include "dialog/tabledialog.h"
#include "dialog/insertlatexdialog.h"
#include "dialog/endecryptdialog.h"
#include "dialog/encryptdialog.h"
#include "dialog/emaildialog.h"
#include "sql/configstore.h"
#include "utilities/encrypt.h"
#include "utilities/mimereference.h"
#include "html/attachmenticonbuilder.h"
#include "dialog/remindersetdialog.h"
#include "dialog/spellcheckdialog.h"
#include "utilities/pixelconverter.h"

#include <QPlainTextEdit>
#include <QVBoxLayout>
#include <QAction>
#include <QMenu>
#include <QFileIconProvider>
#include <QFontDatabase>
#include <QSplitter>
#include <QDesktopServices>
#include <QMessageBox>
#include <QFileDialog>
#include <QClipboard>
#include <QBuffer>
#include <QDateTime>
#include <QPrintDialog>
#include <QPrinterInfo>
#include <QPrintPreviewDialog>
#include <QPaintEngine>
#include <iostream>
#include <istream>
#include <qcalendarwidget.h>
#include <qplaintextedit.h>

extern Global global;

NBrowserWindow::NBrowserWindow(QWidget *parent) :
    QWidget(parent)
{
    // Setup a unique identifier for this editor instance.
    QUuid uuid;
    this->uuid =  uuid.createUuid().toString().replace("{","").replace("}","");

//    this->setStyleSheet("margins:0px;");
    QHBoxLayout *line1Layout = new QHBoxLayout();
    QVBoxLayout *layout = new QVBoxLayout();   // Note content layout


    // Setup the alarm button & display
    alarmText.setStyleSheet("QPushButton {background-color: transparent; border-radius: 0px;}");
    connect(alarmButton.setAction, SIGNAL(triggered()), this, SLOT(alarmSet()));
    connect(alarmButton.clearAction, SIGNAL(triggered()), this, SLOT(alarmClear()));
    connect(alarmButton.doneAction, SIGNAL(triggered()), this, SLOT(alarmCompleted()));
    connect(&alarmButton.menu, SIGNAL(aboutToShow()), this, SLOT(alarmMenuActivated()));

    // Setup line #1 of the window.  The text & notebook
    connect(&alarmText, SIGNAL(clicked()), this, SLOT(alarmCompleted()));
    layout->addLayout(line1Layout);
    line1Layout->addWidget(&noteTitle);
    line1Layout->addWidget(&alarmText);
    line1Layout->addWidget(&alarmButton);
    line1Layout->addWidget(&notebookMenu);
    line1Layout->addWidget(&expandButton);


    // Add the second layout display
    layout->addLayout(&line2Layout);
    line2Layout.addWidget(&urlEditor,1);
    line2Layout.addWidget(&tagEditor, 3);

    // Add the third layout display
    layout->addLayout(&line3Layout);
    line3Layout.addWidget(&dateEditor);


    editor = new NWebView(this);
    editor->setTitleEditor(&noteTitle);
    setupToolBar();
    layout->addWidget(buttonBar);

    // setup the source editor
    sourceEdit = new QTextEdit(this);
    sourceEdit->setVisible(false);
    sourceEdit->setTabChangesFocus(true);


    QFont font;
    font.setFamily("Courier");
    font.setFixedPitch(true);
    global.getGuiFont(font);
//    font.setPointSize(global.defaultGuiFontSize);
    sourceEdit->setFont(global.getGuiFont(font));
    //XmlHighlighter *highlighter = new XmlHighlighter(sourceEdit->document());
    sourceEditorTimer = new QTimer();
    connect(sourceEditorTimer, SIGNAL(timeout()), this, SLOT(setSource()));

    // addthe actual note editor & source view
    QSplitter *editorSplitter = new QSplitter(Qt::Vertical, this);
    editorSplitter->addWidget(editor);
    editorSplitter->addWidget(sourceEdit);
    layout->addWidget(editorSplitter);
    setLayout(layout);
    layout->setMargin(0);

    findReplace = new FindReplace();
    layout->addWidget(findReplace);
    findReplace->setVisible(false);

    connect(findReplace->nextButton, SIGNAL(clicked()), this, SLOT(findNextInNote()));
    connect(findReplace->findLine, SIGNAL(returnPressed()), this, SLOT(findNextInNote()));
    connect(findReplace->prevButton, SIGNAL(clicked()), this, SLOT(findPrevInNote()));
    connect(findReplace->replaceButton, SIGNAL(clicked()), this, SLOT(findReplaceInNotePressed()));
    connect(findReplace->replaceAllButton, SIGNAL(clicked()), this, SLOT(findReplaceAllInNotePressed()));
    connect(findReplace->closeButton, SIGNAL(clicked()), this, SLOT(findReplaceWindowHidden()));



    // Setup shortcuts
    focusNoteShortcut = new QShortcut(this);
    setupShortcut(focusNoteShortcut, "Focus_Note");
    connect(focusNoteShortcut, SIGNAL(activated()), this, SLOT(focusNote()));
    focusTitleShortcut = new QShortcut(this);
    setupShortcut(focusTitleShortcut, "Focus_Title");
    connect(focusTitleShortcut, SIGNAL(activated()), this, SLOT(focusTitle()));
    insertDatetimeShortcut = new QShortcut(this);
    setupShortcut(insertDatetimeShortcut, "Insert_DateTime");
    connect(insertDatetimeShortcut, SIGNAL(activated()), this, SLOT(insertDatetime()));
    copyNoteUrlShortcut = new QShortcut(this);
    setupShortcut(copyNoteUrlShortcut, "Edit_Copy_Note_Url");
    connect(copyNoteUrlShortcut, SIGNAL(activated()), this, SLOT(copyNoteUrl()));


    // Setup the signals
    connect(&expandButton, SIGNAL(stateChanged(int)), this, SLOT(changeExpandState(int)));
    connect(&notebookMenu, SIGNAL(notebookChanged()), this, SLOT(sendNotebookUpdateSignal()));
    connect(&urlEditor, SIGNAL(textUpdated()), this, SLOT(sendUrlUpdateSignal()));
    connect(&noteTitle, SIGNAL(titleChanged()), this, SLOT(sendTitleUpdateSignal()));
    connect(&dateEditor.authorEditor, SIGNAL(textUpdated()), this, SLOT(sendAuthorUpdateSignal()));
    connect(&dateEditor.locationEditor, SIGNAL(clicked()), this, SLOT(sendLocationUpdateSignal()));
    connect(&dateEditor.createdDate, SIGNAL(editingFinished()), this, SLOT(sendDateCreatedUpdateSignal()));
    connect(&dateEditor.subjectDate, SIGNAL(editingFinished()), this, SLOT(sendDateSubjectUpdateSignal()));
    connect(&dateEditor, SIGNAL(valueChanged()), this, SLOT(sendDateUpdateSignal()));
    connect(&tagEditor, SIGNAL(tagsUpdated()), this, SLOT(sendTagUpdateSignal()));
    connect(&tagEditor, SIGNAL(newTagCreated(qint32)), this, SLOT(newTagAdded(qint32)));
    connect(editor, SIGNAL(noteChanged()), this, SLOT(noteContentUpdated()));
    connect(sourceEdit, SIGNAL(textChanged()), this, SLOT(noteSourceUpdated()));
    connect(editor, SIGNAL(htmlEditAlert()), this, SLOT(noteContentEdited()));
    connect(editor->page(), SIGNAL(linkClicked(QUrl)), this, SLOT(linkClicked(QUrl)));
    connect(editor->page(), SIGNAL(microFocusChanged()), this, SLOT(microFocusChanged()));

    editor->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(editor->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(exposeToJavascript()));
    connect(editor->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), editor, SLOT(exposeToJavascript()));

    editor->page()->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
    factory = new PluginFactory(this);
    editor->page()->setPluginFactory(factory);

    buttonBar->setupVisibleButtons();

    printPage = new QTextEdit();
    printPage->setVisible(false);
    //connect(printPage, SIGNAL(loadFinished(bool)), this, SLOT(printReady(bool)));

    printPreviewPage = new QTextEdit();
    printPreviewPage->setVisible(false);

    hammer = new Thumbnailer(global.db);
    lid = -1;
    thumbnailer = NULL;


    //Setup shortcuts for context menu
    removeFormattingShortcut = new QShortcut(this);
    this->setupShortcut(removeFormattingShortcut, "Edit_Remove_Formatting");
    connect(removeFormattingShortcut, SIGNAL(activated()), this, SLOT(removeFormatButtonPressed()));
    //removeFormattingShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    insertHtmlEntitiesShortcut = new QShortcut(this);
    this->setupShortcut(insertHtmlEntitiesShortcut, QString("Edit_Insert_Html_Entities"));
    connect(insertHtmlEntitiesShortcut, SIGNAL(activated()),this, SLOT(insertHtmlEntities()));
    //insertHtmlEntitiesShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    encryptTextShortcut = new QShortcut(this);
    this->setupShortcut(encryptTextShortcut, QString("Edit_Encrypt_Text"));
    connect(encryptTextShortcut, SIGNAL(activated()),this, SLOT(encryptButtonPressed()));
    //encryptTextShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    insertHyperlinkShortcut = new QShortcut(this);
    this->setupShortcut(insertHyperlinkShortcut, QString("Edit_Insert_Hyperlink"));
    connect(insertHyperlinkShortcut, SIGNAL(activated()),this, SLOT(insertLinkButtonPressed()));
    //insertHyperlinkShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    insertQuicklinkShortcut = new QShortcut(this);
    this->setupShortcut(insertQuicklinkShortcut, QString("Edit_Insert_QuickLink"));
    connect(insertQuicklinkShortcut, SIGNAL(activated()),this, SLOT(insertQuickLinkButtonPressed()));
    //insertQuicklinkShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    removeHyperlinkShortcut = new QShortcut(this);
    this->setupShortcut(removeHyperlinkShortcut, QString("Edit_Remove_Hyperlink"));
    connect(removeHyperlinkShortcut, SIGNAL(activated()),this, SLOT(removeLinkButtonPressed()));
    //removeHyperlinkShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    attachFileShortcut = new QShortcut(this);
    this->setupShortcut(attachFileShortcut, QString("Edit_Attach_File"));
    connect(attachFileShortcut, SIGNAL(activated()),this, SLOT(attachFile()));
    //attachFileShortcut->setContext(Qt::WidgetWithChildrenShortcut);

    insertLatexShortcut = new QShortcut(this);
    this->setupShortcut(insertLatexShortcut, QString("Edit_Insert_Latex"));
    connect(insertLatexShortcut, SIGNAL(activated()),this, SLOT(insertLatexButtonPressed()));
    //insertLatexShortcut->setContext(Qt::WidgetWithChildrenShortcut);




    // Restore the expand/collapse state
    global.settings->beginGroup("SaveState");
    int expandButton = global.settings->value("ExpandButton", EXPANDBUTTON_1).toInt();
    global.settings->endGroup();
    this->expandButton.setState(expandButton);
//    changeExpandState(expandButton);

    connect(&focusTimer, SIGNAL(timeout()), this, SLOT(focusCheck()));
    focusTimer.setInterval(100);
    focusTimer.start();

    hunspellInterface = NULL;
}



// Setup the toolbar window of the editor
void NBrowserWindow::setupToolBar() {
    buttonBar = new EditorButtonBar();

    // Toolbar action
    connect(buttonBar->undoButtonAction, SIGNAL(triggered()), this, SLOT(undoButtonPressed()));
    connect(buttonBar->undoButtonShortcut, SIGNAL(activated()), this, SLOT(undoButtonPressed()));

    connect(buttonBar->redoButtonAction, SIGNAL(triggered()), this, SLOT(redoButtonPressed()));
    connect(buttonBar->redoButtonShortcut, SIGNAL(activated()), this, SLOT(redoButtonPressed()));

    connect(buttonBar->cutButtonAction, SIGNAL(triggered()), this, SLOT(cutButtonPressed()));
    connect(buttonBar->cutButtonShortcut, SIGNAL(activated()), this, SLOT(cutButtonPressed()));

    connect(buttonBar->copyButtonAction, SIGNAL(triggered()), this, SLOT(copyButtonPressed()));
    connect(buttonBar->copyButtonShortcut, SIGNAL(activated()), this, SLOT(copyButtonPressed()));

    connect(buttonBar->pasteButtonAction, SIGNAL(triggered()), this, SLOT(pasteButtonPressed()));
    //connect(buttonBar->pasteButtonShortcut, SIGNAL(activated()), this, SLOT(pasteButtonPressed()));  // Handled via NWebView

    connect(buttonBar->removeFormatButtonAction, SIGNAL(triggered()), this, SLOT(removeFormatButtonPressed()));
    connect(buttonBar->removeFormatButtonShortcut, SIGNAL(activatedAmbiguously()), this, SLOT(removeFormatButtonPressed()));

    connect(buttonBar->boldButtonWidget, SIGNAL(clicked()), this, SLOT(boldButtonPressed()));
    connect(buttonBar->boldButtonShortcut, SIGNAL(activated()), this, SLOT(boldButtonPressed()));

    connect(buttonBar->italicButtonWidget, SIGNAL(clicked()), this, SLOT(italicsButtonPressed()));
    connect(buttonBar->italicButtonShortcut, SIGNAL(activated()), this, SLOT(italicsButtonPressed()));

    connect(buttonBar->underlineButtonWidget, SIGNAL(clicked()), this, SLOT(underlineButtonPressed()));
    connect(buttonBar->underlineButtonShortcut, SIGNAL(activated()), this, SLOT(underlineButtonPressed()));

    connect(buttonBar->leftJustifyButtonAction, SIGNAL(triggered()), this, SLOT(alignLeftButtonPressed()));
    connect(buttonBar->leftJustifyButtonShortcut, SIGNAL(activated()), this, SLOT(alignLeftButtonPressed()));

    connect(buttonBar->rightJustifyButtonAction, SIGNAL(triggered()), this, SLOT(alignRightButtonPressed()));
    connect(buttonBar->rightJustifyButtonShortcut, SIGNAL(activated()), this, SLOT(alignRightButtonPressed()));

    connect(buttonBar->centerJustifyButtonAction, SIGNAL(triggered()), this, SLOT(alignCenterButtonPressed()));
    connect(buttonBar->centerJustifyButtonShortcut, SIGNAL(activated()), this, SLOT(alignCenterButtonPressed()));

    connect(buttonBar->strikethroughButtonAction, SIGNAL(triggered()), this, SLOT(strikethroughButtonPressed()));
    connect(buttonBar->strikethroughButtonShortcut, SIGNAL(activated()), this, SLOT(strikethroughButtonPressed()));

    connect(buttonBar->subscriptButtonAction, SIGNAL(triggered()), this, SLOT(subscriptButtonPressed()));
    connect(buttonBar->subscriptButtonShortcut, SIGNAL(activated()), this, SLOT(subscriptButtonPressed()));

    connect(buttonBar->superscriptButtonAction, SIGNAL(triggered()), this, SLOT(superscriptButtonPressed()));
    connect(buttonBar->superscriptButtonShortcut, SIGNAL(activated()), this, SLOT(superscriptButtonPressed()));

    connect(buttonBar->hlineButtonAction, SIGNAL(triggered()), this, SLOT(horizontalLineButtonPressed()));
    connect(buttonBar->hlineButtonShortcut, SIGNAL(activated()), this, SLOT(horizontalLineButtonPressed()));

    connect(buttonBar->shiftRightButtonAction, SIGNAL(triggered()), this, SLOT(shiftRightButtonPressed()));
    connect(buttonBar->shiftRightButtonShortcut, SIGNAL(activated()), this, SLOT(shiftRightButtonPressed()));

    connect(buttonBar->shiftLeftButtonAction, SIGNAL(triggered()), this, SLOT(shiftLeftButtonPressed()));
    connect(buttonBar->shiftLeftButtonShortcut, SIGNAL(activated()), this, SLOT(shiftLeftButtonPressed()));

    connect(buttonBar->bulletListButtonAction, SIGNAL(triggered()), this, SLOT(bulletListButtonPressed()));
    connect(buttonBar->bulletListButtonShortcut, SIGNAL(activated()), this, SLOT(bulletListButtonPressed()));

    connect(buttonBar->numberListButtonAction, SIGNAL(triggered()), this, SLOT(numberListButtonPressed()));
    connect(buttonBar->numberListButtonShortcut, SIGNAL(activated()), this, SLOT(numberListButtonPressed()));

    connect(buttonBar->todoButtonAction, SIGNAL(triggered()), this, SLOT(todoButtonPressed()));
    connect(buttonBar->todoButtonShortcut, SIGNAL(activated()), this, SLOT(todoButtonPressed()));

    connect(buttonBar->spellCheckButtonAction, SIGNAL(triggered()), this, SLOT(spellCheckPressed()));
    connect(buttonBar->spellCheckButtonShortcut, SIGNAL(activated()), this, SLOT(spellCheckPressed()));

    connect(buttonBar->fontSizes, SIGNAL(currentIndexChanged(int)), this, SLOT(fontSizeSelected(int)));

    connect(buttonBar->fontNames, SIGNAL(currentIndexChanged(int)), this, SLOT(fontNameSelected(int)));

    connect(buttonBar->fontColorButtonWidget, SIGNAL(clicked()), this, SLOT(fontColorClicked()));
    //connect(fontColorButtonShortcut, SIGNAL(activated()), this, SLOT(fontColorClicked()));

    connect(buttonBar->fontColorMenuWidget->getMenu(), SIGNAL(triggered(QAction*)), this, SLOT(fontColorClicked()));

    connect(buttonBar->highlightColorButtonWidget, SIGNAL(clicked()), this, SLOT(fontHighlightClicked()));
    //connect(fontHighlightColorShortcut, SIGNAL(activated()), this, SLOT(fontHighlightClicked()));
    connect(buttonBar->highlightColorAction, SIGNAL(triggered()), this, SLOT(fontHighlightClicked()));

    connect(buttonBar->highlightColorMenuWidget->getMenu(), SIGNAL(triggered(QAction*)), this, SLOT(fontHighlightClicked()));

    connect(buttonBar->insertTableButtonAction, SIGNAL(triggered()), this, SLOT(insertTableButtonPressed()));
    connect(buttonBar->insertTableButtonShortcut, SIGNAL(activated()), this, SLOT(insertTableButtonPressed()));

    connect(buttonBar->htmlEntitiesButtonAction, SIGNAL(triggered()), this, SLOT(insertHtmlEntities()));
    connect(buttonBar->htmlEntitiesButtonShortcut, SIGNAL(activated()), this, SLOT(insertHtmlEntities()));

    connect(buttonBar->insertDatetimeButtonAction, SIGNAL(triggered()), this, SLOT(insertDatetime()));
    connect(buttonBar->insertDatetimeButtonWidget,SIGNAL(clicked()), this, SLOT(insertDatetime()));
    connect(buttonBar->insertDatetimeButtonShortcut, SIGNAL(activated()), this, SLOT(insertDatetime()));
}




// Load any shortcut keys
void NBrowserWindow::setupShortcut(QShortcut *action, QString text) {
    if (!global.shortcutKeys->containsAction(&text))
        return;
    QKeySequence key(global.shortcutKeys->getShortcut(&text));
    action->setKey(key);
}


// Load the note content into the window
void NBrowserWindow::setContent(qint32 lid) {
    QLOG_DEBUG() << "Setting note contents to " << lid;

    // First, make sure we have a valid lid
    if (lid == -1) {
        blockSignals(true);
        setReadOnly(true);
        clear();
        blockSignals(false);
        return;
    }

    // If we are already updating this note, we don't do anything
    QLOG_DEBUG() << "this.lid:" << this->lid << " " << lid;
    if (lid == this->lid)
        return;

    bool hasFocus = false;
    if (this->editor->hasFocus())
        hasFocus = true;

    QLOG_DEBUG() << "editor is dirty";
    if (this->editor->isDirty)
        this->saveNoteContent();

    // let's load the new note
    this->lid = lid;
    this->editor->isDirty = false;

    NoteTable noteTable(global.db);
    Note n;

    QLOG_DEBUG() << "Getting note";
    bool rc = noteTable.get(n, this->lid, false, false);
    if (!rc)
        return;

    QByteArray content;
    bool inkNote = false;
    bool readOnly = false;

    // If we are searching, we never pull from the cache since the search string may
    // have changed since the last time.
    FilterCriteria *criteria = global.filterCriteria[global.filterPosition];
    if (criteria->isSearchStringSet() && criteria->getSearchString().trimmed() != "")
        global.cache.remove(lid);

    QLOG_DEBUG() << "Checking if note is in cache";
    if (global.cache.contains(lid)) {
        QLOG_DEBUG() << "Fetching from cache";
        NoteCache *c = global.cache[lid];
        if (c == NULL || c->noteContent == (char*)NULL) {
            QLOG_DEBUG() << "Invalid note found in cache.  Removing it.";
            global.cache.remove(lid);
        } else {
            QLOG_DEBUG() << "Setting content from cache.";
            content = c->noteContent;
            readOnly = c->isReadOnly;
            inkNote = c->isInkNote;
        }
    }

    if (!global.cache.contains(lid)) {
        QLOG_DEBUG() << "Note not in cache";
        NoteFormatter formatter;
        if (criteria->isSearchStringSet())
            formatter.setHighlightText(criteria->getSearchString());
        formatter.setNote(n, global.pdfPreview);
        //formatter.setHighlight();
        QLOG_DEBUG() << "rebuilding note HTML";
        content = formatter.rebuildNoteHTML();
        if (!criteria->isSearchStringSet()) {
            QLOG_DEBUG() << "criteria search string set";
            NoteCache *newCache = new NoteCache();
            newCache->isReadOnly = formatter.readOnly;
            newCache->isInkNote = formatter.inkNote;
            newCache->noteContent = content;
            QLOG_DEBUG() << "adding to cache";
            global.cache.insert(lid, newCache);
        }
        readOnly = formatter.readOnly;
        inkNote = formatter.inkNote;
    }

    setReadOnly(readOnly);

    QLOG_DEBUG() << "Setting up note title";
    noteTitle.setTitle(lid, n.title, n.title);
    dateEditor.setNote(lid, n);
    QWebSettings::setMaximumPagesInCache(0);
    QWebSettings::setObjectCacheCapacities(0, 0, 0);
    QLOG_DEBUG() << "Setting editor contents";
    editor->setContent(content);
    // is this an ink note?
    if (inkNote)
        editor->page()->setContentEditable(false);

    // Setup the alarm
    NoteAttributes attributes;
    QLOG_DEBUG() << "Setting attributes";
    if (n.attributes.isSet())
        attributes = n.attributes;
    if (attributes.reminderTime.isSet()) {
        Timestamp t;
        if (attributes.reminderTime.isSet())
            t = attributes.reminderTime;
        QFont f = alarmText.font();
        if (attributes.reminderDoneTime.isSet()) {
            f.setStrikeOut(true);
        } else {
            f.setStrikeOut(false);
        }
        alarmText.setFont(f);
        alarmText.setVisible(true);
        QDateTime atime;
        atime.setMSecsSinceEpoch(t);
        //alarmText.setText(atime.toString(Qt::SystemLocaleShortDate));
        if (atime.date() == QDate::currentDate())
            alarmText.setText(tr("Today"));
        else if (atime.date() == QDate::currentDate().addDays(+1))
            alarmText.setText(tr("Tomorrow"));
        else if (atime.date() == QDate::currentDate().addDays(-1))
            alarmText.setText(tr("Yesterday"));
        else
            alarmText.setText(atime.date().toString(global.dateFormat));


    } else {
        alarmText.setText("");
        alarmText.setVisible(false);
    }


    // Set the tag names
    QLOG_DEBUG() << "Setting tags";
    tagEditor.clear();
    QStringList names;
    QList<QString> tagNames;
    if (n.tagNames.isSet())
        tagNames = n.tagNames;
    for (int i=0; i<tagNames.size(); i++) {
        names << tagNames[i];
    }
    tagEditor.setTags(names);
    tagEditor.setCurrentLid(lid);
    NotebookTable notebookTable(global.db);
    qint32 notebookLid = notebookTable.getLid(n.notebookGuid);
    LinkedNotebookTable linkedTable(global.db);
    if (linkedTable.exists(notebookLid))
        tagEditor.setAccount(notebookLid);
    else
        tagEditor.setAccount(0);

    QLOG_DEBUG() << "Setting notebook";
    //this->lid = lid;
    notebookMenu.setCurrentNotebook(lid, n);
    QLOG_DEBUG() << "Setting URL";
    urlEditor.setUrl(lid, "");
    NoteAttributes na;
    QLOG_DEBUG() << "Setting note attributes";
    if (n.attributes.isSet()) {
        na = n.attributes;
        if (na.sourceURL.isSet()) {
            QLOG_DEBUG() << "Setting sourceUrl";
            urlEditor.setUrl(lid, na.sourceURL);
        }
    }

    QLOG_DEBUG() << "Calling set source";
    setSource();

    if (criteria->isSearchStringSet()) {
        QStringList list = criteria->getSearchString().split(" ");
        for (int i=0; i<list.size(); i++) {
            editor->page()->findText(list[i], QWebPage::HighlightAllOccurrences);
        }
    }

    QLOG_DEBUG() << "Checking thumbanail";
    if (hammer->idle && noteTable.isThumbnailNeeded(this->lid)) {
        hammer->render(this->lid);
    } /*else
        hammer->timer.start(1000);*/

    this->setEditorStyle();

    if (hasFocus)
        this->editor->setFocus();
    QLOG_DEBUG() << "Exiting setContent";
}


void NBrowserWindow::setReadOnly(bool readOnly) {
    isReadOnly = readOnly;
    if (readOnly || global.disableEditing) {
        noteTitle.setFocusPolicy(Qt::NoFocus);
        tagEditor.setEnabled(false);
        buttonBar->setVisible(false);
        tagEditor.setFocusPolicy(Qt::NoFocus);
        //authorEditor.setFocusPolicy(Qt::NoFocus);
        //locationEditor.setFocusPolicy(Qt::NoFocus);
        urlEditor.setFocusPolicy(Qt::NoFocus);
        notebookMenu.setEnabled(false);
        dateEditor.setEnabled(false);
        editor->page()->setContentEditable(false);
        alarmButton.setEnabled(false);
        return;
    }
    noteTitle.setFocusPolicy(Qt::StrongFocus);
    tagEditor.setEnabled(true);
    tagEditor.setFocusPolicy(Qt::StrongFocus);
    //authorEditor.setFocusPolicy(Qt::StrongFocus);
    //locationEditor.setFocusPolicy(Qt::StrongFocus);
    urlEditor.setFocusPolicy(Qt::StrongFocus);
    notebookMenu.setEnabled(true);
    dateEditor.setEnabled(true);
    editor->page()->setContentEditable(true);
    alarmButton.setEnabled(true);

}




// Show / hide various note attributes depending upon what the user
// has clicked
void NBrowserWindow::changeExpandState(int value) {
    switch (value) {
    case EXPANDBUTTON_1:
        urlEditor.hide();
        tagEditor.hide();
        dateEditor.hide();
        break;
    case EXPANDBUTTON_2:
        urlEditor.show();
        tagEditor.show();
        break;
    case EXPANDBUTTON_3:
        urlEditor.show();
        tagEditor.show();
        dateEditor.show();
        break;
    }
    global.settings->beginGroup("SaveState");
    global.settings->setValue("ExpandButton", value);
    global.settings->endGroup();
}








// Send a signal that a tag has been added to a note
void NBrowserWindow::newTagAdded(qint32 lid) {
    emit(tagAdded(lid));
}



// Add a tag to a note
void NBrowserWindow::addTagName(qint32 lid) {
    TagTable table(global.db);
    Tag t;
    table.get(t, lid);
    tagEditor.addTag(t.name);
}




// Rename a tag in a note.
void NBrowserWindow::tagRenamed(qint32 lid, QString oldName, QString newName) {
    tagEditor.tagRenamed(lid, oldName, newName);
}



// Remove a tag in a note
void NBrowserWindow::tagDeleted(qint32 lid, QString name) {
    Q_UNUSED(lid);  /* suppress unused */
    tagEditor.removeTag(name);
}



// A notebook was renamed
void NBrowserWindow::notebookRenamed(qint32 lid, QString oldName, QString newName) {
    Q_UNUSED(lid);  /* suppress unused */
    Q_UNUSED(oldName);  /* suppress unused */
    Q_UNUSED(newName)  /* suppress unused */
    notebookMenu.reloadData();
}




// A notebook was deleted
void NBrowserWindow::notebookDeleted(qint32 lid, QString name) {
    Q_UNUSED(lid);  /* suppress unused */
    Q_UNUSED(name); /* suppress unused */
    notebookMenu.reloadData();
}



// A stack was renamed
void NBrowserWindow::stackRenamed(QString oldName, QString newName) {
    Q_UNUSED(oldName);  /* suppress unused */
    Q_UNUSED(newName);  /* suppress unused */
    notebookMenu.reloadData();
}



// A stack was deleted
void NBrowserWindow::stackDeleted(QString name) {
    Q_UNUSED(name);  /* suppress unused */
    notebookMenu.reloadData();
}



// A stack was added
void NBrowserWindow::stackAdded(QString name) {
    Q_UNUSED(name);  /* suppress unused */
    notebookMenu.reloadData();
}



// A notebook was added
void NBrowserWindow::notebookAdded(qint32 lid) {
    Q_UNUSED(lid);  /* suppress unused */
    notebookMenu.reloadData();
}


// A note was synchronized with Evernote's servers
void NBrowserWindow::noteSyncUpdate(qint32 lid) {
    if (lid != this->lid || editor->isDirty)
        return;
    setContent(lid);
}




// A note's content was updated
void NBrowserWindow::noteContentUpdated() {
    if (editor->isDirty) {
        NoteTable noteTable(global.db);
        noteTable.setDirty(this->lid, true);
        editor->isDirty = false;
        qint64 dt = QDateTime::currentMSecsSinceEpoch();
        emit(noteUpdated(this->lid));
        emit(updateNoteList(this->lid, NOTE_TABLE_DATE_UPDATED_POSITION, dt));
    }
//    if (sourceEdit->isVisible()) {
//        sourceEditorTimer->stop();
//        sourceEditorTimer->setInterval(500);
//        sourceEditorTimer->setSingleShot(false);
//        sourceEditorTimer->start();
//    }
}


// Save the note's content
void NBrowserWindow::saveNoteContent() {
    //*** NOTE ***
    // Focus changing is disabled to try and fix the changing position
    // when syncing.
    // Do a little bit of focus changing to make sure things are saved properly
//    this->editor->setFocus();
    microFocusChanged();
//    this->editor->titleEditor->setFocus();


    if (this->editor->isDirty) {
        //QString contents = editor->editorPage->mainFrame()->toHtml();
        QString contents = editor->editorPage->mainFrame()->documentElement().toOuterXml();
        EnmlFormatter formatter;
        formatter.setHtml(contents);
        formatter.rebuildNoteEnml();
        if (formatter.formattingError) {
            QMessageBox::information(this, tr("Unable to Save"), QString(tr("Unable to save this note.  Either tidy isn't installed or the note is too complex to save.")));
            return;
        }


        // get a list of lids found in the note.
        // Purge anything that is no longer needed.
        QList<qint32> validLids = formatter.resources;
        QList<qint32> oldLids;
        ResourceTable resTable(global.db);
        resTable.getResourceList(oldLids, lid);

        QLOG_DEBUG() << "Valid Resource  LIDS:";
        for (int i=0; i<validLids.size(); i++) {
            QLOG_DEBUG() << " * " << i << " : " << validLids[i];
        }


        QLOG_DEBUG() << "Old Resource  LIDS:";
        for (int i=0; i<oldLids.size(); i++) {
            QLOG_DEBUG() << " * " << i << " : " << oldLids[i];
        }


        for (int i=0; i<oldLids.size(); i++) {
            if (!validLids.contains(oldLids[i])) {
                QLOG_DEBUG() << "Expunging old lid " << oldLids[i];
                resTable.expunge(oldLids[i]);
            }
        }

        QLOG_DEBUG() << "Updating note content";
        NoteTable table(global.db);
        table.updateNoteContent(lid, formatter.getEnml());
        editor->isDirty = false;
        if (thumbnailer == NULL)
            thumbnailer = new Thumbnailer(global.db);
        QLOG_DEBUG() << "Beginning thumbnail";
        thumbnailer->render(lid);
        QLOG_DEBUG() << "Thumbnail compleded";

        NoteCache* cache = global.cache[lid];
        if (cache != NULL) {
            QLOG_DEBUG() << "Updating cache";
            QByteArray b;
            b.append(contents);
            cache->noteContent = b;
            global.cache.remove(lid);
//            global.cache.insert(lid, cache);
        }
        QLOG_DEBUG() << "Leaving saveNoteContent()";
        // Make sure the thumnailer is done
        //while(!thumbnailer.idle);
    }
}



// The undo edit button was pressed
void NBrowserWindow::undoButtonPressed() {
    this->editor->triggerPageAction(QWebPage::Undo);
    this->editor->setFocus();
    microFocusChanged();
}



// The redo edit button was pressed
void NBrowserWindow::redoButtonPressed() {
    this->editor->triggerPageAction(QWebPage::Redo);
    this->editor->setFocus();
    microFocusChanged();
}


// The cut button was pressed
void NBrowserWindow::cutButtonPressed() {
    this->editor->triggerPageAction(QWebPage::Cut);
    this->editor->setFocus();
    microFocusChanged();
}


// The copy button was pressed
void NBrowserWindow::copyButtonPressed() {
//    editor->downloadImageAction()->setEnabled(true);
//    selectedFileName = f;
//    selectedFileLid = l.toInt();

    // If we have text selected
    if (this->editor->selectedText().trimmed() != "") {
        this->editor->triggerPageAction(QWebPage::Copy);
        this->editor->setFocus();
    } else {
        // If we have an image selected, we copy it to the clipboard.
        if (editor->downloadImageAction()->isEnabled()) {
            QString fileName = global.fileManager.getDbaDirPath()+selectedFileName;
            QApplication::clipboard()->setPixmap(QPixmap(fileName));
        }
    }

    microFocusChanged();

}


// Build URL from pasted text
QString NBrowserWindow::buildPasteUrl(QString url) {
    if (url.toLower().startsWith("http://") ||
        url.toLower().startsWith("https://") ||
        url.toLower().startsWith("mailto://") ||
        url.toLower().startsWith("mailto:") ||
        url.toLower().startsWith("ftp://")) {
        QString newUrl = QString("<a href=\"") +QApplication::clipboard()->text()
                +QString("\" title=\"") +url
                +QString("\" >") +url +QString("</a>");
        return newUrl;
    }
    return url;
}


// The paste button was pressed
void NBrowserWindow::pasteButtonPressed() {
    if (forceTextPaste) {
        pasteWithoutFormatButtonPressed();
        return;
    }

    const QMimeData *mime = QApplication::clipboard()->mimeData();

    if (mime->hasImage()) {
        editor->setFocus();
        insertImage(mime);
        editor->setFocus();
        return;
    }

    QLOG_DEBUG() << "Have URL?: " << mime->hasUrls();

    if (mime->hasUrls()) {
        QList<QUrl> urls = mime->urls();
        for (int i=0; i<urls.size(); i++) {
            QLOG_DEBUG() << urls[i].toString();
            if (urls[i].toString().startsWith("file://")) {
// Windows Check
#ifndef _WIN32
                QString fileName = urls[i].toString().mid(7);
#else
                QString fileName = urls[i].toString().mid(8);
#endif  // End windows check
                attachFileSelected(fileName);
                this->editor->triggerPageAction(QWebPage::InsertParagraphSeparator);
            }

            // If inserting a URL
            if (urls[i].toString().toLower().startsWith("https://") ||
                    urls[i].toString().toLower().startsWith("http://") ||
                    urls[i].toString().toLower().startsWith("ftp://") ||
                    urls[i].toString().toLower().startsWith("mailto:")) {
                QString url = this->buildPasteUrl(urls[i].toString());
                QString script = QString("document.execCommand('insertHtml', false, '%1');").arg(url);
                editor->page()->mainFrame()->evaluateJavaScript(script);
            }
        }

        this->editor->setFocus();
        microFocusChanged();
        return;
    }
    QLOG_DEBUG() << "Has HTML:" << mime->hasHtml() << " " << mime->html();
    QLOG_DEBUG() << "Has Color:" << mime->hasColor();
    QLOG_DEBUG() << "Has Url:" << mime->hasUrls();

    if (mime->hasText()) {
        QString urltext = mime->text();
        QLOG_DEBUG() << "Url:" << urltext;

        if (urltext.toLower().startsWith("https://") ||
            urltext.toLower().startsWith("http://") ||
            urltext.toLower().startsWith("ftp://") || \
            urltext.toLower().startsWith("mailto:")) {
            QString url = this->buildPasteUrl(urltext);
            QString script = QString("document.execCommand('insertHtml', false, '%1');").arg(url);
            editor->page()->mainFrame()->evaluateJavaScript(script);
            return;
        }


        if (urltext.toLower().mid(0,17) == "evernote:///view/") {
            urltext = urltext.mid(17);
            int pos = urltext.indexOf("/");
            urltext = urltext.mid(pos+1);
            pos = urltext.indexOf("/");
            urltext = urltext.mid(pos+1);
            pos = urltext.indexOf("/");
            urltext = urltext.mid(pos+1);
            pos = urltext.indexOf("/");
            QString guid = urltext.mid(0,pos);
            urltext = urltext.mid(pos);
            pos = urltext.indexOf("/");
            QString locguid = urltext.mid(pos);

            Note n;
            bool goodrc = false;
            NoteTable ntable(global.db);
            goodrc = ntable.get(n, guid,false, false);
            if (!goodrc)
                goodrc = ntable.get(n,locguid,false, false);

            // If we have a good return, then we can paste the link, otherwise we fall out
            // to a normal paste.
            if (goodrc) {
                QString url = QString("<a href=\"%1\" title=\"%2\">%3</a>").arg(QApplication::clipboard()->text(), n.title, n.title);
                QLOG_DEBUG() << "HTML to insert:" << url;
                QString script = QString("document.execCommand('insertHtml', false, '%1');").arg(url);
                editor->page()->mainFrame()->evaluateJavaScript(script);
                return;
            } else {
                QLOG_ERROR() << "Error retrieving note";
            }
        }
    }


    this->editor->triggerPageAction(QWebPage::Paste);
    this->editor->setFocus();
    microFocusChanged();
}




// The paste button was pressed
void NBrowserWindow::selectAllButtonPressed() {
    this->editor->triggerPageAction(QWebPage::SelectAll);
    this->editor->setFocus();
    microFocusChanged();
}



// The paste without mime format was pressed
void NBrowserWindow::pasteWithoutFormatButtonPressed() {
    const QMimeData *mime = QApplication::clipboard()->mimeData();
    if (!mime->hasText())
        return;
    QString text = mime->text();
    QApplication::clipboard()->clear();
    QApplication::clipboard()->setText(text, QClipboard::Clipboard);
    this->editor->triggerPageAction(QWebPage::Paste);

    // This is done because pasting into an encryption block
    // can cause multiple cells (which can't happen).  It
    // just goes through the table, extracts the data, &
    // puts it back as one table cell.
    if (insideEncryption) {
        QString js = QString( "function fixEncryption() { ")
                +QString("   var selObj = window.getSelection();")
                +QString("   var selRange = selObj.getRangeAt(0);")
                +QString("   var workingNode = window.getSelection().anchorNode;")
                +QString("   while(workingNode != null && workingNode.nodeName.toLowerCase() != 'table') { ")
                +QString("           workingNode = workingNode.parentNode;")
                +QString("   } ")
                +QString("   workingNode.innerHTML = window.browserWindow.fixEncryptionPaste(workingNode.innerHTML);")
                +QString("} fixEncryption();");
        editor->page()->mainFrame()->evaluateJavaScript(js);
    }

    this->editor->setFocus();
    microFocusChanged();
}

// This basically removes all the table tags and returns just the contents.
// This is called by JavaScript to fix encryption pastes.
QString NBrowserWindow::fixEncryptionPaste(QString data) {
    data = data.replace("<tbody>", "");
    data = data.replace("</tbody>", "");
    data = data.replace("<tr>", "");
    data = data.replace("</tr>", "");
    data = data.replace("<td>", "");
    data = data.replace("</td>", "<br>");
    data = data.replace("<br><br>", "<br>");
    return QString("<tbody><tr><td>")+data+QString("</td></tr></tbody>");
}



// The bold button was pressed / toggled
void NBrowserWindow::boldButtonPressed() {
    QAction *action = editor->page()->action(QWebPage::ToggleBold);
    action->activate(QAction::Trigger);
    this->editor->setFocus();
    microFocusChanged();
}



// The toggled button was pressed/toggled
void NBrowserWindow::italicsButtonPressed() {
    QAction *action = editor->page()->action(QWebPage::ToggleItalic);
    action->activate(QAction::Trigger);
    this->editor->setFocus();
    microFocusChanged();
}


// The underline button was toggled
void NBrowserWindow::underlineButtonPressed() {
    this->editor->triggerPageAction(QWebPage::ToggleUnderline);
    this->editor->setFocus();
    microFocusChanged();
}



// The underline button was toggled
void NBrowserWindow::removeFormatButtonPressed() {
    this->editor->triggerPageAction(QWebPage::RemoveFormat);
    this->editor->setFocus();
    microFocusChanged();
}



// The strikethrough button was pressed
void NBrowserWindow::strikethroughButtonPressed() {
    this->editor->triggerPageAction(QWebPage::ToggleStrikethrough);
    this->editor->setFocus();
    microFocusChanged();
}



// The horizontal line button was pressed
void NBrowserWindow::horizontalLineButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('insertHorizontalRule', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The center align button was pressed
void NBrowserWindow::alignCenterButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('JustifyCenter', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The left align button was pressed
void NBrowserWindow::alignLeftButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('JustifyLeft', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The align right button was pressed
void NBrowserWindow::alignRightButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('JustifyRight', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The shift right button was pressed
void NBrowserWindow::shiftRightButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('indent', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The shift left button was pressed
void NBrowserWindow::shiftLeftButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('outdent', false, '');");
    editor->setFocus();
    microFocusChanged();
}




// The number list button was pressed
void NBrowserWindow::numberListButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('InsertOrderedList', false, '');");
    editor->setFocus();
    microFocusChanged();
}



// The bullet list button was pressed
void NBrowserWindow::bulletListButtonPressed() {
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('InsertUnorderedList', false, '');");
    editor->setFocus();
    microFocusChanged();
}


void NBrowserWindow::contentChanged() {
    this->editor->isDirty = true;
    saveNoteContent();
    this->sendDateUpdateSignal();
}

// The todo button was pressed
void NBrowserWindow::todoButtonPressed() {
    QString script_start="document.execCommand('insertHtml', false, '";
    QString script_end = "');";
    QString todo =
            "<input TYPE=\"CHECKBOX\" " +
            QString("onMouseOver=\"style.cursor=\\'hand\\'\" ") +
            QString("onClick=\"if(!checked) removeAttribute(\\'checked\\'); else setAttribute(\\'checked\\', \\'checked\\'); editorWindow.editAlert();\" />");

    QString selectedText = editor->selectedText().trimmed();
    QRegExp regex("\\r?\\n");
    QStringList items = selectedText.split(regex);
    if (items.size() == 0)
        items.append(" ");
    QString newLineChar = "<div><br><div>";
    for (int i=0; i<items.size(); i++) {
        if (i == items.size()-1)
            newLineChar = "";
           editor->page()->mainFrame()->evaluateJavaScript(
                script_start +todo +items[i] +newLineChar + script_end);
    }
    editor->setFocus();
    microFocusChanged();
}



// The font size button was pressed
void NBrowserWindow::fontSizeSelected(int index) {
    int size = buttonBar->fontSizes->itemData(index).toInt();

    if (size <= 0)
        return;

    QString text = editor->selectedHtml();
    if (text.trimmed() == "")
        return;

    // Go througth the selected HTML and strip out all of the existing font-sizes.
    // This allows for the font size to be changed multiple times.  Without this the inner most font
    // size would always win.
    for (int i=text.indexOf("<"); i>=0; i=text.indexOf("<",i+1)) {
        QString text1="";
        QString text2="";
        text1 = text.mid(0,i);
        QString interior = text.mid(i);
        if (!interior.startsWith("</")) {
            int endPos = text.indexOf(">",i);
            if (endPos>0) {
                interior = text.mid(i,endPos-i);
                text2 = text.mid(endPos);
            }
            // Now that we have a substring, look for the font-size
            if (interior.contains("font-size:")) {
                interior = interior.mid(0,interior.indexOf("font-size:"))+
                        //QString::number(size)+
                        interior.mid(interior.indexOf("pt;")+3);
                text = text1+interior+text2;
            }
        }
    }

    // Start building a new font span.
    int idx = buttonBar->fontNames->currentIndex();
    QString font = buttonBar->fontNames->itemText(idx);

    QString newText = "<span style=\"font-size: " +QString::number(size) +"pt; font-family:"+font+";\">"+text+"</span>";
    QString script = QString("document.execCommand('insertHtml', false, '"+newText+"');");
    editor->page()->mainFrame()->evaluateJavaScript(script);

    editor->setFocus();
    microFocusChanged();
}



void NBrowserWindow::insertHtml(QString html) {
    QString script = QString("document.execCommand('insertHtml', false, '%1');").arg(html);
    editor->page()->mainFrame()->evaluateJavaScript(script);
    microFocusChanged();
}


// The font name list was selected
void NBrowserWindow::fontNameSelected(int index) {
    QString font = buttonBar->fontNames->itemData(index).toString();
    buttonBar->fontSizes->blockSignals(true);
    buttonBar->loadFontSizeComboBox(font);
    buttonBar->fontSizes->blockSignals(false);
    this->editor->page()->mainFrame()->evaluateJavaScript(
            "document.execCommand('fontName', false, '"+font+"');");
    editor->setFocus();
    microFocusChanged();
}



// The font highlight color was pressed
void NBrowserWindow::fontHighlightClicked() {
    QColor *color = buttonBar->highlightColorMenuWidget->getColor();
    if (color->isValid()) {
        this->editor->page()->mainFrame()->evaluateJavaScript(
                "document.execCommand('backColor', false, '"+color->name()+"');");
        editor->setFocus();
        microFocusChanged();
    }
}



// The font color was pressed
void NBrowserWindow::fontColorClicked() {
    QColor *color = buttonBar->fontColorMenuWidget->getColor();
    if (color->isValid()) {
        this->editor->page()->mainFrame()->evaluateJavaScript(
                "document.execCommand('foreColor', false, '"+color->name()+"');");
        editor->setFocus();
        microFocusChanged();
    }
}


void NBrowserWindow::insertLinkButtonPressed() {
    QString text = editor->selectedText().trimmed();
    if (text == "" && currentHyperlink == "")
        return;

    InsertLinkDialog dialog(insertHyperlink);

    // If we have a link already highlighted, set it to the dialog.
    if (text.startsWith("http://", Qt::CaseInsensitive) ||
            text.startsWith("https://", Qt::CaseInsensitive) ||
            text.startsWith("ftp://", Qt::CaseInsensitive) ||
            text.startsWith("mailto:", Qt::CaseInsensitive)) {
        dialog.setUrl(text);
    }

    if (currentHyperlink != NULL && currentHyperlink != "") {
        dialog.setUrl(currentHyperlink);
    }
    dialog.exec();
    if (!dialog.okButtonPressed()) {
        return;
    }

    // Take care of inserting new links
    if (insertHyperlink) {
        QString selectedText = editor->selectedText().replace("'","\\'");
        if (dialog.getUrl().trimmed() == "")
            return;
        QString durl = dialog.getUrl().trimmed().replace("'","\\'");
        QString url = QString("<a href=\"%1\" title=\"%2\">%3</a>").arg(durl,durl,selectedText);
        QString script = QString("document.execCommand('insertHtml', false, '%1')").arg(url);
        editor->page()->mainFrame()->evaluateJavaScript(script);
        return;
    }

    QString x = dialog.getUrl();
    // Edit existing links
    QString js =  "function getCursorPos() {"
            "var cursorPos;"
            "if (window.getSelection) {"
            "   var selObj = window.getSelection();"
            "   var selRange = selObj.getRangeAt(0);"
            "   var workingNode = window.getSelection().anchorNode.parentNode;"
            "   while(workingNode != null) { "
            "      if (workingNode.nodeName.toLowerCase()=='a') workingNode.setAttribute('href','";
    js = js + dialog.getUrl() +QString("');")
            +QString("      workingNode = workingNode.parentNode;")
            +QString("   }")
            +QString("}")
            +QString("} getCursorPos();");
    editor->page()->mainFrame()->evaluateJavaScript(js);

    if (dialog.getUrl().trimmed() != "" ) {
        contentChanged();
        return;
    }

    // Remove URL
    js = QString( "function getCursorPos() {")
            + QString("var cursorPos;")
            + QString("if (window.getSelection) {")
            + QString("   var selObj = window.getSelection();")
            + QString("   var selRange = selObj.getRangeAt(0);")
            + QString("   var workingNode = window.getSelection().anchorNode.parentNode;")
            + QString("   while(workingNode != null) { ")
            + QString("      if (workingNode.nodeName.toLowerCase()=='a') { ")
            + QString("         workingNode.removeAttribute('href');")
            + QString("         workingNode.removeAttribute('title');")
            + QString("         var text = document.createTextNode(workingNode.innerText);")
            + QString("         workingNode.parentNode.insertBefore(text, workingNode);")
            + QString("         workingNode.parentNode.removeChild(workingNode);")
            + QString("      }")
            + QString("      workingNode = workingNode.parentNode;")
            + QString("   }")
            + QString("}")
            + QString("} getCursorPos();");
        editor->page()->mainFrame()->evaluateJavaScript(js);

        contentChanged();
}





void NBrowserWindow::removeLinkButtonPressed() {
    // Remove URL
    QString js = QString( "function getCursorPos() {")
            + QString("var cursorPos;")
            + QString("if (window.getSelection) {")
            + QString("   var selObj = window.getSelection();")
            + QString("   var selRange = selObj.getRangeAt(0);")
            + QString("   var workingNode = window.getSelection().anchorNode.parentNode;")
            + QString("   while(workingNode != null) { ")
            + QString("      if (workingNode.nodeName.toLowerCase()=='a') { ")
            + QString("         workingNode.removeAttribute('href');")
            + QString("         workingNode.removeAttribute('title');")
            + QString("         var text = document.createTextNode(workingNode.innerText);")
            + QString("         workingNode.parentNode.insertBefore(text, workingNode);")
            + QString("         workingNode.parentNode.removeChild(workingNode);")
            + QString("      }")
            + QString("      workingNode = workingNode.parentNode;")
            + QString("   }")
            + QString("}")
            + QString("} getCursorPos();");
        editor->page()->mainFrame()->evaluateJavaScript(js);
        contentChanged();
}



void NBrowserWindow::insertQuickLinkButtonPressed() {
    QString text = editor->selectedText();
    if (text.trimmed() == "")
        return;

    NoteTable ntable(global.db);
    QList<qint32> lids;
    if (!ntable.findNotesByTitle(lids, text))
        if (!ntable.findNotesByTitle(lids, text.trimmed()+"%"))
            if (!ntable.findNotesByNotebook(lids, "%"+text.trimmed()+"%"))
                return;
    Note n;

    // If we have a good return, then we can paste the link, otherwise we fall out
    // to a normal paste.
    if (ntable.get(n, lids[0],false, false)) {
        UserTable utable(global.db);
        User user;
        utable.getUser(user);

        QString href = "evernote:///view/" + QString::number(user.id) + QString("/") +
               user.shardId +QString("/") +
                n.guid +QString("/") +
                n.guid + QString("/");

        QString url = QString("<a href=\"") +href
                +QString("\" title=\"") +text
                +QString("\">") +text +QString("</a>");
        QString script = QString("document.execCommand('insertHtml', false, '")+url+QString("');");
        editor->page()->mainFrame()->evaluateJavaScript(script);
        return;
    }
}


void NBrowserWindow::insertLatexButtonPressed() {
    this->editLatex("");
}




void NBrowserWindow::insertTableButtonPressed() {
    TableDialog dialog(this);
    dialog.exec();
    if (!dialog.isOkPressed()) {
        return;
    }

    int cols = dialog.getCols();
    int rows = dialog.getRows();
    int width = dialog.getWidth();
    bool percent = dialog.isPercent();

    QString newHTML = QString("<table border=\"1\" width=\"") +QString::number(width);
    if (percent)
        newHTML = newHTML +"%";
    newHTML = newHTML + "\"><tbody>";

    for (int i=0; i<rows; i++) {
        newHTML = newHTML +"<tr>";
        for (int j=0; j<cols; j++) {
            newHTML = newHTML +"<td>&nbsp;</td>";
        }
        newHTML = newHTML +"</tr>";
    }
    newHTML = newHTML+"</tbody></table>";

    QString script = "document.execCommand('insertHtml', false, '"+newHTML+"');";
    editor->page()->mainFrame()->evaluateJavaScript(script);
    contentChanged();
}

void NBrowserWindow::insertTableRowButtonPressed() {
    QString js ="function insertTableRow() {"
        "   var selObj = window.getSelection();"
        "   var selRange = selObj.getRangeAt(0);"
        "   var workingNode = window.getSelection().anchorNode.parentNode;"
        "   var cellCount = 0;"
        "   while(workingNode != null) { "
        "      if (workingNode.nodeName.toLowerCase()=='tr') {"
        "           row = document.createElement('TR');"
        "           var nodes = workingNode.getElementsByTagName('td');"
        "           for (j=0; j<nodes.length; j=j+1) {"
        "              cell = document.createElement('TD');"
        "              cell.innerHTML='&nbsp;';"
        "              row.appendChild(cell);"
        "           }"
        "           workingNode.parentNode.insertBefore(row,workingNode.nextSibling);"
        "           return;"
        "      }"
        "      workingNode = workingNode.parentNode;"
        "   }"
        "} insertTableRow();";
    editor->page()->mainFrame()->evaluateJavaScript(js);
    contentChanged();
}


void NBrowserWindow::insertTableColumnButtonPressed() {
    QString js = "function insertTableColumn() {"
            "   var selObj = window.getSelection();"
            "   var selRange = selObj.getRangeAt(0);"
            "   var workingNode = window.getSelection().anchorNode.parentNode;"
            "   var current = 0;"
            "   while (workingNode.nodeName.toLowerCase() != 'table' && workingNode != null) {"
            "       if (workingNode.nodeName.toLowerCase() == 'td') {"
            "          var td = workingNode;"
            "          while (td.previousSibling != null) { "
            "             current = current+1; td = td.previousSibling;"
            "          }"
            "       }"
            "       workingNode = workingNode.parentNode; "
            "   }"
            "   if (workingNode == null) return;"
            "   for (var i=0; i<workingNode.rows.length; i++) { "
            "      var cell = workingNode.rows[i].insertCell(current+1); "
            "      cell.innerHTML = '&nbsp'; "
            "   }"
            "} insertTableColumn();";
        editor->page()->mainFrame()->evaluateJavaScript(js);
        contentChanged();
}


void NBrowserWindow::deleteTableRowButtonPressed() {
    QString js = "function deleteTableRow() {"
        "   var selObj = window.getSelection();"
        "   var selRange = selObj.getRangeAt(0);"
        "   var workingNode = window.getSelection().anchorNode.parentNode;"
        "   var cellCount = 0;"
        "   while(workingNode != null) { "
        "      if (workingNode.nodeName.toLowerCase()=='tr') {"
        "           workingNode.parentNode.removeChild(workingNode);"
        "           return;"
        "      }"
        "      workingNode = workingNode.parentNode;"
        "   }"
        "} deleteTableRow();";
    editor->page()->mainFrame()->evaluateJavaScript(js);
    contentChanged();
}


void NBrowserWindow::deleteTableColumnButtonPressed() {
    QString js = "function deleteTableColumn() {"
            "   var selObj = window.getSelection();"
            "   var selRange = selObj.getRangeAt(0);"
            "   var workingNode = window.getSelection().anchorNode.parentNode;"
            "   var current = 0;"
            "   while (workingNode.nodeName.toLowerCase() != 'table' && workingNode != null) {"
            "       if (workingNode.nodeName.toLowerCase() == 'td') {"
            "          var td = workingNode;"
            "          while (td.previousSibling != null) { "
            "             current = current+1; td = td.previousSibling;"
            "          }"
            "       }"
            "       workingNode = workingNode.parentNode; "
            "   }"
            "   if (workingNode == null) return;"
            "   for (var i=0; i<workingNode.rows.length; i++) { "
            "      workingNode.rows[i].deleteCell(current); "
            "   }"
            "} deleteTableColumn();";
        editor->page()->mainFrame()->evaluateJavaScript(js);
        contentChanged();
}

void NBrowserWindow::rotateImageLeftButtonPressed() {
    rotateImage(-90.0);
}




void NBrowserWindow::rotateImageRightButtonPressed() {
    rotateImage(90.0);
}


void NBrowserWindow::rotateImage(qreal degrees) {

    // rotate the image
    QWebSettings::setMaximumPagesInCache(0);
    QWebSettings::setObjectCacheCapacities(0, 0, 0);
    QImage image(global.fileManager.getDbaDirPath() +selectedFileName);
    QMatrix matrix;
    matrix.rotate( degrees );
    image = image.transformed(matrix);
    image.save(global.fileManager.getDbaDirPath() +selectedFileName);
    editor->setHtml(editor->page()->mainFrame()->toHtml());

    // Now, we need to update the note's MD5
    QFile f(global.fileManager.getDbaDirPath() +selectedFileName);
    f.open(QIODevice::ReadOnly);
    QByteArray filedata = f.readAll();
    QCryptographicHash hash(QCryptographicHash::Md5);
    QByteArray b = hash.hash(filedata, QCryptographicHash::Md5);
    updateImageHash(b);

    // Reload the web page
    editor->triggerPageAction(QWebPage::ReloadAndBypassCache);
    contentChanged();
}


void NBrowserWindow::updateImageHash(QByteArray newhash) {
    QString content = editor->page()->mainFrame()->toHtml();
    int pos = content.indexOf("<img ");
    for (; pos != -1; pos=content.indexOf("<img ", pos+1) ) {
        int endPos = content.indexOf(">", pos);
        QString section = content.mid(pos, endPos-pos);
        if (section.contains("lid=\"" +QString::number(selectedFileLid) + "\"")) {
            ResourceTable rtable(global.db);
            QString oldhash = section.mid(section.indexOf("hash=\"")+6);
            oldhash = oldhash.mid(0,oldhash.indexOf("\""));
            section.replace(oldhash, newhash.toHex());
            QString newcontent = content.mid(0,pos) +section +content.mid(endPos);
            QByteArray c;
            c.append(newcontent);
            editor->page()->mainFrame()->setContent(c);
            rtable.updateResourceHash(selectedFileLid, newhash);
            return;
        }
    }
}

void NBrowserWindow::imageContextMenu(QString l, QString f) {
    editor->downloadAttachmentAction()->setEnabled(true);
    editor->rotateImageRightAction->setEnabled(true);
    editor->rotateImageLeftAction->setEnabled(true);
    editor->openAction->setEnabled(true);
    editor->downloadImageAction()->setEnabled(true);
    selectedFileName = f;
    selectedFileLid = l.toInt();
}


void NBrowserWindow::attachFile() {
    QFileDialog fileDialog;
    if (attachFilePath != "")
        fileDialog.setDirectory(attachFilePath);
    else
        fileDialog.setDirectory(QDir::homePath());
    fileDialog.setFileMode(QFileDialog::ExistingFile);
    connect(&fileDialog, SIGNAL(fileSelected(QString)), this, SLOT(attachFileSelected(QString)));
    fileDialog.exec();
}



//****************************************************************
//* MicroFocus changed
//****************************************************************
 void NBrowserWindow::microFocusChanged() {
     buttonBar->boldButtonWidget->setDown(false);
     buttonBar->italicButtonWidget->setDown(false);
     buttonBar->underlineButtonWidget->setDown(false);
     editor->openAction->setEnabled(false);
     editor->downloadAttachmentAction()->setEnabled(false);
     editor->rotateImageLeftAction->setEnabled(false);
     editor->rotateImageRightAction->setEnabled(false);
     editor->insertTableAction->setEnabled(true);
     editor->insertTableColumnAction->setEnabled(false);
     editor->insertTableRowAction->setEnabled(false);
     editor->deleteTableRowAction->setEnabled(false);
     editor->deleteTableColumnAction->setEnabled(false);
     editor->insertLinkAction->setText(tr("Insert Link"));
     editor->removeLinkAction->setEnabled(false);
     editor->insertQuickLinkAction->setEnabled(true);
     editor->rotateImageRightAction->setEnabled(false);
     editor->rotateImageLeftAction->setEnabled(false);

//     QLOG_DEBUG() << editor->page()->inputMethodQuery(Qt::ImCursorPosition).toInt();
//     QLOG_DEBUG() << editor->page()->inputMethodQuery(Qt::ImSurroundingText).toString();

     insertHyperlink = true;
     currentHyperlink ="";
     insideList = false;
     insideTable = false;
     insideEncryption = false;
     forceTextPaste = false;

     if (editor->selectedText().trimmed().length() > 0 && global.javaFound)
         editor->encryptAction->setEnabled(true);
     else
         editor->encryptAction->setEnabled(false);


         //     +QString("            window.browserWindow.printNodeName(workingNode.firstChild.nodeValue);")
    QString js = QString("function getCursorPos() {")
        +QString("var cursorPos;")
        +QString("var insideUrl=false;")
        +QString("if (window.getSelection) {")
        +QString("   var selObj = window.getSelection();")
        +QString("   var selRange = selObj.getRangeAt(0);")
        +QString("   var workingNode = window.getSelection().anchorNode.parentNode;")
        //+QString("    window.browserWindow.printNodeName(workingNode.nodeName);")
        +QString("   while(workingNode != null) { ")
        //+QString("      window.browserWindow.printNodeName(workingNode.nodeName);")
        +QString("      if (workingNode.nodeName=='TABLE') {")
        +QString("          if (workingNode.getAttribute('class').toLowerCase() == 'en-crypt-temp') window.browserWindow.insideEncryptionArea();")
        +QString("      }")
        +QString("      if (workingNode.nodeName=='B') window.browserWindow.boldActive();")
        +QString("      if (workingNode.nodeName=='I') window.browserWindow.italicsActive();")
        +QString("      if (workingNode.nodeName=='U') window.browserWindow.underlineActive();")
        +QString("      if (workingNode.nodeName=='UL') window.browserWindow.setInsideList();")
        +QString("      if (workingNode.nodeName=='OL') window.browserWindow.setInsideList();")
        +QString("      if (workingNode.nodeName=='LI') window.browserWindow.setInsideList();")
        +QString("      if (workingNode.nodeName=='TBODY') window.browserWindow.setInsideTable();")
        +QString("      if (workingNode.nodeName=='A') {")
        +QString("           insideUrl = true;")
        +QString("           for(var x = 0; x < workingNode.attributes.length; x++ ) {")
        +QString("              if (workingNode.attributes[x].nodeName.toLowerCase() == 'href')")
        +QString("                  window.browserWindow.setInsideLink(workingNode.attributes[x].nodeValue);")
        +QString("           }")
        +QString("      }")
        +QString("      if (workingNode.nodeName=='SPAN') {")
        +QString("         if (workingNode.getAttribute('style') == 'text-decoration: underline;') window.browserWindow.underlineActive();")
        +QString("      }")
        +QString("      workingNode = workingNode.parentNode;")
        +QString("   }")
        +QString("}")
        +QString("}  getCursorPos();");
    editor->page()->mainFrame()->evaluateJavaScript(js);


    QString js2 = QString("function getFontSize() {") +
                  QString("    var node = document.getSelection().anchorNode;") +
                  QString("    var anchor = (node.nodeType == 3 ? node.parentNode : node);") +
                  QString("      var size = window.getComputedStyle(anchor,null)[\"fontSize\"];") +
                  QString("      var font = window.getComputedStyle(anchor,null)[\"fontFamily\"];") +
                  QString("      window.browserWindow.changeDisplayFontSize(size);") +
                  QString("      window.browserWindow.changeDisplayFontName(font);") +
                  QString("} getFontSize();");
    editor->page()->mainFrame()->evaluateJavaScript(js2);
 }

 void NBrowserWindow::printNodeName(QString v) {
     QLOG_DEBUG() << v;
 }


 // Tab button pressed
 void NBrowserWindow::tabPressed() {
     if (insideEncryption)
         return;
     if (!insideList && !insideTable) {
         QString script_start =  "document.execCommand('insertHtml', false, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');";
         editor->page()->mainFrame()->evaluateJavaScript(script_start);
         return;
     }
     if (insideList) {
         shiftRightButtonPressed();
     }
     if (insideTable) {
         QString js =  "function getCursorPosition() { "
                 "   var selObj = window.getSelection();"
                 "   var selRange = selObj.getRangeAt(0);"
                 "   var workingNode = window.getSelection().anchorNode;"
                 "   var rowCount = 0;"
                 "   var colCount = 0;"
                 "   while(workingNode != null && workingNode.nodeName.toLowerCase() != 'table') { "
                 "      if (workingNode.nodeName.toLowerCase()=='tr') {"
                 "         rowCount = rowCount+1;"
                 "      }"
                 "      if (workingNode.nodeName.toLowerCase() == 'td') {"
                 "         colCount = colCount+1;"
                 "      }"
                 "      if (workingNode.previousSibling != null)"
                 "          workingNode = workingNode.previousSibling;"
                 "      else "
                 "           workingNode = workingNode.parentNode;"
                 "   }"
                 "   var nodes = workingNode.getElementsByTagName('tr');"
                 "   var tableRows = nodes.length;"
                 "   nodes = nodes[0].getElementsByTagName('td');"
                 "   var tableColumns = nodes.length;"
                 "   window.browserWindow.setTableCursorPositionTab(rowCount, colCount, tableRows, tableColumns);"
                 "} getCursorPosition();";
         editor->page()->mainFrame()->evaluateJavaScript(js);
     }

 }


 // Backtab pressed.
 void NBrowserWindow::backtabPressed() {
     if (insideEncryption)
         return;
     if (insideList)
         shiftLeftButtonPressed();
     if (insideTable) {
         QString js = "function getCursorPosition() { "
                 "   var selObj = window.getSelection();"
                 "   var selRange = selObj.getRangeAt(0);"
                 "   var workingNode = window.getSelection().anchorNode;"
                 "   var rowCount = 0;"
                 "   var colCount = 0;"
                 "   while(workingNode != null && workingNode.nodeName.toLowerCase() != 'table') { "
                 "      if (workingNode.nodeName.toLowerCase()=='tr') {"
                 "         rowCount = rowCount+1;"
                 "      }"
                 "      if (workingNode.nodeName.toLowerCase() == 'td') {"
                 "         colCount = colCount+1;"
                 "      }"
                 "      if (workingNode.previousSibling != null)"
                 "          workingNode = workingNode.previousSibling;"
                 "      else "
                 "           workingNode = workingNode.parentNode;"
                 "   }"
                 "   var nodes = workingNode.getElementsByTagName('tr');"
                 "   var tableRows = nodes.length;"
                 "   nodes = nodes[0].getElementsByTagName('td');"
                 "   var tableColumns = nodes.length;"
                 "   window.browserWindow.setTableCursorPositionBackTab(rowCount, colCount, tableRows, tableColumns);"
                 "} getCursorPosition();";
         editor->page()->mainFrame()->evaluateJavaScript(js);
     }
 }



 // If a user presses backtab from within a table
void NBrowserWindow::setTableCursorPositionBackTab(int currentRow, int currentCol, int tableRows, int tableColumns) {
    // suppress unused warninsg
    Q_UNUSED(tableRows);
    Q_UNUSED(tableColumns);

    // Determine what key to emulate.
     if (currentRow  == 1 && currentCol == 1) {
         return;
     }
     QKeyEvent *up = new QKeyEvent(QEvent::KeyPress, Qt::Key_Up, Qt::NoModifier);
     QCoreApplication::postEvent(editor->editorPage, up);
}



// If a user presses backtab from within a table
void NBrowserWindow::setTableCursorPositionTab(int currentRow, int currentCol, int tableRows, int tableColumns) {
    if (currentRow  == tableRows && currentCol == tableColumns) {
        return;
    }
    QKeyEvent *down = new QKeyEvent(QEvent::KeyPress, Qt::Key_Down, Qt::NoModifier);
    QCoreApplication::postEvent(editor->editorPage, down);
}



// Set the background color of a note
 void NBrowserWindow::setBackgroundColor(QString value) {
     QString js = QString("function changeBackground(color) {")
         +QString("document.body.style.background = color;")
         +QString("}")
         +QString("changeBackground('" +value+"');");
     editor->page()->mainFrame()->evaluateJavaScript(js);
     NoteTable noteTable(global.db);
     noteTable.setDirty(this->lid, true);
     this->editor->isDirty = true;
     editor->setFocus();
     microFocusChanged();
 }


 // The user clicked a link in the note
 void NBrowserWindow::linkClicked(const QUrl url) {
     if (url.toString().startsWith("latex:///", Qt::CaseInsensitive)) {
         editLatex(url.toString().mid(9));
         return;
     }
     if (url.toString().startsWith("evernote:/view/", Qt::CaseInsensitive) ||
             url.toString().startsWith("evernote:///view/", Qt::CaseInsensitive)) {

         QStringList tokens;
         if (url.toString().startsWith("evernote:/view/", Qt::CaseInsensitive))
            tokens = url.toString().replace("evernote:/view/", "").split("/", QString::SkipEmptyParts);
         else
            tokens = url.toString().replace("evernote:///view/", "").split("/", QString::SkipEmptyParts);
         QString oguid =tokens[2];
         QString eguid = tokens[3];
         NoteTable ntable(global.db);
         qint32 newlid = ntable.getLid(eguid);
         if (newlid <= 0)
             newlid = ntable.getLid(oguid);
         if (newlid <= 0)
             return;

         bool newExternalWindow = false;
         bool newTab = false;
         if (QApplication::keyboardModifiers() & Qt::ShiftModifier) {
            if (global.getMiddleClickAction() == MOUSE_MIDDLE_CLICK_NEW_WINDOW)
                newExternalWindow = true;
            else
                newTab = true;
         } else {
             // Setup a new filter
             FilterCriteria *criteria = new FilterCriteria();
             global.filterCriteria[global.filterPosition]->duplicate(*criteria);
             criteria->unsetSelectedNotes();
             criteria->unsetLid();
             criteria->setLid(newlid);
             global.appendFilter(criteria);
             global.filterPosition++;
         }
         emit(evernoteLinkClicked(newlid, newTab, newExternalWindow));

         return;
     }
     if (url.toString().startsWith("nnres:", Qt::CaseInsensitive)) {
         if (url.toString().endsWith("/vnd.evernote.ink")) {
             QMessageBox::information(this, tr("Unable Open"), QString(tr("This is an ink note.\nInk notes are not supported since Evernote has not\n published any specifications on them\nand I'm too lazy to figure them out by myself.")));
             return;
         }
         QString filepath = global.fileManager.getDbaDirPath();
// Windows check
#ifdef _WIN32
         filepath = filepath.replace("\\", "/");
#endif // End windows check
         QString fullName = url.toString().mid(6).replace(filepath,"");
         filepath = filepath.replace("\\", "/");
         QLOG_DEBUG() << global.fileManager.getDbaDirPath();
         int index = fullName.lastIndexOf(".");
         QString guid = "";
         if (index != -1) {
             guid = fullName.mid(0,index);
         } else
             guid = fullName;
         QDirIterator dirIt(global.fileManager.getDbaDirPath());
         QString fileUrl = "";
         while (dirIt.hasNext()) {
             if (QFileInfo(dirIt.filePath()).isFile() && QFileInfo(dirIt.filePath()).baseName() == guid) {
                 fileUrl = dirIt.fileName();
             }
             dirIt.next();
         }
         if (fileUrl == "")
             return;
         fileUrl = global.fileManager.getDbaDirPath()+fileUrl;

// Windows check
#ifdef _WIN32
         fileUrl = fileUrl.replace("\\", "/");
#endif // End windows check
         global.resourceWatcher.addPath(fileUrl);
         QDesktopServices::openUrl(fileUrl);
         return;
     }
     QDesktopServices::openUrl(url);
 }



 // show/hide view source window
void NBrowserWindow::showSource(bool value) {
     setSource();
     sourceEdit->setVisible(value);
     sourceEditorTimer->setInterval(1000);
     if (!value)
         sourceEditorTimer->stop();
     else
         sourceEditorTimer->start();
 }



// Toggle the show source button
void NBrowserWindow::toggleSource() {
    if (sourceEdit->isVisible())
        showSource(false);
    else
        showSource(true);
}



// Clear out the window's contents
void NBrowserWindow::clear() {

    sourceEdit->blockSignals(true);
    editor->blockSignals(true);
    sourceEdit->setPlainText("");
    editor->setContent("<html><body></body></html>");
    sourceEdit->setReadOnly(true);
    editor->page()->setContentEditable(false);
    lid = -1;
    editor->blockSignals(false);
    sourceEdit->blockSignals(false);

    noteTitle.blockSignals(true);
    noteTitle.setTitle(-1, "", "");
    noteTitle.blockSignals(false);

    tagEditor.blockSignals(true);
    tagEditor.clear();
    tagEditor.blockSignals(false);

//    authorEditor.blockSignals(true);
//    authorEditor.setText("");
//    authorEditor.blockSignals(false);

    urlEditor.blockSignals(true);
    urlEditor.setUrl(-1, "");
    urlEditor.blockSignals(false);

//    dateEditor.setEnabled(false);
//    editor->page()->setContentEditable(false);

    dateEditor.clear();
}



// Set the source for the "show source" button
void NBrowserWindow::setSource() {
    if (sourceEdit->hasFocus())
        return;

    QString text = editor->editorPage->mainFrame()->toHtml();
    sourceEdit->blockSignals(true);
    int body = text.indexOf("<body", Qt::CaseInsensitive);
    if (body != -1) {
        body = text.indexOf(">",body);
        if (body != -1) {
            sourceEditHeader =text.mid(0, body+1);
            text = text.mid(body+1);
        }
    }
    text = text.replace("</body></html>", "");
    sourceEdit->setPlainText(text);
 //   sourceEdit->setReadOnly(true);
    sourceEdit->setReadOnly(!editor->page()->isContentEditable());
    sourceEdit->blockSignals(false);
}



// Expose the programs to the javascript process
void NBrowserWindow::exposeToJavascript() {
    editor->page()->mainFrame()->addToJavaScriptWindowObject("browserWindow", this);
}



// If we are within bold text, set the bold button active
void NBrowserWindow::boldActive() {
    buttonBar->boldButtonWidget->setDown(true);
}



// If we are within italics text, make the text button active
void NBrowserWindow::italicsActive() {
   buttonBar->italicButtonWidget->setDown(true);
}



// If we are within encrypted text, make sure we force a paste text
void NBrowserWindow::insideEncryptionArea() {
    insideEncryption = true;
    forceTextPaste = true;
}



// If we are within underlined text, make the button active
void NBrowserWindow::underlineActive() {
    buttonBar->underlineButtonWidget->setDown(true);
}



// Set true if we are within some type of list
void NBrowserWindow::setInsideList() {
    insideList = true;
}



// If we are within a table, set the menu options active
void NBrowserWindow::setInsideTable() {
    editor->insertTableAction->setEnabled(false);
    editor->insertTableRowAction->setEnabled(true);
    editor->insertTableColumnAction->setEnabled(true);
    editor->deleteTableRowAction->setEnabled(true);
    editor->deleteTableColumnAction->setEnabled(true);
    editor->encryptAction->setEnabled(false);
    insideTable = true;
}


// Set if we are within a link
void NBrowserWindow::setInsideLink(QString link) {
    currentHyperlink = link;
    editor->insertLinkAction->setText(tr("Edit Link"));
    editor->removeLinkAction->setEnabled(true);
    currentHyperlink = link;
    insertHyperlink = false;
}




// Edit a latex formula
void NBrowserWindow::editLatex(QString guid) {
    QString text = editor->selectedText();
    QString oldFormula = "";
    if (text.trimmed() == "\n" || text.trimmed() == "") {
        InsertLatexDialog dialog;
        if (guid.trimmed() != "") {
            Resource r;
            ResourceTable resTable(global.db);
            resTable.get(r, guid.toInt(), false);
            if (r.attributes.isSet()) {
                ResourceAttributes attributes;
                attributes = r.attributes;
                if (attributes.sourceURL.isSet()) {
                    QString formula = attributes.sourceURL;
                    formula = formula.replace("http://latex.codecogs.com/gif.latex?", "");
                    oldFormula = formula;
                    dialog.setFormula(formula);
                }
            }
        }
        dialog.exec();
        if (!dialog.okPressed()) {
            return;
        }
        text = dialog.getFormula().trimmed();
    }

    ConfigStore cs(global.db);
    qint32 newlid = cs.incrementLidCounter();
    Resource r;
    NoteTable ntable(global.db);
    ResourceTable rtable(global.db);
    QString outfile = global.fileManager.getDbaDirPath() + QString::number(newlid) +QString(".gif");

    // Run it through "mimetex" to create the gif
    QProcess latexProcess;
    QStringList args;
    args.append("-e");
    args.append(outfile);
    args.append(text);
    QLOG_DEBUG() << "Formula:" << "mimetex -e "+outfile +" '" +text +"'";
    //latexProcess.start(formula, QIODevice::ReadWrite|QIODevice::Unbuffered);
    latexProcess.start("mimetex", args, QIODevice::ReadWrite|QIODevice::Unbuffered);

    latexProcess.waitForStarted();
    latexProcess.waitForFinished();
    QLOG_DEBUG() << " LaTeX Return Code: " << latexProcess.state();
    QLOG_DEBUG() << "mimetex Errors:" << latexProcess.readAllStandardError();
    QLOG_DEBUG() << "mimetex Output:" << latexProcess.readAllStandardOutput();

    // Now, check if the file exists.  If it does, we continue to create the resource
    QFile f(outfile);
    if (!f.exists()) {
        QMessageBox msgBox;
        msgBox.setText(tr("Unable to create LaTeX image"));
        msgBox.setInformativeText(tr("Unable to create LaTeX image.  Are you sure mimetex is installed?"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        return;
    }
    f.open(QIODevice::ReadOnly);
    QByteArray data = f.readAll();
    f.close();
    f.open(QIODevice::ReadOnly);
    QCryptographicHash md5hash(QCryptographicHash::Md5);
    QByteArray hash = md5hash.hash(data, QCryptographicHash::Md5);

    Data d;
    if (r.data.isSet())
        d = r.data;
    d.body = f.read(data.size());
    r.data = d;
    f.close();
    d.bodyHash = hash;
    d.size = data.size();
    r.data = d;

    r.guid = QString::number(newlid);
    r.noteGuid = ntable.getGuid(lid);

    r.mime = "image/gif";
    r.active = true;
    r.updateSequenceNum = 0;
    r.width = 0;
    r.height = 0;
    r.duration = 0;

    ResourceAttributes a;
    a.attachment = false;
    a.sourceURL = "http://latex.codecogs.com/gif.latex?" +text;
    r.attributes = a;

    rtable.add(newlid, r, true, lid);

    // do the actual insert into the note

    QString buffer;
    buffer.append("<a onmouseover=\"cursor:&apos;hand&apos;\" title=\"");
    buffer.append(text.remove(QRegExp("[^a-zA-Z +-*/^{}()]")));
    buffer.append("\" href=\"latex:///");
    buffer.append(QString::number(newlid));
    buffer.append("\">");
    buffer.append("<img src=\"file://");
    buffer.append(outfile);
    buffer.append("\" type=\"image/gif\" hash=\"");
    buffer.append(hash.toHex());
    buffer.append("\" onContextMenu=\"window.browser.imageContextMenu(&apos;");
    buffer.append(QString::number(newlid));
    buffer.append("&apos;, &apos;");
    buffer.append(outfile);
    buffer.append("&apos;);\" ");
    buffer.append(" en-tag=\"en-latex\" lid=\"");
    buffer.append(QString::number(newlid));
    buffer.append("\"></a>");

    // If this is a new formula, we insert it, otherwise we replace the old one.
    if (oldFormula == "") {
        QString script_start = "document.execCommand('insertHTML', false, '";
        QString script_end = "');";

        editor->page()->mainFrame()->evaluateJavaScript(
                script_start + buffer + script_end);
    } else {
        QString oldHtml = editor->page()->mainFrame()->toHtml();
        int startPos = oldHtml.indexOf("<a");
        while (startPos != -1) {
	    int endPos = oldHtml.indexOf("</a>", startPos);
            if (endPos != -1) {
                QString slice = oldHtml.mid(startPos, endPos-startPos+4);
                if (slice.contains("lid=\""+guid+"\"") && slice.contains("en-latex")) {
                    oldHtml.replace(slice, buffer);
                }
                startPos = oldHtml.indexOf("<a", endPos);
                editor->page()->mainFrame()->setHtml(oldHtml);
            }
        }
	editor->reload();
	contentChanged();
    }
}


// Set the focus to the note title
void NBrowserWindow::focusTitle() {
    this->noteTitle.setFocus();
}


// Set the focus to the note
void NBrowserWindow::focusNote() {
    this->editor->setFocus();
}


// Insert the date/time into a note
void NBrowserWindow::insertDatetime() {
    QDateTime dt = QDateTime::currentDateTime();
    QLocale locale;
    QString dts = dt.toString(locale.dateTimeFormat(QLocale::ShortFormat));

    editor->page()->mainFrame()->evaluateJavaScript(
        "document.execCommand('insertHtml', false, '"+dts+"');");
    editor->setFocus();
}



// Insert an image into the editor
void NBrowserWindow::insertImage(const QMimeData *mime) {

    // Get the image from the clipboard and save it into a QByteArray
    // that can be saved
    QImage img = qvariant_cast<QImage>(mime->imageData());
//    QClipboard *clipboard = global.clipboard;
//    QImage img = clipboard->pixmap().toImage();
    QByteArray imageBa;
    QBuffer b(&imageBa);
    b.open(QIODevice::WriteOnly);
    img.save(&b, "PNG");

    QString script_start = "document.execCommand('insertHTML', false, '";
    QString script_end = "');";

    Resource newRes;
    qint32 rlid = createResource(newRes, 0, imageBa, "image/png", false, "");
    if (rlid <= 0)
        return;

    // The resource is done, now we need to add it to the
    // note body
    QString g =  QString::number(rlid)+QString(".png");
    QString path = global.fileManager.getDbaDirPath() + g;

    // do the actual insert into the note
    QString buffer;
    Data d;
    if (newRes.data.isSet())
        d =newRes.data;
    QByteArray hash;
    if (d.bodyHash.isSet())
         hash = d.bodyHash;
    buffer.append("<img src=\"file://");
    buffer.append(path);
    buffer.append("\" type=\"image/png\" hash=\"");
    buffer.append(hash.toHex());
    buffer.append("\" onContextMenu=\"window.browser.imageContextMenu(&apos;");
    buffer.append(QString::number(rlid));
    buffer.append("&apos;, &apos;");
    buffer.append(g);
    buffer.append("&apos;);\" ");
    buffer.append(" en-tag=\"en-media\" style=\"cursor: default;\" lid=\"");
    buffer.append(QString::number(rlid));
    buffer.append("\">");

    // Insert the actual note
    editor->page()->mainFrame()->evaluateJavaScript(
            script_start + buffer + script_end);

    return;
}


// Create  a new resource and add it to the database
qint32 NBrowserWindow::createResource(Resource &r, int sequence, QByteArray data,  QString mime, bool attachment, QString filename) {
    ConfigStore cs(global.db);
    qint32 rlid = cs.incrementLidCounter();

    QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5);

    QString guid =  QString::number(rlid);
    NoteTable noteTable(global.db);
    r.guid = guid;
    r.noteGuid = noteTable.getGuid(lid);
    QString noteguid = r.noteGuid;
    if (noteguid == "")
        return 0;
    r.mime = mime;
    r.active = true;
    r.updateSequenceNum = sequence;
    r.width = 0;
    r.height = 0;
    r.duration = 0;
    ResourceAttributes a;
    if (r.attributes.isSet())
        a = r.attributes;
    a.attachment = attachment;
    if (filename != "") {
        a.fileName = filename;
    }

    Data d;
    d.body = data;
    d.bodyHash = hash;
    d.size = data.size();

    r.data = d;
    r.attributes = a;
    ResourceTable resourceTable(global.db);
    resourceTable.add(rlid, r, true, lid);

    return rlid;
}




// Prepare the email for sending.  This function scans through
// the email for images & attachments.  The resulting
// MimeMessage has all of the email contents.
void NBrowserWindow::prepareEmailMessage(MimeMessage *message, QString note) {
    MimeHtml *text = new MimeHtml();

    // Prepare the massage the same as if we were printing it.
    QString contents = this->stripContentsForPrint();
    QString textContents = editor->page()->currentFrame()->toPlainText();
    QStringList images;
    QStringList attachments;

    // Now, go thgough & reformat all the img tags.
    int cidCount=0;
    int pos = contents.indexOf("src=\"file:");
    while (pos>=0) {
        QString localFile = contents.mid(pos+13);
        int endPos = localFile.indexOf("\"");
        localFile = localFile.mid(0,endPos);
        images.append(localFile);
        endPos = pos+endPos;
        QString part1 = contents.mid(0,pos);
        QString part2 = contents.mid(endPos+14);
        cidCount++;
        contents = part1 + "src='cid:file" +QString::number(cidCount) +"'" + part2;

        pos = contents.indexOf("src=\"file:", pos+5);
    }

    // next, look for all the attachments
    pos = contents.indexOf("href=\"nnres:");
    while (pos != -1) {
        QString localFile = contents.mid(pos+12);
        int endPos = localFile.indexOf("\"");
        localFile = localFile.mid(0,endPos);
        attachments.append(localFile);
        cidCount++;
        pos = contents.indexOf("href=\"nnres:", pos+5);
    }

    // If the user adds a note, then prepend it to the beginning.
    if (note.trimmed() != "") {
        int pos = contents.indexOf("<body");
        int endPos = contents.indexOf(">", pos);
        contents.insert(endPos+1,  Qt::escape(note)+"<p><p><hr><p>");
    }
    text->setHtml(contents);
    message->addPart(text);


    // Add all the images
    for (int i=0; i<images.size(); i++) {
        MimeReference mimeRef;
        QString localFile = images[i];
        QString mime = mimeRef.getMimeFromFileName(localFile);
        MimeInlineFile *file = new MimeInlineFile(new QFile(localFile));
        QString lidFile = localFile.mid(localFile.lastIndexOf(QDir::separator())+1);
        qint32 lid = lidFile.mid(0,lidFile.lastIndexOf(".")).toInt();
        ResourceTable rtable(global.db);
        Resource r;
        ResourceAttributes ra;
        if (rtable.get(r, lid, false) && r.attributes.isSet()) {
            ra = r.attributes;
            if (ra.fileName.isSet())
                file->setContentName(ra.fileName);
        }
        file->setContentId("file"+QString::number(i+1));
        file->setContentType(mime);
        message->addPart(file);
    }

    // Add all the attachments
    for (int i=0; i<attachments.size(); i++) {
        MimeReference mimeRef;
        QString localFile = attachments[i];
        QString mime = mimeRef.getMimeFromFileName(localFile);
        MimeInlineFile *file = new MimeInlineFile(new QFile(localFile));
        QString lidFile = localFile.mid(localFile.lastIndexOf(QDir::separator())+1);
        qint32 lid = lidFile.mid(0,lidFile.lastIndexOf(".")).toInt();
        ResourceTable rtable(global.db);
        Resource r;
        ResourceAttributes ra;
        if (rtable.get(r, lid, false) && r.attributes.isSet()) {
            ra = r.attributes;
            if (ra.fileName.isSet())
                file->setContentName(ra.fileName);
        }
        file->setContentType(mime);
        message->addPart(file);
    }
    return;

}





// Email current note.
void NBrowserWindow::emailNote() {
    global.settings->beginGroup("Email");
    QString server = global.settings->value("smtpServer", "").toString();
    int port = global.settings->value("smtpPort", 25).toInt();
    QString smtpConnectionType = global.settings->value("smtpConnectionType", "TcpConnection").toString();
    QString userid = global.settings->value("userid", "").toString();
    QString password = global.settings->value("password", "").toString();
    QString senderEmail = global.settings->value("senderEmail", "").toString();
    QString senderName = global.settings->value("senderName", "").toString();
    global.settings->endGroup();

    if (senderEmail.trimmed() == "" || server.trimmed() == "") {
        QMessageBox::critical(this, tr("Setup Error"),
             tr("SMTP Server has not been setup.\n\nPlease specify server settings\nin the Preferences menu."), QMessageBox::Ok);
        return;
    }

    EmailDialog emailDialog;
    emailDialog.subject->setText(noteTitle.text());
    emailDialog.exec();
    if (emailDialog.cancelPressed)
        return;
    emit(setMessage(tr("Sending Email. Please be patient.")));

    QStringList toAddresses = emailDialog.getToAddresses();
    QStringList ccAddresses = emailDialog.getCcAddresses();
    QStringList bccAddresses = emailDialog.getBccAddresses();

    if (senderName.trimmed() == "")
        senderName = senderEmail;

    SmtpClient::ConnectionType type = SmtpClient::TcpConnection;
    if (smtpConnectionType == "SslConnection")
        type = SmtpClient::SslConnection;
    if (smtpConnectionType == "TlsConnection")
        type = SmtpClient::TlsConnection;

    SmtpClient smtp(server, port, type);
    smtp.setResponseTimeout(-1);

    // We need to set the username (your email address) and password
    // for smtp authentication.
    smtp.setUser(userid);
    smtp.setPassword(password);

    // Now we create a MimeMessage object. This is the email.
    MimeMessage message;

    EmailAddress sender(senderEmail, senderName);
    message.setSender(&sender);

    for (int i=0; i<toAddresses.size(); i++) {
        EmailAddress *to = new EmailAddress(toAddresses[i], toAddresses[i]);
        message.addRecipient(to);
    }

    for (int i=0; i<ccAddresses.size(); i++) {
        EmailAddress *cc = new EmailAddress(ccAddresses[i], ccAddresses[i]);
        message.addRecipient(cc);
    }


    if (emailDialog.ccSelf->isChecked()) {
        EmailAddress *cc = new EmailAddress(senderEmail, senderName);
        message.addRecipient(cc);
    }

    for (int i=0; i<bccAddresses.size(); i++) {
        EmailAddress *bcc = new EmailAddress(bccAddresses[i], bccAddresses[i]);
        message.addRecipient(bcc);
    }

    // Set the subject
    message.setSubject(emailDialog.subject->text().trimmed());

    // Build the note content
    QString text =  emailDialog.note->toPlainText();
    prepareEmailMessage(&message, text);

    // Send the actual message.
    if (!smtp.connectToHost()) {
        QLOG_ERROR()<< "Failed to connect to host!";
        QMessageBox::critical(this, tr("Connection Error"), tr("Unable to connect to host."), QMessageBox::Ok);
        return;
    }

    if (!smtp.login()) {
        QLOG_ERROR() << "Failed to login!";
        QMessageBox::critical(this, tr("Login Error"), tr("Unable to login."), QMessageBox::Ok);
        return;
    }

    if (!smtp.sendMail(message)) {
        QMessageBox::critical(this, tr("Send Error"), tr("Unable to send email."), QMessageBox::Ok);
        QLOG_ERROR() << "Failed to send mail!";
        return;
    }

    smtp.quit();
    emit(setMessage("Message Sent"));
//    QMessageBox::information(this, tr("Message Sent"), tr("Message sent."), QMessageBox::Ok);
}





// Strip the contents from the current webview in preparation for printing.
QString NBrowserWindow::stripContentsForPrint() {
    // Start removing object tags
    QString contents = this->editor->selectedHtml().trimmed();
    if (contents == "")
       contents = editor->editorPage->mainFrame()->toHtml();
    int pos = contents.indexOf("<object");
    while (pos != -1) {
        int endPos = contents.indexOf(">", pos);
        QString lidString = contents.mid(contents.indexOf("lid=", pos)+5);
        lidString = lidString.mid(0,lidString.indexOf("\" "));
        contents = contents.mid(0,pos) + "<img src=\"file://" +
                global.fileManager.getTmpDirPath() + lidString +
                QString("-print.png\" width=\"10%\" height=\"10%\"></img>")+contents.mid(endPos+1);

        pos = contents.indexOf("<object", endPos);
    }
    return contents.replace("src=\"file:////", "src=\"/");
}


// Do a print preview of this note.  This works
// in much the same way as printNote().  It removes all the
// <object> tags & replaces them with <img>.
void NBrowserWindow::printPreviewNote() {
    QString contents = stripContentsForPrint();

    // Load the print page.  When it is ready the printReady() slot will
    // do the actual print
    printPreviewPage->setHtml(contents.toUtf8());
    QPrinter printer(QPrinter::HighResolution);
    QPrintPreviewDialog preview(&printer, this);
    preview.setWindowFlags(Qt::Window);
    connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printPreviewReady(QPrinter*)));
    preview.exec();
}


// Slot for when the printPreview is ready.
void NBrowserWindow::printPreviewReady(QPrinter *printer) {
   printPreviewPage->print(printer);
}



// Print the contents of a note.  Basically it loops through the
// note and repaces the <object> tags with <img> tags.  The plugin
// object should be creating temporary images for the print.
void NBrowserWindow::printNote() {
    QString contents = stripContentsForPrint();

    // Load the print page.  When it is ready the printReady() slot will
    // do the actual print
    printPage->setDocumentTitle(editor->title());
    printPage->setHtml(contents.toUtf8());

    QPrinter *printer;

    global.settings->beginGroup("Printer");
    QPrinter::Orientation orientation = static_cast<QPrinter::Orientation>(global.settings->value("orientation").toUInt());
    QString name = global.settings->value("printerName", "").toString();
    QPrinter::OutputFormat format = static_cast<QPrinter::OutputFormat>(global.settings->value("outputFormat", 0).toUInt());
    QPrinter::PaperSize pageSize  = static_cast<QPrinter::PageSize>(global.settings->value("pageSize", 2).toUInt());
    QPrinter::ColorMode colorMode  = static_cast<QPrinter::ColorMode>(global.settings->value("colorMode", 1).toUInt());
    QString fileName = global.settings->value("outputFileName", "").toString();
    global.settings->endGroup();

    bool error = false;
    printer = new QPrinter();
    printer->setPageSize(pageSize);
    printer->setOutputFormat(format);
    printer->setOrientation(orientation);
    printer->setColorMode(colorMode);


    if (fastPrint) {
        if (format == QPrinter::PdfFormat) {
            if (fileName == "")
                error = true;
            else
                printer->setOutputFileName(fileName);
        } else {
            if (name == "")
                error = true;
            else
                printer->setPrinterName(name);
        }
        if (error) {
            fastPrint = false;

            // Re-initialize printer object so we don't have any bugus
            // values from settings.
            delete printer;
            printer = new QPrinter();
        }
    }

    if (!fastPrint) {
        if (format == QPrinter::PdfFormat && fileName.trimmed() != "")
            printer->setOutputFileName(fileName);
        if (name.trimmed() != "")
            printer->setPrinterName(name);

        QPrintDialog dialog(printer);
        if (dialog.exec() ==  QDialog::Accepted) {
            printer = dialog.printer();
            global.settings->beginGroup("Printer");
            global.settings->setValue("orientation", printer->orientation());
            global.settings->setValue("printerName", printer->printerName());
            global.settings->setValue("outputFormat", printer->outputFormat());
            global.settings->setValue("outputFileName", printer->outputFileName());
            global.settings->setValue("pageSize", printer->pageSize());
            global.settings->setValue("colorMode", printer->colorMode());
            global.settings->endGroup();
            printPage->print(printer);
        }
    } else {
            printPage->print(printer);
//        QTextDocument td;
//        td.setHtml(printPage->toHtml());
//        td.setPageSize(printer->pageRect().size());
//            QRect innerRect = printer->pageRect();
//            innerRect.setTop(innerRect.top() + 20);
//            innerRect.setBottom(innerRect.bottom() - 30);
//            QRect contentRect = QRect(QPoint(0,0), td.size().toSize());
//            QRect currentRect = QRect(QPoint(0,0), innerRect.size());
//            QPainter painter(printer);
//            int count = 0;
//            painter.save();
//            painter.translate(0, 30);
//            while (currentRect.intersects(contentRect) && count < td.pageCount()) {
//                td.drawContents(&painter, currentRect);
//                count++;
//                currentRect.translate(0, currentRect.height());
//                painter.restore();
//                painter.drawText(10, 10, editor->title());
//                painter.drawText(10, printer->pageRect().bottom() - 10, QString("Page %1 of %2").arg(count).arg(td.pageCount()));
//                painter.save();
//                painter.translate(0, -currentRect.height() * count + 30);
//                if (currentRect.intersects(contentRect) && count < td.pageCount())
//                    printer->newPage();
//            }
//            painter.restore();
//            painter.end();
    }

    this->fastPrint = false;
}



void NBrowserWindow::noteSourceUpdated() {
    QByteArray ba;
    QString source = sourceEdit->toPlainText();
   //source = Qt::escape(source);
    ba.append(sourceEditHeader);
    ba.append(source);
    ba.append("</body></html>");
    editor->setContent(ba);
    this->editor->isDirty = true;
    emit noteContentEditedSignal(uuid, lid, editor->editorPage->mainFrame()->documentElement().toOuterXml());
}

// Update a resource's hash if it was edited somewhere else
void NBrowserWindow::updateResourceHash(qint32 noteLid, QByteArray oldHash, QByteArray newHash) {
    if (noteLid != lid)
        return;

    QString content = editor->editorPage->mainFrame()->documentElement().toOuterXml();

    // Start going through & looking for the old hash
    int pos = content.indexOf("<body");
    int endPos;
    int hashPos = -1;
    QString hashString = "hash=\"" +oldHash.toHex() +"\"";
    while (pos != -1) {
        endPos = content.indexOf(">", pos);  // Find the matching end of the tag
        hashPos = content.indexOf(hashString, pos);
        if (hashPos < endPos && hashPos != -1) {  // If we found the hash, begin the update
            QString startString = content.mid(0, hashPos);
            QString endString = content.mid(hashPos+hashString.length());
            QString newContent = startString + "hash=\"" +newHash.toHex() +"\"" +endString;
            QByteArray byteArray;
            byteArray.append(newContent);
            editor->setContent(byteArray);
            noteUpdated(lid);
            return;
        } else {
            pos = content.indexOf("<", pos+1);
        }
    }


}



void NBrowserWindow::attachFileSelected(QString filename) {
    // Read in the file
    QFile file(filename);

    // Save prior path for future use
    QFileInfo fileInfo(file);
    attachFilePath = fileInfo.path();

    file.open(QIODevice::ReadOnly);
    QByteArray ba = file.readAll();
    file.close();

    QString script_start = "document.execCommand('insertHTML', false, '";
    QString script_end = "');";

    MimeReference mimeRef;
    QString extension = filename;
    int endPos = filename.lastIndexOf(".");
    if (endPos != -1)
        extension = extension.mid(endPos);
    QString mime =  mimeRef.getMimeFromExtension(extension);
    Resource newRes;
    bool attachment = true;
    if (mime == "application/pdf" || mime.startsWith("image/"))
        attachment = false;
    qint32 rlid = createResource(newRes, 0, ba, mime, attachment, QFileInfo(filename).fileName());
    QByteArray hash;
    if (newRes.data.isSet()) {
        Data d = newRes.data;
        if (d.bodyHash.isSet())
            hash = d.bodyHash;
    }
    if (rlid <= 0)
        return;

    // If we have an image, then insert it.
    if (mime.startsWith("image", Qt::CaseInsensitive)) {

        // The resource is done, now we need to add it to the
        // note body
        QString g =  QString::number(rlid)+extension;
        QString path = global.fileManager.getDbaDirPath() + g;

        // do the actual insert into the note
        QString buffer;
        QByteArray hash = "";
        if (newRes.data.isSet()) {
            Data d= newRes.data;
            if (d.bodyHash.isSet())
            hash = d.bodyHash;
        }
        buffer.append("<img src=\"file://");
        buffer.append(path);
        buffer.append("\" type=\"");
        buffer.append(mime);
        buffer.append("\" hash=\"");
        buffer.append(hash.toHex());
        buffer.append("\" onContextMenu=\"window.browser.imageContextMenu(&apos;");
        buffer.append(QString::number(rlid));
        buffer.append("&apos;, &apos;");
        buffer.append(g);
        buffer.append("&apos;);\" ");
        buffer.append(" en-tag=\"en-media\" style=\"cursor: default;\" lid=\"");
        buffer.append(QString::number(rlid));
        buffer.append("\">");

        // Insert the actual image
        editor->page()->mainFrame()->evaluateJavaScript(
                script_start + buffer + script_end);
        return;
    }

    if (mime == "application/pdf" && global.pdfPreview) {
        // The resource is done, now we need to add it to the
        // note body
        QString g =  QString::number(rlid)+extension;

        // do the actual insert into the note
        QString buffer;
        QByteArray hash;
        if (newRes.data.isSet()) {
            Data data = newRes.data;
            if (data.bodyHash.isSet())
                hash = data.bodyHash;
        }
        buffer.append("<object width=\"100%\" height=\"100%\" lid=\"" +QString::number(rlid) +"\" hash=\"");
        buffer.append(hash.toHex());
        buffer.append("\" type=\"application/pdf\" />");

        // Insert the actual image
        editor->page()->mainFrame()->evaluateJavaScript(
                script_start + buffer + script_end);
        return;

    }

    // If we have something other than an image or PDF
    // First get the icon for this type of file
    AttachmentIconBuilder builder;
    QString g =  global.fileManager.getDbaDirPath()+ QString::number(rlid)+extension;
    QString tmpFile = builder.buildIcon(rlid, filename);

    // do the actual insert into the note
    QString buffer;
    buffer.append("<a en-tag=\"en-media\" ");
    buffer.append("lid=\""+QString::number(rlid) +QString("\" "));
    buffer.append("type=\"" +mime +"\" ");
    buffer.append("hash=\"" +hash.toHex()+"\" ");
    buffer.append("href=\"nnres:" +g+"\" ");
    buffer.append("oncontextmenu=\"window.browserWindow.resourceContextMenu(&apos");
    buffer.append(g +QString("&apos);\" "));
    buffer.append(">");

    buffer.append("<img en-tag=\"temporary\" title=\""+QFileInfo(filename).fileName() +"\" ");
    buffer.append("src=\"file://");
    buffer.append(tmpFile);
    buffer.append("\" />");
    buffer.append("</a>");
    buffer.replace("\'", "&quot;");

    // Insert the actual attachment
    editor->page()->mainFrame()->evaluateJavaScript(
            script_start + buffer + script_end);
}



// Alarm has been completed
void NBrowserWindow::alarmCompleted() {
    QFont f = alarmText.font();
    f.setStrikeOut(!f.strikeOut());
    alarmText.setFont(f);

    NoteTable noteTable(global.db);
    noteTable.setDirty(this->lid, true);
    noteTable.setReminderCompleted(this->lid, f.strikeOut());
    global.reminderManager->remove(this->lid);
    emit(noteUpdated(this->lid));
    emit noteAlarmEditedSignal(uuid, lid, f.strikeOut(), alarmText.text());
}



void NBrowserWindow::alarmSet() {
    ReminderSetDialog dialog;
    Note n;
    NoteTable ntable(global.db);
    ntable.get(n, lid, false, false);
    NoteAttributes attributes;
    if (n.attributes.isSet())
        attributes = n.attributes;
    if (attributes.reminderTime.isSet()) {
        QDateTime dt;
        dt.setMSecsSinceEpoch(attributes.reminderTime);
        dialog.time->setTime(dt.time());
        dialog.calendar->setSelectedDate(dt.date());
    } else {
        QTime t = QTime::currentTime();
        dialog.time->setTime(t.addSecs(60*60));
    }
    dialog.exec();
    if (!dialog.okPressed)
        return;

    QDateTime dt;
    dt.setTime(dialog.time->time());
    QTime t = dialog.time->time();
    t.setHMS(t.hour(), t.minute(), 0,0);
    dt.setTime(t);
    dt.setDate(dialog.calendar->selectedDate());

    ntable.updateDate(this->lid, dt.toMSecsSinceEpoch(), NOTE_ATTRIBUTE_REMINDER_TIME, true);
    //alarmText.setText(dt.date().toString(Qt::SystemLocaleShortDate));
    if (dt.date() == QDate::currentDate())
        alarmText.setText(tr("Today"));
    else if (dt.date() == QDate::currentDate().addDays(+1))
        alarmText.setText(tr("Tomorrow"));
    else if (dt.date() == QDate::currentDate().addDays(-1))
        alarmText.setText(tr("Yesterday"));
    else
        alarmText.setText(dt.date().toString(global.dateFormat));

    alarmText.setVisible(true);
    QFont f = alarmText.font();
    f.setStrikeOut(false);
    alarmText.setFont(f);

    // Update the reminders
    global.reminderManager->updateReminder(this->lid, dt);
    this->noteUpdated(this->lid);
    this->editor->isDirty = true;
    emit noteAlarmEditedSignal(uuid, lid, false, alarmText.text());
}

void NBrowserWindow::alarmClear() {
    alarmText.setText("");
    alarmText.setVisible(false);

    NoteTable noteTable(global.db);
    noteTable.setDirty(this->lid, true);
    noteTable.removeReminder(this->lid);
    emit(noteUpdated(this->lid));
    emit noteAlarmEditedSignal(uuid, lid, false, "");
}

void NBrowserWindow::alarmMenuActivated() {
    QFont f = alarmText.font();
    f.setStrikeOut(false);
    emit noteAlarmEditedSignal(uuid, lid, false, alarmText.text());
    alarmText.setFont(f);

    NoteTable noteTable(global.db);
    noteTable.setDirty(this->lid, true);
    noteTable.setReminderCompleted(this->lid, false);
    emit(noteUpdated(this->lid));
}



void NBrowserWindow::decryptText(QString id, QString text, QString hint, QString cipher, int len) {
    if (cipher != "RC2") {
        QMessageBox::critical(this, tr("Decryption Error"),
                                       tr("Unknown encryption method.\n"
                                          "Unable to decrypt."));
        return;
    }

    EnCrypt crypt;
    QString plainText = "";
    QUuid uuid;
    QString slot = uuid.createUuid().toString().replace("{","").replace("}","");

    // First, try to decrypt with any keys we already have
    for (int i=0; i<global.passwordRemember.size(); i++) {
        QString password = global.passwordRemember.at(i).first;
        int rc = crypt.decrypt(plainText, text, password, cipher, len);
        if (rc == 0) {
            QPair<QString, QString> newEntry;
            newEntry.first = id;
            newEntry.second = global.passwordRemember.at(i).second;
            global.passwordRemember.append(newEntry);
            removeEncryption(id, plainText, false, slot);
            return;
        }
    }


    EnDecryptDialog dialog;
    if (hint.trimmed() != "")
        dialog.hint->setText(hint);
    while (plainText == "" || !dialog.okPressed) {
        dialog.exec();
        if (!dialog.okPressed) {
            return;
        }
        int rc = crypt.decrypt(plainText, text, dialog.password->text().trimmed());
        if (rc == EnCrypt::Invalid_Key) {
//            QMessageBox.warning(this, tr("Incorrect Password"), tr("The password entered is not correct"));
        }
    }
    QPair<QString,QString> passwordPair;
    passwordPair.first = dialog.password->text().trimmed();
    passwordPair.second = dialog.hint->text().trimmed();
    global.passwordSafe.insert(slot, passwordPair);
    bool permanentlyDecrypt = dialog.permanentlyDecrypt->isChecked();
    removeEncryption(id, plainText, permanentlyDecrypt, slot);
    bool rememberPassword = dialog.rememberPassword->isChecked();
    if (rememberPassword) {
        QPair<QString, QString> pair;
        pair.first = dialog.password->text().trimmed();
        pair.second = dialog.hint->text().trimmed();
        global.passwordRemember.append(pair);
    }
}



void NBrowserWindow::removeEncryption(QString id, QString plainText, bool permanent, QString slot) {
    if (!permanent) {
        plainText = " <table class=\"en-crypt-temp\" slot=\""
                +slot
                +"\""
                +"border=1 width=100%><tbody><tr><td>"
                +plainText+"</td></tr></tbody></table>";
    }

    QString html = editor->page()->mainFrame()->toHtml();
    QString text = html;
    int imagePos = html.indexOf("<img");
    int endPos;
    for ( ;imagePos != -1; ) {
        // Find the end tag
        endPos = text.indexOf(">", imagePos);
        QString tag = text.mid(imagePos-1,endPos);
        if (tag.indexOf("id=\""+id+"\"") > -1) {
                text = text.mid(0,imagePos) +plainText+text.mid(endPos+1);
                editor->page()->mainFrame()->setHtml(text);
                editor->reload();
                if (permanent)
                    contentChanged();
        }
        imagePos = text.indexOf("<img", imagePos+1);
    }
}


void NBrowserWindow::encryptButtonPressed() {
        EnCrypt encrypt;

    QString text = editor->selectedText();
    if (text.trimmed() == "")
        return;
    text = text.replace("\n", "<br/>");

    EnCryptDialog dialog;
    dialog.exec();
    if (!dialog.okPressed()) {
        return;
    }

    EnCrypt crypt;
    QString encrypted;
    int rc = crypt.encrypt(encrypted, text, dialog.getPassword().trimmed());

    if (rc != 0) {
        QMessageBox::information(this, tr("Error"),
                                tr("Error Encrypting String.  Please verify you have Java installed."));
        return;
    }
    QString buffer;
    buffer.append("<img en-tag=\"en-crypt\" cipher=\"RC2\" hint=\""
            + dialog.getHint().replace("'","\\'") + "\" length=\"64\" ");
    buffer.append("contentEditable=\"false\" alt=\"");
    buffer.append(encrypted);
    buffer.append("\" src=\"file://").append(global.fileManager.getImageDirPath("encrypt.png") +"\"");
    global.cryptCounter++;
    buffer.append(" id=\"crypt"+QString::number(global.cryptCounter) +"\"");
    buffer.append(" onMouseOver=\"style.cursor=\\'hand\\'\"");
    buffer.append(" onClick=\"window.browserWindow.decryptText(\\'crypt"+QString::number(global.cryptCounter)
                  +"\\', \\'"+encrypted+"\\', \\'"+dialog.getHint().replace("'", "\\&amp;apos;")+"\\', \\'RC2\\', 64);\"");
    buffer.append("style=\"display:block\" />");


    QString script_start = "document.execCommand('insertHtml', false, '";
    QString script_end = "');";
    editor->page()->mainFrame()->evaluateJavaScript(
            script_start + buffer + script_end);
}


void NBrowserWindow::sendAuthorUpdateSignal() {
    emit noteAuthorEditedSignal(uuid, lid, dateEditor.authorEditor.getText());
}



void NBrowserWindow::sendLocationUpdateSignal() {
    double longitude, latitude, altitude;
    QString name;
    dateEditor.locationEditor.getGeography(longitude, latitude, altitude, name);
    emit noteLocationEditedSignal(uuid, lid, longitude, latitude, altitude, name);
}


void NBrowserWindow::sendDateCreatedUpdateSignal() {
    emit noteDateEditedSignal(uuid, lid, NOTE_CREATED_DATE, dateEditor.createdDate.dateTime());
}


void NBrowserWindow::sendDateSubjectUpdateSignal() {
    emit noteDateEditedSignal(uuid, lid, NOTE_ATTRIBUTE_SUBJECT_DATE, dateEditor.subjectDate.dateTime());
}




// Send a signal that the note has been updated
void NBrowserWindow::sendTitleUpdateSignal() {
    NoteTable ntable(global.db);
    ntable.updateTitle(this->lid, this->noteTitle.text().trimmed(), true);
    emit noteTitleEditedSignal(uuid, lid, this->noteTitle.text().trimmed());
    emit(this->noteUpdated(lid));
    emit(this->updateNoteList(lid, NOTE_TABLE_TITLE_POSITION, this->noteTitle.text()));
    sendDateUpdateSignal();
}


// Send a signal that the note has been updated
void NBrowserWindow::sendNotebookUpdateSignal() {
    NoteTable ntable(global.db);

//    QString notebook = notebookMenu.d
//    ntable.updateNotebook(this->lid, this->noteTitle.text().trimmed(), true);
//    this->editor->isDirty = true;
    ntable.setDirty(this->lid, true,false);
    emit(this->noteUpdated(lid));
    qint32 lid = notebookMenu.notebookLid;
    QString name = notebookMenu.notebookName;
    emit(this->updateNoteList(lid, NOTE_TABLE_NOTEBOOK_POSITION, name));
    emit(this->updateNoteList(lid, NOTE_TABLE_NOTEBOOK_LID_POSITION, lid));
    emit noteNotebookEditedSignal(uuid, this->lid, lid, name);


    //sendDateUpdateSignal();
}


// Send a signal that the note has been updated
void NBrowserWindow::sendDateUpdateSignal(qint64 dt) {
    NoteTable ntable(global.db);
    ntable.setDirty(this->lid, true);
    if (dt == 0) {
        dt = QDateTime::currentMSecsSinceEpoch();
        this->dateEditor.setUpdateDate(dt);
    }
    emit(this->noteUpdated(lid));
    emit(this->updateNoteList(lid, NOTE_TABLE_DATE_UPDATED_POSITION, dt));
}



// Send a signal that the note has been updated
void NBrowserWindow::sendTagUpdateSignal() {
    NoteTable ntable(global.db);
    ntable.setDirty(this->lid, true,false);
    emit(this->noteUpdated(lid));
    //sendDateUpdateSignal();
    QStringList names;
    tagEditor.getTags(names);
    emit noteTagsEditedSignal(uuid, lid, names);

}


// Send a signal that the note has been updated
void NBrowserWindow::sendUrlUpdateSignal() {
    NoteTable ntable(global.db);
    ntable.setDirty(this->lid, true);
    emit(this->noteUpdated(lid));
    sendDateUpdateSignal();
    emit(this->updateNoteList(lid, NOTE_TABLE_SOURCE_URL_POSITION, urlEditor.getText()));
    emit noteUrlEditedSignal(uuid, lid, urlEditor.getText());

}




void NBrowserWindow::spellCheckPressed() {
    // Check if we have a plugin for Hunspell loaded. This could have been done at startup, but if this is
    // an external window we could need to load it again.
    if (!hunspellInterface) {
        this->loadPlugins();
    }

    // If we STILL don't have a plugin then it can't be loaded. Quit out
    if (!hunspellPluginAvailable) {
        QMessageBox::critical(this, tr("Plugin Error"), tr("Hunspell plugin not found or could not be loaded."), QMessageBox::Ok);
        return;
    }

    QWebPage *page = editor->page();
    page->action(QWebPage::MoveToStartOfDocument);
    page->mainFrame()->setFocus();

    Qt::KeyboardModifier ctrl(Qt::ControlModifier);

    QKeyEvent key(QEvent::KeyPress, Qt::Key_Home, ctrl);
    editor->keyPressEvent(&key);
    page->mainFrame()->setFocus();

    QStringList words = page->mainFrame()->toPlainText().split(" ");
    QStringList ignoreWords;
    QStringList rwords;
    //SpellChecker checker;
    bool finished = false;

    for (int i=0; i<words.size() && !finished; i++) {
        QString currentWord = words[i];
        page->findText(currentWord);
        rwords.clear();
        if (!hunspellInterface->spellCheck(currentWord, rwords) && !ignoreWords.contains(currentWord)) {
            SpellCheckDialog dialog(currentWord, rwords, this);
            dialog.move(0,0);
            dialog.exec();
            if (dialog.cancelPressed)
                finished = true;
            if (dialog.ignoreAllPressed)
                ignoreWords.append(currentWord);
            if (dialog.replacePressed)  {
                QApplication::clipboard()->setText(dialog.replacement);
                pasteButtonPressed();
            }
            if (dialog.addToDictionaryPressed) {
                hunspellInterface->addWord(global.fileManager.getSpellDirPathUser() +"user.lst", currentWord);
            }
        }
    }

    // Go to the end of the document & finish up
    QKeyEvent key2(QEvent::KeyPress, Qt::Key_End, ctrl);
    editor->keyPressEvent(&key2);

    QMessageBox::information(this, tr("Spell Check Complete"), tr("Spell Check Complete."), QMessageBox::Ok);
}



void NBrowserWindow::insertHtmlEntities() {
    emit showHtmlEntities();
}



void NBrowserWindow::hideHtmlEntities() {
    buttonBar->htmlEntitiesButtonVisible->setVisible(false);
    buttonBar->htmlEntitiesButtonAction->setVisible(false);
    editor->insertHtmlEntitiesAction->setVisible(false);
}




void NBrowserWindow::handleUrls(const QMimeData *mime) {
    QList<QUrl> urlList = mime->urls();
    bool ctrlModifier = QApplication::keyboardModifiers() & Qt::ControlModifier;
    for (int i=0; i<urlList.size(); i++) {
        QString file  = urlList[i].toString();
        if (file.toLower().startsWith("file://") && !ctrlModifier) {
            attachFileSelected(file.mid(7));
            if (i<urlList.size()-1)
                insertHtml("<div><br/></div>");
        } else if (file.toLower().startsWith("file://") && ctrlModifier) {
            QString url = QString("<a href=\"%1\" title=\"%2\">%3</a>").arg(file).arg(file).arg(file);
            QLOG_DEBUG() << url;
            insertHtml(url);
            if (i<urlList.size()-1)
                insertHtml("<div><br/></div>");
        } else {
            editor->setFocus();
            QApplication::clipboard()->clear();
            QApplication::clipboard()->setText(file, QClipboard::Clipboard);
            this->editor->triggerPageAction(QWebPage::Paste);
        }
    }
}



// This is used to notify the tab window that the contents of a
// note have changed.  It avoids some of the overhead that happens
// when a note is first edited, but it is signaled on every change.
// The tab window uses it to update any duplicate windows (i.e. a note
// was edited in an external editor and is still being viewed internally
// so we need to keep the contents in sync.
void NBrowserWindow::noteContentEdited() {
    emit noteContentEditedSignal(uuid, lid, editor->editorPage->mainFrame()->documentElement().toOuterXml());
}




void NBrowserWindow::changeDisplayFontSize(QString size) {
    bool convert =true;
    if (size.endsWith("px", Qt::CaseInsensitive))
        convert = true;
    size.chop(2);  // Remove px from the end
    int converted = size.toInt();
    if (convert) {
        PixelConverter c;
        converted = c.getPoints(converted);
        size = QString::number(converted);
    }
    int idx = buttonBar->fontSizes->findData(size, Qt::UserRole);
    if (idx > 0) {
        buttonBar->fontSizes->blockSignals(true);
        buttonBar->fontSizes->setCurrentIndex(idx);
        buttonBar->fontSizes->blockSignals(false);
    }
}



// This function is called when the cursor position within the document changes.  It should
// change the combo box to the current font name.
void NBrowserWindow::changeDisplayFontName(QString name) {
    //QLOG_DEBUG() << "Font Name:" << name;
    if (name.startsWith("'")) {
            name = name.mid(1);
            int idx = name.indexOf("'");
            if (idx != -1)
                name = name.mid(0,idx);
    }
    name = name.toLower();
    buttonBar->fontNames->blockSignals(true);
    int idx = buttonBar->fontNames->findData(name, Qt::UserRole);
    if (idx != -1)
        buttonBar->fontNames->setCurrentIndex(idx);
    buttonBar->fontNames->blockSignals(false);
}



void NBrowserWindow::focusCheck() {
    bool buttonBarVisible = false;
    if (editor->hasFocus())
        buttonBarVisible = true;
    if (editor->contextMenu->hasFocus())
        buttonBarVisible = true;
    if (buttonBar->hasFocus())
        buttonBarVisible = true;
    if (buttonBar->fontNames->isExpanded())
        buttonBarVisible = true;
    if (buttonBar->fontNames->lineEdit()->hasFocus())
        buttonBarVisible = true;
    if (buttonBar->fontSizes->lineEdit()->hasFocus())
        buttonBarVisible = true;
    if (buttonBar->fontSizes->isExpanded())
        buttonBarVisible = true;
    if (!global.autoHideEditorToolbar)
        buttonBarVisible = true;
    if (global.isFullscreen)
        buttonBarVisible = false;

    if (!editor->page()->isContentEditable())
        buttonBarVisible = false;
    buttonBar->setVisible(buttonBarVisible);
}




void NBrowserWindow::notebookFocusShortcut() {
    this->notebookMenu.setFocus();
    this->notebookMenu.click();
}



void NBrowserWindow::fontFocusShortcut() {
    if (this->buttonBar->fontNames->isVisible()) {
        this->buttonBar->fontNames->setFocus();
        this->buttonBar->fontNames->showPopup();
    }
}



void NBrowserWindow::fontSizeFocusShortcut() {
    if (this->buttonBar->fontSizes->isVisible()) {
        this->buttonBar->fontSizes->setFocus();
        this->buttonBar->fontSizes->showPopup();
    }
}



void NBrowserWindow::authorFocusShortcut() {
    if (!this->dateEditor.authorEditor.isVisible()) {
        this->changeExpandState(EXPANDBUTTON_3);
        this->expandButton.setState(EXPANDBUTTON_3);
    }
    dateEditor.authorEditor.setFocus();
}

void NBrowserWindow::urlFocusShortcut() {
    if (!this->urlEditor.isVisible()) {
        this->changeExpandState(EXPANDBUTTON_2);
        this->expandButton.setState(EXPANDBUTTON_2);
    }
    this->urlEditor.setFocus();
}




void NBrowserWindow::copyNoteUrl() {
    Note n;
    NoteTable ntable(global.db);
    ntable.get(n,this->lid,false,false);
    UserTable utable(global.db);
    User user;
    utable.getUser(user);

    QString href = "evernote:///view/" + QString::number(user.id) + QString("/") +
           user.shardId +QString("/") +
            n.guid +QString("/") +
            n.guid + QString("/");
    QApplication::clipboard()->setText(href, QClipboard::Clipboard);
}



void NBrowserWindow::newTagFocusShortcut() {
    if (!this->tagEditor.newTag.isVisible()) {
        this->changeExpandState(EXPANDBUTTON_2);
        this->expandButton.setState(EXPANDBUTTON_2);
    }
    tagEditor.newTag.setFocus();
}


// User pressed the superscript editor button
void NBrowserWindow::superscriptButtonPressed() {
    editor->page()->mainFrame()->evaluateJavaScript("document.execCommand('superscript')");
}



// User pressed the subscript editor button
void NBrowserWindow::subscriptButtonPressed() {
    editor->page()->mainFrame()->evaluateJavaScript("document.execCommand('subscript');");
}

// Set the editor background & font color
void NBrowserWindow::setEditorStyle() {
    QString qss = global.getEditorCss();
    editor->settings()->setUserStyleSheetUrl(QUrl("file://"+qss));
    return;
}


void NBrowserWindow::loadPlugins() {
    hunspellPluginAvailable = false;

    // Start loading plugins
    QDir pluginsDir(global.fileManager.getProgramDirPath(""));
    pluginsDir.cd("plugins");
    QStringList filter;
    filter.append("libhunspellplugin.so");
    foreach (QString fileName, pluginsDir.entryList(filter)) {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = pluginLoader.instance();
        if (fileName == "libhunspellplugin.so") {
            if (plugin) {
                hunspellInterface = qobject_cast<HunspellInterface *>(plugin);
                if (hunspellInterface) {
                    hunspellPluginAvailable = true;
                    hunspellInterface->initialize(global.fileManager.getProgramDirPath(""), global.fileManager.getSpellDirPathUser());
                }
            } else {
                QLOG_ERROR() << pluginLoader.errorString();
            }
        }
    }
}


// Find shortcut activated
void NBrowserWindow::findShortcut() {
    if (!findReplace->isVisible()) {
        findReplace->showFind();
    } else {
        if (findReplace->findLine->hasFocus())
            findReplace->hide();
        else {
            findReplace->showFind();
            findReplace->findLine->setFocus();
            findReplace->findLine->selectAll();
        }
    }

}


//*******************************************
//* Search for the next occurrence of text
//* in a note.
//*******************************************
void NBrowserWindow::findNextShortcut() {
    findReplace->showFind();
    QString find = findReplace->findLine->text();
    if (find != "")
        editor->page()->findText(find,
            findReplace->getCaseSensitive() | QWebPage::FindWrapsAroundDocument);
}



//*******************************************
//* Search for the previous occurrence of
//* text in a note.
//*******************************************
void NBrowserWindow::findPrevShortcut() {
    findReplace->showFind();
    QString find = findReplace->findLine->text();
    if (find != "")
        editor->page()->findText(find,
            findReplace->getCaseSensitive() | QWebPage::FindBackward | QWebPage::FindWrapsAroundDocument);
}



// Find shortcut activated
void NBrowserWindow::findReplaceShortcut() {
    this->findReplace->showFindReplace();
}



//***************************************
//* Find/replace button pressed, so we
//* need to highlight all the occurrences
//* in a note.
//***************************************
void NBrowserWindow::findReplaceInNotePressed() {
    QString find = findReplace->findLine->text();
    QString replace = findReplace->replaceLine->text();
    if (find == "")
        return;
    bool found = false;
    found = editor->page()->findText(find,
        findReplace->getCaseSensitive() | QWebPage::FindWrapsAroundDocument);
    if (!found)
        return;

    QApplication::clipboard()->setText(replace);
    editor->pasteAction->trigger();
}




//*************************************************
//* Replace All button pressed.
//*************************************************
void NBrowserWindow::findReplaceAllInNotePressed() {
    QString find = findReplace->findLine->text();
    QString replace = findReplace->replaceLine->text();
    if (find == "")
        return;
    bool found = false;
    while (true) {
        found = editor->page()->findText(find,
            findReplace->getCaseSensitive() | QWebPage::FindWrapsAroundDocument);
        if (!found)
            return;
        QApplication::clipboard()->setText(replace);
        editor->pasteAction->trigger();
    }
}




//*******************************************
//* Search for the next occurrence of text
//* in a note.
//*******************************************
void NBrowserWindow::findNextInNote() {
    findReplace->showFind();
    QString find = findReplace->findLine->text();
    if (find != "")
        editor->page()->findText(find,
            findReplace->getCaseSensitive() | QWebPage::FindWrapsAroundDocument);
}



//*******************************************
//* Search for the previous occurrence of
//* text in a note.
//*******************************************
void NBrowserWindow::findPrevInNote() {
    findReplace->showFind();
    QString find = findReplace->findLine->text();
    if (find != "")
        editor->page()->findText(find,
            findReplace->getCaseSensitive() | QWebPage::FindBackward | QWebPage::FindWrapsAroundDocument);

}




//*******************************************
//* This just does a null find to reset the
//* text in a note so nothing is highlighted.
//* This is triggered when the find dialog
//* box is hidden.
//*******************************************
void NBrowserWindow::findReplaceWindowHidden() {
   editor->page()->findText("");
}