File: widget.cpp

package info (click to toggle)
cortina 0.7.3-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 2,420 kB
  • ctags: 132
  • sloc: cpp: 1,280; makefile: 10
file content (1242 lines) | stat: -rwxr-xr-x 48,767 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
/*
        This Program was written by Eric Baudach <Eric.Baudach@web.de>
        and is licensed under the GPL version 3 or newer versions of GPL.

                    <Copyright (C) 2010-2011 Eric Baudach>
 */

#include "widget.h"
#include "ui_widget.h"
#include "helper.h"
#include <gconf/2/gconf/gconf-client.h>
#include <QNetworkProxyFactory>


void MessageOutput(QtMsgType type, const char *msg)
{
    QString msg2;
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        if(QString(msg).contains("null image")) {
            qDebug() << "Couldn't load image!";
            return;
        }
        if(QString(msg).contains("Application asked to unregister timer")) {
            qDebug() << "Application asked to unregister timer, which is not registered in this thread.";
            return;
        }
        fprintf(stderr, "Warning: %s\n", msg);
        QMessageBox::warning(NULL, "Warning", QString(msg).remove('"'));
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        msg2 = QString(msg) % "\n\nPlease report the bug at:\nhttps://bugs.launchpad.net/cortina/+filebug";
        QMessageBox::critical(NULL, "Critical", QString(msg2).remove('"'));
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        msg2 = QString(msg) % "\n\nPlease report the bug at:\nhttps://bugs.launchpad.net/cortina/+filebug";
        QMessageBox::critical(NULL, "Fatal", QString(msg2).remove('"'));
        abort();
        break;
    }
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    MessageHandler = qInstallMsgHandler(MessageOutput);
    ui->setupUi(this);
    this->statisticer();
    this->current = 0;
    this->firstload = 0;
    this->firstTime = false;    
    /*
        trayIcon  = gtk_status_icon_new_from_file ("/home/eric/Projekt_Cortina/lucid/cortina-0.6.4/cortina.svg");

       g_signal_connect(G_OBJECT(trayIcon),"activate",(GCallback) &Widget::RandomWallpaper, NULL);
          g_signal_connect(G_OBJECT(trayIcon),"popup-menu",(GCallback) &Widget::trayIcon_on_menu, NULL);

                QString current = this->currentWP();
                QString Pfad = QFileInfo(current).absolutePath();
                QString Datei = QFileInfo(current).fileName();
                QPixmap currentpix = QPixmap(current);
                QByteArray text = trUtf8("Filename: %1\nPath: %2\nResolution: %3x%4").arg(Datei).arg(Pfad).arg(currentpix.width()).arg(currentpix.height()).toUtf8();
                gtk_status_icon_set_tooltip(trayIcon, text.data());
                currentpix = QPixmap();
                currentpix.detach();
*/

    Tray = new QSystemTrayIcon(QIcon(QString::fromUtf8(":/icons/cortina.svg")), this);
    // Tray->installEventFilter(this);
    TrayContextMenu = new QMenu();
    TrayContextMenu->addAction(trUtf8("Open GUI"), this, SLOT(StartGui()), 0);
    const QString removeFromDiskString = QString(trUtf8("remove from disk"));
    removeAction = new QAction(removeFromDiskString, this);
    connect(removeAction, SIGNAL(triggered()), this, SLOT(DeleteCurrentWP()));
    QMenu *CurrentWallpaper = new QMenu(trUtf8("Current wallpaper"));
    CurrentWallpaper->addAction(removeAction);

    if(!QFileInfo(this->currentWP()).isWritable()) {
        removeAction->setEnabled(false);
    }
    // TrayContextMenu->addMenu(trUtf8("Current wallpaper"))->addAction(trUtf8("remove from disk"), this, SLOT(DeleteCurrentWP()));
    TrayContextMenu->addMenu(CurrentWallpaper);
    TrayContextMenu->addSeparator();
    TrayContextMenu->addAction(trUtf8("Exit"), this, SLOT(close()), 0);
    this->Tray->setContextMenu(TrayContextMenu);

    setTooltipText();
    Tray->show();

    if(!connect(this->Tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(TrayClick(QSystemTrayIcon::ActivationReason)))) {
        qDebug() << "Tray Connect Failure!";
    }
    connect(ui->listWidget_Dirs, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemCheckStateChanged(QListWidgetItem*)));
    connect(ui->comboBox_wpstyle, SIGNAL(currentIndexChanged(int)), this, SLOT(SaveWpStyle(int)));
    Settings = new QSettings(QSettings::NativeFormat,QSettings::UserScope,QString("Cortina"),QString("Cortina"), NULL);
    b = new threadb();
    connect(b, SIGNAL(ImageSaved(bool)), this, SLOT(ImageSaved(bool)));
    connect(this, SIGNAL(ThreadShouldSleep(int)), this->b, SLOT(sleeping(int)), Qt::AutoConnection);
    this->CreateUI();
    watcher = new QFileSystemWatcher();
    watcher->connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(DirChanged()));
    this->LoadSettings();
    this->ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->btn_close, SIGNAL(clicked()), this, SLOT(hider()));
    if(!connect(ui->listWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(listWidget_doubleClicked(QModelIndex)))) {
        qDebug() << "listWidget Connect Failure!";
    }
    if(!connect(ui->listWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(listWidget_customContextMenuRequested(const QPoint &)))) {
        qDebug() << "listWidget Connect Failure!";
    }
    if(!connect(ui->checkBox_loadOnStartup, SIGNAL(toggled(bool)), this, SLOT(setAutoStart(bool)))) {
        qDebug() << "checkBox_loadOnStartup Connect Failure!";
    }
    connect(this, SIGNAL(toAddSignal(const QStringList &)), b, SLOT(FileAdded(const QStringList &)), Qt::AutoConnection);
    connect(this, SIGNAL(shown(const QStringList &)), b, SLOT(FileAdded(const QStringList &)));
    connect(this, SIGNAL(toRemSignal(const QStringList &)), this, SLOT(toRem(const QStringList &)));
    connect(this->b, SIGNAL(valueChanged(const QImage &,const QString &)), this, SLOT(addToList(const QImage &,const QString &)), Qt::AutoConnection);
    this->b->start();
    this->DateiListe();
    if(ui->checkBox_changeWPOnStartup->checkState() == Qt::Checked) {
        RandomWallpaper();
    }
    Started = QTime::currentTime();
}

void Widget::setTooltipText(){
    QString current = this->currentWP();
    QString Pfad = QFileInfo(current).absolutePath();
    QString Datei = QFileInfo(current).fileName();
    QPixmap currentpix = QPixmap(current);
    const QString text = trUtf8("Filename: %1\nPath: %2\nResolution: %3x%4").arg(Datei).arg(Pfad).arg(currentpix.width()).arg(currentpix.height());
    Tray->setToolTip(text);
    currentpix = QPixmap();
    currentpix.detach();

}

/*void Widget::trayIcon_on_click(GtkStatusIcon *status_icon,gpointer user_data)
       {
    qDebug() << user_data;
    QString WP;
    const int & reflenght = this->Files.length();
    if(reflenght != 0) {
            if(Settings->value("randomOrNot") == 2) {
                    srand((unsigned)time(0));
                    int random_integer = (rand()%reflenght);
                    const int & refrandom_integer = random_integer;
                    WP = Files[refrandom_integer];
            } else {
                    if((current) != reflenght) {
                            WP = Files[current];
                            current++;
                    } else {
                            current = 0;
                            WP = Files[current];
                    }
            }
    } else {
            QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
            if(!stringlist.isEmpty()) {
                    //this->DateiListe();
                    if(Files.length() == 0) {
                            return;
                    }
                    this->RandomWallpaper();
            }
    }
    if(QFile(WP).exists()) {
            this->setWP(WP);
    } else {
            qDebug() << "File not found! " << WP;

    }
    }


void Widget::trayIcon_on_menu(GtkStatusIcon *status_icon, guint button,
                       guint activate_time, gpointer user_data)
{
    GtkMenu *Menu = new GtkMenu();
    GtkMenuItem *MenuItem_OpenGui = new GtkMenuItem();

       // this->Tray->setContextMenu(TrayContextMenu);
}

bool Widget::eventFilter(QObject* w,QEvent*e){
       if(w==Tray && e->type()==QEvent::ToolTip) {
  QString current = this->currentWP();
  QString Pfad = QFileInfo(current).absolutePath();
  QString Datei = QFileInfo(current).fileName();
  QPixmap currentpix = QPixmap(current);
                //QByteArray text = trUtf8("Filename: %1\nPath: %2\nResolution: %3x%4").arg(Datei).arg(Pfad).arg(currentpix.width()).arg(currentpix.height()).toUtf8();
               const QString text = trUtf8("Filename: %1\nPath: %2\nResolution: %3x%4").arg(Datei).arg(Pfad).arg(currentpix.width()).arg(currentpix.height());
                // gtk_status_icon_set_tooltip(trayIcon, text.data());

Tray->setToolTip(text);

                //Tray->showMessage(trUtf8("Current wallpaper"), trUtf8("Filename: %1\nPath: %2\nResolution: %3x%4").arg(Datei).arg(Pfad).arg(currentpix.width()).arg(currentpix.height()), QSystemTrayIcon::NoIcon, 5000);
  currentpix = QPixmap();
  currentpix.detach();
        }
 return true;
}
*/
void Widget::statisticer(){
    QFile* installed = new QFile(QDir::homePath() % "/.gconf/apps/Cortina/installed");

    if(installed->exists() == false) {
        QUrl url = QUrl("http://eric32.er.funpic.de/counter.php?version=" % QApplication::applicationVersion());
        QNetworkAccessManager *manager = new QNetworkAccessManager();
        connect(manager, SIGNAL(finished(QNetworkReply*)), SLOT(counterFinished(QNetworkReply*)));
        QNetworkRequest request = QNetworkRequest(url);

        QString var(getenv("http_proxy"));
        QRegExp regex("(http://)?(.*):(\\d*)/?");
        int pos = regex.indexIn(var);

        if(pos > -1){
            QString host = regex.cap(2);
            int port = regex.cap(3).toInt();
            QNetworkProxy proxy(QNetworkProxy::HttpProxy, host, port);
            QNetworkProxy::setApplicationProxy(proxy);
        }

        manager->get(request);
    }else {
        if ( installed->open(QIODevice::ReadOnly) )
        {
            QByteArray installed_version = installed->readAll();
            if(installed_version != QApplication::applicationVersion()){
                installed->close();
                installed->remove();
                this->statisticer();
            }
        }
        else
        {
            QString DebugString = "Could not open file %1";
            qDebug() << DebugString.arg(installed->fileName());
        }
    }
}

void Widget::counterFinished(QNetworkReply* reply){
    QUrl url = reply->url();
    if (!reply->error()) {
        const QString Cortinagconfdir = QDir::homePath() % "/.gconf/apps/Cortina";
        QDir *gconfCortina = new QDir(Cortinagconfdir);
        if(!gconfCortina->exists()) {
            gconfCortina->mkdir(Cortinagconfdir);
        }
        QFile* installed = new QFile(QDir::homePath() % "/.gconf/apps/Cortina/installed");
        if ( installed->open(QIODevice::WriteOnly) )
        {

            installed->write(QApplication::applicationVersion().toUtf8());
            installed->close();
        }
        else
        {
            QString DebugString = "Could not create file %1";

            qDebug() << DebugString.arg(installed->fileName());
        }

    }
}

void Widget::itemCheckStateChanged(QListWidgetItem* item){
    if(firstload > 0) {
        QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
        QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();
        ui->listWidget_Dirs->setCurrentRow(0, QItemSelectionModel::SelectCurrent);
        if(stringlist.length() != 0) {
            for (int i = 0; i<stringlist.length(); i++) {
                int bla2 = ui->listWidget_Dirs->selectedItems()[0]->checkState();
                QString bla = checkstatelist.at(i);
                if(bla.toInt() != bla2) {
                    for (int q = 0; q<stringlist.length(); q++) {
                        if(item->text() == stringlist.at(q)) {
                            if(item->checkState() == 2) {
                                QString ItemToChange = item->text();
                                for (int q = 0; q<stringlist.length(); q++) {
                                    if(stringlist.at(q) != ItemToChange){
                                        if(stringlist.at(q).startsWith(ItemToChange) == true) {

                                            QString dublicateString = trUtf8("%1 would be double monitored, please remove that entry before!")
                                                    .arg(stringlist.at(q));
                                            ui->listWidget_Dirs->selectedItems()[0]->setCheckState(Qt::Unchecked);
                                            QMessageBox::information(this, trUtf8("dublicate detected"),  dublicateString);
                                            return;
                                        } else {
                                            checkstatelist.replace(q, "2");                                          
                                        }
                                    } else if(stringlist.length() == 1){
                                        checkstatelist.replace(q, "2");
                                    }
                                }
                            } else {
                                checkstatelist.replace(q, "0");
                            }
                            Settings->setValue("listWidget_Dirs_flags", checkstatelist);
                            this->DirChanged();
                        }
                    }
                }
            }
            ui->listWidget_Dirs->setCurrentRow(ui->listWidget_Dirs->currentRow() + 1, QItemSelectionModel::SelectCurrent);
        }
    }
}

void Widget::ThreadShouldStop(){
    this->SaveSettings();
    this->b->terminate();
    delete this->b;
    delete ui;
}

Widget::~Widget()
{
    this->SaveSettings();
    if(b->isRunning()) {
        connect(this->b, SIGNAL(IShouldStop()), this, SLOT(ThreadShouldStop()));
        this->b->shouldIStop = true;
    } else {
        this->SaveSettings();
        this->b->terminate();
        delete this->b;
        delete ui;
    }
}

void Widget::hider(){
    mutex.lock();
    this->b->IShouldSleep = true;
    mutex.unlock();
    this->hide();

}

void Widget::setAutoStart(bool set){

    QDir autostartdir = QDir(QDir::homePath() % "/.config/autostart");
    if(!autostartdir.exists()){
        if(!autostartdir.mkdir(QDir::homePath() % "/.config/autostart")){
            qWarning() << "Autostart could not be activated: "+ QDir::homePath() % "/.config/autostart" +" could not be created!"  ;
        }
    }
    QFile *startfile = new QFile(QDir::homePath() % "/.config/autostart/cortina.desktop");
    if(set) {
        QByteArray FileData =  QString("[Desktop Entry]\nType=Application\nExec="%QApplication::applicationFilePath()%"\nHidden=false\nNoDisplay=false\nX-GNOME-Autostart-enabled=true\nName=Cortina").toUtf8();
        if(!startfile->exists()) {
            if(startfile->open(QIODevice::WriteOnly)) {
                int returnStartFile = startfile->write(FileData);
                if(returnStartFile != -1 && returnStartFile == FileData.size()) {
                    startfile->flush();
                    startfile->close();
                } else {
                    qDebug() << "Failure while writing to autostart file";
                }
            }
        } else {
            if(startfile->size() != FileData.size()) {
                if(!startfile->remove()) {
                    qDebug() << "cant remove startup file!";
                }
                this->setAutoStart(set);
            }
        }
    } else {
        if(startfile->exists()) {
            if(!startfile->remove()) {
                qDebug() << "cant remove startup file!";
            }
        }
    }
}
void Widget::StartGui(){
    b->start();
    emit(this->shown(waitOnShow));
    this->waitOnShow.clear();
    mutex.lock();
    this->b->IShouldSleep = 0;
    mutex.unlock();
    this->show();
    if(!this->firstTime) {
        this->b->fileschanged = false;
        emit(toAddSignal(Files));
        this->CheckVersion();
        firstTime=true;
    }
}
void Widget::DeleteCurrentWP(){
    QString toRemove = this->currentWP();
    if(!QFileInfo(toRemove).isWritable()) {
        qWarning() << QString("Couldn't remove %1  -  insufficent permissions.").arg(toRemove);
    } else {
        if(toRemove != ""){
            QMessageBox *msgBox = new QMessageBox(this);
            msgBox->setText(trUtf8("Do you really want to delete this image from disk?"));
            msgBox->setStandardButtons(QMessageBox::Yes |QMessageBox::No);
            connect(msgBox, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(YesDeleteCurrentWP(QAbstractButton*)), Qt::AutoConnection);
            msgBox->show();
        }  else {
            return;
        }
    }
}
void Widget::YesDeleteCurrentWP(QAbstractButton* button){
    QString toRemove = this->currentWP();
    QString Pfad = QFileInfo(toRemove).absolutePath();

    QString Datei = QFileInfo(toRemove).fileName();
    if(button->text() ==  "&Yes") {

        this->RandomWallpaper();

        if(QFile(toRemove).remove()) {
            Tray->showMessage(trUtf8("Successful removed"), trUtf8("Filename: %1\nPath: %2").arg(Datei).arg(Pfad), QSystemTrayIcon::NoIcon, 5000);
        } else {
            if(QFile(toRemove).exists()){
                qWarning() << QString("Couldn't remove %1").arg(toRemove);
            } else {
                qWarning() << QString("Couldn't remove %1 because it is not existing anymore.").arg(toRemove);
            }
        }
    }
    if(button->text() ==  "&No") {
        Tray->showMessage(trUtf8("Not removed"), trUtf8("Filename: %1\nPath: %2").arg(Datei).arg(Pfad), QSystemTrayIcon::NoIcon, 2500);
    }

}

void Widget::TrayClick(QSystemTrayIcon::ActivationReason Reason){

    switch(Reason)
    {
    case QSystemTrayIcon::Trigger:
        on_timeEdit_timeChanged(ui->timeEdit->time());
        this->RandomWallpaper();
        break;
    case QSystemTrayIcon::Context:
        break;
    case QSystemTrayIcon::Unknown:
        break;
    case QSystemTrayIcon::DoubleClick:
        break;
    case QSystemTrayIcon::MiddleClick:
        break;

    }

}

void Widget::SaveWpStyle(int stylenum){

    GConfClient *gconf_client;
    gconf_client = gconf_client_get_default();
    Settings->setValue("comboBox_wpstyle", stylenum);
    QStringList styles;
    styles << "zoom" << "wallpaper" << "centered" << "scaled" << "stretched" << "spanned";
    QByteArray style = styles[stylenum].toUtf8();
    if (gconf_client) {
        GError *error = 0;
        char  *path = g_strdup_printf("/desktop/gnome/background/picture_options");
        if (!gconf_client_set_string(gconf_client, path, style.data(), &error)) {
            qDebug() << style.data() << error->message;
            g_error_free(error);
        }
        g_free(path);
        g_object_unref(gconf_client);
    } else
        qDebug("Cannot get GConf2 client");
}

void Widget::SaveSettings(){
    Settings->setValue("checkBox_changeWPOnStartup", ui->checkBox_changeWPOnStartup->checkState());
    Settings->setValue("checkBox_loadOnStartup", ui->checkBox_loadOnStartup->checkState());
    Settings->setValue("checkBox_loadOnStartup", ui->checkBox_loadOnStartup->checkState());
    Settings->setValue("timeEdit", ui->timeEdit->time());
    Settings->setValue("comboBox_wpstyle", ui->comboBox_wpstyle->currentIndex());
    if(Settings->isWritable() == false) {
        qDebug() << "Cant save Settings, because the path is not writable: " << Settings->fileName();
    }
    Settings->sync();
}


void Widget::LoadSettings(){   
    this->ui->comboBox_wpstyle->setCurrentIndex(Settings->value("comboBox_wpstyle").toInt());
    switch(Settings->value("checkBox_changeWPOnStartup").toInt())
    {
    case 2:
        ui->checkBox_changeWPOnStartup->setCheckState(Qt::Checked);
        this->setAutoStart(true);
        break;
    default: ui->checkBox_changeWPOnStartup->setCheckState(Qt::Unchecked);
        this->setAutoStart(false);
    }

    switch(Settings->value("checkBox_loadOnStartup").toInt())
    {
    case 2: ui->checkBox_loadOnStartup->setCheckState(Qt::Checked);
        break;
    default: ui->checkBox_loadOnStartup->setCheckState(Qt::Unchecked);
    }
    ui->timeEdit->setTime(Settings->value("timeEdit").toTime());

    QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
    QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();

    if(!stringlist.isEmpty()) {

        for (int i = 0; i<stringlist.length(); i++) {
            QListWidgetItem *tmpwidget =  new QListWidgetItem(stringlist[i], ui->listWidget_Dirs, 0);
            tmpwidget->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
            if(!checkstatelist.isEmpty() && !stringlist.isEmpty()) {
                if(checkstatelist.at(i) == "0")
                {
                    tmpwidget->setCheckState(Qt::Unchecked);
                } else {
                    tmpwidget->setCheckState(Qt::Checked);
                }
            } else {
                qDebug() << "index out of range: checkstatelist \nTry to fix the issue...";
                Settings->remove("listWidget_Dirs");
                Settings->sync();
                if(Settings->value("listWidget_Dirs").type() == QVariant::Invalid) {
                    qDebug() << "The issue should be fixed. \nRetry...";
                    this->DirDialog();
                } else {
                    qDebug() << "The issue couldn't' be fixed. \n Please contact the Developer!";
                }
            }
        }
    } else {
        this->DirDialog();
    }
    this->firstload++;
}
void Widget::adjustSizer(){
    ui->btn_about->adjustSize();
    ui->btn_close->adjustSize();
    ui->btn_DirListAdd->adjustSize();
    ui->btn_DirListRem->adjustSize();
    ui->checkBox_changeWPOnStartup->adjustSize();
    ui->checkBox_loadOnStartup->adjustSize();
    ui->comboBox_wpstyle->adjustSize();
    ui->Display->adjustSize();
    ui->label->adjustSize();
    ui->label_changingInterval->adjustSize();
    ui->label_startoptions->adjustSize();
    ui->label_Style->adjustSize();
    ui->label_title1_listwidget_Dirs->adjustSize();
    ui->label_title2_listwidget_Dirs->adjustSize();
    ui->label_wpDir->adjustSize();
    ui->Preference->adjustSize();
    ui->ThumbCounter->adjustSize();
}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        this->adjustSizer();
        break;
    default:
        break;
    }
}

//void Widget::resizeEvent(QResizeEvent *event){
//}

void Widget::about()
{
    //QString License = "This program is free software: you can redistribute it and/or modify\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis package is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.";
    QMessageBox *about = new QMessageBox(this);
    QString name = QApplication::applicationName();
    QString version = QApplication::applicationVersion();
    QString versiontr = trUtf8("version");

    QLabel *website_launchpad = new QLabel(about);
    website_launchpad->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
    website_launchpad->setOpenExternalLinks(true);
    website_launchpad->setText("<a href=\"https://launchpad.net/cortina\">Launchpad</a>");
    website_launchpad->setGeometry(35, about->height() + 30, 100, website_launchpad->height());

    QLabel *website_sourcforge = new QLabel(about);
    website_sourcforge->setTextInteractionFlags(Qt::LinksAccessibleByMouse);
    website_sourcforge->setOpenExternalLinks(true);
    website_sourcforge->setText("<a href=\"http://sourceforge.net/projects/cortina\">Sourceforge</a>");
    website_sourcforge->setGeometry(website_launchpad->x(), website_launchpad->y() + 20, 100, website_sourcforge->height());

    QLabel *email = new QLabel(about);
    email->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::TextSelectableByMouse);
    email->setOpenExternalLinks(true);
    email->setText("<a href=\"mailto:Eric.Baudach@web.de\">Eric.Baudach@web.de</a>");
    email->setGeometry(website_launchpad->x(), website_launchpad->y() + 40, 200, email->height());

    about->setText(name %"\n"% versiontr %": "% version %"\nCopyright 2010-2011 Eric Baudach\n\n\n\n");
    about->setWindowTitle(trUtf8("about"));
    about->show();
}

gchar* Widget::currentWP(){
    GConfClient *gconf_client = gconf_client_get_default();
    gchar *wp;
    wp = gconf_client_get_string(gconf_client, "/desktop/gnome/background/picture_filename", NULL);
    g_object_unref(gconf_client);
    return wp;
}

void Widget::setWP(QString tempwpfile){
    if(WidgetIcon == false) {
        this->setWindowIcon(QIcon(QString::fromUtf8(":/icons/cortina.svg")));
        this->Tray->setIcon(QIcon(QString::fromUtf8(":/icons/cortina.svg")));

        WidgetIcon = true;
    } else {
        WidgetIcon = false;
        this->setWindowIcon(QIcon(QString::fromUtf8(":/icons/cortina2.svg")));
        this->Tray->setIcon(QIcon(QString::fromUtf8(":/icons/cortina2.svg")));
    }
    QByteArray wpfile = tempwpfile.toUtf8();
    GConfClient *gconf_client = gconf_client_get_default ();
    if (gconf_client) {
        GError *error = 0;
        char  *path = g_strdup_printf("/desktop/gnome/background/picture_filename");
        if (!gconf_client_set_string(gconf_client, path, wpfile.data(), &error)) {
            qDebug() << wpfile.data() << error->message;
            g_error_free(error);
        }
        g_free(path);
        g_object_unref(gconf_client);
        if(QFileInfo(this->currentWP()).isWritable()) {
            removeAction->setEnabled(true);
        } else {
            removeAction->setEnabled(false);
        }
        setTooltipText();
    } else
        qDebug("Cannot get GConf2 client");
}

void Widget::addToList(const QImage& image,const QString& filename){
    if(b->fileschanged == false) {
        QString fileDir = QFileInfo(filename).absolutePath();
        QString filename2 = QFileInfo(filename).fileName();
        QString thumb = fileDir % "/.thumb_" % filename2;
        QPixmap Pixmap;
        mutex.tryLock();
        if(image.isNull()) {
            Pixmap = QPixmap(thumb);
        } else {
            try{
                Pixmap = QPixmap::fromImage(image);
            } catch (...) {
                qDebug() << filename << " couldn't be loaded!";
                return;
            }
        }
        ItemList.append(filename);
        mutex.unlock();
        QPixmap & refPixmap = Pixmap;
        QIcon Icon = QIcon(refPixmap);
        const QIcon & refIcon = Icon;
        QString filenameWithoutPath = QFileInfo(filename).fileName();
        this->ui->listWidget->addItem(new QListWidgetItem(refIcon, filenameWithoutPath, this->ui->listWidget,0));
        Pixmap = QPixmap();
        Icon = QIcon();
        Counter = this->ItemList.count();
        this->ui->ThumbCounter->setNum(Counter);
    }
}
void Widget::YesDeleteSelectedWP(QAbstractButton* button){	
    if(button->text() ==  "&Yes") {
        QString toRemove = this->ItemList.at(this->ui->listWidget->currentIndex().row());
        if(!QFileInfo(toRemove).isWritable()) {
            qWarning() << QString("Couldn't remove %1  -  insufficent permissions.").arg(toRemove);
        } else {
            QString Pfad = QFileInfo(toRemove).absolutePath();
            QString Datei = QFileInfo(toRemove).fileName();
            if(QFile(toRemove).remove()) {
                //Tray->setToolTip(trUtf8("Filename: %1\nPath: %2").arg(Datei).arg(Pfad));
                Tray->showMessage(trUtf8("Successful removed"), trUtf8("Filename: %1\nPath: %2").arg(Datei).arg(Pfad), QSystemTrayIcon::NoIcon, 5000);
            } else {
                if(QFile(toRemove).exists()){
                    qWarning() << QString("Couldn't remove %1").arg(toRemove);
                } else {
                    qWarning() << QString("Couldn't remove %1 because it is not existing anymore.").arg(toRemove);
                }
            }
        }
    }
}

void Widget::DeleteSelectedWP(){
    QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setText(trUtf8("Do you really want to delete this image from disk?"));
    msgBox->setStandardButtons(QMessageBox::Yes |QMessageBox::No);
    connect(msgBox, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(YesDeleteSelectedWP(QAbstractButton*)));
    msgBox->show();
}
void Widget::listWidget_customContextMenuRequested(const QPoint & pointer){
    QAction *Aktion = new QAction(trUtf8("delete"), ui->listWidget);
    connect(Aktion, SIGNAL(triggered()), this, SLOT(DeleteSelectedWP()));
    QMenu menu(ui->listWidget);
    menu.addAction( Aktion );
    menu.exec(ui->listWidget->mapToGlobal( pointer ));
}
void Widget::listWidget_doubleClicked(QModelIndex i)
{
    on_timeEdit_timeChanged(ui->timeEdit->time());
    QString Zeile = ItemList.at(i.row());
    if(QFile(Zeile).exists()) {
        this->setWP(Zeile);
        //  qDebug() << "Changed Wallpaper to:" << Zeile;
    } else {
        qDebug() << "File not found! " << Zeile;
    }
}

void Widget::DirDialog(){
    FD = new QFileDialog(NULL, Qt::Dialog);
    FD->setAcceptMode(QFileDialog::AcceptOpen);
    FD->setLabelText(QFileDialog::Accept, trUtf8("add"));
    FD->setLabelText(QFileDialog::FileType, trUtf8("File typ"));
    FD->setLabelText(QFileDialog::FileName, trUtf8("Directory name"));
    FD->setLabelText(QFileDialog::Reject, trUtf8("close"));
    FD->setWindowTitle(trUtf8("Choose directory..."));
    connect(this->FD, SIGNAL(finished(int)), this, SLOT(FDChangeDir(int)));
    FD->setDirectory(QDir::home());
    FD->setFileMode(QFileDialog::DirectoryOnly);
    FD->exec();

}

void Widget::FDChangeDir(int i){
    //   int add = 0;
    if(i != 0) {
        QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
        QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();
        foreach(QString selectedFile, this->FD->selectedFiles())
        {

            for(int i = 0; i<stringlist.length(); i++) {
                if(selectedFile.startsWith(stringlist[i]) == true  &&  checkstatelist[i] == "2") {
                    //  add++;
                    QString dublicateString = trUtf8("%1 is already monitored through %2!")
                            .arg(selectedFile).arg(stringlist[i]);
                    QMessageBox::information(this, trUtf8("dublicate detected"),  dublicateString);
                    return;
                } else if(stringlist[i] == selectedFile){
                    //  add++;
                    QString dublicateString = trUtf8("%1 is already monitored!").arg(selectedFile);
                    QMessageBox::information(this, trUtf8("dublicate detected"),  dublicateString);
                    return;
                }
            }
            // if(add == 0) {
            QListWidgetItem *tmpwidget = new QListWidgetItem(selectedFile, ui->listWidget_Dirs, 0);
            tmpwidget->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
            tmpwidget->setCheckState(Qt::Unchecked);
            stringlist.append(selectedFile);
            checkstatelist.append("0");
            Settings->setValue("listWidget_Dirs", stringlist);
            Settings->setValue("listWidget_Dirs_flags", checkstatelist);
            //this->DateiListe();
            this->DirChanged();
            /*if(Files.count() != 0) {
                for(int i = 0; i < this->ItemList.count(); i++)    {
                    if(Files.contains(ItemList[i])) {
                        Files.removeAll(ItemList[i]);
                    }
                }
            }*/
            this->b->IShouldSleep = false;
            this->b->fileschanged = false;
            //this->DateiListe();
            //emit(toAddSignal(Files));
            this->SaveSettings();
            this->FD->deleteLater();

            // }
        }
    }
}


void Widget::DirListRem(){

    this->b->IShouldSleep = true;
    DateiListe();
    //if(ui->listWidget_Dirs->selectedItems().count() != 0) {
    QString removedItem =  ui->listWidget_Dirs->selectedItems()[0]->text();

    QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
    QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();
    if(this->ui->listWidget_Dirs->count() != 0) {
        for(int i = 0; i < stringlist.count(); i++) {
            if(stringlist[i] == removedItem) {

                helper *thumb_del_thread = new helper();
                thumb_del_thread->autoDelete();
                thumb_del_thread->path = stringlist[i];
                thumb_del_thread->recursiv = checkstatelist[i];
                this->watcher->removePath(removedItem);
                QThreadPool::globalInstance()->start(thumb_del_thread);

                delete ui->listWidget_Dirs->selectedItems()[0];
                stringlist.removeAt(i);
                checkstatelist.removeAt(i);

            }
        }
        if(this->ui->listWidget_Dirs->count() != 0) {
            this->b->fileschanged = true;
        }else{
            this->watcher->removePath(removedItem);
            this->ItemList.clear();
            this->ui->listWidget->clear();
            this->Counter = 0;
            this->ui->ThumbCounter->setNum(Counter);
            this->Files.clear();
        }
        Settings->setValue("listWidget_Dirs", stringlist);
        Settings->setValue("listWidget_Dirs_flags", checkstatelist);
        QStringList tmpremFiles;
        QDir verzeichnis = QDir(removedItem);
        const QStringList & SubDirs = verzeichnis.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::NoSort);
        foreach(QString File, Files) {
            if(SubDirs.count() != 0){
                int helperCount = 0;
                for(int i = 0; i<SubDirs.count(); i++) {
                    if(!File.contains(verzeichnis.path() + "/" + SubDirs[i]))
                    {
                        helperCount++;
                    }
                }
                int bla = SubDirs.count() - helperCount;
                if(bla == 0 && File.contains(removedItem)) {
                    tmpremFiles.append(File);
                }

            }else{
                if(File.contains(removedItem)) {
                    tmpremFiles.append(File);
                }
            }
        }
        if(tmpremFiles.count() != 0){
            DateiListe();
            const QStringList & remFiles = tmpremFiles;
            toRem(remFiles);
        }
        /*} else {
   Settings->remove("listWidget_Dirs");
   Settings->remove("listWidget_Dirs_flags");
   this->ItemList.clear();
   this->ui->listWidget->clear();
   this->Counter = 0;
   this->ui->ThumbCounter->setNum(Counter);
   this->Files.clear();
                }*/

    }

}
void Widget::CheckVersion(){
    QUrl url = QUrl("http://eric32.er.funpic.de/cortina/natty_current");
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    connect(manager, SIGNAL(finished(QNetworkReply*))
            , SLOT(downloadFinished(QNetworkReply*)));

    QString var(getenv("http_proxy"));
    QRegExp regex("(http://)?(.*):(\\d*)/?");
    int pos = regex.indexIn(var);

    if(pos > -1){
        QString host = regex.cap(2);
        int port = regex.cap(3).toInt();
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, host, port);
        QNetworkProxy::setApplicationProxy(proxy);
    }

    //qDebug() << QNetworkProxy::applicationProxy().hostName();
    QNetworkRequest request = QNetworkRequest(url);
    manager->get(request);
}

void Widget::downloadFinished(QNetworkReply* reply){   
    QUrl url = reply->url();
    if (reply->error()) {
        qDebug() << "Version check failed: " % reply->errorString();
        /*fprintf(stderr, "Version check failed \n",
                url.toEncoded().constData(),
                qPrintable(reply->errorString()));*/
    } else if(reply->isReadable() && reply->size() != 0) {
        QByteArray buf = reply->readAll();
        QString inhalt;
        for(int i = 0; i<buf.length(); i++) {
            inhalt += buf.at(i);
        }
        inhalt = inhalt.trimmed();
        QString InstalledVersion = QApplication::applicationVersion();
        if(inhalt != InstalledVersion) {
            QStringList splittedlocal = InstalledVersion.split(".");
            QStringList splittedRemote = inhalt.split(".");
            int local = 0;
            int remote = 0;
            int i = 0;
            foreach(QString num, splittedlocal) {
                if(i == 0)
                {
                    local = local + num.toInt() * 100;
                }
                if(i == 1)
                {
                    local = local + num.toInt() * 10;
                } else{
                    local = local + num.toInt();
                }
                i++;
            }
            i = 0;
            foreach(QString num, splittedRemote) {
                if(i == 0)
                {
                    remote = remote + num.toInt() * 100;
                }
                if(i == 1)
                {
                    remote = remote + num.toInt() * 10;
                } else{
                    remote = remote + num.toInt();
                }
                i++;
            }
            qDebug() << "remote=" << remote << "\n" << "local=" << local;
            if(remote > local) {
                QString versionmsg = trUtf8("%1 is avaible!\nClick on the about button to see where you can get it!").arg(inhalt);
                QMessageBox::information(this, trUtf8("Update avaible!"), versionmsg);
            }
        }
    }
    return;
    reply->deleteLater();
}

void Widget::CreateUI(){
    this->adjustSizer();
    connect(ui->btn_DirListAdd, SIGNAL(clicked()), this, SLOT(DirDialog()));
    connect(ui->btn_DirListRem, SIGNAL(clicked()), this, SLOT(DirListRem()));
    intervalTimer = new QTimer(this);
    connect(intervalTimer, SIGNAL(timeout()), this, SLOT(RandomWallpaper()));
    ui->Tab->setCurrentIndex(0);
}
QStringList Widget::DateiListeNeu(){
    QStringList FilesNeu;
    QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
    QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();
    if(stringlist.length() != 0) {
        if(Settings->value("listWidget_Dirs").toStringList().length() != 0) {
            for (int i = 0; i<stringlist.length(); i++) {
                QDir tempDir = QDir(stringlist.at(i));
                QDir & verzeichnis = tempDir;
                QStringList filters;
                const QStringList & SubDirs = verzeichnis.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::NoSort);
                filters << "*.jpg" << "*.jpeg" << "*.gif" << "*.png" << "*.svg";
                verzeichnis.setNameFilters(filters);
                int SubDirscount = SubDirs.count();
                if(checkstatelist.at(i) == "0") {
                    SubDirscount = 0;
                }
                if(SubDirscount >= 1) {
                    foreach(QString dir, SubDirs) {
                        verzeichnis.setPath(stringlist.at(i) % "/" % dir);
                        foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                            FilesNeu.append(verzeichnis.path() % "/" % Datei);
                        }}

                    verzeichnis.setPath(stringlist.at(i));
                    foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                        FilesNeu.append(verzeichnis.path() % "/" % Datei);
                    }

                } else {
                    foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                        FilesNeu.append(verzeichnis.path() % "/" % Datei);
                    }
                }
            }
        }
    }

    return FilesNeu;
}

void Widget::DateiListe(){
    Files.clear();
    if(!Settings->value("listWidget_Dirs").toStringList().isEmpty()) {
        QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
        QStringList checkstatelist = Settings->value("listWidget_Dirs_flags").toStringList();
        QStringList Hidden;
        QStringList Hidden2;
        if(stringlist.length() != 0) {
            for (int i = 0; i<stringlist.length(); i++) {
                QDir tempDir = QDir(stringlist.at(i));
                QDir & verzeichnis = tempDir;
                QStringList filters;
                const QStringList & SubDirs = verzeichnis.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::NoSort);
                filters << "*.jpg" << "*.jpeg" << "*.gif" << "*.png" << "*.svg";
                verzeichnis.setNameFilters(filters);
                int SubDirscount = SubDirs.count();
                if(!checkstatelist.isEmpty()) {

                    if(checkstatelist.at(i) == "0") {
                        SubDirscount = 0;
                    }
                    if(SubDirscount >= 1) {
                        if(!watcher->directories().contains(verzeichnis.path())) {
                            watcher->addPath(verzeichnis.path());
                        }

                        foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                            Files.append(verzeichnis.path() % "/" % Datei);
                        }
                        foreach(QString dir, SubDirs) {
                            verzeichnis.setPath(stringlist.at(i) % "/" % dir);
                            if(!watcher->directories().contains(verzeichnis.path())) {
                                watcher->addPath(verzeichnis.path());
                            }
                            foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                                Files.append(verzeichnis.path() % "/" % Datei);
                            }

                        }

                    } else {
                        if(!watcher->directories().contains(verzeichnis.path())) {
                            watcher->addPath(verzeichnis.path());
                        }

                        foreach(QString Datei,verzeichnis.entryList(verzeichnis.nameFilters(), QDir::Files | QDir::Readable, QDir::NoSort)) {
                            Files.append(verzeichnis.path() % "/" % Datei);
                        }
                    }
                }    else {
                    qFatal("index out of range: checkstatelist");
                }
            }
        }
    }
    if(Files.length() == 0) {
        qDebug() << "Can't work without wallpapers!";
        return;
    }
}
void Widget::ImageSaved(bool saved){
    this->ImageSavedWatcher = saved;
}
/*
void Widget::LoopWatcher(){
    qDebug() << Started;
qDebug() << QTime::currentTime().addSecs(-5);
    while( Started < QTime::currentTime().addSecs(-5) ) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }
    watcher->
    Started = QTime::currentTime();
}
*/
void Widget::DirChanged(){
    // this->LoopWatcher();
    if(this->ImageSavedWatcher == false) {
        this->b->fileschanged = true;
        QTime dieTime = QTime::currentTime().addSecs(1);
        while( QTime::currentTime() < dieTime ) {

        }
        const QStringList & NeueListe = DateiListeNeu();
        const QStringList & AlteListe = Files;
        const int & NeueAnzahl = NeueListe.count();
        const int & AlteAnzahl = AlteListe.count();
        QStringList addy;
        const QStringList & refaddy = addy;
        QStringList remy;
        const QStringList & refremy = remy;
        addy.clear();
        remy.clear();
        /*
        qDebug() << "NeueAnzahl";
        qDebug() << NeueAnzahl;
        qDebug() << "AlteAnzahl";
        qDebug() << AlteAnzahl;
        */
        int NeueAnzahltmp = NeueAnzahl;
        if(NeueAnzahl > AlteAnzahl) {
            // Datei wurde hinzugefügt:
            foreach(QString Datei, NeueListe)
            {
                if(NeueAnzahltmp != AlteAnzahl) {
                    if(AlteListe.indexOf(Datei) == -1) {
                        addy.append(Datei);
                        NeueAnzahltmp--;
                    }
                }

            }
            for(int i = 0; i < this->ItemList.count(); i++)    {
                if(refaddy.contains(ItemList[i])) {
                    addy.removeAll(ItemList[i]);
                }
            }
            if(!this->isHidden()) {
                this->b->fileschanged = false;
                emit(toAddSignal(refaddy));
                this->Files.append(refaddy);
            } else {
                waitOnShow.append(refaddy);
                this->Files.append(refaddy);
            }
        } else if(NeueAnzahl < AlteAnzahl) {
            // Datei wurde gelöscht:
            foreach(QString Datei, AlteListe)
            {
                if(NeueListe.indexOf(Datei) == -1) {
                    remy.append(Datei);
                }
            }
            this->toRem(refremy);
        } else if(NeueAnzahl == AlteAnzahl) {
            foreach(QString Datei, AlteListe)
            {
                if(!QFile(Datei).exists()) {
                    remy.append(Datei);
                }
            }
            this->toRem(refremy);
            //this->DirChanged();
        }
    }
    //qDebug() << "DirChanged!";
    // qDebug() << watcher->directories();
}

void Widget::toRem(const QStringList & Liste){
    // emit(ThreadShouldSleep(5));
    foreach(QString remDatei, Liste) {
        for(int i = 0; i < ItemList.length(); i++) {
            if(this->ItemList.at(i) == remDatei) {
                QString fileDir = QFileInfo(remDatei).absolutePath();
                QString filename2 = QFileInfo(remDatei).fileName();
                QString thumb = fileDir % "/.thumb_" % filename2;
                delete this->ui->listWidget->item(i);
                this->ItemList.removeAt(i);
                this->ImageSavedWatcher = true;
                QFile(thumb).remove();
                Counter--;
                this->ui->ThumbCounter->setNum(Counter);
            }
        }
    }
    this->DateiListe();
    this->b->IShouldSleep = false;
    this->ImageSavedWatcher = false;
}




void Widget::RandomWallpaper(){
    QString WP;
    const int & reflenght =   this->Files.length();
    if(reflenght != 0) {
        //if(Settings->value("randomOrNot") == 2) {
        srand((unsigned)time(0));
        int random_integer = (rand()%reflenght);
        const int & refrandom_integer = random_integer;
        WP = Files[refrandom_integer];
        /* } else {
            if((current) != reflenght) {
                WP = Files[current];
                current++;
            } else {
                current = 0;
                WP = Files[current];
            }
       }*/
    } else {
        QStringList stringlist = Settings->value("listWidget_Dirs").toStringList();
        if(!stringlist.isEmpty()) {
            //this->DateiListe();
            if(Files.length() == 0) {
                return;
            }
            this->RandomWallpaper();
        }
    }
    if(QFile(WP).exists()) {
        this->setWP(WP);
    } else {
        qDebug() << "File not found! " << WP;

    }

}

void Widget::on_timeEdit_timeChanged(QTime date)
{
    float hours2ms = 0;
    float min2ms = 0;
    float sec2ms = 0;
    if(date.hour() > 0){
        hours2ms = ((date.hour() * 60) * 60) * 1000;
    }
    if(date.minute() > 0){
        min2ms = (date.minute() * 60) * 1000;
    }
    if(date.second() > 0){
        sec2ms = date.second() * 1000;
    }
    int msecs = hours2ms + min2ms + sec2ms;
    //qDebug() << msecs;

    if(intervalTimer->isActive())
    {
        intervalTimer->setInterval(msecs);
    } else {
        intervalTimer->start(msecs);
    }
}