aboutsummaryrefslogtreecommitdiff
path: root/lumina-fm/MainUI.cpp
blob: 8712ebbb0cff74b43d53c4452061661965e0b107 (plain)
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
//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "MainUI.h"
#include "ui_MainUI.h"

MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
  ui->setupUi(this);
  //Be careful about the QSettings setup, it must match the lumina-desktop setup
  QSettings::setPath(QSettings::NativeFormat, QSettings::UserScope, QDir::homePath()+"/.lumina");
  settings = new QSettings( QSettings::UserScope, "LuminaDE", "lumina-fm", this);
  favdir = QDir::homePath()+"/.lumina/favorites/"; //save this for later
  //Reset the UI to the previously used size (if possible)
  int height = settings->value("geometry/height",-1).toInt();
  if(height>100 && height <= QApplication::desktop()->availableGeometry(this).height()){ this->resize(this->width(), height); }
  int width = settings->value("geometry/width",-1).toInt();
  if(width>100 && width <= QApplication::desktop()->availableGeometry(this).width()){ this->resize(width, this->height() ); }
  //initialize the non-ui widgets
  tabBar = new QTabBar(this);
    tabBar->setTabsClosable(true);
    tabBar->setMovable(true); //tabs are independant - so allow the user to sort them
    tabBar->setShape(QTabBar::RoundedNorth);
    tabBar->setFocusPolicy(Qt::NoFocus);
    ui->verticalLayout_browser->insertWidget(0,tabBar);
  currentDir = new QLineEdit(this);
    ui->toolBar->insertWidget(ui->actionBookMark, currentDir);
    currentDir->setFocusPolicy(Qt::StrongFocus);
  
  workThread = new QThread;
    workThread->setObjectName("Lumina-fm filesystem worker");
  worker = new BackgroundWorker;
    worker->moveToThread(workThread);
  
  fsmod = new QFileSystemModel(this);
    fsmod->setRootPath("/");
    ui->tree_dir_view->setModel(fsmod);
    ui->tree_dir_view->sortByColumn(0, Qt::AscendingOrder);
    ui->tree_dir_view->setColumnWidth(0,200);
    ui->tree_dir_view->setColumnWidth(1,80); //size column should be small
    ui->tree_dir_view->setColumnWidth(2,80); //type column should be small
    ui->list_dir_view->setModel(fsmod);
  dirCompleter = new QCompleter(fsmod, this);
    dirCompleter->setModelSorting( QCompleter::CaseInsensitivelySortedModel );
    currentDir->setCompleter(dirCompleter);
  snapmod = new QFileSystemModel(this);
    ui->tree_zfs_dir->setModel(snapmod);
    ui->tree_zfs_dir->sortByColumn(0, Qt::AscendingOrder);
  iconProv = new MimeIconProvider();
    fsmod->setIconProvider(iconProv);
    snapmod->setIconProvider(iconProv);
  contextMenu = new QMenu(this);
  radio_view_details = new QRadioButton(tr("Detailed List"), this);
  radio_view_list = new QRadioButton(tr("Basic List"), this);
  radio_view_icons = new QRadioButton(tr("Icons"), this);
  detWA = new QWidgetAction(this);
    detWA->setDefaultWidget(radio_view_details);
  listWA = new QWidgetAction(this);
    listWA->setDefaultWidget(radio_view_list);
  icoWA = new QWidgetAction(this);
    icoWA->setDefaultWidget(radio_view_icons);
    ui->menuView->addAction(detWA);
    ui->menuView->addAction(listWA);
    ui->menuView->addAction(icoWA);
  //Setup the special Phonon widgets
  mediaObj = new Phonon::MediaObject(this);
    mediaObj->setTickInterval(200); //1/5 second ticks for updates
  videoDisplay = new Phonon::VideoWidget(this);
    videoDisplay->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->videoLayout->addWidget(videoDisplay);
    Phonon::createPath(mediaObj, videoDisplay);
    videoDisplay->setVisible(false);
  audioOut = new Phonon::AudioOutput(Phonon::VideoCategory, this);
    Phonon::createPath(mediaObj, audioOut);
  playerSlider = new Phonon::SeekSlider(this);
    playerSlider->setMediaObject(mediaObj);
    ui->videoControlLayout->insertWidget(4, playerSlider);
    ui->tool_player_stop->setEnabled(false); //nothing to stop yet
    ui->tool_player_pause->setVisible(false); //nothing to pause yet
  //Setup any specialty keyboard shortcuts
  nextTabLShort = new QShortcut( QKeySequence(tr("Shift+Left")), this);
  nextTabRShort = new QShortcut( QKeySequence(tr("Shift+Right")), this);
  closeTabShort = new QShortcut( QKeySequence(tr("Ctrl+W")), this);
  copyFilesShort = new QShortcut( QKeySequence(tr("Ctrl+C")), this);
  pasteFilesShort = new QShortcut( QKeySequence(tr("Ctrl+V")), this);
  deleteFilesShort = new QShortcut( QKeySequence(tr("Delete")), this);
  //Finish loading the interface
  workThread->start();
  setupIcons();
  setupConnections();
  loadSettings();
  RebuildBookmarksMenu();
  RebuildDeviceMenu();
  //Make sure we start on the browser page
  goToBrowserPage();
}

MainUI::~MainUI(){
  workThread->quit();
  workThread->wait();
}

void MainUI::OpenDirs(QStringList dirs){
  for(int i=0; i<dirs.length(); i++){
    //Add this directory in a new tab
    if(dirs[i].endsWith("/")){ dirs[i].chop(1); }
    qDebug() << "Open Directory:" << dirs[i];
    int index = tabBar->addTab( dirs[i].section("/",-1) );
    tabBar->setTabWhatsThis( index, dirs[i] );
    if(index==0){ setCurrentDir(dirs[i]); }//display this as the current dir
  }
  tabBar->setVisible( tabBar->count() > 1 );
}

//==========
//    PRIVATE
//==========
void MainUI::setupIcons(){
  this->setWindowIcon( LXDG::findIcon("Insight-FileManager","") );
	
  //Setup all the icons using libLumina
  ui->actionClose->setIcon( LXDG::findIcon("application-exit","") );
  ui->actionNew_Tab->setIcon( LXDG::findIcon("tab-new-background","") );
  //ui->action_Preferences->setIcon( LXDG::findIcon("configure","") );
  ui->actionUpDir->setIcon( LXDG::findIcon("go-up","") );
  ui->actionBack->setIcon( LXDG::findIcon("go-previous","") );
  ui->actionHome->setIcon( LXDG::findIcon("go-home","") );
  ui->actionBookMark->setIcon( LXDG::findIcon("bookmarks","") );
  ui->actionBackToBrowser->setIcon( LXDG::findIcon("go-previous","") );
  ui->actionManage_Bookmarks->setIcon( LXDG::findIcon("bookmarks-organize","") );
  ui->actionScan->setIcon( LXDG::findIcon("system-search","") );
	
  //Browser page
  ui->tool_addToDir->setIcon( LXDG::findIcon("folder-new","") );
  ui->tool_goToImages->setIcon( LXDG::findIcon("fileview-preview","") );
  ui->tool_goToPlayer->setIcon( LXDG::findIcon("applications-multimedia","") );
  ui->tool_goToRestore->setIcon( LXDG::findIcon("document-revert","") );
  ui->tool_act_run->setIcon( LXDG::findIcon("run-build-file","") );
  ui->tool_act_runwith->setIcon( LXDG::findIcon("run-build-configure","") );
  ui->tool_act_cut->setIcon( LXDG::findIcon("edit-cut","") );
  ui->tool_act_copy->setIcon( LXDG::findIcon("edit-copy","") );
  ui->tool_act_paste->setIcon( LXDG::findIcon("edit-paste","") );
  ui->tool_act_rename->setIcon( LXDG::findIcon("edit-rename","") );
  ui->tool_act_rm->setIcon( LXDG::findIcon("edit-delete","") );
  ui->tool_act_fav->setIcon( LXDG::findIcon("quickopen","") );
	
  //Multimedia Player page
  ui->tool_player_next->setIcon( LXDG::findIcon("media-skip-forward","") );
  ui->tool_player_prev->setIcon( LXDG::findIcon("media-skip-backward","") );
  ui->tool_player_pause->setIcon( LXDG::findIcon("media-playback-pause","") );
  ui->tool_player_play->setIcon( LXDG::findIcon("media-playback-start","") );
  ui->tool_player_stop->setIcon( LXDG::findIcon("media-playback-stop","") );
	
  //Slideshow page
  ui->tool_image_goBegin->setIcon( LXDG::findIcon("go-first-view","") );
  ui->tool_image_goEnd->setIcon( LXDG::findIcon("go-last-view","") );
  ui->tool_image_goPrev->setIcon( LXDG::findIcon("go-previous-view","") );
  ui->tool_image_goNext->setIcon( LXDG::findIcon("go-next-view","") );
  
  //ZFS Restore page
  ui->tool_zfs_nextSnap->setIcon( LXDG::findIcon("go-next-view","") );
  ui->tool_zfs_prevSnap->setIcon( LXDG::findIcon("go-previous-view","") );
  ui->tool_zfs_restoreItem->setIcon( LXDG::findIcon("document-revert","") );
}

void MainUI::setupConnections(){
  connect(QApplication::instance(), SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(startEditDir(QWidget*, QWidget*)) );
  connect(tabBar, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)) );
  connect(tabBar, SIGNAL(tabCloseRequested(int)), this, SLOT(tabClosed(int)) );
  connect(ui->menuBookmarks, SIGNAL(triggered(QAction*)), this, SLOT(goToBookmark(QAction*)) );
  connect(ui->menuExternal_Devices, SIGNAL(triggered(QAction*)), this, SLOT(goToDevice(QAction*)) );
  connect(currentDir, SIGNAL(returnPressed()), this, SLOT(goToDirectory()));
  connect(radio_view_details, SIGNAL(toggled(bool)), this, SLOT(viewModeChanged(bool)) );
  connect(radio_view_list, SIGNAL(toggled(bool)), this, SLOT(viewModeChanged(bool)) );
  connect(radio_view_icons, SIGNAL(toggled(bool)), this, SLOT(viewModeChanged(bool)) );
  connect(fsmod, SIGNAL(directoryLoaded(QString)), this, SLOT(currentDirectoryLoaded()) );
	
  //Background worker class
  connect(this, SIGNAL(DirChanged(QString)), worker, SLOT(startDirChecks(QString)) );
  connect(worker, SIGNAL(ImagesAvailable(QStringList)), this, SLOT(AvailablePictures(QStringList)) );
  connect(worker, SIGNAL(MultimediaAvailable(QStringList)), this, SLOT(AvailableMultimediaFiles(QStringList)) );
  connect(worker, SIGNAL(SnapshotsAvailable(QString, QStringList)), this, SLOT(AvailableBackups(QString, QStringList)) );
	
  //Action buttons on browser page
  connect(ui->tool_act_run, SIGNAL(clicked()), this, SLOT(OpenItem()) );
  connect(ui->tool_act_runwith, SIGNAL(clicked()), this, SLOT(OpenItemWith()) );
  connect(ui->tool_act_rm, SIGNAL(clicked()), this, SLOT(RemoveItem()) );
  connect(ui->tool_act_rename, SIGNAL(clicked()), this, SLOT(RenameItem()) );
  connect(ui->tool_act_paste, SIGNAL(clicked()), this, SLOT(PasteItems()) );
  connect(ui->tool_act_cut, SIGNAL(clicked()), this, SLOT(CutItems()) );
  connect(ui->tool_act_copy, SIGNAL(clicked()), this, SLOT(CopyItems()) );
  connect(ui->tool_act_fav, SIGNAL(clicked()), this, SLOT(FavoriteItem()) );
	
  //Tree Widget interaction
  connect(ui->tree_dir_view, SIGNAL(activated(const QModelIndex&)), this, SLOT(ItemRun(const QModelIndex&)) );	
  connect(ui->list_dir_view, SIGNAL(activated(const QModelIndex&)), this, SLOT(ItemRun(const QModelIndex&)) );
  connect(ui->tree_dir_view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OpenContextMenu(const QPoint&)) );
  connect(ui->list_dir_view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OpenContextMenu(const QPoint&)) );
  connect(ui->tree_dir_view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection, const QItemSelection)), this, SLOT(ItemSelectionChanged()) );
  connect(ui->list_dir_view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection, const QItemSelection)), this, SLOT(ItemSelectionChanged()) );
	
  //Page Switching
  connect(ui->tool_goToPlayer, SIGNAL(clicked()), this, SLOT(goToMultimediaPage()) );
  connect(ui->tool_goToRestore, SIGNAL(clicked()), this, SLOT(goToRestorePage()) );
  connect(ui->tool_goToImages, SIGNAL(clicked()), this, SLOT(goToSlideshowPage()) );
  connect(ui->actionBackToBrowser, SIGNAL(triggered()), this, SLOT(goToBrowserPage()) );
	
  //Slideshow page
  connect(ui->combo_image_name, SIGNAL(currentIndexChanged(int)), this, SLOT(showNewPicture()) );
  connect(ui->tool_image_goBegin, SIGNAL(clicked()), this, SLOT(firstPicture()) );
  connect(ui->tool_image_goEnd, SIGNAL(clicked()), this, SLOT(lastPicture()) );
  connect(ui->tool_image_goNext, SIGNAL(clicked()), this, SLOT(nextPicture()) );
  connect(ui->tool_image_goPrev, SIGNAL(clicked()), this, SLOT(prevPicture()) );
	
  //ZFS Restore page
  connect(ui->slider_zfs_snapshot, SIGNAL(valueChanged(int)), this, SLOT(showSnapshot()) );
  connect(ui->tool_zfs_nextSnap, SIGNAL(clicked()), this, SLOT(nextSnapshot()) );
  connect(ui->tool_zfs_prevSnap, SIGNAL(clicked()), this, SLOT(prevSnapshot()) );
  connect(ui->tool_zfs_restoreItem, SIGNAL(clicked()), this, SLOT(restoreItems()) );
  
  //Multimedia Player page
  connect(ui->tool_player_next, SIGNAL(clicked()), this, SLOT(playerNext()));
  connect(ui->tool_player_prev, SIGNAL(clicked()), this, SLOT(playerPrevious()));
  connect(ui->tool_player_pause, SIGNAL(clicked()), this, SLOT(playerPause()));
  connect(ui->tool_player_play, SIGNAL(clicked()), this, SLOT(playerStart()));
  connect(ui->tool_player_stop, SIGNAL(clicked()), this, SLOT(playerStop()));
  connect(ui->combo_player_list, SIGNAL(currentIndexChanged(int)), this, SLOT(playerFileChanged()) );
  connect(mediaObj, SIGNAL(finished()), this, SLOT(playerFinished()) );
  connect(mediaObj, SIGNAL(tick(qint64)), this, SLOT(playerTimeChanged(qint64)) );
  connect(mediaObj, SIGNAL(stateChanged(Phonon::State, Phonon::State)), this, SLOT(playerStateChanged(Phonon::State, Phonon::State)) );
  connect(mediaObj, SIGNAL(hasVideoChanged(bool)), this, SLOT(playerVideoAvailable(bool)) );
  //Special Keyboard Shortcuts
  connect(nextTabLShort, SIGNAL(activated()), this, SLOT( prevTab() ) );
  connect(nextTabRShort, SIGNAL(activated()), this, SLOT( nextTab() ) );
  connect(closeTabShort, SIGNAL(activated()), this, SLOT( tabClosed() ) );
  connect(copyFilesShort, SIGNAL(activated()), this, SLOT( CopyItems() ) );
  connect(pasteFilesShort, SIGNAL(activated()), this, SLOT( PasteItems() ) );
  connect(deleteFilesShort, SIGNAL(activated()), this, SLOT( RemoveItem() ) );
}

void MainUI::loadSettings(){
  //Note: make sure this is run after all the UI elements are created and connected to slots
  // but before the first directory gets loaded
  ui->actionView_Hidden_Files->setChecked( settings->value("showhidden", false).toBool() );
  on_actionView_Hidden_Files_triggered(); //make sure to update the models too
  ui->actionShow_Action_Buttons->setChecked(settings->value("showactions", true).toBool() );
  on_actionShow_Action_Buttons_triggered(); //make sure to update the UI
  QString view = settings->value("viewmode","details").toString();
  if(view=="icons"){ radio_view_icons->setChecked(true); }
  else if(view=="list"){ radio_view_list->setChecked(true); }
  else{ radio_view_details->setChecked(true); }
}

void MainUI::RebuildBookmarksMenu(){
  //Create the bookmarks menu
  ui->menuBookmarks->clear();
    ui->menuBookmarks->addAction(ui->actionManage_Bookmarks);
    ui->menuBookmarks->addSeparator();
  QStringList BM = settings->value("bookmarks", QStringList()).toStringList();
  ui->menuBookmarks->clear();
    ui->menuBookmarks->addAction(ui->actionManage_Bookmarks);
    ui->menuBookmarks->addSeparator();
  bool changed = false;
  BM.sort(); //Sort alphabetically
  for(int i=0; i<BM.length(); i++){
    if(QFile::exists(BM[i].section("::::",1,1)) ){
      QAction *act = new QAction(BM[i].section("::::",0,0),this);
        act->setWhatsThis(BM[i].section("::::",1,1));
      ui->menuBookmarks->addAction(act);
    }else{
      //Invalid directory - remove the bookmark
      BM.removeAt(i);
      i--;
      changed = true;
    }
  }
  if(changed){ settings->setValue("bookmarks",BM); }
  ui->actionManage_Bookmarks->setEnabled(BM.length()>0);
}

void MainUI::RebuildDeviceMenu(){
  //Create the External Devices Menu appropriately
  ui->menuExternal_Devices->clear();
    ui->menuExternal_Devices->addAction( ui->actionScan );
    ui->menuExternal_Devices->addSeparator();
  //Scan for externally mounted devices
  QStringList devs = LOS::ExternalDevicePaths();
    //Output Format: <type>::::<filesystem>::::<path>  (6/24/14 - version 0.4.0 )
        // <type> = [USB, HDRIVE, SDCARD, DVD, UNKNOWN]
	
  //Now add them to the menu appropriately
  for(int i=0; i<devs.length(); i++){
    //Skip hidden mount points (usually only for system usage - not user browsing)
    if(devs[i].section("::::",2,2).section("/",-1).startsWith(".")){ continue; } 
    //Create entry for this device
    QAction *act = new QAction(devs[i].section("::::",2,2).section("/",-1),this);
        act->setWhatsThis(devs[i].section("::::",2,2)); //full path to mountpoint
	act->setToolTip( QString(tr("Filesystem: %1")).arg( devs[i].section("::::",1,1) ) );
	//Now set the appropriate icon
	QString type = devs[i].section("::::",0,0);
	if(type=="USB"){ type = "drive-removable-media-usb"; }
	else if(type=="HDRIVE"){ type = "drive-harddisk"; }
	else if(type=="SDCARD"){ type = "media-flash-sd-mmc"; }
	else if(type=="DVD"){ type = "media-optical"; }
	else{ type = "drive-removable-media"; }
	act->setIcon( LXDG::findIcon(type, "") );
      ui->menuExternal_Devices->addAction(act);
  }
}

bool MainUI::checkUserPerms(){
  if(!isUserWritable){
    QMessageBox::warning(this, tr("Invalid Permissions"), tr("You do not have permission to edit this directory!") );
  }
  return isUserWritable;
}

QString MainUI::msToText(qint64 ms){
  QString disp;
  if(ms>3600000){
    disp.append( QString::number(ms/3600000)+":" ); 
    ms = ms%3600000; 
  }
  if(ms>60000){
    disp.append( QString::number(ms/60000)+":" );
    ms = ms%60000;
  }else{
    disp.append("0:");
  }
  if(ms>1000){
    if(ms>=10000){ disp.append( QString::number(ms/1000) ); }
    else{ disp.append( "0"+QString::number(ms/1000) ); }
  }else{
    disp.append("00");
  }
  return disp;
}

QString MainUI::getCurrentDir(){
  return currentDir->whatsThis();
}

void MainUI::setCurrentDir(QString dir){
  if(dir.isEmpty()){ return; }
  QFileInfo info(dir);
  QString olddir = currentDir->whatsThis();
  if(!info.isDir() || !info.exists() ){ 
    qDebug() << "Invalid Directory:" << dir;
    //Try to just go up the dir tree one level
    dir.chop(dir.section("/",-1).length());
    if(!QFile::exists(dir)){
      //Still bad dir - try to return to previously shown dir
      if(currentDir->whatsThis().isEmpty()){ return; } //nothing to return to
      else{ dir = currentDir->whatsThis(); }
    }
  }
  //qDebug() << "Show Directory:" << dir;
  //qDebug() << "Dir Info:" << dir;
  //qDebug() << " - RWXLOG:" << info.isReadable() << info.isWritable() << info.isExecutable() << info.isSymLink() << info.ownerId() << info.groupId();
  isUserWritable = info.isWritable();
  if(dir.endsWith("/") && dir!="/" ){ dir.chop(1); }
  QString rawdir = dir;
  //dir.replace(QDir::homePath()+"/", "~/");
  currentDir->setText(dir);  
  //Update the directory viewer and update the line edit
    keepFocus = !currentDir->hasFocus();
    currentDir->setWhatsThis(dir); //save the full path internally
    if(radio_view_details->isChecked()){
      ui->tree_dir_view->setRootIndex(fsmod->index(dir));
      ui->tree_dir_view->selectionModel()->clearSelection();
    }else{
      ui->list_dir_view->setRootIndex(fsmod->index(dir));
      ui->list_dir_view->selectionModel()->clearSelection();
    }
  //Adjust the tab data
  tabBar->setTabWhatsThis( tabBar->currentIndex(), rawdir );
  if(dir!="/"){ tabBar->setTabText( tabBar->currentIndex(), dir.section("/",-1) ); }
  else{ tabBar->setTabText( tabBar->currentIndex(), dir); }
  QStringList history = tabBar->tabData(tabBar->currentIndex()).toStringList();
  if(history.isEmpty() || history.first()!=rawdir){ history.prepend(rawdir); history.removeAll(""); }
  //qDebug() << "History:" << history;
  tabBar->setTabData(tabBar->currentIndex(), history);
  //Now adjust the items as necessary
  ui->tool_goToPlayer->setVisible(false);
  ui->tool_goToRestore->setVisible(false);
  ui->tool_goToImages->setVisible(false);
  if(olddir==rawdir){
    emit DirChanged(rawdir); //This will be automatically run when a new dir is loaded
  }
  if(isUserWritable){ ui->label_dir_stats->setText(""); }
  else{ ui->label_dir_stats->setText(tr("Limited Access Directory")); }
  ui->tool_addToDir->setVisible(isUserWritable);
  ui->actionUpDir->setEnabled(dir!="/");
  ui->actionBack->setEnabled(history.length() > 1);
  ui->actionBookMark->setEnabled( rawdir!=QDir::homePath() && settings->value("bookmarks", QStringList()).toStringList().filter("::::"+rawdir).length()<1 );
  ItemSelectionChanged();
  RebuildDeviceMenu(); //keep this refreshed
}

QFileInfoList MainUI::getSelectedItems(){
  QFileInfoList out;
  if(radio_view_details->isChecked()){
    QModelIndexList items = ui->tree_dir_view->selectionModel()->selectedIndexes();
    for(int i=0; i<items.length(); i++){
      if(!out.contains(fsmod->fileInfo(items[i]))){
        out << fsmod->fileInfo(items[i]);
      }
    }
  }else{
    QModelIndexList items = ui->list_dir_view->selectionModel()->selectedIndexes();
    for(int i=0; i<items.length(); i++){
      if(!out.contains(fsmod->fileInfo(items[i]))){
        out <<  fsmod->fileInfo(items[i]);
      }
    }
  }	
  return out;
}

//==============
//    PRIVATE SLOTS
//==============
//General button check functions
void MainUI::AvailableMultimediaFiles(QStringList files){
  /*ui->tool_goToPlayer->setVisible(false);

  QDir dir(getCurrentDir());
  if(multiFilter.isEmpty()){
    QStringList mimes = Phonon::BackendCapabilities::availableMimeTypes();
    mimes = mimes.filter("audio/") + mimes.filter("video/");
    for(int i=0; i<mimes.length(); i++){
      multiFilter << LXDG::findFilesForMime(mimes[i]);
    }
    multiFilter.removeDuplicates();
    qDebug() << "Supported Multimedia Formats:" << multiFilter;
  }
  QStringList files = dir.entryList(multiFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  */
  if(!files.isEmpty()){
    ui->combo_player_list->clear();
    ui->combo_player_list->addItems(files);
    ui->tool_goToPlayer->setVisible(true);
  }else{
    ui->tool_goToPlayer->setVisible(false);
  }
  
}

void MainUI::AvailableBackups(QString basedir, QStringList snapdirs){
  /*ui->tool_goToRestore->setVisible(false);
  snapDirs.clear(); //clear the internal variable
  if(!isUserWritable){ 
    //cannot restore files into a non-writable directory
    //No dir found: put the snapmod on the lumina directory (someplace out of the way)
    snapmod->setRootPath(QDir::homePath()+"/.lumina");
    return; 
  }
  //Now recursively try to find snapshots of this directory
  QString cdir = getCurrentDir();
  QDir dir(cdir);
  bool found = false;
  while(dir.absolutePath()!="/" && !found){
    if(dir.exists(".zfs/snapshot")){ found = true;}
    else{ dir.cdUp(); }
    QApplication::processEvents(); //keep the UI snappy
  }
  //Now find the snapshots that contain this directory and save them
  if(found){
    QString reldir = getCurrentDir();
	  reldir.remove(dir.absolutePath());
    dir.cd(".zfs/snapshot");
    snapmod->setRootPath(dir.canonicalPath()); //set the base snapshot dir as the new root
    snapDirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
    //Check that the current directory exists in each snapshot
    for(int i=0; i<snapDirs.length(); i++){
      if( !dir.exists(snapDirs[i]+"/"+reldir) ){
        snapDirs.removeAt(i);
	i--;
      }else{
	snapDirs[i] = QFileInfo(dir, snapDirs[i]+"/"+reldir).created().toString("yyyyMMddhhmmsszzz")+"::::"+snapDirs[i];
      }
      QApplication::processEvents(); //keep the UI snappy
    }
    snapDirs.sort();
    //Sort the snapshots by time (newest last) and format them
    for(int i=0; i<snapDirs.length(); i++){
      snapDirs[i] = dir.absolutePath()+"/"+snapDirs[i].section("::::",1,50)+"/"+reldir;
      QApplication::processEvents(); //keep the UI snappy
    }
    //qDebug() << "Found snapshots:" << snapDirs;
  }else{
    //No dir found: put the snapmod on the lumina directory (someplace out of the way)
    snapmod->setRootPath(QDir::homePath()+"/.lumina");
  }*/
  snapmod->setRootPath(basedir); //set the base snapshot dir as the new root
  snapDirs = snapdirs;
  
  //Now enable the button if any snapshots available
  ui->tool_goToRestore->setVisible(!snapDirs.isEmpty());
}

void MainUI::AvailablePictures(QStringList pics){
  /*ui->tool_goToImages->setVisible(false);
  QDir dir(getCurrentDir());
  if(imgFilter.isEmpty()){
    QList<QByteArray> fmt = QImageReader::supportedImageFormats();
    for(int i=0; i<fmt.length(); i++){ imgFilter << "*."+QString(fmt[i]).toLower(); }
    qDebug() << "Supported Image Formats:" << imgFilter;
  }
  QStringList pics = dir.entryList(imgFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  */
  if(!pics.isEmpty()){
    ui->combo_image_name->clear();
    ui->combo_image_name->addItems(pics);
    ui->tool_goToImages->setVisible(true);	  
  }
	
}

//-----------------------------------
//General page switching
//-----------------------------------
void MainUI::goToMultimediaPage(){
  //Make toolbar items disappear appropriately	
  ui->actionBackToBrowser->setVisible(true);
  ui->actionBack->setVisible(false);
  ui->actionUpDir->setVisible(false);
  ui->actionHome->setVisible(false);
  ui->actionBookMark->setVisible(false);
  currentDir->setEnabled(false);
  //Disable all the UI elements specifically for the Browser side of things
  ui->actionNew_Tab->setEnabled(false);
  ui->menuView->setEnabled(false);
  ui->menuBookmarks->setEnabled(false);
  ui->menuExternal_Devices->setEnabled(false);
  //Start the player on the first selected item
  QFileInfoList sel = getSelectedItems();
  if(!sel.isEmpty()){
    QStringList names;
    for(int i=0; i<sel.length(); i++){ names << sel[i].fileName(); }
    //start the slideshow on the first selected picture
    for(int i=0; i<ui->combo_player_list->count(); i++){
      if(names.contains( ui->combo_player_list->itemText(i) )){ ui->combo_player_list->setCurrentIndex(i); break; }
    }
  }
  //Now go to the Multimedia player
  ui->label_player_novideo->setText(tr("Click Play to Start"));
  ui->stackedWidget->setCurrentWidget(ui->page_audioPlayer);
}

void MainUI::goToRestorePage(){
  //Make toolbar items disappear appropriately
  ui->actionBackToBrowser->setVisible(true);	
  ui->actionBack->setVisible(false);
  ui->actionUpDir->setVisible(false);
  ui->actionHome->setVisible(false);
  ui->actionBookMark->setVisible(false);
  currentDir->setEnabled(false);
  //Disable all the UI elements specifically for the Browser side of things
  ui->actionNew_Tab->setEnabled(false);
  ui->menuView->setEnabled(false);
  ui->menuBookmarks->setEnabled(false);
  ui->menuExternal_Devices->setEnabled(false);
  //Load all the info into the file restore page
  ui->slider_zfs_snapshot->setRange(1,snapDirs.length());
  ui->slider_zfs_snapshot->setValue(snapDirs.length());
  //Now go to the file restore page
  showSnapshot(); //Make sure it is updated for the current directory
  ui->stackedWidget->setCurrentWidget(ui->page_zfs);	
}

void MainUI::goToSlideshowPage(){
  //Make toolbar items disappear appropriately	
  ui->actionBackToBrowser->setVisible(true);
  ui->actionBack->setVisible(false);
  ui->actionUpDir->setVisible(false);
  ui->actionHome->setVisible(false);
  ui->actionBookMark->setVisible(false);
  currentDir->setEnabled(false);
  //Disable all the UI elements specifically for the Browser side of things
  ui->actionNew_Tab->setEnabled(false);
  ui->menuView->setEnabled(false);
  ui->menuBookmarks->setEnabled(false);
  ui->menuExternal_Devices->setEnabled(false);
  QFileInfoList sel = getSelectedItems();
  if(!sel.isEmpty()){
    QStringList names;
    for(int i=0; i<sel.length(); i++){ names << sel[i].fileName(); }
    //start the slideshow on the first selected picture
    for(int i=0; i<ui->combo_image_name->count(); i++){
      if(names.contains( ui->combo_image_name->itemText(i) )){ ui->combo_image_name->setCurrentIndex(i); break; }
    }
  }
  //Now go to the Slideshow player
  ui->stackedWidget->setCurrentWidget(ui->page_image_view);
  showNewPicture(); //make sure it is up to date with the widget size
}

void MainUI::goToBrowserPage(){
  //Make toolbar items re-appear appropriately	
  ui->actionBackToBrowser->setVisible(false);
  ui->actionBack->setVisible(true);
  ui->actionUpDir->setVisible(true);
  ui->actionHome->setVisible(true);
  ui->actionBookMark->setVisible(true);
  currentDir->setEnabled(true);
  //Disable all the UI elements specifically for the Browser side of things
  ui->actionNew_Tab->setEnabled(true);
  ui->menuView->setEnabled(true);
  ui->menuBookmarks->setEnabled(true);
  ui->menuExternal_Devices->setEnabled(true);
  //Now go to the browser
  if(ui->stackedWidget->currentWidget()==ui->page_audioPlayer){ mediaObj->stop(); }
  ui->stackedWidget->setCurrentWidget(ui->page_browser);	
}
	
//---------------------
//Menu Actions
//---------------------
void MainUI::on_actionNew_Tab_triggered(){
  OpenDirs(QStringList() << QDir::homePath());
  //Now go to that tab (always last)
  tabBar->setCurrentIndex(tabBar->count()-1);
}

void MainUI::on_actionClose_triggered(){
  if(tabBar->count() > 1){
    if(QMessageBox::Yes != QMessageBox::question(this, tr("Verify Quit"), tr("You have multiple tabs open. Are you sure you want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ) ){
      return;
    }
  }
  qDebug() << "Closing Down...";
  this->close();
}

void MainUI::on_actionView_Hidden_Files_triggered(){
  if(ui->actionView_Hidden_Files->isChecked()){
    fsmod->setFilter( QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden );
    snapmod->setFilter( QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden );
  }else{
    fsmod->setFilter( QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs );
    snapmod->setFilter( QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs );
  }
  //Now save this setting for later
  settings->setValue("showhidden", ui->actionView_Hidden_Files->isChecked());
  //Re-load the view widget
  setCurrentDir(getCurrentDir());
}

void MainUI::on_actionShow_Action_Buttons_triggered(){
  ui->group_actions->setVisible(ui->actionShow_Action_Buttons->isChecked());
  settings->setValue("showactions", ui->actionShow_Action_Buttons->isChecked());
}
void MainUI::goToBookmark(QAction *act){
  if(act==ui->actionManage_Bookmarks){
    BMMDialog dlg(this);
      dlg.loadSettings(settings);
      dlg.exec();
    RebuildBookmarksMenu();
  }else{
    setCurrentDir(act->whatsThis());
  }
}

void MainUI::goToDevice(QAction *act){
  if(act==ui->actionScan){
    RebuildDeviceMenu();
  }else{
    setCurrentDir(act->whatsThis());
  }
}

void MainUI::viewModeChanged(bool active){
  if(!active){ return; } //on every view change, all 3 radio buttons will call this function - only run this once though
  if(radio_view_details->isChecked()){
    ui->tree_dir_view->setVisible(true);
    ui->list_dir_view->setVisible(false);
	settings->setValue("viewmode","details");
  }else if(radio_view_list->isChecked()){
    ui->tree_dir_view->setVisible(false);
    ui->list_dir_view->setVisible(true);
    ui->list_dir_view->setViewMode( QListView::ListMode );
	ui->list_dir_view->setUniformItemSizes(false);
	ui->list_dir_view->setIconSize( QSize(20,20) );
	settings->setValue("viewmode","list");
  }else{  //icons
    ui->tree_dir_view->setVisible(false);
    ui->list_dir_view->setVisible(true);
    ui->list_dir_view->setViewMode( QListView::IconMode );
	ui->list_dir_view->setUniformItemSizes(true);
	ui->list_dir_view->setIconSize( QSize(90,64) );
	settings->setValue("viewmode","icons");
  }
  //Re-load the view widget
  setCurrentDir(getCurrentDir());
	
}

//-----------------------
//Toolbar Actions
//-----------------------
void MainUI::on_actionBack_triggered(){
  QStringList history = tabBar->tabData(tabBar->currentIndex()).toStringList();
  if(history.length() <= 1){ return; } //need the second item
  history.removeAt(0); //remove the first item (the current dir)
  tabBar->setTabData(tabBar->currentIndex(), history); //re-write the saved history
  setCurrentDir(history.first()); //go to the previous entry in the history
}

void MainUI::on_actionUpDir_triggered(){
  QString dir =  getCurrentDir();
    dir.chop( dir.section("/",-1).length() );
    setCurrentDir(dir);
}

void MainUI::on_actionHome_triggered(){
  setCurrentDir(QDir::homePath());
}

void MainUI::on_actionBookMark_triggered(){
  QString dir = getCurrentDir();
  bool ok = false;
  QString name = QInputDialog::getText(this, tr("New Bookmark"), tr("Name:"), QLineEdit::Normal, dir, \
		&ok, 0, Qt::ImhFormattedNumbersOnly | Qt::ImhUppercaseOnly | Qt::ImhLowercaseOnly);
  if(!ok || name.isEmpty()){ return; } //cancelled
  QStringList BM = settings->value("bookmarks",QStringList()).toStringList();
  if(BM.filter(name+"::::").length() >0){
    QMessageBox::warning(this, tr("Invalid Name"), tr("This bookmark name already exists. Please choose another.") );
    QTimer::singleShot(0,this, SLOT(on_actionBookMark_triggered()));
    return;
  }
  BM.append(name+"::::"+dir);
  BM.sort(); //sort alphabetically by name
  settings->setValue("bookmarks", BM);
  //Now rebuild the bookmarks menu
  RebuildBookmarksMenu();
  ui->actionBookMark->setEnabled(false); //already bookmarked
}

//-----------------------------
//Browser Functions
//-----------------------------
void MainUI::startEditDir(QWidget *old, QWidget *now){
  if(now==currentDir){
    //The dir edit just got focus
    QString dir = currentDir->text();
      dir.replace("~/", QDir::homePath()+"/");
      currentDir->setText(dir);
      //Try to move to the end
      currentDir->selectAll();
  }else if(old==currentDir){
    QString dir = currentDir->text();
      setCurrentDir(dir);
  }
}

void MainUI::goToDirectory(){
  QString dir = currentDir->text();
  dir.replace("~/",QDir::homePath()+"/");
  setCurrentDir(dir);
}

void MainUI::reloadDirectory(){
  setCurrentDir( getCurrentDir() );
}

void MainUI::currentDirectoryLoaded(){
  //The directory was just loaded: refresh the action buttons as neccesary
  ui->tool_goToPlayer->setVisible(false);
  ui->tool_goToRestore->setVisible(false);
  ui->tool_goToImages->setVisible(false);
  emit DirChanged(getCurrentDir());
}

void MainUI::on_tool_addToDir_clicked(){
  bool ok = false;
  QString newdir = QInputDialog::getText(this, tr("New Directory"), tr("Name:"), QLineEdit::Normal, "", \
		&ok, 0, Qt::ImhFormattedNumbersOnly | Qt::ImhUppercaseOnly | Qt::ImhLowercaseOnly);
  if(!ok || newdir.isEmpty()){ return; }
  QString full = getCurrentDir();
  if(!full.endsWith("/")){ full.append("/"); }
  QDir dir(full); //open the current dir
  full.append(newdir); //append the new name to the current dir
  //Verify that the new dir does not already exist
  if(dir.exists(full)){
    QMessageBox::warning(this, tr("Invalid Name"), tr("A file or directory with that name already exists! Please pick a different name."));
    QTimer::singleShot(0,this, SLOT(on_tool_addToDir_clicked()) ); //repeat this function
  }else{
    if(!dir.mkdir(newdir) ){
      QMessageBox::warning(this, tr("Error Creating Directory"), tr("The directory could not be created. Please ensure that you have the proper permissions to modify the current directory."));
    }
  }
}

void MainUI::tabChanged(int tab){
  //Load the directory contained in the new tab
  qDebug() << "Change to Tab:" << tab << tabBar->tabText(tab);
  QString dir = tabBar->tabWhatsThis(tab); //get the full directory
  setCurrentDir(dir); //display this as the current dir
}

void MainUI::tabClosed(int tab){
  if(tabBar->count()==1){ return; } //Can't close the only tab
  if(tab < 0){ tab = tabBar->currentIndex(); }
  //Remove the tab (will automatically move to a different one);
  qDebug() << "Closing tab:" << tab << tabBar->tabText(tab);
  tabBar->removeTab(tab);
  tabBar->setVisible( tabBar->count() > 1 );
}

void MainUI::prevTab(){
  int cur = tabBar->currentIndex();
  if(cur == 0){ tabBar->setCurrentIndex( tabBar->count()-1 ); }
  else{ tabBar->setCurrentIndex( cur-1 ); }
}

void MainUI::nextTab(){
  int cur = tabBar->currentIndex();
  if(cur == (tabBar->count()-1) ){ tabBar->setCurrentIndex(0); }
  else{ tabBar->setCurrentIndex( cur+1 ); }	
}

void MainUI::ItemRun(const QModelIndex &index){
  //This is called when the user double clicks a file/directory
  QString val = fsmod->filePath(index).section("/",-1);
  QString itemPath = getCurrentDir();
  if( !itemPath.endsWith("/")){ itemPath.append("/"); }
  itemPath.append(val);
  if(fsmod->isDir(index)){
    setCurrentDir( itemPath );
  }else{
    //Must be a file, try to run it
    QProcess::startDetached("lumina-open \""+itemPath+"\"");
  }
}

void MainUI::OpenContextMenu(const QPoint &pt){
  QFileInfo info; 
  if(radio_view_details->isChecked()){ 
    QModelIndex it = ui->tree_dir_view->indexAt(pt);
    if(!it.isValid()){ CItem.clear();}
    else{ 
      info = fsmod->fileInfo(it); 
      CItem = info.absoluteFilePath(); 
    }
  }else{ 
    QModelIndex it = ui->list_dir_view->indexAt(pt);
    if(!it.isValid()){ CItem.clear();}
    else{ 
      info = fsmod->fileInfo(it); 
      CItem = info.absoluteFilePath(); 
    }
  }
  //Create the context menu
  contextMenu->clear();
  if(!CItem.isEmpty()){  
    if(info.isDir()){
      contextMenu->addAction(LXDG::findIcon("tab-new-background",""), tr("Open in new tab"), this, SLOT(OpenDir()) );
    }else{
      contextMenu->addAction(LXDG::findIcon("run-build-file",""), tr("Open"), this, SLOT(OpenItem()) );
      contextMenu->addAction(LXDG::findIcon("run-build-configure",""), tr("Open With..."), this, SLOT(OpenItemWith()) );
    }
    contextMenu->addAction(LXDG::findIcon("edit-rename",""), tr("Rename"), this, SLOT(RenameItem()) )->setEnabled(info.isWritable());
    contextMenu->addSeparator();
  }
  bool hasSelection = !getSelectedItems().isEmpty();
  //Now add the general selection options
  contextMenu->addAction(LXDG::findIcon("edit-cut",""), tr("Cut Selection"), this, SLOT(CutItems()) )->setEnabled(info.isWritable() && hasSelection);
  contextMenu->addAction(LXDG::findIcon("edit-copy",""), tr("Copy Selection"), this, SLOT(CopyItems()) )->setEnabled(hasSelection);
  contextMenu->addAction(LXDG::findIcon("edit-paste",""), tr("Paste"), this, SLOT(PasteItems()) )->setEnabled(QApplication::clipboard()->mimeData()->hasFormat("x-special/lumina-copied-files") && isUserWritable);
  contextMenu->addSeparator();
  contextMenu->addAction(LXDG::findIcon("edit-delete",""), tr("Delete Selection"), this, SLOT(RemoveItem()) )->setEnabled(info.isWritable()&&hasSelection);
  //Now show the menu
  if(radio_view_details->isChecked()){
    contextMenu->popup(ui->tree_dir_view->mapToGlobal(pt));
  }else{
    contextMenu->popup(ui->list_dir_view->mapToGlobal(pt));
  }
}

void MainUI::ItemSelectionChanged(){
  //Enable/disable the action buttons
  QFileInfoList sel = getSelectedItems();
  ui->tool_act_run->setEnabled(sel.length()==1);
  ui->tool_act_runwith->setEnabled(sel.length()==1);
  ui->tool_act_rm->setEnabled(!sel.isEmpty() && isUserWritable);
  ui->tool_act_rename->setEnabled(sel.length()==1 && isUserWritable);
  ui->tool_act_cut->setEnabled(!sel.isEmpty() && isUserWritable);
  ui->tool_act_copy->setEnabled(!sel.isEmpty());
  ui->tool_act_paste->setEnabled(QApplication::clipboard()->mimeData()->hasFormat("x-special/lumina-copied-files") && isUserWritable);
  if(ui->tool_act_paste->isEnabled()){
    ui->tool_act_paste->setToolTip( QString(tr("Currently on clipboard:\n%1")).arg( QString(QApplication::clipboard()->mimeData()->data("x-special/lumina-copied-files")).replace("::::",": ") ) );
  }else{
    ui->tool_act_paste->setToolTip("");
  }
  QString itname;
  if(sel.length()==1){ itname = sel[0].fileName(); }
  ui->tool_act_fav->setEnabled(!itname.isEmpty() && !QFile::exists(favdir+itname) );
}

//-------------------------------
//Slideshow Functions
//-------------------------------
void MainUI::showNewPicture(){
  if( !ui->label_image->isVisible() ){ return; } //don't update if not visible - can cause strange resizing issues
  QString file = getCurrentDir();
  if(!file.endsWith("/")){ file.append("/"); }
  file.append(ui->combo_image_name->currentText());
  //qDebug() << "Show Image:" << file;
  QPixmap pix(file);
  if(pix.size().width() > ui->label_image->contentsRect().width() || pix.size().height() > ui->label_image->contentsRect().height()){ 
    pix = pix.scaled(ui->label_image->contentsRect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); 
  }
  ui->label_image->setPixmap(pix);
  //Now set/load the buttons
  ui->tool_image_goBegin->setEnabled(ui->combo_image_name->currentIndex()>0);
  ui->tool_image_goPrev->setEnabled(ui->combo_image_name->currentIndex()>0);
  ui->tool_image_goEnd->setEnabled(ui->combo_image_name->currentIndex()<(ui->combo_image_name->count()-1));
  ui->tool_image_goNext->setEnabled(ui->combo_image_name->currentIndex()<(ui->combo_image_name->count()-1));
  ui->label_image_index->setText( QString::number(ui->combo_image_name->currentIndex()+1)+"/"+QString::number(ui->combo_image_name->count()) );
}

void MainUI::firstPicture(){
  ui->combo_image_name->setCurrentIndex(0);
}

void MainUI::prevPicture(){
  ui->combo_image_name->setCurrentIndex( ui->combo_image_name->currentIndex()-1 );
}

void MainUI::nextPicture(){
  ui->combo_image_name->setCurrentIndex( ui->combo_image_name->currentIndex()+1 );
}

void MainUI::lastPicture(){
  ui->combo_image_name->setCurrentIndex( ui->combo_image_name->count()-1 );
}

//----------------------------------
//ZFS Restore Functions
//----------------------------------
void MainUI::snapshotLoaded(){
  ui->tree_zfs_dir->resizeColumnToContents(0);
}

void MainUI::showSnapshot(){
  ui->tool_zfs_prevSnap->setEnabled(ui->slider_zfs_snapshot->value()!=1);
  ui->tool_zfs_nextSnap->setEnabled(ui->slider_zfs_snapshot->value()!=ui->slider_zfs_snapshot->maximum());
  ui->label_zfs_snap->setText( snapDirs[ui->slider_zfs_snapshot->value()-1].section("/.zfs/snapshot/",1,1).section("/",0,0) );
  //Load the dir contents
  ui->tree_zfs_dir->setRootIndex(snapmod->index(snapDirs[ui->slider_zfs_snapshot->value()-1]));
}

void MainUI::prevSnapshot(){
  ui->slider_zfs_snapshot->setValue(ui->slider_zfs_snapshot->value()-1);
}

void MainUI::nextSnapshot(){
  ui->slider_zfs_snapshot->setValue(ui->slider_zfs_snapshot->value()+1);
}

void MainUI::restoreItems(){
   //Get the selected items
   QStringList sel; //= getSelectedItems();
   QModelIndexList items = ui->tree_zfs_dir->selectionModel()->selectedIndexes();
   for(int i=0; i<items.length(); i++){
     sel << snapmod->filePath(items[i]).section("/",-1);
   }
   sel.removeDuplicates();
   if(sel.isEmpty()){ return; } //nothing selected
   if(!checkUserPerms()){ return; }
   //Get the directories
   QString snapdir = snapDirs[ui->slider_zfs_snapshot->value()-1];
   QString basedir = getCurrentDir();
   if(!basedir.endsWith("/")){ basedir.append("/"); }
   if(!snapdir.endsWith("/")){ snapdir.append("/"); }
   //Fill out the lists appropriately
   QStringList resto;
   qDebug() << "Items Selected:" << sel;
   for(int i=0; i<sel.length(); i++){
     resto << basedir+sel[i];
     sel[i] = snapdir+sel[i];
   }
   qDebug() << "Restore Items:" << sel << "\n" << resto;
   //Restore the items
   FODialog dlg(this);
	dlg.setOverwrite(ui->check_zfs_overwrite->isChecked());
	dlg.RestoreFiles(sel, resto);
   dlg.exec();
   if(dlg.noerrors){
     QMessageBox::information(this, tr("Success"), tr("Successfully restored selection") );
   }
}

//----------------------------
// Multimedia Player
//----------------------------
void MainUI::playerStart(){
  if(ui->stackedWidget->currentWidget()!=ui->page_audioPlayer){ return; } //don't play if not in the player
  
  if(mediaObj->state()==Phonon::PausedState){
    mediaObj->play();
  }else{ // if(mediaObj->state()==Phonon::StoppedState || mediaObj->state()==Phonon::ErrorState || (playerFile->fileName().section("/",-1) != ui->combo_player_list->currentText()) || playerFile->isOpen() ){
    mediaObj->stop();
    //Get the selected file path
    QString filePath = getCurrentDir();
    if(!filePath.endsWith("/")){ filePath.append("/"); }
    filePath.append( ui->combo_player_list->currentText() );
    //if(playerFile->isOpen()){ playerFile->close(); }
    //playerFile->setFileName(filePath);
    //if(playerFile->open(QIODevice::ReadOnly)){
      mediaObj->setCurrentSource( QUrl(filePath) );
      playerSlider->setMediaObject(mediaObj);
      mediaObj->play();
    //}
  }
}

void MainUI::playerStop(){
  mediaObj->stop();
}

void MainUI::playerPause(){
  mediaObj->pause();
}

void MainUI::playerNext(){
  ui->combo_player_list->setCurrentIndex( ui->combo_player_list->currentIndex()+1);
}

void MainUI::playerPrevious(){
  ui->combo_player_list->setCurrentIndex( ui->combo_player_list->currentIndex()-1);	
}

void MainUI::playerFinished(){
  //playerFile->close();
  if(ui->combo_player_list->currentIndex()<(ui->combo_player_list->count()-1) && ui->check_player_gotonext->isChecked()){
    ui->combo_player_list->setCurrentIndex( ui->combo_player_list->currentIndex()+1 );
  }else{
    ui->label_player_novideo->setText(tr("Finished"));
  }
}

void MainUI::playerStateChanged(Phonon::State newstate, Phonon::State oldstate){
  //This function keeps track of updating the visuals of the player
  bool running = false;
  bool showVideo = false;
  QString msg;
  switch(newstate){
    case Phonon::LoadingState:
	running=true;
	ui->label_player_novideo->setText(tr("Loading File..."));
        break;
    case Phonon::PlayingState:
	running=true;
	showVideo = mediaObj->hasVideo();
	msg = mediaObj->metaData(Phonon::TitleMetaData).join(" ");
	if(msg.simplified().isEmpty()){ msg = ui->combo_player_list->currentText(); }
	ui->label_player_novideo->setText(tr("Playing:")+"\n"+msg);
	break;
    case Phonon::BufferingState:
	running=true;
	showVideo=true; //don't blank the screen
	break;
    case Phonon::PausedState:
	showVideo=videoDisplay->isVisible(); //don't change the screen
	break;
    case Phonon::StoppedState:
	if(oldstate==Phonon::LoadingState){ mediaObj->play(); }
	else{ ui->label_player_novideo->setText(tr("Stopped")); }
        break;
    case Phonon::ErrorState:
	ui->label_player_novideo->setText(tr("Error Playing File")+"\n("+mediaObj->errorString()+")");
        break;
  }
  ui->tool_player_play->setVisible(!running);
  ui->tool_player_pause->setVisible(running);
  ui->tool_player_stop->setEnabled(running);
  ui->label_player_novideo->setVisible(!showVideo);
  videoDisplay->setVisible(showVideo);
}

void MainUI::playerVideoAvailable(bool showVideo){
  ui->label_player_novideo->setVisible(!showVideo);
  videoDisplay->setVisible(showVideo);	
}

void MainUI::playerTimeChanged(qint64 ctime){
  if(playerTTime=="0:00" || playerTTime.isEmpty()){ playerTTime = msToText(mediaObj->totalTime()); } //only calculate as necessary
  //qDebug() << "Time:" << msToText(ctime) << playerTTime << mediaObj->isSeekable() << mediaObj->hasVideo();
  ui->label_player_runstats->setText( msToText(ctime)+"/"+playerTTime );
}

void MainUI::playerFileChanged(){
  ui->tool_player_next->setEnabled( ui->combo_player_list->count() > (ui->combo_player_list->currentIndex()+1) );	
  ui->tool_player_prev->setEnabled( (ui->combo_player_list->currentIndex()-1) >= 0 );
  if(ui->stackedWidget->currentWidget()!=ui->page_audioPlayer){ return; } //don't play if not in the player
  //If one is playing, so ahead and start playing the new selection
  if(ui->check_player_gotonext->isChecked() ){
    QTimer::singleShot(0,this,SLOT(playerStart()));
  }
}

//----------------------------------
// Context Menu Actions
//----------------------------------
void MainUI::OpenItem(){
  if(CItem.isEmpty()){ 
    QFileInfoList sel = getSelectedItems();
    if(sel.isEmpty()){ return; }
    else{ CItem = sel[0].absoluteFilePath(); }
    if(sel[0].isDir()){ OpenDir(); return; } //just in case - open it in a new tab
  }
  qDebug() << "Opening File:" << CItem;
  QProcess::startDetached("lumina-open \""+CItem+"\"");
  CItem.clear();
}

void MainUI::OpenItemWith(){
  if(CItem.isEmpty()){ 
    QFileInfoList sel = getSelectedItems();
    if(sel.isEmpty()){ return; }
    else{ CItem = sel[0].absoluteFilePath(); }
    if(sel[0].isDir()){ OpenDir(); return; } //just in case - open it in a new tab
  }
  qDebug() << "Opening File:" << CItem;
  QProcess::startDetached("lumina-open -select \""+CItem+"\"");	
  CItem.clear();
}

void MainUI::OpenDir(){
  if(CItem.isEmpty()){ 
    QFileInfoList sel = getSelectedItems();
    if(sel.isEmpty()){ return; }
    else{ CItem = sel[0].absoluteFilePath(); }
  }
  OpenDirs(QStringList() << CItem);	
  CItem.clear();  
}

void MainUI::RemoveItem(){
  //Only let this run if viewing the browser page
  if(ui->stackedWidget->currentWidget()!=ui->page_browser){ return; }
   if(!checkUserPerms()){ return; }
   //Get the selected items
   QStringList paths, names;
   QFileInfoList sel = getSelectedItems();
   for(int i=0; i<sel.length(); i++){
     paths << sel[i].absoluteFilePath();
     names << sel[i].fileName();
   }
   if(sel.isEmpty()){ return; } //nothing selected
  //Verify permanent removal of file/dir
  if(QMessageBox::Yes != QMessageBox::question(this, tr("Verify Removal"), tr("WARNING: This will permanently delete the file(s) from the system!")+"\n"+tr("Are you sure you want to continue?")+"\n\n"+names.join("\n"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
    return; //cancelled
  }
  //Now remove the file/dir
  qDebug() << "Delete: "<<paths;
  FODialog dlg(this);
    dlg.RemoveFiles(paths);
    dlg.exec();
}

void MainUI::RenameItem(){
  //Only let this run if viewing the browser page
  if(ui->stackedWidget->currentWidget()!=ui->page_browser){ return; }
  if(!checkUserPerms()){ return; }
  if(CItem.isEmpty()){ 
    QFileInfoList sel = getSelectedItems();
    if(sel.isEmpty()){ return; }
    else{ CItem = sel[0].absoluteFilePath(); }
  }
  QString fname = CItem;
  QString path = fname;
    fname = fname.section("/",-1); //turn this into just the file name
    path.chop(fname.length()); 	//turn this into the base directory path (has a "/" at the end)
  //Now prompt for the new filename
  bool ok = false;
  QString nname = QInputDialog::getText(this, tr("Rename File"),tr("New Name:"), QLineEdit::Normal, fname, &ok);
  if(!ok || nname.isEmpty()){ CItem.clear(); return; } //cancelled
  //Now check for a file extension and add it if necessary
  QString oext = fname.section(".",-1);
    if("."+oext == fname){ oext.clear(); } //hidden file without an extension
    else if(oext==fname){ oext.clear(); } //no extension
  QString next = nname.section(".",-1);
    if(next==nname){ next.clear(); } //no extension
  if(next.isEmpty() && !oext.isEmpty()){
    nname.append( "."+oext );
  }
  //Check if this filename already exists
  bool overwrite = QFile::exists(path+nname);
  if(overwrite){
    if(QMessageBox::Yes != QMessageBox::question(this, tr("Overwrite File?"), tr("An existing file with the same name will be replaced. Are you sure you want to proceed?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ){
      CItem.clear(); return; //cancelled
    }
  }
  //Now perform the move
  qDebug() << "Rename:" << path+fname << "->" << path+nname;
  FODialog dlg(this);
    dlg.setOverwrite(overwrite);
    dlg.MoveFiles(QStringList() << path+fname, QStringList() << path+nname);
    dlg.exec();
  CItem.clear();
}

void MainUI::FavoriteItem(){
  if(CItem.isEmpty()){ 
    QFileInfoList sel = getSelectedItems();
    if(sel.isEmpty()){ return; }
    else{ CItem = sel[0].absoluteFilePath(); }
  }
  QString fname = CItem;
  QString fullpath = fname;
    fname = fname.section("/",-1); //turn this into just the file name
  QFile::link(fullpath, favdir+fname);
  CItem.clear();
  ItemSelectionChanged();
}

void MainUI::CutItems(){
  //Only let this run if viewing the browser page
  if(ui->stackedWidget->currentWidget()!=ui->page_browser){ return; }
  if(!checkUserPerms()){ return; }
  //Get all the selected Items 
  QFileInfoList sel = getSelectedItems();
  QStringList items;
  if(sel.isEmpty()){ return; } //nothing selected
  //Format the data string
  for(int i=0; i<sel.length(); i++){
    items << "cut::::"+sel[i].absoluteFilePath();
    //sel[i] = sel[i].prepend("cut::::");
  }
  
  //Now save that data to the global clipboard
  QMimeData *dat = new QMimeData;
	dat->clear();
	dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit());
  QApplication::clipboard()->clear();
  QApplication::clipboard()->setMimeData(dat);
  ItemSelectionChanged();
}

void MainUI::CopyItems(){
  //Only let this run if viewing the browser page
  if(ui->stackedWidget->currentWidget()!=ui->page_browser){ return; }
  //Get all the selected Items 
  QFileInfoList sel = getSelectedItems();
  QStringList items;
  if(sel.isEmpty()){ return; } //nothing selected
  //Format the data string
  for(int i=0; i<sel.length(); i++){
    items << "copy::::"+sel[i].absoluteFilePath();
    //sel[i] = sel[i].prepend("copy::::");
  }
  //Now save that data to the global clipboard
  QMimeData *dat = new QMimeData;
	dat->clear();
	dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit());
  QApplication::clipboard()->clear();
  QApplication::clipboard()->setMimeData(dat);	
  ItemSelectionChanged();
}

void MainUI::PasteItems(){
  //Only let this run if viewing the browser page
  if(ui->stackedWidget->currentWidget()!=ui->page_browser){ return; }
  const QMimeData *dat = QApplication::clipboard()->mimeData();
  if(!dat->hasFormat("x-special/lumina-copied-files")){ return; } //nothing to paste
  if(!checkUserPerms()){ return; }
  QStringList cut, copy, newcut, newcopy;
  QStringList raw = QString(dat->data("x-special/lumina-copied-files")).split("\n");
  QString base = getCurrentDir();
  if(!base.endsWith("/")){ base.append("/"); }
  for(int i=0; i<raw.length(); i++){
    if(raw[i].startsWith("cut::::")){ 
	cut << raw[i].section("::::",1,50);
	newcut << base+raw[i].section("::::",1,50).section("/",-1);
    }
    else if(raw[i].startsWith("copy::::")){ 
	copy << raw[i].section("::::",1,50); 
	newcopy<< base+raw[i].section("::::",1,50).section("/",-1);
    }
  }
  bool errs = false;
  //Perform the copy/move operations
  if(!copy.isEmpty()){ 
    qDebug() << "Paste Copy:" << copy << "->" << newcopy;
    FODialog dlg(this);
      dlg.CopyFiles(copy, newcopy);
      dlg.exec();
      errs = errs || !dlg.noerrors;
  }
  if(!cut.isEmpty()){
    qDebug() << "Paste Cut:" << cut << "->" << newcut;
    FODialog dlg(this);
      dlg.MoveFiles(cut, newcut);
      dlg.exec();
      errs = errs || !dlg.noerrors;
  }
  //Modify the clipboard appropriately
  if(!errs && !cut.isEmpty()){
    //Now clear the clipboard since those old file locations are now invalid
    QApplication::clipboard()->clear(); 
    if(!copy.isEmpty()){
      //There were also files copied: save those files back into the clipboard
       QMimeData *dat = new QMimeData;
	dat->clear();
	dat->setData("x-special/lumina-copied-files", raw.filter("copy::::").join("\n").toLocal8Bit());
	QApplication::clipboard()->setMimeData(dat);
    }
  }
  ItemSelectionChanged();
	
}

void MainUI::resizeEvent(QResizeEvent *event){
  //Save the new size internally
  settings->setValue("geometry/height", event->size().height());
  settings->setValue("geometry/width", event->size().width());
}
bgstack15