summaryrefslogtreecommitdiff
path: root/vdr_menu.c
blob: 015b22d6bf005937444c9d9008eddaad926449a4 (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
/*!
 * \file   vdr_menu.c
 * \brief  Implements menu handling for browsing media libraries within VDR
 *
 * \version $Revision: 1.27 $ * \date    $Date$
 * \author  Ralf Klueber, Lars von Wedel, Andreas Kellner, Wolfgang Rohdewald
 * \author  Responsible author: $Author$
 *
 * $Id$
 */

#include <stdio.h>
#include <assert.h>

#include <typeinfo>
#include <string>
#include <vector>

#include <menuitems.h>
#include <tools.h>
#include <config.h>
#include <plugin.h>

#if VDRVERSNUM >= 10307
#include <interface.h>
#include <skins.h>
#endif

#include "mg_setup.h"
#include "vdr_menu.h"
#include "vdr_player.h"
#include "mg_incremental_search.h"
#include "mg_thread_sync.h"
#include "i18n.h"

#include "mg_tools.h"
#include "mg_sel_gd.h"

void
mgStatus::OsdCurrentItem(const char* Text)
{
	cOsdItem* i = main->Get(main->Current());
	if (!i) return;
	mgAction * a = dynamic_cast<mgAction *>(i);
	if (!a)
		mgError("mgStatus::OsdCurrentItem expected an mgAction*");
	if (a)
		a->TryNotify();
}

void Play(mgSelection *sel, bool enter)
{
	mgSelection *s = GenerateSelection(sel);
	if (s->ordersize()==0)
		s->InitDefaultOrder(1);
	if (enter)
		s->enter();
	s->skipItems(0);	// make sure we start with a valid item
	if (s->empty()) 	// no valid item exists
	{
		delete s;
		return;
	}
	mgPlayerControl *c = PlayerControl ();
	if (c)
		c->NewPlaylist (s);
	else
		cControl::Launch (new mgPlayerControl (s));
}

mgSelection*
GenerateSelection(const mgSelection* s)
{
	return new mgSelectionGd(s);
}

//! \brief queue the selection for playing, abort ongoing instant play
void
mgMainMenu::PlayQueue()
{
	queue_playing=true;
	instant_playing=false;
	Play(playselection());
}

//! \brief queue the selection for playing, abort ongoing queue playing
void
mgMainMenu::PlayInstant(bool enter)
{
	instant_playing=true;
	Play(selection(),enter);
}

bool
mgMainMenu::SwitchSelection()
{
	UseNormalSelection();
	mgSelection* newsel = getSelection(Current());
	if (newsel->ordersize()>0)
	{
		newsel->CopyKeyValues(selection());
		newsel->Activate();
		m_current_selection = Current();
		newposition = selection()->getPosition();
		SaveState();
		return true;
	}
	else
	{
		Message1(tr("Order is undefined"),"");
		return false;
	}
}

void mgMainMenu::setSelection(unsigned int idx,mgSelection *s)
{
	if (idx>=selections.size())
		mgError("mgMainMenu::getSelection(%u): selections.size() is %d",
				idx,selections.size());
	delete selections[idx];
	selections[idx] = s;
}

mgSelection* mgMainMenu::getSelection(unsigned int idx)
{
	if (idx>=selections.size())
		mgError("mgMainMenu::getSelection(%u): selections.size() is %d",
				idx,selections.size());
	return selections[idx];
}

void
mgMainMenu::CollectionChanged(string name,bool added)
{
    delete moveselection;
    moveselection = NULL;
    forcerefresh = true; // TODO brauchen wir das?
    if (name == play_collection)
    {
	playselection()->clearCache();
	mgPlayerControl *c = PlayerControl();
	if (c)
	   c->ReloadPlaylist();
	else if (added)
	   PlayQueue();
    }
    if (CollectionEntered(name) || selection()->isCollectionlist())
       selection()->clearCache();
}

bool
mgMainMenu::ShowingCollections()
{
    return (UsingCollection && selection ()->orderlevel () == 0);
}


bool
mgMainMenu::DefaultCollectionSelected()
{
    string this_sel = trim(selection ()->getCurrentValue());
    return (ShowingCollections () && this_sel == default_collection);
}

bool
mgMainMenu::CollectionEntered(string name)
{
    if (!UsingCollection) return false;
    if (selection()->orderlevel()==0) return false;
    return trim(selection ()->getKeyItem(0)->value()) == name;
}


mgMenu *
mgMainMenu::Parent ()
{
    if (Menus.size () < 2)
        return NULL;
    return Menus[Menus.size () - 2];
}


mgAction* 
mgMenu::GenerateAction(const mgActions action,mgActions on)
{
	mgAction *result = actGenerate(action);
	if (result)
	{
		result->SetMenu(this);
		if (!result->Enabled(on))
		{
			delete result;
			result=NULL;
		}
	}
	return result;
}

eOSState
mgMenu::ExecuteAction(const mgActions action,mgActions on)
{
    mgAction *a = GenerateAction (action,on);
    if (a)
    {
    	a->Execute ();
    	delete a;
	return osContinue;
    }
    return osUnknown;
}


mgPlayerControl *
PlayerControl ()
{
    mgPlayerControl *result = NULL;
    cControl *control = cControl::Control ();
    if (control && typeid (*control) == typeid (mgPlayerControl))
// is there a running MP3 player?
        result = static_cast < mgPlayerControl * >(control);
    return result;
}


mgMenu::mgMenu ()
{
    m_osd = NULL;
    m_parent_index=-1;
    TreeRedAction = actNone;
    TreeGreenAction = actNone;
    TreeYellowAction = actNone;
    TreeBlueAction = actNone;
    CollRedAction = actNone;
    CollGreenAction = actNone;
    CollYellowAction = actNone;
    CollBlueAction = actNone;
}


// ----------------------- mgMainMenu ----------------------


void
mgMainMenu::DumpSelections(mgValmap& nv)
{
	for (unsigned int idx=0;idx<selections.size();idx++)
	{
		mgSelection *s = selections[idx];
		if (!s) 
			mgError("DumpSelections:selection[%u] is 0",idx);
		char prefix[20];
		sprintf(prefix,"order%u",idx);
		s->DumpState(nv,prefix);
	}
}

void
mgMainMenu::SaveState()
{
    char *oldfile;
    char *newfile;
    char *statefile;
    mgValmap nmain("MainMenu");
    mgValmap nsel("tree");
    mgValmap ncol("collection");
    asprintf(&oldfile,"%s/muggle.state.old",cPlugin::ConfigDirectory ("muggle"));
    asprintf(&newfile,"%s/muggle.state.new",cPlugin::ConfigDirectory ("muggle"));
    asprintf(&statefile,"%s/muggle.state",cPlugin::ConfigDirectory ("muggle"));
    FILE *f = fopen(newfile,"w");
    if (!f) 
    {
	    if (!m_save_warned)
		    mgWarning("Cannot write %s",newfile);
	    m_save_warned=true;
	    goto err_exit;
    }
    nmain.put(default_collection,"DefaultCollection");
    nmain.put(UsingCollection,"UsingCollection");
    nmain.put(int(Menus.front()->TreeRedAction),"TreeRedAction");
    nmain.put(int(Menus.front()->TreeGreenAction),"TreeGreenAction");
    nmain.put(int(Menus.front()->TreeYellowAction),"TreeYellowAction");
    nmain.put(int(Menus.front()->CollRedAction),"CollRedAction");
    nmain.put(int(Menus.front()->CollGreenAction),"CollGreenAction");
    nmain.put(int(Menus.front()->CollYellowAction),"CollYellowAction");
    nsel.put(m_current_selection,"CurrentSelection");
    DumpSelections(nsel);
    m_collectionsel->DumpState(ncol,"collection");
    nmain.Write(f);
    nsel.Write(f);
    ncol.Write(f);
    fclose(f);
    rename(statefile,oldfile);
    rename(newfile,statefile);
err_exit:
    free(oldfile);
    free(newfile);
    free(statefile);
}

mgMainMenu::mgMainMenu ():cOsdMenu ("",25)
{
    m_Status = new mgStatus(this);
    m_message = 0;
    moveselection = 0;
    m_root = 0;
    external_commands = 0;
    queue_playing=false;
    instant_playing=false;
    m_save_warned=false;
    play_collection = tr("play");
    mgValmap nsel("tree");
    mgValmap ncol("collection");
    mgValmap nmain("MainMenu");

    // define defaults for values missing in state file:
    nsel.put(true,"FallThrough");
    nmain.put(play_collection,"DefaultCollection");
    nmain.put(false,"UsingCollection");
    nmain.put(int(actAddThisToCollection),"TreeRedAction");
    nmain.put(int(actInstantPlay),"TreeGreenAction");
    nmain.put(int(actToggleSelection),"TreeYellowAction");
    nmain.put(int(actAddThisToCollection),"CollRedAction");
    nmain.put(int(actInstantPlay),"CollGreenAction");
    nmain.put(int(actToggleSelection),"CollYellowAction");
    nmain.put(0,"CurrentOrder");


    // load values from state file
    char *b;
    asprintf(&b,"%s/muggle.state",cPlugin::ConfigDirectory ("muggle"));
    FILE *f = fopen(b,"r");
    free(b);
    if (f) {
	    nsel.Read(f);
	    ncol.Read(f);
	    nmain.Read(f);
	    fclose(f);
    }

    // get values from mgValmaps
    InitMapFromSetup(nsel);
    InitMapFromSetup(ncol);
    LoadSelections(nsel);
    default_collection = nmain.getstr("DefaultCollection");
    UsingCollection = nmain.getbool("UsingCollection");
    selections[m_current_selection]->CreateCollection(default_collection);
    if (default_collection!=play_collection)
	    selections[m_current_selection]->CreateCollection(play_collection);
    m_collectionsel = GenerateSelection();
    m_collectionsel->InitFrom ("order0",ncol);
    m_collectionsel->MakeCollection();
    m_playsel = GenerateSelection();
    m_playsel->InitFrom("order0",ncol);
    m_playsel->MakeCollection();
    // initialize
    if (m_playsel->orderlevel()!=1)
    {
    	m_playsel->leave_all();
    	m_playsel->enter(play_collection);
    }
    mgSelection *s = selections[m_current_selection];
    s->CopyKeyValues(s);
    s->Activate();
    unsigned int posi = selection()->gotoPosition();
    LoadExternalCommands();	// before AddMenu()
    m_root = new mgTree;
    m_root->TreeRedAction = mgActions(nmain.getuint("TreeRedAction"));
    m_root->TreeGreenAction = mgActions(nmain.getuint("TreeGreenAction"));
    m_root->TreeYellowAction = mgActions(nmain.getuint("TreeYellowAction"));
    m_root->CollRedAction = mgActions(nmain.getuint("CollRedAction"));
    m_root->CollGreenAction = mgActions(nmain.getuint("CollGreenAction"));
    m_root->CollYellowAction = mgActions(nmain.getuint("CollYellowAction"));
    AddMenu (m_root,posi);
    forcerefresh = false;
}

void
mgMainMenu::AddSelection()
{
	selections.push_back(GenerateSelection());
	newposition = selections.size()-1;
}

void
mgMainMenu::DeleteSelection()
{
	mgSelection *o = selections[Current()];
	delete o;
	selections.erase(selections.begin()+Current());
}

void
mgMainMenu::LoadSelections(mgValmap& nv)
{
	for (unsigned int idx=0;idx<1000;idx++) 
	{
		char prefix[10];
		sprintf(prefix,"order%u",idx);
		mgSelection *s = GenerateSelection();
		s->InitFrom(prefix,nv);
		if (s->ordersize())
			selections.push_back(s);
		else
		{
			delete s;
			break;
		}
	}
	if (selections.size()==0)
	{
		for (unsigned int i=1; i<100;i++)
		{
			mgSelection* s=GenerateSelection();
			if (s->InitDefaultOrder(i))
				selections.push_back(s);
			else
			{
				delete s;
				break;
			}
		}
	}
    	m_current_selection = nv.getuint("CurrentSelection");
	if (m_current_selection >= selections.size())
		m_current_selection=0;
}

void
mgMainMenu::LoadExternalCommands()
{
// Read commands for collections in etc. /video/muggle/playlist_commands.conf
    external_commands = new cCommands ();

#if VDRVERSNUM >= 10318
    cString cmd_file = AddDirectory (cPlugin::ConfigDirectory ("muggle"),
        "playlist_commands.conf");
    mgDebug (1, "mgMuggle::Start: %d Looking for file %s",VDRVERSNUM, *cmd_file);
    bool have_cmd_file = external_commands->Load (*cmd_file);
#else
    const char *
        cmd_file = (const char *) AddDirectory (cPlugin::ConfigDirectory ("muggle"),
        "playlist_commands.conf");
    mgDebug (1, "mgMuggle::Start: %d Looking for file %s",VDRVERSNUM, cmd_file);
    bool have_cmd_file = external_commands->Load ((const char *) cmd_file);
#endif

    if (!have_cmd_file)
    {
        delete external_commands;
        external_commands = NULL;
    }
}

mgMainMenu::~mgMainMenu()
{
	delete m_collectionsel;
	delete m_playsel;
	delete m_Status;
	delete moveselection;
	delete m_root;
	delete external_commands;
	for (unsigned int i=0;i<selections.size();i++)
		delete selections[i];
}

void
mgMainMenu::InitMapFromSetup (mgValmap& nv)
{
    // values from setup override saved values
    nv["Directory"] = cPlugin::ConfigDirectory ("muggle");
}

void
mgMenu::AddAction (const mgActions action, mgActions on,const bool hotkey)
{
    mgAction *a = GenerateAction(action,on);
    if (!a) return;
    const char *mn = a->MenuName();
    if (strlen(mn)==0)
	    mgError("AddAction(%d):MenuName is empty",int(action));
    if (hotkey)
    	a->SetText(osd()->hk(mn));
    else
    	a->SetText(mn);
    free(const_cast<char*>(mn));
    osd()->AddItem(a);
}


void
mgMenu::AddExternalAction(const mgActions action, const char *title)
{
    mgAction *a = GenerateAction(action,actNone);
    if (!a) return;
    a->SetText(osd()->hk(title));
    osd()->AddItem(a);
}

void
mgMainMenu::AddOrderActions(mgMenu* m)
{
    for (unsigned int idx=0;idx<selections.size();idx++)
    {
        mgSelection *o = selections[idx];
	if (!o) 
		mgError("AddOrderAction:selections[%u] is 0",idx);
    	mgAction *a = m->GenerateAction(actOrder,actNone);
    	assert(a);
	string name = o->Name(); // do not combine these 2 lines!
	const char *oname = name.c_str();
	if (strlen(oname)==0)
		oname = tr("Order is undefined");
    	a->SetText(hk(oname));
    	AddItem(a);
    }
}

void
mgMenu::AddSelectionItems (mgSelection *sel,mgActions act)
{
    sel->Activate();
    for (unsigned int i = 0; i < sel->listitems.size (); i++)
    {
    	mgAction *a = GenerateAction(act, actEntry);
	if (!a) continue;
	const char *name = a->MenuName(i+1,sel->listitems[i]);
	a->SetText(name,false);
	a->setHandle(i);
        osd()->AddItem(a);
    }
    if (osd()->ShowingCollections ())
    {
    	mgAction *a = GenerateAction(actCreateCollection,actNone);
    	if (a) 
	{
    		a->SetText(a->MenuName(),false);
    		osd()->AddItem(a);
	}
    }
}


const char*
mgMenu::HKey(const mgActions act,mgActions on)
{
    const char* result = NULL;
    mgAction *a = GenerateAction(act,on);
    if (a)
    {
        result = a->ButtonName();	
	delete a;
    }
    return result;
}

void
mgMenu::SetHelpKeys(mgActions on)
{
    mgActions r,g,y,b;
    if (osd()->UsingCollection)
    {
	r = CollRedAction;
	g = CollGreenAction;
	y = CollYellowAction;
	b = CollBlueAction;
    }
    else
    {
	r = TreeRedAction;
	g = TreeGreenAction;
	y = TreeYellowAction;
	b = TreeBlueAction;
    }
    osd()->SetHelpKeys(HKey(r,on),
			HKey(g,on),
			HKey(y,on),
			HKey(b,on));
}


void
mgMainMenu::RefreshTitle()
{
    SetTitle(Menus.back()->Title().c_str());
    Display ();
}

void
mgMenu::InitOsd (const bool hashotkeys)
{
    osd ()->InitOsd (Title(),hashotkeys);
    SetHelpKeys();	// Default, will be overridden by the single items
}


void
mgMainMenu::InitOsd (string title,const bool hashotkeys)
{
    Clear ();
    SetTitle (title.c_str());
    if (hashotkeys) SetHasHotkeys ();
}

void
mgMainMenu::AddItem(mgAction *a)
{
    cOsdItem *c = dynamic_cast<cOsdItem*>(a);
    if (!c)
	    mgError("AddItem with non cOsdItem");
    Add(c);
}

string
mgSubmenu::Title() const
{
    static char b[100];
    snprintf(b,99,tr("Commands:%s"),trim(osd()->selection()->getCurrentValue()).c_str());
    return b;
}

void
mgSubmenu::BuildOsd ()
{
    mgActions on = osd()->CurrentType();
    InitOsd ();
    if (!osd ()->Parent ())
	    return;
    AddAction(actInstantPlay,on);
    AddAction(actAddThisToCollection,on);
    AddAction(actAddThisToDefaultCollection,on);
    AddAction(actSetDefaultCollection,on);
    AddAction(actRemoveThisFromCollection,on);
    AddAction(actToggleSelection,on);
    AddAction(actDeleteCollection,on);
    AddAction(actClearCollection,on);
    AddAction(actChooseOrder,on);
    AddAction(actExportItemlist,on);
    cCommand *command;
    if (osd()->external_commands)
    {
        int idx=0;
    	while ((command = osd ()->external_commands->Get (idx)) != NULL)
        {
		if (idx>actExternalHigh-actExternal0)
		{
			mgWarning("Too many external commands");
			break;
		}
        	AddExternalAction (mgActions(idx+int(actExternal0)),command->Title());
		idx++;
	}
    }
    TreeRedAction = actSetButton;
    TreeGreenAction = actSetButton;
    TreeYellowAction = actSetButton;
    CollRedAction = actSetButton;
    CollGreenAction = actSetButton;
    CollYellowAction = actSetButton;
}

mgActions
mgMainMenu::CurrentType()
{
    mgActions result = actNone;
    cOsdItem* c = Get(Current());
    if (c)
    {
	mgAction *a = dynamic_cast<mgAction*>(c);
	if (!a)
		mgError("Found an OSD item which is not mgAction:%s",c->Text());
	result = a->Type();
    }
    return result;
}

eOSState
mgMenu::ExecuteButton(eKeys key)
{
    mgActions on = osd()->CurrentType();
    mgActions action = actNone;
    if (osd()->UsingCollection)
    	switch (key)
    	{
        	case kRed: action = CollRedAction; break;
        	case kGreen: action = CollGreenAction; break;
        	case kYellow: action = CollYellowAction; break;
        	case kBlue: action = CollBlueAction; break;
        	default: break;
        }
    else
    	switch (key)
    	{
        	case kRed: action = TreeRedAction; break;
        	case kGreen: action = TreeGreenAction; break;
        	case kYellow: action = TreeYellowAction; break;
        	case kBlue: action = TreeBlueAction; break;
        	default: break;
        }
    return ExecuteAction(action,on);
}

mgTree::mgTree()
{
  TreeBlueAction = actShowCommands;
  CollBlueAction = actShowCommands;
  m_incsearch = NULL;
  m_start_position = 0;
}

eOSState
mgMenu::Process (eKeys key)
{
    return ExecuteButton(key);
}

void
mgTree::UpdateSearchPosition()
{
  if( !m_incsearch || m_filter.empty() )
	osd()->newposition = m_start_position;
  else
	osd()->newposition = osd()->selection()->searchPosition(m_filter);
}

bool
mgTree::UpdateIncrementalSearch( eKeys key )
{
  bool result; // false if no search active and keystroke was not used

  if( !m_incsearch )
    {
      switch( key )
	{
	case k0...k9:
	  { // create a new search object as this is the first keystroke
	    m_incsearch = new mgIncrementalSearch();
	    
	    // remember the position where we started to search
	    m_start_position = osd()->Current();

	    // interprete this keystroke
	    m_filter = m_incsearch->KeyStroke( key - k0 );
	    result = true;
	    UpdateSearchPosition();
	  } break;
	default:
	  {
	    result = false;
	  }
	}
    }
  else
    { // an incremental search is already active
      switch( key )
	{
	case kBack:
	  {
	    m_filter = m_incsearch->Backspace();

	    if( m_filter.empty() )
	      { // search should be terminated, returning to the previous item
		TerminateIncrementalSearch( false );
	      }
	    else
	      { // just find the first item for the current search string
		UpdateSearchPosition();
	      }
	    result = true;
	  } break;
	case k0...k9:
	  {
	    // evaluate the keystroke
	    m_filter = m_incsearch->KeyStroke( key - k0 );	    
	    result = true;
	    UpdateSearchPosition();
	  } break;
	default:
	  {
	    result = false;
	  }
	}  
    }
  return result;
}

void mgTree::TerminateIncrementalSearch( bool remain_on_current )
{
  if( m_incsearch )
    {
      m_filter = "";
      delete m_incsearch;
      m_incsearch = NULL;

      if( remain_on_current )
	{
	  m_start_position = osd()->Current();
	}

      UpdateSearchPosition();
    }
}

string
mgTree::Title () const
{
  string title = selection ()->getListname ();

  if( !m_filter.empty() )
    {
      title += " (" + m_filter + ")";
    }

  return title;
}

void
mgTree::BuildOsd ()
{
    InitOsd (false);
    AddSelectionItems (selection());
}

void
mgMainMenu::Message1(const char *msg, const char *arg1)
{
    if (strlen(msg)==0) return;
    asprintf (&m_message, tr (msg), arg1);
}


eOSState mgMainMenu::ProcessKey (eKeys key)
{
    eOSState result = osContinue;
    if (Menus.size()<1)
	mgError("mgMainMenu::ProcessKey: Menus is empty");
    
    mgPlayerControl * c = PlayerControl ();
    if (c)
    {
        if (!c->Playing ())
	{
            	c->Shutdown ();
		if (instant_playing && queue_playing) {
			PlayQueue();
		} 
		else
		{
			instant_playing = false;
			queue_playing = false;
		}
	}
	else
        {
	  switch (key)
	      {
	    case kPause:
	      c->Pause ();
	      break;
	    case kStop:
	      if (instant_playing && queue_playing) 
		{
		  PlayQueue();
		}
	      else
		{
		  queue_playing = false;
		  c->Stop ();
		}
	      break;
	    case kChanUp:
	      c->Forward ();
	      break;
	    case kChanDn:
	      c->Backward ();
	      break;
	    default:
	      goto otherkeys;
            }
            goto pr_exit;
        }
    }
    else
      if (key==kPlay) 
	{ 
	  PlayQueue();
	  goto pr_exit;
	}
otherkeys:
    newmenu = Menus.back();           // Default: Stay in current menu
    newposition = -1;
    
    {
      mgMenu * oldmenu = newmenu;
      
       // item specific key logic:
      result = cOsdMenu::ProcessKey (key);
      
      // mgMenu specific key logic:
      if (result == osUnknown)
	result = oldmenu->Process (key);
    }
    // catch osBack for empty OSD lists . This should only happen for playlistitems
    // (because if the list was empty, no mgActions::ProcessKey was ever called)
    if (result == osBack)
    {
      // do as if there was an entry
      mgAction *a = Menus.back()->GenerateAction(actEntry,actEntry);
      if (a) 
	{
	  result = a->Back();
	  delete a;
	}
    }

// do nothing for unknown keys:
    if (result == osUnknown) 
	    goto pr_exit;

// change OSD menu as requested:
    if (newmenu == NULL)
    {
        if (Menus.size () > 1)
        {
   	    CloseMenu();
            forcerefresh = true;
        }
        else
	{
            result = osBack;	// game over
	    goto pr_exit;
	}
    }
    else if (newmenu != Menus.back ())
        AddMenu (newmenu,newposition);

    forcerefresh |= selection()->cacheIsEmpty();

    forcerefresh |= (newposition>=0);

    if (forcerefresh)
    {
    	forcerefresh = false;
	if (newposition<0) 
		newposition = selection()->gotoPosition();
        Menus.back ()->Display ();
    }
pr_exit:
    showMessage();
    return result;
}

void
mgMainMenu::CloseMenu()
{
    mgMenu* m = Menus.back();
    if (newposition==-1) newposition = m->getParentIndex();
    Menus.pop_back ();
    delete m;
}

void
mgMainMenu::showMessage()
{
    if (m_message)
    {
	showmessage(0,m_message);
	free(m_message);
	m_message = NULL;
    }
}

void
showmessage(int duration,const char * msg, ...)
{
	va_list ap;
	va_start(ap,msg);
	char buffer[200];
	vsnprintf(buffer,199,tr(msg),ap);
#if VDRVERSNUM >= 10307
	if (!duration) duration=2;
    	Skins.Message (mtInfo, buffer,duration);
    	Skins.Flush ();
#else
    	Interface->Status (buffer);
    	Interface->Flush ();
#endif
	va_end(ap);
}

void
showimportcount(unsigned int impcount,bool final=false)
{
#if 0
	// we should not write to the OSD since this is not the 
	// foreground thread. We could go thru port 2001.
	if (final)
		showmessage(1,"Import done:Imported %d items",impcount);
	else
		showmessage(2,"Imported %d items...",impcount);
#endif
}

void
mgMainMenu::AddMenu (mgMenu * m,unsigned int position)
{
    Menus.push_back (m);
    selection()->Activate();
    m->setosd (this);
    m->setParentIndex(Current());
    if (Get(Current()))
    	m->setParentName(Get(Current())->Text());
    newposition = position;
    m->Display ();
}

void
mgMenu::setosd(mgMainMenu *osd)
{
    m_osd = osd;
    m_prevUsingCollection = osd->UsingCollection;
    m_prevpos=osd->selection()->getPosition();
}

mgSubmenu::mgSubmenu()
{
    TreeBlueAction = actShowList;
    CollBlueAction = actShowList;
}

string
mgMenuOrders::Title() const
{
	return tr("Select an order");
}

void
mgMenuOrders::BuildOsd ()
{
	TreeRedAction = actEditOrder;
	TreeGreenAction = actCreateOrder;
	TreeYellowAction = actDeleteOrder;
    	InitOsd ();
	osd()->AddOrderActions(this);
}

mgMenuOrder::mgMenuOrder()
{
    m_selection=0;
    m_orgselection = 0;
}

mgMenuOrder::~mgMenuOrder()
{
    if (m_selection)
	    delete m_selection;
}

string
mgMenuOrder::Title() const
{
	return m_selection->Name();
}

void
mgMenuOrder::BuildOsd ()
{
    if (!m_orgselection)
	    m_orgselection = osd()->getSelection(getParentIndex());;
    if (!m_selection)
        m_selection = GenerateSelection(m_orgselection);
    if (m_selection->ordersize()==0)
	    m_selection->InitDefaultOrder(1);
    InitOsd ();
    m_keytypes.clear();
    m_keynames.clear();
    m_orderbycount = m_selection->getOrderByCount();
    for (unsigned int i=0;i<m_selection->ordersize();i++)
    {
	if (m_selection->getKeyType(i)==keyGdUnique)
		break;
	unsigned int kt;
	m_keynames.push_back(m_selection->Choices(i,&kt));
	m_keytypes.push_back(kt);
    }
    for (unsigned int i=0;i<m_selection->ordersize();i++)
    {
	if (m_selection->getKeyType(i)==keyGdUnique)
		break;
	char buf[20];
	sprintf(buf,tr("Key %d"),i+1);
	mgAction *a = actGenerateKeyItem(buf,(int*)&m_keytypes[i],m_keynames[i].size(),&m_keynames[i][0]);
	a->SetMenu(this);
        osd()->AddItem(a);
    }
    mgAction *a = actGenerateBoolItem(tr("Sort by count"),&m_orderbycount);
    a->SetMenu(this);
    osd()->AddItem(a);
}

bool
mgMenuOrder::ChangeSelection(eKeys key)
{
    vector <const char*> newtypes;
    newtypes.clear();
    for (unsigned int i=0; i<m_keytypes.size();i++)
    	newtypes.push_back(m_keynames[i][m_keytypes[i]]);
    mgSelection *newsel = GenerateSelection(m_orgselection);
    newsel->setKeys(newtypes);
    newsel->setOrderByCount(m_orderbycount);
    bool changed = !newsel->SameOrder(m_selection);
    if (changed)
    {
	delete m_selection;
	m_selection = newsel;
    	osd()->forcerefresh = true;
	int np = osd()->Current();
	if (key==kUp && np) np--;
	if (key==kDown) np++;
    	osd()->newposition = np;
    }
    else
	delete newsel;
    return changed;
}

void
mgMenuOrder::SaveSelection()
{
    m_selection->CopyKeyValues(osd()->selection());
    m_selection->Activate();
    osd()->setSelection(getParentIndex(),m_selection);
    m_selection = 0;
    m_orgselection = 0;
    osd()->SaveState();
}


mgTreeCollSelector::mgTreeCollSelector()
{
    TreeBlueAction = actShowList;
    CollBlueAction = actShowList;
}

mgTreeCollSelector::~mgTreeCollSelector()
{
    osd()->UsingCollection = m_prevUsingCollection;
    osd()->newposition = m_prevpos;
}

string
mgTreeCollSelector::Title () const
{ 
    return m_title;
}

void
mgTreeCollSelector::BuildOsd ()
{
    osd()->UsingCollection = true;
    mgSelection *coll = osd()->collselection();
    InitOsd ();
    coll->leave_all();
    coll->setPosition(osd()->default_collection);
    AddSelectionItems (coll,coll_action());
    osd()->newposition = coll->gotoPosition();
    cOsdItem *c = osd()->Get(osd()->newposition);
    mgAction *a = dynamic_cast<mgAction *>(c);
    a->IgnoreNextEvent = true;
}

mgTreeAddToCollSelector::mgTreeAddToCollSelector(string title)
{
    m_title = title;
}

mgTreeRemoveFromCollSelector::mgTreeRemoveFromCollSelector(string title)
{
    m_title = title;
}

void
mgMainMenu::DisplayGoto ()
{
    if (newposition >= 0)
    {
        if ((int)newposition>=Count())
	    newposition = Count() -1;
        SetCurrent (Get (newposition));
        RefreshCurrent ();
    }
    Display ();
}

void
mgMenu::Display ()
{
    BuildOsd ();
    osd ()->DisplayGoto ();
}

bool
create_question()
{
    char *b;
    asprintf(&b,tr("Create database %s?"),the_setup.DbName);
    bool result = Interface->Confirm(b);
    free(b);
    return result;
}

bool
import()
{
    if (!Interface->Confirm(tr("Import items?")))
	    return false;
    mgThreadSync *s = mgThreadSync::get_instance();
    if (!s)
	    return false;
    static char *tld_arg[] = { ".", 0};
    int res = chdir(the_setup.ToplevelDir);
    if (res)
    {
	    showmessage(2,tr("Cannot access directory %s:%d"),
			    the_setup.ToplevelDir,errno);
	    return false;
    }
    s->Sync(tld_arg);
    return true;
}