File: mainwindow.cpp

package info (click to toggle)
robojournal 0.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,176 kB
  • sloc: cpp: 3,952; makefile: 10
file content (2053 lines) | stat: -rw-r--r-- 67,105 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
/*
    This file is part of RoboJournal.
    Copyright (c) 2012 by Will Kraft <pwizard@gmail.com>.


    RoboJournal 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 3 of the License, or
    (at your option) any later version.

    RoboJournal 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 RoboJournal.  If not, see <http://www.gnu.org/licenses/>.
  */


#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_editor.h"
#include "editor.h"
#include "entrysearch.h"
#include "ui_entrysearch.h"
#include <iostream>
#include "buffer.h"
#include "dblogin.h"
#include "ui_dblogin.h"
#include "config.h"
#include "ui_config.h"
#include <QtSql/QSqlDatabase>
#include "configmanager.h"
//#include <QDebug>
#include "psqlcore.h"
#include <QMessageBox>
#include "mysqlcore.h"
#include "sqlitecore.h"
#include "aboutrj.h"
#include "ui_aboutrj.h"
#include <QTreeWidgetItem>
#include <QListIterator>
#include <QTreeWidgetItem>
#include <QList>
#include <QSqlError>
#include "firstrun.h"
#include "ui_firstrun.h"
#include <QPalette>
#include <QInputDialog>
#include <QCloseEvent>
#include <QPrinter>
#include <QPrintDialog>
#include <QAbstractButton>

//################################################################################################
// Confirm the user's intention to quit the program. This function replaces Quit();
void MainWindow::closeEvent(QCloseEvent *event){
    using namespace std;
    event->ignore();

    // Make RoboJournal show confirmation dialogs if config says so
    if(Buffer::showwarnings){

        // dialog that gets shown if user is connected to a journal
        if(ui->DisconnectButton->isEnabled()){
            QMessageBox q(this);
            q.setText("Currently connected to <b>" + Buffer::database_name + "@" + Buffer::host + "</b>!");
            q.setWindowTitle("Quit Robojournal");
            q.setInformativeText("Do you really want to quit?");
            q.setStandardButtons(QMessageBox::Cancel);

            QPushButton *quit=q.addButton("Quit",QMessageBox::AcceptRole);

            q.setIcon(QMessageBox::Question);
            q.setDefaultButton(QMessageBox::Cancel);

            q.exec();

            if(q.clickedButton() == quit){
                cout << "OUTPUT: User quit the program" << endl;
                event->accept();
            }
            else{
                //do nothing
                event->ignore();
            }
        }

        // dialog that gets shown if user is NOT connected to a journal
        // update: Don't show dialog if there is no journal active b/c it can get annoying after awhile
        else{
            cout << "OUTPUT: User quit the program" << endl;
            event->accept();
        }
    }

    // just quit silently if user has turned off confirm dialogs
    else{
        cout << "OUTPUT: User quit the program" << endl;
        event->accept();
    }
}

//################################################################################################
// Private function to auto-update Currentid whenever new function is selected
void MainWindow::UpdateSelectedEntry(QString id){
    using namespace std;

    // CurrentID is called by several different functions so it should ALWAYS be up
    // to date so you don't accidentally change the wrong entry

    CurrentID=id;

    //cout << "Current index: " << CurrentID.toStdString() << endl;
}

//################################################################################################

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow){
    using namespace std;
    ui->setupUi(this);



    // Set current version in TitleBar
    this->setWindowTitle("RoboJournal " + Buffer::version);

    // Do initial UI configuration (set up toolbar, statusbar, etc.) before showing the main window
    PrimaryConfig();
}

//################################################################################################
// Create Stylesheets for Decorate_GUI() to allow the user to apply a custom
// background and font to RoboJournal GUI. This feature was requested by Sandra Goodhew
// because she thought people would want to use their own backgrounds and fonts.

QString MainWindow::CreateStyleSheet(bool for_entrylist, bool is_TextEdit){
    using namespace std;
    QList<QString> stylelist;

    // if the user wants to use a background image, apply it
    if(Buffer::use_background){

        // apply style to entire QTextEdit class type
        if(is_TextEdit){
            stylelist.append("QTextEdit { ");
        }
//        else{
//            stylelist.append("QTreeWidget { ");
//        }

        // create style for QTextEdit

        // get system colors for border/background.  That way, it will look
        //good no matter what scheme user has

        QPalette pal;
        QBrush bg=pal.window();
        QBrush border=pal.dark();

        QColor swatch=bg.color();
        QColor c_border=border.color();


        stylelist.append("background: " + swatch.name() + " url(" + Buffer::background_image + "); ");
        stylelist.append("border: solid 2px " + c_border.name() + ";  ");


        // don't tile background if  config says not to
        if(!Buffer::tile_bg){
            stylelist.append("background-repeat: no-repeat; ");
        }
    }

    stylelist.append("color: " + Buffer::text_hexcolor + "; ");

    // prevent font size/style from being applied to entrylist if user doesn't want it to be
    if(!for_entrylist){
        stylelist.append("font-family: " + Buffer::font_face + "; ");
        stylelist.append("font-size:" + Buffer::font_size + "pt; ");
    }

    //close the QTextEdit class
    if(is_TextEdit){
        stylelist.append(" }");
    }

    QString stylesheet;
    QListIterator<QString> styleiterator(stylelist);

    while(styleiterator.hasNext()){
        stylesheet.append(styleiterator.next());
    }

    //cout << "Style: " << stylesheet.toStdString() << endl;
    return stylesheet;
}

//################################################################################################
// Call updater
void MainWindow::UpgradeJournal(){
    using namespace std;


    QInputDialog d(this);
    d.setWindowTitle("Authenticate");
    d.setLabelText("Provide root password for " + Buffer::host);
    d.setTextEchoMode(QLineEdit::Password);
    bool accept=d.exec();

    if(accept){
        QString root_pass=d.textValue();
        MySQLCore my;
        my.UpgradeJournal(root_pass);

        QMessageBox m;

        if(my.db.isOpenError()){
            m.critical(this,"RoboJournal","Could not connect! Please make sure the root password is correct and try again.");
            UpgradeJournal();
        }
        else{
            m.information(this,"RoboJournal", "<b>" + Buffer::database_name +
                          "</b> has been upgraded successfully. Click <b>Connect</b> (or hit F2) to log in.");
            cout << "DONE!" << endl;
        }
    }
    else{
        cout << "FAILED!" << endl;
        d.close();
    }
}

//################################################################################################
// Print current entry
void MainWindow::Print(){
    QPrinter p;
    QPrintDialog *d=new QPrintDialog(&p, this);
    d->setWindowTitle("Print Current Entry");

    int choice=d->exec();

    switch(choice){

    case QPrintDialog::Accepted:
        ui->Output->print(&p);
        break;

    case QPrintDialog::Rejected:
        // do nothing
        break;
    }
}

//################################################################################################
// Save current entry as a text file
bool MainWindow::SaveEntry(){
    bool saved=true;
    return saved;
}


//################################################################################################
// Function that returns the inverse Hex color of the provided text color.
// Since the text color is used for the date bar bg if custom theme is used, we want to make sure
// that the text displayed  is always readable. Inverse colors provide the best contrast.

QString MainWindow::InvertColor(QString textcolor){

    using namespace std;
    QColor input;
    input.setNamedColor(textcolor);

    int ired, igreen, iblue;

    ired=input.red();
    igreen=input.green();
    iblue=input.blue();

    //cout << "Input RGB: " << ired << igreen << iblue << endl;

    int ored, ogreen, oblue;

    ored=255-ired;
    ogreen=255-igreen;
    oblue=255-iblue;

    //cout << "Output RGB: " << ored << ogreen << oblue << endl;

    QColor output=QColor::fromRgb(ored,ogreen,oblue);

    QString invertcolor=output.name();
    //cout << "Inverse hex: "  << invertcolor.toStdString() << endl;
    return invertcolor;
}

//################################################################################################
// Function to style GUI with custom background, font, etc.
void MainWindow::Decorate_GUI(){

    // Alternating Row colors can be very good or very bad depending on color scheme.
    //Users have a way to turn it off at long last
    if(!Buffer::alternate_rows){
        ui->EntryList->setAlternatingRowColors(false);
    }
    else{
        ui->EntryList->setAlternatingRowColors(true);
    }


    // remove icon labels if user doesn't want them
    if(!Buffer::show_icon_labels){
        ui->ConnectButton->setText("");
        ui->DisconnectButton->setText("");
        ui->LastEntry->setText("");
        ui->WriteButton->setText("");
        ui->EditEntryButton->setText("");
        ui->DeleteEntry->setText("");
        ui->NextEntry->setText("");
        ui->TodayButton->setText("");
        ui->ConfigButton->setText("");
    }
    else{ // restore values in case user wishes to enable them at runime
        ui->ConnectButton->setText("Connect");
        ui->DisconnectButton->setText("Disconnect");
        ui->LastEntry->setText("Previous");
        ui->WriteButton->setText("Write in Journal");
        ui->EditEntryButton->setText("Modify Entry");
        ui->DeleteEntry->setText("Delete Entry");
        ui->NextEntry->setText("Next");
        ui->TodayButton->setText("Latest");
        ui->ConfigButton->setText("Preferences");
    }

    if(Buffer::use_custom_theme){


         QString stylesheet=CreateStyleSheet(false,true);

         ui->Output->setStyleSheet(stylesheet);

         if(Buffer::set_tree_background){
             stylesheet=CreateStyleSheet(true,false);
             ui->EntryList->setStyleSheet(stylesheet);
         }

    }
    // clear all styles if the user disables them during runtime
    else{
        ui->Output->setStyleSheet(NULL);

        if(!Buffer::set_tree_background){
            ui->EntryList->setStyleSheet(NULL);
        }
    }
}

//################################################################################################
// this function will eventually launch the help file. Right now, just show a warning message.
void MainWindow::ShowHelp(){
    QMessageBox b;
    b.critical(this,"RoboJournal","The help file is not available in this release. It will be included in RoboJournal 0.3");
}


//################################################################################################
// Fetch entry based on ID
void MainWindow::GetEntry(QString id){
    using namespace std;
    // Current record should be the ID of the most recent selected entry
    Record=id;

    if(Buffer::backend=="MySQL"){
        MySQLCore my;
        QString entry=my.RetrieveEntry(id);
        QString datestamp=my.TimeStamp(id);

        // convert plain text linebreaks to html
        entry.replace("\n","<br>");

        // find and use system colors
        QPalette pal;
        QBrush bg=pal.highlight();
        QBrush fg=pal.highlightedText();

        QColor bgcolor=bg.color();
        QColor fgcolor=fg.color();

        QString color1=bgcolor.name();
        QString color2=fgcolor.name();

        // set masthead and display text
        QString text;

        // use timestamp?

        if(Buffer::keep_time){

            // fetch timestamp
            QString timestamp=my.GetTimestamp(Record);
            //cout << "Record: " + Record.toStdString() << endl;


            // get title if buffer has it
            if(Buffer::show_title){

                QString title=my.GetTitle(id);
                title="<h2>" + title + "</h2>";

                if(Buffer::use_custom_theme){
                    QString invertcolor=InvertColor(Buffer::text_hexcolor);

                    text= title + "<div style=\"background-color:" + Buffer::text_hexcolor + ";  color: " +
                            invertcolor +"; width=100%;\"><small>&nbsp;&nbsp;On " +
                            datestamp + " at "+ timestamp + ",  " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";

                }
                else{

                    text= title + "<div style=\"background-color:" + color1 + "; margin: -3px; color: " +
                            color2 +"; width=100%; \"><small>&nbsp;&nbsp; On " +
                            datestamp + " at "+ timestamp + ", " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";
                }
            }
            // do not show title
            else{
                if(Buffer::use_custom_theme){
                    QString invertcolor=InvertColor(Buffer::text_hexcolor);

                    text="<div style=\"background-color:" + Buffer::text_hexcolor + "; margin: -3px; color: " +
                            invertcolor +"; width=100%; padding: 20px 80px;\"><small>&nbsp;&nbsp; On " +
                            datestamp + " at "+ timestamp + ", " + Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";

                }
                else{

                    text="<div style=\"background-color:" + color1 + "; margin: -3px; color: " +
                            color2 +"; width=100%; padding: 20px 80px;\"><small>&nbsp;&nbsp; On " +
                            datestamp + " at "+ timestamp + ", " +  Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";
                }

            }

        }


        //no timestamp

        else{
            // get title if buffer has it
            if(Buffer::show_title){

                QString title=my.GetTitle(id);
                title="<h2>" + title + "</h2>";

                if(Buffer::use_custom_theme){
                    QString invertcolor=InvertColor(Buffer::text_hexcolor);

                    text= title + "<div style=\"background-color:" + Buffer::text_hexcolor + "; margin: -3px; color: " +
                            invertcolor +"; width=100%; \"><small>&nbsp;&nbsp; On " +
                            datestamp + ", " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";

                }
                else{

                    text= title + "<div style=\"background-color:" + color1 + "; margin: -3px; color: " +
                            color2 +"; width=100%; \"><small>&nbsp;&nbsp; On " +
                            datestamp + ", " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";
                }
            }
            // do not show title
            else{
                if(Buffer::use_custom_theme){
                    QString invertcolor=InvertColor(Buffer::text_hexcolor);

                    text="<div style=\"background-color:" + Buffer::text_hexcolor + "; margin: -3px; color: " +
                            invertcolor +"; width=100%; \"><small>&nbsp;&nbsp; On " +
                            datestamp + ", " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";

                }
                else{

                    text="<div style=\"background-color:" + color1 + "; margin: -3px; color: " +
                            color2 +"; width=100%; \"><small>&nbsp;&nbsp; On " +
                            datestamp + ", " +   Buffer::username +
                            " wrote:</small></div><div><br>" + entry + "</div>";
                }

            }

        }

        // set entry text
        ui->Output->setText(text);
    }
}

//################################################################################################
// Function that sets up main window GUI when mainwindow is called at startup
void MainWindow::PrimaryConfig(){
    switch(Buffer::toolbar_pos){

        case 0:
            this->addToolBar(Qt::LeftToolBarArea,ui->mainToolBar);
        break;

        case 1:
            this->addToolBar(Qt::TopToolBarArea,ui->mainToolBar);
        break;

        case 2:
            this->addToolBar(Qt::RightToolBarArea,ui->mainToolBar);
        break;
    }



    // Setup Statusbar
    ui->TotalCount->clear();
    ui->statusBar->addWidget(ui->StatusMessage,1);
    ui->statusBar->addPermanentWidget(ui->TotalCount,0);


    // setup toolbars
    ui->mainToolBar->addWidget(ui->ConnectButton);
    ui->mainToolBar->addWidget(ui->DisconnectButton);
    ui->mainToolBar->addSeparator();

    ui->mainToolBar->addWidget(ui->TodayButton);
    ui->mainToolBar->addWidget(ui->LastEntry);
    ui->mainToolBar->addWidget(ui->NextEntry);

    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addWidget(ui->WriteButton);
    ui->mainToolBar->addWidget(ui->EditEntryButton);

    // This function should be invisible in the beta until the feature is fully built
    ui->SearchButton->setVisible(false);

    // hide export entry feature for now... we need to include it in 0.3
    ui->actionSave_Current_Entry->setVisible(false);

    ui->mainToolBar->addWidget(ui->SearchButton);


    ui->mainToolBar->addWidget(ui->DeleteEntry);

    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addWidget(ui->ConfigButton);


    ui->WriteButton->setDisabled(true);
    ui->actionPrint->setDisabled(true);

    ui->NextEntry->setDisabled(true);
    ui->LastEntry->setDisabled(true);
    ui->TodayButton->setDisabled(true);
    ui->SearchButton->setDisabled(true);
    ui->DeleteEntry->setDisabled(true);
    ui->EditEntryButton->setDisabled(true);
    ui->DisconnectButton->setDisabled(true);

    ui->actionLatest_Entry->setDisabled(true);
    ui->actionNext_Entry->setDisabled(true);
    ui->actionPrevious_Entry->setDisabled(true);
    ui->actionDisconnect->setDisabled(true);
    ui->actionWrite->setDisabled(true);
    ui->actionDelete_Current_Entry->setDisabled(true);
    ui->actionEdit_Selected_Entry->setDisabled(true);

    QPixmap noicon("qrc:///icons/database_error.png");
    ui->StatusMessage->setPixmap(noicon);
    ui->StatusMessage->setText("Click <b>Connect</b> (or hit <b>F2</b>) to begin working with a journal database.");

    ui->EntryList->setColumnWidth(0,450);

    //Column 1 (Entry ID) is important since it contains the DB row ID, that we check the DB with
    // but it's not necessary for the user to see the column since it just
    // clutters the form
    ui->EntryList->setColumnWidth(1,70);
    ui->EntryList->setColumnHidden(1,true);

    // flip the connection active switch
    ConnectionActive=false;


    // keep the program from crashing if the user clicks Modify before selecting an entry
    CurrentID="-1";

    //Decorate the GUI
    Decorate_GUI();
}

//################################################################################################
// Connect to database function
void MainWindow::Connect(){
    using namespace std;
    DBLogin l(this);
    l.setWindowTitle("New Connection [" + Buffer::backend + "]");

    bool is_connected=false; // check to see if connection is true


    l.Refresh();
    l.exec();

    // if user provided login data
    if(Buffer::login_succeeded){

        this->setCursor(Qt::WaitCursor);

        if(Buffer::backend=="MySQL"){
            this->setCursor(Qt::WaitCursor);
            MySQLCore my;


            MySQLCore::dialogX=l.x();
            MySQLCore::dialogY=l.y();

            bool success=my.Connect();
            bool is_sane=my.SanityCheck();

            if(!success){

                // check to make sure the MYSQL driver is installed, return error if false
                // If you're using a static build of QT you're probably never going to see this error
                if(!my.db.isDriverAvailable("QMYSQL")){
                    this->setCursor(Qt::ArrowCursor);
                   QMessageBox j;
                   j.critical(this,"Database Error","The MySQL driver (QT 4.7) is not installed correctly! RoboJournal"
                              " will not be able to use MySQL databases until this problem is fixed.");
                }

                // if the user got this far, the driver is good but there was a different problem encountered
                //logging in. (permission error, bad passwd, etc.)
                if(my.db.isOpenError()){
                    this->setCursor(Qt::ArrowCursor);
                    QMessageBox m;
                    QString reason="<ul><li><li>Make sure that you are authorized to access <b>" +
                            Buffer::database_name + "</b> from this workstation.<li>Make sure the port, username," +
                            " and password you provided are correct.</ul>Please check and/or rectify these problems and try again.";
                    m.critical(this,"Connection Error","Connection attempt with <b>" +
                               Buffer::database_name + "</b> on <b>" +
                               Buffer::host + "</b> failed." + reason );

                    // allow user to try again
                    l.ResetPassword();
                    Connect();

                }

            }
            else{

                if(!is_sane){

                    // does the journal fail sanity check because it is old....
                    if(Buffer::needs_upgrade){

                        // show upgrade dialog
                        QMessageBox u(this);
                        u.setIcon(QMessageBox::Question);
                        u.setWindowTitle("Journal Upgrade Required");
                        u.setText("<b>" + Buffer::database_name + "</b> is a valid journal but it must be upgraded before RoboJournal "
                        + Buffer::version + " can use it. After this journal has been upgraded to the new format, it will no longer be "
                        "compatible with older versions of RoboJournal.<br><br> Do you want to upgrade this journal now?");

                        u.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
                        u.setDefaultButton(QMessageBox::Yes);
                        int choice=u.exec();

                        switch(choice){
                        case QMessageBox::Yes:
                            // Update journal
                            cout << "OUTPUT: Starting journal upgrade process...";
                            UpgradeJournal();
                            break;
                        case QMessageBox::No:
                            // do nothing
                            break;
                        }

                        // reset upgrade flag
                        Buffer::needs_upgrade=false;
                    }

                    // or because it is just 100% invalid due to structure
                    else{
                        QMessageBox m;
                        m.critical(this,"Integrity Error","Database <b>" + Buffer::database_name +
                                   "</b> is not a valid journal!");

                        cout << "ERROR: Database " << Buffer::database_name.toStdString() <<
                                " FAILED sanity check, aborting load sequence!" << endl;

                    }
                }
                else{


                    ui->WriteButton->setEnabled(true);


                    ui->TodayButton->setEnabled(true);
                    ui->SearchButton->setEnabled(true);
                    ui->EditEntryButton->setEnabled(true);
                    ui->DisconnectButton->setEnabled(true);
                    ui->NextEntry->setEnabled(true);
                    ui->LastEntry->setEnabled(true);
                    ui->DeleteEntry->setEnabled(true);
                    ui->actionWrite->setEnabled(true);
                    ui->actionLatest_Entry->setEnabled(true);
                    ui->actionNext_Entry->setEnabled(true);
                    ui->actionPrevious_Entry->setEnabled(true);
                    ui->actionDisconnect->setEnabled(true);
                    ui->actionDelete_Current_Entry->setEnabled(true);
                    ui->actionEdit_Selected_Entry->setEnabled(true);
                    ui->actionPrint->setEnabled(true);

                    ui->actionConnect->setDisabled(true);
                    ui->ConnectButton->setDisabled(true);

                    // Get ID list
                    int year_range=Buffer::entryrange.toInt();
                    IDList=my.Create_ID_List(year_range);

                    CreateTree();
                    ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
                    Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
                    Buffer::username + "\"</b>");

                    is_connected=true;

                }
                this->setCursor(Qt::ArrowCursor);

            }


        }

        if(Buffer::backend=="Postgres"){
            PSQLCore po;
            bool success=po.Connect();

            if(!success){
                QMessageBox m;
                m.critical(this,"Error","Connection attempt with <b>" +
                           Buffer::database_name + "</b> on <b>" +
                           Buffer::host + "</b> failed.");
            }
            else{
                ui->WriteButton->setEnabled(true);


                ui->TodayButton->setEnabled(true);
                ui->SearchButton->setEnabled(true);
                ui->EditEntryButton->setEnabled(true);
                ui->DisconnectButton->setEnabled(true);
                ui->NextEntry->setEnabled(true);
                ui->LastEntry->setEnabled(true);

                ui->ConnectButton->setDisabled(true);
                ui->StatusMessage->setText("Connected to <b>" + Buffer::database_name + "</b> on <b>" +
                Buffer::host + "</b> as user <b>\"" + Buffer::username + "\"</b>");
            }

        }
    }
    if(Buffer::backend=="SQLite"){

        SQLiteCore sl;
        bool success=sl.Connect();

        if(!success){
            QMessageBox m;
            m.critical(this,"Error", Buffer::backend + " connection attempt with <b>" +
                       Buffer::database_name + "</b> on <b>" +
                       Buffer::host + "</b> failed.");
        }
        else{
            ui->WriteButton->setEnabled(true);


            ui->TodayButton->setEnabled(true);
            ui->SearchButton->setEnabled(true);
            ui->EditEntryButton->setEnabled(true);
            ui->DisconnectButton->setEnabled(true);
            ui->NextEntry->setEnabled(true);
            ui->LastEntry->setEnabled(true);

            ui->ConnectButton->setDisabled(true);
            ui->StatusMessage->setText("Connected to <b>" + Buffer::database_name + "</b> on <b>" +
            Buffer::host + "</b> as user <b>\"" + Buffer::username + "\"</b>");
        }



        // create the entry tree
        CreateTree();



        this->setCursor(Qt::ArrowCursor);

        // flip the connection active switch
        ConnectionActive=true;



    }

    // connect to latest entry automatically

    if((is_connected && num_records != 0) || (ConnectionActive)){

        ui->NextEntry->setEnabled(true);
        ui->LastEntry->setEnabled(true);
        ui->TodayButton->setEnabled(true);

        MostRecent();
        Record=CurrentID;
    }
    // if there are no entries at login, disable a few buttons to prevent crashes
    else{

        if(num_records==0){
            ui->TodayButton->setEnabled(false);
            ui->NextEntry->setEnabled(false);
            ui->LastEntry->setEnabled(false);
            ui->DeleteEntry->setEnabled(false);
            ui->EditEntryButton->setEnabled(false);
            ui->actionLatest_Entry->setDisabled(true);
            ui->actionNext_Entry->setDisabled(true);
            ui->actionPrevious_Entry->setDisabled(true);
            ui->actionDelete_Current_Entry->setDisabled(true);
            ui->actionEdit_Selected_Entry->setDisabled(true);
        }

    }
 }

//################################################################################################
/*
  Launch editor in revision mode. QString entry is the selected index.

  */
void MainWindow::Modify(){

    if(CurrentID != "-1"){

        Buffer::editentry=CurrentID;
        Buffer::editmode=true;

        Editor e(this);
        e.exec();

        // Update Tree
        CreateTree();

        // refresh entry in Output Pane
        GetEntry(CurrentID);

        ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
        Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
        Buffer::username + "\"</b>");

        // keep current entry selected
        HighlightCurrentSelection(CurrentID);


    }
    else{ // show error if no  valid entries are selected
        QMessageBox a;
        a.critical(this,"RoboJournal","Please select an entry to modify before clicking the <b>Modify Entry</b> button.");

    }
}
//################################################################################################
// Delete an entry
void MainWindow::DeleteSelectedEntry(){

    MySQLCore my;

    // make sure we're not working with a node, since nodes always have -1 as Current ID
    if(CurrentID!="-1"){

        if(Buffer::showwarnings){
            QMessageBox b;
            int choice=b.question(this,"Delete entry?","Do you really want to delete the selected journal entry?"
            " This action can't be undone.",QMessageBox::Cancel,QMessageBox::Ok);

            switch(choice){
                case QMessageBox::Ok:
                    if(Buffer::backend=="MySQL"){
                        my.DeleteEntry(CurrentID);
                        CreateTree();
                        ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
                        Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
                        Buffer::username + "\"</b>");
                        ui->Output->setPlainText(NULL);
                    }
                break;

                case QMessageBox::Cancel:
                // do nothing
                break;


            }
        }
        else{
            if(Buffer::backend=="MySQL"){
                my.DeleteEntry(CurrentID);
                CreateTree();
                ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
                Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
                Buffer::username + "\"</b>");
                ui->Output->setPlainText(NULL);
            }
        }



    }
}

//################################################################################################
void MainWindow::Disconnect(){

    /*
      This function doesn't really terminate a connection since there is no persistent connection...
      all SQL queries are called directly as needed. it just resets the MainWindow class to its
      intial state so a new connection could be made later.
      */

    ui->WriteButton->setDisabled(true);

    ui->NextEntry->setDisabled(true);
    ui->LastEntry->setDisabled(true);

    ui->TodayButton->setDisabled(true);
    ui->SearchButton->setDisabled(true);
    ui->DeleteEntry->setDisabled(true);
    ui->EditEntryButton->setDisabled(true);
    ui->DisconnectButton->setDisabled(true);
    ui->ConnectButton->setEnabled(true);

    ui->Output->setText(NULL);
    ui->EntryList->clear();

    ui->actionWrite->setDisabled(true);
    ui->actionDisconnect->setDisabled(true);
    ui->actionLatest_Entry->setDisabled(true);
    ui->actionNext_Entry->setDisabled(true);
    ui->actionPrevious_Entry->setDisabled(true);
    ui->actionDelete_Current_Entry->setDisabled(true);
    ui->actionEdit_Selected_Entry->setDisabled(true);
    ui->actionConnect->setEnabled(true);
    ui->EntryList->setHeaderHidden(true);
    ui->actionWrite->setDisabled(true);
    ui->actionPrint->setDisabled(true);


    // Clear the ID list so we don't have data from previous connections on it. That sure would cause problems....
    IDList.clear();

    // flip the connection active switch
    ConnectionActive=false;


    ui->StatusMessage->setText("Terminated connection with <b>" + Buffer::host + "</b>");
    ui->TotalCount->clear();
    ui->TotalCount->setToolTip(NULL);
}

//################################################################################################
// show preferences window
void MainWindow::Preferences(){
    Config c(this);
    c.setWindowTitle("RoboJournal Preferences");

//    if(!this->isMaximized()){
//        int posX=this->x()+200;
//        int posY=this->y()+80;
//        //c.move(posX,posY);
//    }


    c.exec();



    if(c.MadeChanges){
        ConfigManager cm;
        cm.ReadConfig();

        if(!ConnectionActive && ui->DisconnectButton->isEnabled()){
            CreateTree();
            ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
            Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
            Buffer::username + "\"</b>");
        }

        // Setup toolbar position again in case user changed it
        switch(Buffer::toolbar_pos){

            case 0:
                this->addToolBar(Qt::LeftToolBarArea,ui->mainToolBar);
            break;

            case 1:
                this->addToolBar(Qt::TopToolBarArea,ui->mainToolBar);
            break;

            case 2:
                this->addToolBar(Qt::RightToolBarArea,ui->mainToolBar);
            break;
        }
    }

    //Re-decorate the GUI
    Decorate_GUI();

}
//################################################################################################
// show credits window
void MainWindow::ShowCredits(){
    AboutRJ a(this);

  int width=a.width();
  int height=a.height();
  a.setMaximumSize(width, height);
  a.setMinimumSize(width, height);
  a.setWindowTitle("About RoboJournal");
  a.exec();
}

//################################################################################################
// Call editor dialog class
void MainWindow::Write(){
    using namespace std;

    // Start Editor in new entry mode
    Buffer::editmode=false;

    // Declare and show a journal editor object
    Editor e(this);
    e.setWindowTitle("Untitled Entry -- RoboJournal");
    e.exec();

    // Refresh the entry list
    cout << "OUTPUT: Re-creating entry list to include newest entry." << endl;
    CreateTree();

    // rebuild ID list
    MySQLCore my;
    int year_range=Buffer::entryrange.toInt();
    IDList.clear();
    IDList=my.Create_ID_List(year_range);


    // Reset Status bar message
    ui->StatusMessage->setText("Connected to " + Buffer::backend  + " database <b>" +
    Buffer::database_name + "</b> on <b>" +  Buffer::host + "</b> as user <b>\"" +
    Buffer::username + "\"</b>");
}

//################################################################################################
// Function that highlights the tree item corresponding to current entry being viewed
void MainWindow::HighlightCurrentSelection(QString CurrentID){
    using namespace std;
    ui->EntryList->clearSelection();
    QTreeWidgetItemIterator it(ui->EntryList,QTreeWidgetItemIterator::NoChildren);

        while (*it) {
            if ((*it)->text(1) == CurrentID)
                (*it)->setSelected(true);
                ++it;

                // Make sure CurrentID always reflects current highlighted index
                // This is necessary in case the user wants to edit an entry
                this->CurrentID=CurrentID;
        }

}

//################################################################################################
// All-important function that sets up the Entry tree list.
void MainWindow::CreateTree(){
    using namespace std;
    ui->StatusMessage->setText("Populating entry list, please wait...");
    QIcon rooticon(":/icons/database.png");
    //QIcon monthicon(":/icons/bullet_black.png");
    //QIcon yearicon(":/icons/bullet_blue.png");

    QIcon entryicon(":/icons/pencil.png");

    QFont heavy("sans",10);
    heavy.setWeight(QFont::DemiBold);

    int totalcount=0;

    // clear message and tree panes
    ui->EntryList->clear();
    ui->Output->clear();

    // MySQL code
    if(Buffer::backend=="MySQL"){

        // sort entries by day
        if(Buffer::sortbyday){
            cout << "OUTPUT: Creating entry list from contents of MySQL database " << Buffer::database_name.toStdString() << " ...";
            MySQLCore my;

            bool NewJournal=true;

            QList<QString> YearList;
            QList<QString> MonthList;
            QList<QString> DayList;
            QList<QString> EntryList;

            YearList=my.getYear();


            QListIterator<QString> IteratorYear(YearList);


            ui->EntryList->setHeaderLabel("Database contents (chronological)");
            ui->EntryList->setToolTip(NULL);
            ui->EntryList->setHeaderHidden(false);

            QString db=Buffer::database_name;



            QTreeWidgetItem *root = new QTreeWidgetItem(ui->EntryList);
            root->setText(0, db);
            root->setIcon(0,rooticon);
            root->setToolTip(0, "<b>" + Buffer::database_name + "</b>@<b>" + Buffer::host + "</b>");
            //root->setFont(0,heavy);


            for(int y=0; y<YearList.count(); y++){
                QTreeWidgetItem *year = new QTreeWidgetItem(root);

                QString nextyear=IteratorYear.next();
                year->setText(0, nextyear);


                MonthList=my.getMonth(nextyear);
                QListIterator<QString> IteratorMonth(MonthList);


                for(int m=0; m < MonthList.count(); m++){
                    QTreeWidgetItem *month = new QTreeWidgetItem(year);
                    //month->setFont(0,heavy);

                    //month->setIcon(0,monthicon);

                    QString itemmonth=IteratorMonth.next();

                    //cout << "Item month:" << itemmonth.toStdString() <<endl;
                    int switchmonth=itemmonth.toInt();

                    QString longmonth;


                    switch(switchmonth){
                        case 1:
                        longmonth="January";
                        break;

                        case 2:
                        longmonth="February";
                        break;

                        case 3:
                        longmonth="March";
                        break;

                        case 4:
                        longmonth="April";
                        break;

                        case 5:
                        longmonth="May";
                        break;

                        case 6:
                        longmonth="June";
                        break;

                        case 7:
                        longmonth="July";
                        break;

                        case 8:
                        longmonth="August";
                        break;

                        case 9:
                        longmonth="September";
                        break;

                        case 10:
                        longmonth="October";
                        break;

                        case 11:
                        longmonth="November";
                        break;

                        case 12:
                            longmonth="December";
                        break;
                    }

                    DayList=my.getDay(itemmonth,nextyear);
                    //cout << "Daylist: " << DayList.length();
                    QListIterator<QString> IteratorDay(DayList);


                    int EntryCount=0; // keep track of the number of entries for each month

                    for(int d=0; d<DayList.length(); d++){
                        QString itemday=IteratorDay.next();
                        QTreeWidgetItem *day = new QTreeWidgetItem(month);

                        // Organize Date depending on Buffer data

                        int dateformat=Buffer::date_format.toInt();

                        switch(dateformat){

                        case 0: // international
                            day->setText(0, itemday + " " + longmonth  );
                            break;

                        case 1:  // usa
                            day->setText(0,longmonth + " " + itemday);
                            break;

                        case 2: // japan
                            day->setText(0,longmonth + " " + itemday);
                            break;
                        }





                        EntryList=my.getEntries(itemday,itemmonth);

                        QListIterator<QString> IteratorEntry(EntryList);



                        for(int e=0; e<EntryList.length(); e++){
                            QString entry=IteratorEntry.next();
                            QTreeWidgetItem *EntryItem = new QTreeWidgetItem(day);
                            QStringList item=entry.split("|");
                            QString tooltip=longmonth + " " + itemday + ", " +
                                    nextyear + " : " + item[0];

                            EntryItem->setText(0, item[0]);
                            EntryItem->setToolTip(0, tooltip);
                            EntryItem->setText(1, item[1]);
                            EntryItem->setIcon(0,entryicon);

                            // since we know there are entries at this point, NewJournal should be set to false.
                            NewJournal=false;


                            EntryCount++; // auto-increment entry count

                            totalcount++; // update totalcount

                            // append to highlight list;




                            //hilite_list.append();

                        }

                        //if EntryCount==0, we have a new journal. Show a message if this happens.
                        if(EntryCount==0){
                            QMessageBox a;
                            a.information(this,"RoboJournal","Welcome to your new journal! Click <b>Write in Journal</b> (or hit F4) to get started.");
                        }

                        EntryList.clear();

                    }
                    DayList.clear();

                    month->setText(0, longmonth);
                    QString monthcount=QString::number(EntryCount);

                    if(EntryCount==1){
                        month->setToolTip(0, longmonth + " " + nextyear +
                                          " (" + monthcount + " entry)");
                    }
                    else{
                        month->setToolTip(0, longmonth + " " + nextyear +
                                          " (" + monthcount + " entries)");
                    }


                    EntryCount=0;
                }
                MonthList.clear();
            }

            //if NewJournal is still true, that means we have a new journal. Show a message if this happens.
            if(NewJournal){
                root->setHidden(true);
                QMessageBox a;
                a.information(this,"RoboJournal","Welcome to your new journal! Click <b>Write in Journal</b> (or hit F4) to get started.");
            }

            YearList.clear();

            TotalEntryCount(totalcount);


        }

        //#################################################
        //          Sort entries by month only
        //#################################################

        else{
            cout << "OUTPUT: Creating entry list from contents of MySQL database " << Buffer::database_name.toStdString() << " ...";
            MySQLCore my;

            bool NewJournal=true;

            QList<QString> YearList;
            QList<QString> MonthList;
            QList<QString> EntryList;

            YearList=my.getYear();


            QListIterator<QString> IteratorYear(YearList);


            ui->EntryList->setHeaderLabel("Database contents (chronological)");
            ui->EntryList->setToolTip(NULL);
            ui->EntryList->setHeaderHidden(false);

            QString db=Buffer::database_name;

            QTreeWidgetItem *root = new QTreeWidgetItem(ui->EntryList);


            root->setText(0, db);
            root->setIcon(0,rooticon);
            root->setToolTip(0, "<b>" + Buffer::database_name + "</b>@<b>" + Buffer::host + "</b>");
            //root->setFont(0,heavy);



            for(int y=0; y<YearList.count(); y++){
                QTreeWidgetItem *year = new QTreeWidgetItem(root);
                //year->setIcon(0,yearicon);

                QString nextyear=IteratorYear.next();
                year->setText(0, nextyear);
                //year->setFont(0,heavy);

                //cout << "Current Year: " << nextyear.toStdString() << endl;

                MonthList=my.getMonth(nextyear);
                QListIterator<QString> IteratorMonth(MonthList);


                for(int m=0; m < MonthList.count(); m++){
                    QTreeWidgetItem *month = new QTreeWidgetItem(year);
                    //month->setFont(0,heavy);

                    //month->setIcon(0,monthicon);

                    QString itemmonth=IteratorMonth.next();

                    //cout << "Item month:" << itemmonth.toStdString() <<endl;
                    int switchmonth=itemmonth.toInt();

                    QString longmonth;


                    switch(switchmonth){
                        case 1:
                        longmonth="January";
                        break;

                        case 2:
                        longmonth="February";
                        break;

                        case 3:
                        longmonth="March";
                        break;

                        case 4:
                        longmonth="April";
                        break;

                        case 5:
                        longmonth="May";
                        break;

                        case 6:
                        longmonth="June";
                        break;

                        case 7:
                        longmonth="July";
                        break;

                        case 8:
                        longmonth="August";
                        break;

                        case 9:
                        longmonth="September";
                        break;

                        case 10:
                        longmonth="October";
                        break;

                        case 11:
                        longmonth="November";
                        break;

                        case 12:
                            longmonth="December";
                        break;
                    }

                    EntryList=my.getEntriesMonth(itemmonth,nextyear);
                    //cout << "Daylist: " << DayList.length();
                    QListIterator<QString> IteratorEntry(EntryList);

                    int EntryCount=0; // keep track of the number of entries for each month

                    for(int e=0; e<EntryList.length(); e++){
                        QString raw_entry=IteratorEntry.next();
                        //cout << entry.toStdString() << endl;
                        QTreeWidgetItem *EntryItem = new QTreeWidgetItem(month);

                        QStringList item=raw_entry.split(",");

                        // Organize Date depending on Buffer data

                        int dateformat=Buffer::date_format.toInt();
                        QString entry;
                        switch(dateformat){

                        case 0: // international
                            entry=item[2] + " " + longmonth + ": " + item [1];
                            break;

                        case 1:  // usa
                            entry=longmonth + " " + item[2] + ": " + item [1];
                            break;

                        case 2: // japan
                            entry=longmonth + " " + item[2] + ": " + item [1];
                            break;
                        }





                        EntryItem->setText(0,entry);
                        EntryItem->setToolTip(0,entry);

                        EntryItem->setText(1,item[0]);
                        EntryItem->setIcon(0, entryicon);

                        // since we know there are entries at this point, NewJournal should be set to false.
                        NewJournal=false;

                        EntryCount++; // auto-increment entry count

                        totalcount++; // update totalcount
                    }



                    EntryList.clear();



                    QString monthcount=QString::number(EntryCount);

                    month->setText(0, longmonth);

                    // do month post count
                    if(EntryCount==1){
                        month->setToolTip(0, longmonth + " " + nextyear +
                                          " (" + monthcount + " entry)");
                    }
                    else{
                        month->setToolTip(0, longmonth + " " + nextyear +
                                          " (" + monthcount + " entries)");
                    }

                    EntryCount=0;
                }
                MonthList.clear();
            }
            YearList.clear();

            TotalEntryCount(totalcount);

            //if NewJournal is still true, that means we have a new journal. Show a message if this happens.
            if(NewJournal){
                root->setHidden(true);
                QMessageBox a;
                a.information(this,"RoboJournal","Welcome to your new journal! Click <b>Write in Journal</b> (or hit F4) to get started.");
            }

        }
    }
    ui->EntryList->expandAll();
    cout << "Done!" << endl;

    // re-enable a few buttons just in case they were disabled.
    // (e.g. we log into a new journal and then switch to an existing one)

    if(num_records > 0){
        ui->TodayButton->setEnabled(true);
        ui->NextEntry->setEnabled(true);
        ui->LastEntry->setEnabled(true);
        ui->DeleteEntry->setEnabled(true);
        ui->EditEntryButton->setEnabled(true);
        ui->actionLatest_Entry->setDisabled(false);
        ui->actionNext_Entry->setDisabled(false);
        ui->actionPrevious_Entry->setDisabled(false);
        ui->actionDelete_Current_Entry->setDisabled(false);
        ui->actionEdit_Selected_Entry->setDisabled(false);
    }
    else{
        ui->TodayButton->setEnabled(false);
        ui->NextEntry->setEnabled(false);
        ui->LastEntry->setEnabled(false);
        ui->DeleteEntry->setEnabled(false);
        ui->EditEntryButton->setEnabled(false);
        ui->actionLatest_Entry->setDisabled(true);
        ui->actionNext_Entry->setDisabled(true);
        ui->actionPrevious_Entry->setDisabled(true);
        ui->actionDelete_Current_Entry->setDisabled(true);
        ui->actionEdit_Selected_Entry->setDisabled(true);

    }
}

//################################################################################################
// Update status bar label with total entry count
void MainWindow::TotalEntryCount(int totalcount){

    QString count=QString::number(totalcount);

    // update num_count. If num_count==0, the new journal notification will show and we will not
    //jump to first entry at login
    num_records=totalcount;

    if(totalcount==1){
        ui->TotalCount->setText(count  + " entry ");
    }
    else{
        ui->TotalCount->setText(count  + " entries ");
    }

    QString indicator;

    // create status bar messages
    if(Buffer::allentries){
        indicator="<nobr>Total number of entries to date in <b>" + Buffer::database_name + "</b></nobr>";
        ui->TotalCount->setToolTip(indicator);
        ui->statusBar->showMessage("Displaying all entries in the database...",1500);
    }
    else{
        int range=Buffer::entryrange.toInt();

        if(range==1){

            indicator="<nobr>Total number of entries for current range (" +
                    Buffer::entryrange + " year) in <b>" + Buffer::database_name + "</b></nobr>";
             ui->TotalCount->setToolTip(indicator);
             ui->statusBar->showMessage("Displaying all entries from this year...",1500);
        }
        else{
            indicator="<nobr>Total number of entries for current range (" +
                    Buffer::entryrange + " years) in <b>" + Buffer::database_name + "</b></nobr>";
            ui->TotalCount->setToolTip(indicator);
            ui->statusBar->showMessage("Displaying all entries from the last " + Buffer::entryrange
                                       + " years...",1500);
        }
    }
}

//################################################################################################
// Get the most recent entry from the db
void MainWindow::MostRecent(){
    if(Buffer::backend=="MySQL"){
        MySQLCore c;
        QString body=c.Recent();



        // convert plain text linebreaks to html
        body.replace("\n","<br>");

        // find and use system colors
        QPalette pal;
        QBrush bg=pal.highlight();
        QBrush fg=pal.highlightedText();

        QColor bgcolor=bg.color();
        QColor fgcolor=fg.color();

        QString color1=bgcolor.name();
        QString color2=fgcolor.name();

        //QString timestamp=c.TimeStamp(id);

        // display title above entry
        if(Buffer::show_title){

            QString id=c.recordnum;
            QString title=c.GetTitle(id);
            title="<h2>" + title + "</h2>";

            if(Buffer::use_custom_theme){
                QString invertcolor=InvertColor(Buffer::text_hexcolor);
                ui->Output->setText(title + "<div style=\"background-color: " + Buffer::text_hexcolor +
                                    "; color: " + invertcolor + "; width=100%; \"><small>&nbsp;&nbsp; " +
                                    Buffer::username + " wrote:</small></div><div><br>" + body  + "</div>");
            }
            else{
                ui->Output->setText(title + "<div style=\"background-color: " + color1 +
                                    "; color: " + color2 + "; width=100%; \"><small>&nbsp;&nbsp; " +
                                    Buffer::username + " wrote:</small></div><div><br>" + body  + "</div>");
            }

        }
        // don't display title
        else{
            if(Buffer::use_custom_theme){
                QString invertcolor=InvertColor(Buffer::text_hexcolor);
                ui->Output->setText("<div style=\"background-color: " + Buffer::text_hexcolor +
                                    "; color: " + invertcolor + "; width=100%; \"><small>&nbsp;&nbsp; " +
                                    Buffer::username + " wrote:</small></div><div><br>" + body  + "</div>");
            }
            else{
                ui->Output->setText("<div style=\"background-color: " + color1 +
                                    "; color: " + color2 + "; width=100%; \"><small>&nbsp;&nbsp; " +
                                    Buffer::username + " wrote:</small></div><div><br>" + body  + "</div>");
            }

        }



        ui->NextEntry->setDisabled(true);

        CurrentID=QString::number(c.ID);
        HighlightCurrentSelection(CurrentID);
    }
}
//################################################################################################
void MainWindow::GetPrevious(){
    if(Buffer::backend=="MySQL"){
        MySQLCore c;
        QString body=c.GetPrevious();
        ui->Output->setText(body);
    }
}
//################################################################################################
MainWindow::~MainWindow()
{
    delete ui;
}
//################################################################################################
void MainWindow::on_WriteButton_clicked()
{
    Write();
}

//################################################################################################

void MainWindow::on_SearchButton_clicked()
{
    using namespace std;
    EntrySearch es;
    es.exec();

}
//################################################################################################


void MainWindow::on_ConnectButton_clicked()
{
    Connect();
}
//################################################################################################
void MainWindow::on_DisconnectButton_clicked()
{
    Disconnect();

}

//################################################################################################

void MainWindow::on_ConfigButton_clicked()
{
    Preferences();
}
//################################################################################################

void MainWindow::on_actionPreferences_2_triggered()
{
    Preferences();
}
//################################################################################################
void MainWindow::on_actionConnect_triggered()
{
    Connect();
}
//################################################################################################
void MainWindow::on_actionToolbar_triggered(bool checked)
{
    if(!checked){
        ui->mainToolBar->hide();
    }
    else{
        ui->mainToolBar->show();
    }

}

//################################################################################################

void MainWindow::on_actionCopy_triggered()
{
    ui->Output->copy();
}
//################################################################################################
void MainWindow::on_actionSelect_all_triggered()
{
    ui->Output->selectAll();
}
//################################################################################################
void MainWindow::on_actionMain_toolbar_triggered(bool checked)
{
    if(!checked){
        ui->mainToolBar->hide();
    }
    else{
        ui->mainToolBar->show();
    }
}
//################################################################################################
void MainWindow::on_actionLeft_default_triggered()
{
    this->addToolBar(Qt::LeftToolBarArea,ui->mainToolBar);
}
//################################################################################################
void MainWindow::on_actionTop_triggered()
{
    this->addToolBar(Qt::TopToolBarArea,ui->mainToolBar);
}
//################################################################################################
void MainWindow::on_actionRight_triggered()
{
    this->addToolBar(Qt::RightToolBarArea,ui->mainToolBar);
}
//################################################################################################
void MainWindow::on_actionQuit_triggered()
{

    this->close();
}
//################################################################################################
void MainWindow::on_actionAbout_RoboJournal_triggered()
{
    ShowCredits();
}
//################################################################################################
void MainWindow::on_TodayButton_clicked()
{
    MostRecent();
}
//################################################################################################
void MainWindow::on_LastEntry_clicked()
{
    //GetPrevious();
    int direction=0;
    GetAdjacent(direction);
}

//################################################################################################

void MainWindow::on_actionLatest_Entry_triggered()
{
    MostRecent();
}
//################################################################################################
void MainWindow::on_actionDisconnect_triggered()
{
    Disconnect();
}

//################################################################################################
// Function that retrieves an entry when its entry is clicked on
void MainWindow::on_EntryList_itemClicked(QTreeWidgetItem *item)
{

    using namespace std;

    // make sure selected item is an entry and not just another subnode
    if(item->child(0)==NULL){
        QString id=item->text(1);

        GetEntry(id);

        // update selected entry
        UpdateSelectedEntry(id);

        //cout << id.toStdString() << endl;
    }
    else{
        //cout << "This is **NOT** an entry!" << endl;
        CurrentID="-1";
    }
}



//################################################################################################
// Function that moves to the next adjacent entry based on row ID.
// direction 1=forward; direction 0 =backward;
void MainWindow::GetAdjacent(int direction){

    using namespace std;
    if(Record!=NULL){
        QListIterator<QString> browser(IDList);
        using namespace std;

        //go backward one entry
        if(direction==0){

                if(!ui->NextEntry->isEnabled()){
                    ui->NextEntry->setEnabled(true);
                    ui->actionNext_Entry->setEnabled(true);
                }

                int position=IDList.indexOf(Record);
                position--;
                //cout << position << endl;

                QString lastindex=IDList.value(position);
                QString id=lastindex;
                //cout << lastindex.toStdString() << endl;

                if(position<0){
                    ui->LastEntry->setDisabled(true);
                    ui->actionPrevious_Entry->setDisabled(true);
                    if(!ui->NextEntry->isEnabled()){
                        ui->NextEntry->setEnabled(true);
                        ui->actionNext_Entry->setEnabled(true);
                    }
                }
                else{

                    if(CurrentID != "-1"){
                        GetEntry(id);
                        Record=lastindex;
                    }
                }


        }
        // go forward one entry
        if(direction==1){

            if(browser.next()==NULL){
                ui->NextEntry->setDisabled(true);
                ui->actionNext_Entry->setDisabled(true);
            }
            else{
                if(!ui->LastEntry->isEnabled()){
                    ui->LastEntry->setEnabled(true);
                    ui->actionPrevious_Entry->setEnabled(true);
                }



                int position=IDList.indexOf(Record);
                position++;

                QString nextindex=IDList.value(position);
                QString id=nextindex;
                //cout << nextindex.toStdString() << endl;

                if(position==IDList.size()){
                    ui->NextEntry->setDisabled(true);
                    ui->actionNext_Entry->setDisabled(true);
                    if(!ui->LastEntry->isEnabled()){
                        ui->LastEntry->setEnabled(true);
                        ui->actionPrevious_Entry->setEnabled(true);
                    }
                }
                else{

                    if(CurrentID != "-1"){
                        GetEntry(id);
                        Record=nextindex;
                    }


                }

            }
        }
    }

    if(CurrentID != "-1"){
       HighlightCurrentSelection(Record);
    }


}

//################################################################################################

void MainWindow::on_NextEntry_clicked()
{
    int direction=1;
    GetAdjacent(direction);
}
//################################################################################################
void MainWindow::on_actionPrevious_Entry_triggered()
{
    int direction=0;
    GetAdjacent(direction);
}
//################################################################################################
void MainWindow::on_actionNext_Entry_triggered()
{
    int direction=1;
    GetAdjacent(direction);
}

//################################################################################################

void MainWindow::on_actionEdit_Selected_Entry_triggered()
{
    Modify();
}

//################################################################################################

void MainWindow::on_actionSetup_Wizard_2_triggered()
{

    FirstRun f;


    if(Buffer::showwarnings){



        QMessageBox m;
        int reconfigure=m.question(this,"Reconfigure RoboJournal?",
        "Running the RoboJournal Setup Wizard again will purge all existing configuration settings. "
        "(however, any journal databases you have already created will be preserved) "
        " Are you sure you want to do this?",QMessageBox::Cancel,QMessageBox::Ok);

        switch(reconfigure){
            case QMessageBox::Ok:
            f.exec();

            break;

            case QMessageBox::Cancel:
            // do nothing
            break;
        }
    }
    else{
        f.exec();
    }
}

//################################################################################################
void MainWindow::on_actionPrint_triggered()
{
    if(ui->Output->toPlainText()!=NULL){
//        QMessageBox m;
//        m.critical(this,"Error","Printing is not implemented yet!");

        Print();
        //ui->Output->print();
    }
}

//################################################################################################

void MainWindow::on_DeleteEntry_clicked()
{
    DeleteSelectedEntry();
}

//################################################################################################
void MainWindow::on_actionDelete_Current_Entry_triggered()
{
    DeleteSelectedEntry();
}

//################################################################################################
void MainWindow::on_actionWrite_triggered()
{
    Write();
}
//################################################################################################
void MainWindow::on_actionHelp_file_triggered()
{
    ShowHelp();
}
//################################################################################################
void MainWindow::on_EditEntryButton_clicked()
{
Modify();
}