FIX: selection now visible again with newer images
[enigma2-plugins.git] / movietagger / src / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2 from Screens.Screen import Screen
3 from Components.Label import Label
4 from Components.MenuList import MenuList
5 from Components.MovieList import MovieList
6 from Screens.InputBox import InputBox
7 from Screens.MessageBox import MessageBox
8 from Components.ActionMap import ActionMap
9 from Components.MultiContent import MultiContentEntryText
10 from enigma import eServiceReference, eListboxPythonMultiContent, eListbox, eServiceCenter, gFont, iServiceInformation, eServiceReference
11
12 from Tools.Directories import *
13
14 class MovieTagger(Screen):
15         skin = """
16                 <screen position="100,100" size="550,400" title="Movie Tagger" >
17                         <widget name="moviename" position="10,10" size="530,50"   font="Regular;25"/>
18                         <widget name="cTaglist" position="10,60" size="220,280"  scrollbarMode="showOnDemand"/>
19                         <widget name="aTaglist" position="240,60" size="300,280"  scrollbarMode="showOnDemand"/>
20                         <widget name="buttonred" position="6,350" size="130,40" backgroundColor="red" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
21                 <widget name="buttongreen" position="142,350" size="130,40" backgroundColor="green" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
22                 <widget name="buttonyellow" position="278,350" size="130,40" backgroundColor="yellow" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
23                 <widget name="buttonblue" position="414,350" size="130,40" backgroundColor="blue" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
24                 </screen>"""
25         currList = None
26         pretagfile = "/etc/enigma2/movietags"
27
28         def __init__(self, session, service):
29                 self.session = session
30                 self.service = service
31                 self.serviceHandler = eServiceCenter.getInstance()
32                 self.info = self.serviceHandler.info(self.service)
33
34                 self.skin = MovieTagger.skin
35                 Screen.__init__(self, session)
36                 self["moviename"] = Label(self.info.getName(self.service))
37                 self["buttonred"] = Label(_("red"))
38                 self["buttongreen"] = Label(_("green"))
39                 self["buttonyellow"] = Label(_("yellow"))
40                 self["buttonblue"] = Label(_("blue"))
41                 self["cTaglist"] = MenuList([])
42                 self["aTaglist"] = TagMenuList([])
43                 self["actions"] = ActionMap(["WizardActions","MenuActions","ShortcutActions"],
44             {
45              "back":    self.close,
46              "red":     self.keyRed,
47              "green":   self.keyGreen,
48              "yellow":  self.keyYellow,
49              "blue":    self.keyBlue,
50              "up":              self.up,
51              "down":    self.down,
52              "left":    self.left,
53              "right":   self.right,
54              }, -1)
55                 self.loadPreTags()
56                 self.updateCurrentTagList()
57                 self.updateAllTagList()
58                 self.currList =self["aTaglist"]
59                 self.onLayoutFinish.append(self.keyBlue)
60
61         def loadPreTags(self):
62                 if pathExists(self.pretagfile):
63                         fp = open(self.pretagfile,"r")
64                         t = fp.read()
65                         fp.close()
66                         self.pretags = t.replace("\n"," ").strip().split(" ")
67                         self.pretags.sort()
68                         print "pretags loaded ", self.pretags
69                 else:
70                         print "pretagsfile",self.pretagfile," does not exists"
71                         self.pretags = []
72
73         def updateCurrentTagList(self):
74                 print "updating cTagList"
75                 self.serviceHandler = eServiceCenter.getInstance()
76                 self.info = self.serviceHandler.info(self.service)
77                 self.tags = self.info.getInfoString(self.service, iServiceInformation.sTags).split(' ')
78                 self.tags.sort()
79                 self["cTaglist"].l.setList(self.tags)
80
81         def updateAllTagList(self):
82                 root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
83                 ml = MovieList(root)
84                 ml.load(root,None)
85                 xtmp = []
86                 xtmp.extend(ml.tags)
87                 self.usedTags = xtmp
88
89                 e = []+self.pretags
90                 for i in ml.tags:
91                         try:
92                                 self.pretags.index(i)
93                         except ValueError:
94                                 e.append(i)
95
96                 taglist = []
97                 for i in e:
98                                 res = [ i ]
99                                 res.append(MultiContentEntryText(pos=(5, 0), size=(500, 25), font=0, text=i))
100                                 if self.isUsedTag(i):
101                                         res.append(MultiContentEntryText(pos=(220, 0),size=(61, 86), font=1,text="X",color=0x00FFFF00))
102                                 if self.isUserTag(i) :
103                                         res.append(MultiContentEntryText(pos=(240, 0),size=(61, 86), font=1,text="X",color=0x00FF0000))#red
104                                 if self.isPreTag(i):
105                                         res.append(MultiContentEntryText(pos=(260, 0),size=(61, 86), font=1,text="X",color=0x000000FF))#blue
106
107                                 taglist.append(res)
108
109                 taglist.sort()
110                 self["aTaglist"].l.setList(taglist)
111
112         def addTag(self,tagname):
113                 try:
114                         self.tags.index(tagname)
115                 except ValueError:
116                         self.tags.append(tagname)
117                         if len(self.tags) >1:
118                                 self.setTags(" ".join(self.tags))
119                         else:
120                                 self.setTags(tagname)
121                 self.updateCurrentTagList()
122                 self.updateAllTagList()
123
124
125         def removeTag(self,tagname):
126                 newtags = []
127                 for i in self.tags:
128                         if i is not tagname:
129                                 newtags.append(i)
130                 self.setTags(" ".join(newtags))
131                 self.updateCurrentTagList()
132                 self.updateAllTagList()
133
134
135         def setTags(self,tagstring,service=False,userNotice=True):
136                 if service is False:
137                         serviceRef = self.service
138                 else:
139                         serviceRef = service
140
141                 service_name =serviceRef.toString().split(":")[-1]
142                 filename = service_name+".meta"
143                 metadata = self.readMETAData(filename)
144                 if metadata is not False:
145                         metadata.append(tagstring.strip())
146                         return  self.writeMETAData(filename,metadata)
147                 else:
148                         if userNotice is True:
149                                 self.session.open(MessageBox,_("cant write movietags, because no meta-file found!"), MessageBox.TYPE_ERROR)
150                         return  False
151
152
153         def readMETAData(self,filename):
154                 if pathExists(filename):
155                         fp = open(filename,"r")
156                         data = []
157                         data.append(fp.readline())
158                         data.append(fp.readline())
159                         data.append(fp.readline())
160                         data.append(fp.readline())
161                         fp.close()
162                         return data
163                 else:
164                         return False
165         def writeMETAData(self,filename,metadata):
166                 if pathExists(filename):
167                         fp = open(filename,"w")
168                         fp.write(metadata[0])
169                         fp.write(metadata[1])
170                         fp.write(metadata[2])
171                         fp.write(metadata[3])
172                         fp.write(metadata[4])
173                         fp.close()
174                         return True
175                 else:
176                         return False
177
178         def clearAllTags(self,yesno):
179                 if yesno is True:
180                         self.serviceHandler = eServiceCenter.getInstance()
181                         root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
182                         list = self.serviceHandler.list(root)
183                         tags = set()
184                         if list is None:
185                                 pass
186                         else:
187                                 while 1:
188                                         serviceref = list.getNext()
189                                         if not serviceref.valid():
190                                                 break
191                                         if serviceref.flags & eServiceReference.mustDescent:
192                                                 continue
193                                         self.setTags("",service=serviceref,userNotice=False)
194                 self.updateCurrentTagList()
195                 self.updateAllTagList()
196
197         def isUsedTag(self,tag):
198                 try:
199                         self.usedTags.index(tag)
200                         return True
201                 except ValueError:
202                         return False
203
204         def isPreTag(self,tag):
205                 try:
206                         self.pretags.index(tag)
207                         return True
208                 except ValueError:
209                         return False
210
211         def isUserTag(self,tag):
212                 if self.isPreTag(tag) is False and self.isUsedTag(tag) is True:
213                         return True
214                 else:
215                         return False
216
217         def keyRed(self):
218                 if self.currList is self["cTaglist"]:
219                         self.removeTag(self["cTaglist"].getCurrent())
220
221                 elif self.currList is self["aTaglist"]:
222                         print "adding Tag",self["aTaglist"].getCurrent()[0]
223                         self.addTag(self["aTaglist"].getCurrent()[0])
224
225         def keyGreen(self):
226                 if self.currList is self["cTaglist"]:
227                         self.session.openWithCallback(self.newTagEntered,InputBox, title=_("Whitepace will be replaced by Underscore"),windowTitle = _("enter the new Tag"))
228
229         def keyYellow(self):
230                 if  self.currList is self["aTaglist"]:
231                         self.session.openWithCallback(self.clearAllTags,MessageBox,_("clear all Tags?\n\nThis will delete ALL tags in ALL recodings!\nAre you sure?"), MessageBox.TYPE_YESNO)
232
233         def keyBlue(self):
234                 if self.currList is self["aTaglist"] or self.currList is None:
235                         self["aTaglist"].selectionEnabled(0)
236                         self["cTaglist"].selectionEnabled(1)
237                         self["buttonred"].setText(_("remove Tag"))
238                         self["buttongreen"].setText(_("add new Tag"))
239                         self["buttonyellow"].setText("")
240                         self["buttonblue"].setText(_("toggle List"))
241                         self.currList = self["cTaglist"]
242                 else:
243                         self["aTaglist"].selectionEnabled(1)
244                         self["cTaglist"].selectionEnabled(0)
245                         self["buttonred"].setText(_("add Tag"))
246                         self["buttongreen"].setText("")
247                         self["buttonyellow"].setText("clear all Tags")
248                         self["buttonblue"].setText(_("toggle List"))
249                         self.currList = self["aTaglist"]
250
251         def up(self):
252                 self.currList.up()
253
254         def down(self):
255                 self.currList.down()
256
257         def left(self):
258                 self.currList.pageUp()
259
260         def right(self):
261                 self.currList.pageDown()
262
263         def newTagEntered(self,newTag):
264                 if newTag >=0:
265                         self.addTag(newTag.strip().replace(" ","_"))
266
267 class TagMenuList(MenuList):
268         def __init__(self, list, enableWrapAround = False):
269                 MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
270                 self.l.setFont(0, gFont("Regular", 20))
271                 self.l.setFont(1, gFont("Regular", 25))
272
273         def postWidgetCreate(self, instance):
274                 MenuList.postWidgetCreate(self, instance)
275                 instance.setItemHeight(25)
276
277 def main(session, service, **kwargs):
278         try:
279                 session.open(MovieTagger, service)
280         except Exception,e:
281                 raise e
282
283 def Plugins(path,**kwargs):
284         return PluginDescriptor(name="Movie Tagger", description=_("Movie Tagger..."), where = PluginDescriptor.WHERE_MOVIELIST, fnc=main)