Author: dmeyer
Date: Sat Oct 20 05:30:35 2007
New Revision: 10002

Log:
improve the item.get function

Modified:
   trunk/core/src/beacon.py
   trunk/ui/src/audio/audioitem.py
   trunk/ui/src/directory.py
   trunk/ui/src/gui/widgets/infotext.py
   trunk/ui/src/image/imageitem.py
   trunk/ui/src/menu/gridmenu.py
   trunk/ui/src/menu/item.py
   trunk/ui/src/menu/listing.py
   trunk/ui/src/menu/mediaitem.py
   trunk/ui/src/playlist.py
   trunk/ui/src/tv/__init__.py
   trunk/ui/src/tv/favorite.py
   trunk/ui/src/tv/program.py
   trunk/ui/src/video/fxdhandler.py
   trunk/ui/src/video/playlist.py
   trunk/ui/src/video/videoitem.py

Modified: trunk/core/src/beacon.py
==============================================================================
--- trunk/core/src/beacon.py    (original)
+++ trunk/core/src/beacon.py    Sat Oct 20 05:30:35 2007
@@ -35,6 +35,7 @@
 import sys
 
 # kaa imports
+import kaa.notifier
 import kaa.beacon
 
 class ExtMap(dict):
@@ -67,14 +68,19 @@
             extmap.get('beacon:item').append(r)
     return extmap
 
+def register_attributes(info):
+    for type in info['types']:
+        if type != 'media':
+            kaa.beacon.register_file_type_attrs(type,
+               freevo_cache  = (list, kaa.beacon.ATTR_SIMPLE),
+               freevo_config = (dict, kaa.beacon.ATTR_SIMPLE),
+               last_played = (int, kaa.beacon.ATTR_SEARCHABLE))
+
 kaa.beacon.register_filter('extmap', extmap_filter)
 try:
     kaa.beacon.connect()
 except kaa.beacon.ConnectError:
     kaa.beacon.launch(verbose='all', autoshutdown=True)
 
-kaa.beacon.register_file_type_attrs('video',
-    last_played = (int, kaa.beacon.ATTR_SEARCHABLE))
-
-kaa.beacon.register_file_type_attrs('audio',
-    last_played = (int, kaa.beacon.ATTR_SEARCHABLE))
+# get db info and connect additional attributes
+kaa.beacon.get_db_info().connect(register_attributes)

Modified: trunk/ui/src/audio/audioitem.py
==============================================================================
--- trunk/ui/src/audio/audioitem.py     (original)
+++ trunk/ui/src/audio/audioitem.py     Sat Oct 20 05:30:35 2007
@@ -76,17 +76,6 @@
         return MediaItem.sort(self, mode)
 
 
-    def set_url(self, url):
-        """
-        Sets a new url to the item. Always use this function and not set 'url'
-        directly because this functions also changes other attributes, like
-        filename, mode and network_play
-        """
-        MediaItem.set_url(self, url)
-        if self.url.startswith('cdda://'):
-            self.network_play = False
-
-
     def actions(self):
         """
         return a list of possible actions on this item

Modified: trunk/ui/src/directory.py
==============================================================================
--- trunk/ui/src/directory.py   (original)
+++ trunk/ui/src/directory.py   Sat Oct 20 05:30:35 2007
@@ -62,12 +62,6 @@
 # get config object directory
 config = config.directory
 
-# register to beacon as string: on/off/auto
-kaa.beacon.register_file_type_attrs('dir',
-    freevo_cache  = (list, kaa.beacon.ATTR_SIMPLE),
-    freevo_config = (dict, kaa.beacon.ATTR_SIMPLE),
-)
-
 def find_start_string(s1, s2):
     """
     Find similar start in both strings
@@ -115,7 +109,7 @@
         self.menu_type = type
         if type == 'tv':
             type = 'video'
-            
+
         Playlist.__init__(self, parent=parent, type=type)
         self.item_menu  = None
         self.set_url(directory)
@@ -129,17 +123,74 @@
             # FIXME: no way to set this
             self.media_type = None
         self.query = None
-        
 
-    @kaa.notifier.yield_execution()
-    def _calculate_num_items(self):
+
+    def get_freespace(self):
         """
-        calculate the number of items in the directory.
+        Return free space in the directory in MB.
+        """
+        s = os.statvfs(self.filename)
+        space = (s[statvfs.F_BAVAIL] * long(s[statvfs.F_BSIZE])) / 1000000
+        space = space / 1000000
+        if space > 1000:
+            return '%s,%s' % (space / 1000, space % 1000)
+        return space
+
+
+    def get_totalspace(self):
+        """
+        Return total space in the directory in MB.
+        """
+        s = os.statvfs(self.filename)
+        space = (s[statvfs.F_BLOCKS] * long(s[statvfs.F_BSIZE])) / 1000000
+        if space > 1000:
+            return '%s,%s' % (space / 1000, space % 1000)
+        return space
+
+
+    def get_type(self):
+        """
+        Return type of the item as i18n string.
+        """
+        return _('Directory')
+
+
+    def get_cfg(self, var):
+        """
+        Return config variable value based on parent and config file.
+        """
+        value = self._mem.get(var)
+        if value is not None:
+            # memory override of that value
+            return value
+        # get config value from freevo_config
+        value = Playlist.get_cfg(self, var)
+        if value not in (None, 'auto'):
+            # value is set for this item
+            if value == 'on':
+                return True
+            if value == 'off':
+                return False
+            return value
+        if isinstance(self.parent, DirItem):
+            # return the value from the parent (auto)
+            return self.parent.get_cfg(var)
+        # auto and no parent, use config file values
+        if var == 'sort':
+            if self.menu_type == 'tv':
+                return config.tvsort
+            return config.sort
+        # config files does not know about hide_played and reverse
+        value = getattr(config, var, False)
+        if isinstance(value, bool):
+            return value
+        return self.media_type in value.split(',')
+
+
+    def set_num_items(self, listing, redraw=False):
+        """
+        Set the number of items in the directory based on the listing.
         """
-        log.info('create metainfo for %s', self.filename)
-        listing = kaa.beacon.query(parent=self.info)
-        if not listing.valid:
-            yield listing.wait()
         listing = listing.get(filter='extmap')
         mediatype = ''
         if self.media_type:
@@ -147,74 +198,39 @@
         num = 0
         for p in MediaPlugin.plugins(self.media_type):
             num += p.count(self, listing)
-        self['cache:num_play_items%s' % media_type] = num
-        self['cache:num_dir_items%s' % media_type] = 
len(listing.get('beacon:dir'))
-        self['cache:num_items%s' % media_type] = num + 
len(listing.get('beacon:dir'))
-        # update menu since we have the info now
-        # FIXME: what happens if a download is happening in that dir?
-        self.get_menustack().refresh()
-
-        
-    def __getitem__(self, key):
-        """
-        return the specific attribute
-        """
-        if key == 'type':
-            return _('Directory')
-
-        if key.startswith('num_'):
-            if self.media_type:
-                key = 'cache:' + key + '_' + self.media_type
-            num = Playlist.__getitem__(self, key)
-            if num is None:
-                self._calculate_num_items()
-            return num
+        self['cache:num_items_play%s' % media_type] = num
+        self['cache:num_items_dir%s' % media_type] = 
len(listing.get('beacon:dir'))
+        self['cache:num_items_all%s' % media_type] = num + 
len(listing.get('beacon:dir'))
+        if redraw:
+            # FIXME: what happens if a download is happening in that dir?
+            self.get_menustack().refresh()
 
-        if key in ( 'freespace', 'totalspace' ):
-            s = os.statvfs(self.filename)
-            if key == 'freespace':
-                space = s[statvfs.F_BAVAIL] * long(s[statvfs.F_BSIZE])
-            else:
-                space = s[statvfs.F_BLOCKS] * long(s[statvfs.F_BSIZE])
-            space = space / 1000000
-            if space > 1000:
-                space='%s,%s' % (space / 1000, space % 1000)
-            return space
-
-        if key.startswith('cfg:'):
-            value = self.info.get('tmp:%s' % key[4:])
-            if value is not None:
-                # tmp override of that value
-                return value
-            # get config value from freevo_config
-            value = Playlist.__getitem__(self, key)
-            if value not in (None, 'auto'):
-                # value is set for this item
-                if value == 'on':
-                    return True
-                if value == 'off':
-                    return False
-                return value
-            if isinstance(self.parent, DirItem):
-                # return the value from the parent (auto)
-                return self.parent[key]
-            # auto and no parent, use config file values
-            if key == 'cfg:sort':
-                if self.menu_type == 'tv':
-                    return config.tvsort
-                return config.sort
-            # config files does not know about hide_played and reverse
-            value = getattr(config, key[4:], False)
-            if isinstance(value, bool):
-                return value
-            return self.media_type in value.split(',')
 
-        return Playlist.__getitem__(self, key)
+    def get_num_items(self, type='all'):
+        """
+        Return number of items for the directory. Possible values
+        of type are 'all' and 'play'.
+        """
+        key = 'cache:num_items_%s' % type
+        if self.media_type:
+            key += '_' + self.media_type
+        num = Playlist.get(self, key)
+        if num is not None:
+            return num
+        log.info('create metainfo for %s', self.filename)
+        # FIXME: make sure this is only called once in each iteration and
+        listing = kaa.beacon.query(parent=self.info)
+        if not listing.valid:
+            listing.wait().connect(self.set_num_items, redraw=True)
+            return None
+        self.set_num_items(listing, redraw=False)
+        return get_num_items(type)
 
 
-    # eventhandler for this item
     def eventhandler(self, event):
-
+        """
+        Eventhandler for a directory item.
+        """
         if self.item_menu == None:
             return Playlist.eventhandler(self, event)
 
@@ -234,7 +250,7 @@
 
             self.media_type = self.menu_type = type
             # deactivate autoplay but not save it
-            self['tmp:autoplay_single_item'] = False
+            self['mem:autoplay_single_item'] = False
             self.item_menu.autoselect = False
             self.browse()
             OSD_MESSAGE.post('%s view' % type)
@@ -242,7 +258,7 @@
 
         if event == DIRECTORY_TOGGLE_HIDE_PLAYED:
             self['cfg:hide_played'] = not self['cfg:hide_played']
-            self['tmp:autoplay_single_item'] = False
+            self['mem:autoplay_single_item'] = False
             self.item_menu.autoselect = False
             self.browse()
             if self['cfg:hide_played']:
@@ -265,7 +281,7 @@
         play = Action(_('Play all files in directory'), self.play)
 
         if self['num_items']:
-            if self['cfg:autoplay_items'] and not self['num_dir_items']:
+            if self['cfg:autoplay_items'] and not self['num_items:dir']:
                 items = [ play, browse ]
             else:
                 items = [ browse, play ]
@@ -277,7 +293,7 @@
             a.parameter(random=True)
             items.append(a)
 
-        if self['num_dir_items']:
+        if self['num_items:dir']:
             a = Action(_('Recursive random play all items'), self.play)
             a.parameter(random=True, recursive=True)
             items.append(a)
@@ -341,7 +357,7 @@
                 # the changed signal will be called when the listing
                 # is ready and this will trigger browse again.
                 return
-                
+
         listing = self.query.get(filter='extmap')
 
         #

Modified: trunk/ui/src/gui/widgets/infotext.py
==============================================================================
--- trunk/ui/src/gui/widgets/infotext.py        (original)
+++ trunk/ui/src/gui/widgets/infotext.py        Sat Oct 20 05:30:35 2007
@@ -82,7 +82,7 @@
 
     def __getattr(self, attr):
         """
-        wrapper for __getitem__ to return the attribute as string or
+        wrapper for item.get to return the attribute as string or
         an empty string if the value is 'None'
         """
         if attr[:4] == 'len(' and attr[-1] == ')':

Modified: trunk/ui/src/image/imageitem.py
==============================================================================
--- trunk/ui/src/image/imageitem.py     (original)
+++ trunk/ui/src/image/imageitem.py     Sat Oct 20 05:30:35 2007
@@ -48,7 +48,7 @@
     An item for image files
     """
     type = 'image'
-    
+
     def __init__(self, url, parent, duration = config.image.viewer.duration):
         MediaItem.__init__(self, parent)
         self.user_stop = False
@@ -57,19 +57,13 @@
         self.duration = duration
 
 
-    def __getitem__(self, key):
+    def get_geometry(self):
         """
-        Return the specific attribute as string or an empty string
+        Return width x height of the image or None
         """
-        if key == 'geometry':
-            if self['width'] and self['height']:
-                return '%sx%s' % (self['width'], self['height'])
-            return ''
-
-        # if key == 'date':
-        # date could be time.strptime(t, '%Y:%m:%d %H:%M:%S')
-
-        return MediaItem.__getitem__(self, key)
+        if self.get('width') and self.get('height'):
+            return '%sx%s' % (self.get('width'), self.get('height'))
+        return None
 
 
     def actions(self):

Modified: trunk/ui/src/menu/gridmenu.py
==============================================================================
--- trunk/ui/src/menu/gridmenu.py       (original)
+++ trunk/ui/src/menu/gridmenu.py       Sat Oct 20 05:30:35 2007
@@ -148,7 +148,7 @@
             else:
                 self.selected = 
self.choices[self.selected_row][self.selected_col]
 
-        self.selected_id  = self.selected.__id__()
+        self.selected_id  = self.selected.get_id()
 
         # Find Which columns/rows to draw, the next update
         if self.selected_col-self.base_col > self.cols-1:

Modified: trunk/ui/src/menu/item.py
==============================================================================
--- trunk/ui/src/menu/item.py   (original)
+++ trunk/ui/src/menu/item.py   Sat Oct 20 05:30:35 2007
@@ -65,6 +65,7 @@
         self.name = u''
         self.description  = ''
         self.info = {}
+        self._mem = {}
         self._image = None
         self.menu = None
         self.parent = None
@@ -86,7 +87,7 @@
     image = property(_get_image, _set_image, None, 'image object')
 
 
-    def __id__(self):
+    def get_id(self):
         """
         Return a unique id of the item. This id should be the same when the
         item is rebuild later with the same information
@@ -190,29 +191,110 @@
         return False
 
 
-    def __getitem__(self, attr):
+    def get_name(self):
+        """
+        Return name of the item.
+        """
+        return self.name
+
+
+    def get_cfg(self, var):
+        """
+        Return stored config variable value.
+        """
+        cfg = self.info.get('freevo_config', {})
+        return cfg.get(var)
+
+
+    def get_cache(self, var):
+        """
+        Return stored cache variable value.
+        """
+        # freevo_config attribute in beacon
+        mtime, cache = self.info.get('freevo_cache', ( 0, {} ))
+        if mtime == self.info.get('mtime'):
+            return cache.get(var)
+        # cache not up-to-date, delete it
+        self.info['freevo_cache'] = [ self.info.get('mtime'), {} ]
+        return None
+
+
+    def get(self, attr):
         """
         Return the specific attribute
         """
         if attr[:7] == 'parent(' and attr[-1] == ')' and self.parent:
             return self.parent[attr[7:-1]]
+
         if attr[:4] == 'len(' and attr[-1] == ')':
             value = self[attr[4:-1]]
             if value == None or value == '':
                 return 0
             return len(value)
-        if attr == 'name':
-            return self.name
+
+        if attr in self._mem:
+            # temp memory override
+            return self._mem.get(attr)
+
+        if attr.find(':') > 0:
+            # get function with parameter
+            keys = attr.split(':')
+            func = getattr(self, 'get_' + keys[0], None)
+            if func is not None:
+                return func(*keys[1:])
+        else:
+            # get function without parameter
+            func = getattr(self, 'get_' + attr, None)
+            if func is not None:
+                return func()
+
+        # try beacon
         r = self.info.get(attr)
-        if r in (None, ''):
-            r = getattr(self, attr, None)
-        return r
+        if r not in (None, ''):
+            return r
+        # try item attribute
+        # TODO: is this needed?
+        return getattr(self, attr, None)
+
+
+    def __getitem__(self, attr):
+        """
+        Return the specific attribute
+        """
+        return self.get(attr)
 
 
     def __setitem__(self, key, value):
         """
         set the value of 'key' to 'val'
         """
+        if key.startswith('mem:'):
+            # temp setting only in memory
+            self._mem[key[4:]] = value
+            return
+
+        if key.startswith('cfg:'):
+            # freevo_config attribute in beacon
+            key = key[4:]
+            cfg = self.info.get('freevo_config', {})
+            cfg[key] = value
+            if key in self._mem:
+                # remove mem setting
+                del self._mem[key]
+            # set again to notify beacon
+            self.info['freevo_config'] = cfg
+            return
+
+        if key.startswith('cache:'):
+            # freevo_config attribute in beacon
+            mtime, cache = self.info.get('freevo_cache', ( 0, {} ))
+            if mtime != self.info.get('mtime'):
+                cache = {}
+            cache[key[6:]] = value
+            # set again to notify beacon
+            self.info['freevo_cache'] = [ mtime, cache ]
+            return
+
         self.info[key] = value
 
 

Modified: trunk/ui/src/menu/listing.py
==============================================================================
--- trunk/ui/src/menu/listing.py        (original)
+++ trunk/ui/src/menu/listing.py        Sat Oct 20 05:30:35 2007
@@ -89,7 +89,7 @@
             return self.select(self.selected)
 
         for c in self.choices:
-            if c.__id__() == self.selected_id:
+            if c.get_id() == self.selected_id:
                 # item with the same id is there, use it
                 return self.select(c)
         if self.choices:
@@ -125,7 +125,7 @@
                 return False
             self.selected = item
             self.selected_pos = self.choices.index(item)
-            self.selected_id  = self.selected.__id__()
+            self.selected_id  = self.selected.get_id()
             return True
         # select relative
         p = min(max(0, self.selected_pos + item), len(self.choices) - 1)

Modified: trunk/ui/src/menu/mediaitem.py
==============================================================================
--- trunk/ui/src/menu/mediaitem.py      (original)
+++ trunk/ui/src/menu/mediaitem.py      Sat Oct 20 05:30:35 2007
@@ -84,8 +84,7 @@
         if self.mode == 'file':
             # The url is based on a file. We can search for images
             # and extra attributes here
-            self.network_play = False
-            self.filename     = self.url[7:]
+            self.filename = self.url[7:]
             self.files.append(self.filename)
 
             # FIXME: this is slow. Maybe handle this in the gui code
@@ -99,15 +98,14 @@
         else:
             # Mode is not file, it has to be a network url. Other
             # types like dvd are handled inside the derivated class
-            self.network_play = True
-            self.filename     = ''
+            self.filename = ''
             if not self.name:
                 self.name = self.info.get('title')
             if not self.name:
                 self.name = str_to_unicode(self.url)
 
 
-    def format_time(self, time, hours=False):
+    def _format_time(self, time, hours=False):
         """
         Format time string
         """
@@ -116,93 +114,43 @@
         return '%02d:%02d' % (time / 60, time % 60)
 
 
-    def __getitem__(self, attr):
+    def get_length(self, style='clock'):
         """
-        return the specific attribute
+        Return the length of the item as formated unicode string.
         """
-        if attr.startswith('cfg:'):
-            # freevo_config attribute in beacon
-            if not self.info.get('freevo_config'):
-                return None
-            return self['freevo_config'].get(attr[4:])
+        try:
+            if style == 'clock':
+                return self._format_time(self.info.get('length'))
+            if style == 'min':
+                return '%d min' % (int(self.info.get('length')) / 60)
+            raise AttributeError('unknown length style %s' % style)
+        except ValueError:
+            return ''
 
-        if attr.startswith('cache:'):
-            # freevo_config attribute in beacon
-            if not self.info.get('freevo_cache'):
-                return None
-            mtime, cache = self.info.get('freevo_cache')
-            if mtime == self.info.get('mtime'):
-                return cache.get(attr[6:])
-            # cache not up-to-date, delete it
-            self.info['freevo_cache'] = [ self.info.get('mtime'), {} ]
-            return
-            
-        if attr == 'length':
-            try:
-                return self.format_time(self.info.get('length'))
-            except ValueError:
-                return ''
 
-        if attr == 'length:min':
+    def get_elapsed(self, style='clock'):
+        """
+        Return the elapsed time of the item. If style is percent the
+        return value is an integer.
+        """
+        # FIXME: handle elapsed > length
+        if style == 'clock':
             try:
-                return '%d min' % (int(self.info.get('length')) / 60)
+                return self._format_time(self.elapsed)
             except ValueError:
-                return ''
-
-        if attr  == 'elapsed':
-            # FIXME: handle elapsed > length
-            return self.format_time(self.elapsed)
-
-        if attr == 'elapsed:percent':
-            if not hasattr(self, 'elapsed'):
-                return 0
+                return None
+        if style == 'percent':
             try:
                 length = int(self.info.get('length'))
+                if not hasattr(self, 'elapsed') or not lengt:
+                    return 0
+                return min(100 * self.elapsed / length, 100)
             except ValueError:
                 return 0
-            if not length:
-                return 0
-            return min(100 * self.elapsed / length, 100)
-
-        if attr in self.fxdinfo:
-            # FIXME: remove this variable and try to make it work using tmp
-            # variables in beacon (see video/fxdhandler.py)
-            return self.fxdinfo.get(attr)
-
-        return Item.__getitem__(self, attr)
-
-
-    def __setitem__(self, attr, value):
-        """
-        Set attribute to value.
-        """
-        if attr.startswith('cfg:'):
-            # freevo_config attribute in beacon
-            key = attr[4:]
-            if not self.info.get('freevo_config'):
-                self.info['freevo_config'] = {}
-            self.info['freevo_config'][key] = value
-            if self.info.get('tmp:%s' + key):
-                # remove tmp setting
-                self.info['tmp:%s' + key] = None
-            # FIXME: work sround Beacon bug!!!
-            self.info['freevo_config'] = dict(self.info['freevo_config'])
-            return
-
-        if attr.startswith('cache:'):
-            # freevo_config attribute in beacon
-            if not self.info.get('freevo_cache') or \
-                   self.info.get('freevo_cache')[0] != self.info.get('mtime'):
-                self.info['freevo_cache'] = [ self.info.get('mtime'), {} ]
-            self.info['freevo_cache'][1][attr[6:]] = value
-            # FIXME: work sround Beacon bug!!!
-            self.info['freevo_cache'] = self.info['freevo_cache'][:]
-            return
-
-        return Item.__setitem__(self, attr, value)
+        raise AttributeError('unknown length style %s' % style)
 
 
-    def __id__(self):
+    def get_id(self):
         """
         Return a unique id of the item. This id should be the same when the
         item is rebuild later with the same informations
@@ -273,7 +221,7 @@
         """
         # update value
         dbvar = 'cfg:%s' % var.lower()
-        current = MediaItem.__getitem__(self, dbvar) or 'auto'
+        current = MediaItem.get_cfg(self, var.lower()) or 'auto'
         current = choices[(choices.index(current) + 1) % len(choices)]
         self[dbvar] = current
         # change name
@@ -289,8 +237,7 @@
         """
         items = []
         for i, name, values, descr in self.get_configure_items():
-            dbvar = 'cfg:%s' % i.lower()
-            current = MediaItem.__getitem__(self, dbvar) or 'auto'
+            current = MediaItem.get_cfg(self, i.lower()) or 'auto'
             action = ActionItem(name + '\t'  + current, self,
                                 self._set_configure_var, descr)
             action.parameter(var=i, name=name, choices=list(values))

Modified: trunk/ui/src/playlist.py
==============================================================================
--- trunk/ui/src/playlist.py    (original)
+++ trunk/ui/src/playlist.py    Sat Oct 20 05:30:35 2007
@@ -222,13 +222,13 @@
         return True
 
 
-    def __getitem__(self, attr):
+    def get(self, attr):
         """
         return the specific attribute
         """
         if not self._playlist_valid:
             self._playlist_create_items()
-        return MediaItem.__getitem__(self, attr)
+        return MediaItem.get(self, attr)
 
 
     def actions(self):

Modified: trunk/ui/src/tv/__init__.py
==============================================================================
--- trunk/ui/src/tv/__init__.py (original)
+++ trunk/ui/src/tv/__init__.py Sat Oct 20 05:30:35 2007
@@ -43,12 +43,27 @@
 tvserver = freevo.ipc.Instance('freevo').tvserver
 
 class Info(Item):
-    def __getitem__(self, key):
-        if key in ('comingup', 'running'):
-            return getattr(tvserver.recordings, key)
-        if key == 'recordserver':
-            return tvserver.recordings.server
-        return Info.__getitem__(self, key)
+
+    def get_comingup(self):
+        """
+        Return list of recordings scheduled.
+        """
+        return tvserver.recordings.comingup
+
+
+    def get_running(self):
+        """
+        Return list of recordings currently running.
+        """
+        return tvserver.recordings.running
+
+
+    def get_recordserver(self):
+        """
+        Return recordserver ipc connection.
+        """
+        return tvserver.recordings.server
+
 
 
 class TVMenu(MainMenuItem):
@@ -72,7 +87,7 @@
     """
     Plugin interface to integrate the tv module into Freevo
     """
-        
+
     def items(self, parent):
         """
         return the tv menu

Modified: trunk/ui/src/tv/favorite.py
==============================================================================
--- trunk/ui/src/tv/favorite.py (original)
+++ trunk/ui/src/tv/favorite.py Sat Oct 20 05:30:35 2007
@@ -71,7 +71,7 @@
         self.id = 0
         self.start = float(0)
         self.stop = float(1440*60)-1
-        
+
         if isinstance(fav, ProgramItem):
             #check if already a favorite
             f = tvserver.favorites.get(fav.title, fav.channel, fav.start, 
fav.stop)
@@ -82,9 +82,9 @@
                 self.days = [ day ]
                 self.name = self.title = fav.title
                 self.channels = [ fav.channel]
-            else:  
-                # there is already a existing ipc Favorite object 
-                fav = f      
+            else:
+                # there is already a existing ipc Favorite object
+                fav = f
         if isinstance(fav, freevo.ipc.tvserver.Favorite):
             # created with ipc Favorite object
             self.name = self.title = fav.title
@@ -96,31 +96,43 @@
                 self.start, self.stop = self._str_to_time(t)
 
 
-    def __getitem__(self, key):
+    def get_start(self):
         """
-        return the specific attribute as string or an empty string
+        Return start time as formated unicode string.
         """
-        if key == 'date':
-            if self.days == 'ANY':
-                return 'ANY'
-            else:
-                days = ', '.join(['%s' % DAY_NAMES[d] for d in self.days])
-                return days
-        if key == 'channel':
-            if self.channels == 'ANY':
-                return 'ANY'
-            else:
-                channels = ', '.join(['%s' % chan for chan in self.channels])
-                return channels
-        if key == 'time':
-                return self['start'] + u' - ' + self['stop']
-        if key == 'start':
-            return unicode(time.strftime(config.tv.timeformat,
-                                         time.gmtime(self.start)))
-        if key == 'stop':
-            return unicode(time.strftime(config.tv.timeformat,
-                                         time.gmtime(self.stop)))
-        return Item.__getitem__(self, key)
+        return unicode(time.strftime(config.tv.timeformat, 
time.localtime(self.start)))
+
+
+    def get_stop(self):
+        """
+        Return stop time as formated unicode string.
+        """
+        return unicode(time.strftime(config.tv.timeformat, 
time.localtime(self.stop)))
+
+
+    def get_time(self):
+        """
+        Return start time and stop time as formated unicode string.
+        """
+        return self.get_start + u' - ' + self.get_stop()
+
+
+    def get_date(self):
+        """
+        Return day(s) of week as formated unicode string.
+        """
+        if self.days == 'ANY':
+            return _('ANY')
+        return ', '.join(['%s' % DAY_NAMES[d] for d in self.days])
+
+
+    def get_channel(self):
+        """
+        Return channel(s) for this favorite.
+        """
+        if self.channels == 'ANY':
+            return _('ANY')
+        return ', '.join(['%s' % chan for chan in self.channels])
 
 
     def actions(self):
@@ -135,12 +147,12 @@
         show a submenu for this item
         """
         items = []
-        
+
         if self.new:
             items.append(ActionItem(_('Add favorite'), self, self.add))
         else:
             items.append(ActionItem(_('Remove favorite'), self, self.remove))
-        
+
         items.append(ActionItem(_('Change day'), self, self.change_days))
         items.append(ActionItem(_('Change channel'), self, 
self.change_channels))
         action = ActionItem(_('Change start time'), self, self.change_time)
@@ -180,8 +192,8 @@
         if result != tvserver.favorites.SUCCESS:
             text = _('Remove favorite Failed')+(': %s' % result)
         else:
-            text = _('"%s" has been removed from you favorites') % self.title  
  
-            MessageWindow(text).show()    
+            text = _('"%s" has been removed from you favorites') % self.title
+            MessageWindow(text).show()
         self.get_menustack().back_one_menu()
 
     @kaa.notifier.yield_execution()
@@ -203,7 +215,7 @@
             action = ActionItem(dayname, self, self.handle_change)
             action.parameter('days', dayname)
             items.append(action)
-            
+
         s = Menu(self, items, type = 'tv favorite menu')
         s.submenu = True
         s.infoitem = self
@@ -214,13 +226,13 @@
         action = ActionItem('ANY', self, self.handle_change)
         action.parameter('channels', 'ANY')
         items.append(action)
-        
+
         list = kaa.epg.get_channels(sort=True)
         for chan in list:
             action = ActionItem(chan.name, self, self.handle_change)
             action.parameter('channels', chan.name)
             items.append(action)
-            
+
         s = Menu(self, items, type = 'tv favorite menu')
         s.submenu = True
         s.infoitem = self
@@ -242,14 +254,14 @@
             action = ActionItem(showtime, self, self.handle_change)
             action.parameter(startstop, newtime)
             items.append(action)
-            
+
         s = Menu(self, items, type = 'tv favorite menu')
         s.submenu = True
         s.infoitem = self
         self.get_menustack().pushmenu(s)
 
     def handle_change(self, item, value):
-        
+
         info = None
         infovalue = None
         if item == 'days':
@@ -288,7 +300,7 @@
 
         if not self.new:
             self.modify([(info, infovalue)])
-            
+
         self.get_menustack().back_one_menu()
 
     def _time_to_str(self):
@@ -299,7 +311,7 @@
     def _str_to_time(self, t):
         # internal regexp for time format
         _time_re = re.compile('([0-9]*):([0-9]*)-([0-9]*):([0-9]*)')
-        
+
         m = _time_re.match(t).groups()
         start = float(m[0])*3600 + float(m[1])*60
         stop  = float(m[2])*3600 + float(m[3])*60

Modified: trunk/ui/src/tv/program.py
==============================================================================
--- trunk/ui/src/tv/program.py  (original)
+++ trunk/ui/src/tv/program.py  Sat Oct 20 05:30:35 2007
@@ -65,7 +65,7 @@
         Item.__init__(self, parent)
         self.start = program.start
         self.stop  = program.stop
-        
+
         if isinstance(program, kaa.epg.Program):
             # creation form epg Program object
             self.channel = program.channel.name
@@ -79,33 +79,33 @@
             self.genre = ''
             # TODO: add ratings support
             self.ratings = ''
-            
-        
+
+
         elif isinstance(program, freevo.ipc.tvserver.Recording):
             # creation form ipc Recoring object
             self.channel = program.channel
             if program.description.has_key('title'):
                 self.title = program.description['title']
                 self.name  = program.description['title']
-            else: 
-                self.name = self.title = _(u'Unknown') 
-             
+            else:
+                self.name = self.title = _(u'Unknown')
+
             if program.description.has_key('subtitle'):
                 self.subtitle = program.description['subtitle']
-            else:               
+            else:
                 self.subtitle = ''
             if program.description.has_key('episode'):
                 self.episode = program.description['episode']
-            else:               
+            else:
                 self.episode = ''
-            # TODO: check if this is also available    
+            # TODO: check if this is also available
             self.description = ''
             # TODO: add catergory/genre support
             self.categories = ''
             self.genre = ''
             # TODO: add ratings support
-            self.rating = ''                      
-                        
+            self.rating = ''
+
     def __unicode__(self):
         """
         return as unicode for debug
@@ -132,45 +132,59 @@
             return 1
         if isinstance(other, ProgramItem) and self.channel != other.channel:
             return 1
-        if isinstance(other, kaa.epg.Program) and self.channel != 
other.channel.name:   
+        if isinstance(other, kaa.epg.Program) and self.channel != 
other.channel.name:
             return 1
-    
+
         return self.title != other.title or \
                self.start != other.start or \
-               self.stop  != other.stop 
-              
-               
-
-    def __getitem__(self, key):
-        """
-        return the specific attribute as string or an empty string
-        """
-        if key == 'start':
-            return unicode(time.strftime(config.tv.timeformat,
-                                         time.localtime(self.start)))
-        if key == 'stop':
-            return unicode(time.strftime(config.tv.timeformat,
-                                         time.localtime(self.stop)))
-        if key == 'date':
-            return unicode(time.strftime(config.tv.dateformat,
-                                         time.localtime(self.start)))
-        if key == 'time':
-            return self['start'] + u' - ' + self['stop']
-        if key == 'channel':
-            return self.channel
+               self.stop  != other.stop
+
+
+
+    def get_start(self):
+        """
+        Return start time as formated unicode string.
+        """
+        return unicode(time.strftime(config.tv.timeformat, 
time.localtime(self.start)))
+
+
+    def get_stop(self):
+        """
+        Return stop time as formated unicode string.
+        """
+        return unicode(time.strftime(config.tv.timeformat, 
time.localtime(self.stop)))
+
+
+    def get_time(self):
+        """
+        Return start time and stop time as formated unicode string.
+        """
+        return self.get_start + u' - ' + self.get_stop()
+
+
+    def get_date(self):
+        """
+        Return date as formated unicode string.
+        """
+        return unicode(time.strftime(config.tv.dateformat, 
time.localtime(self.start)))
 
-        return Item.__getitem__(self, key)
+
+    def get_channel(self):
+        """
+        Return channel object.
+        """
+        return self.channel
 
 
     ### Submenu
-    
+
     def actions(self):
         """
         return a list of possible actions on this item.
         """
         return [ Action(_('Show program menu'), self.submenu) ]
 
-    
+
     def reload_submenu(self):
         """
         reload function for the submenu
@@ -180,26 +194,26 @@
             self.get_menustack()[-1].set_items(items)
         else:
             self.get_menustack().back_one_menu()
-        
+
 
     def get_menuitems(self):
         """
         create a list of actions for the submenu
         """
-        
+
         # check if this is a recording
         self.scheduled = tvserver.recordings.get(self.channel,
-                                                 self.start, 
+                                                 self.start,
                                                  self.stop)
         # check if this is a favorite
-        self.favorite = tvserver.favorites.get(self.title, 
+        self.favorite = tvserver.favorites.get(self.title,
                                                self.channel,
                                                self.start,
-                                               self.stop)   
-        
+                                               self.stop)
+
         # empty item list
         items = []
-        
+
         # scheduled for recording
         if self.scheduled and not self.scheduled.status in 
('deleted','missed'):
                 if self.start < time.time() + 10  \
@@ -215,16 +229,16 @@
                         items.append(ActionItem(txt, self, self.remove))
                     else:
                         # still in the future
-                        txt =  _('Remove recording')   
+                        txt =  _('Remove recording')
                         items.append(ActionItem(txt, self, self.remove))
-                    
+
         # not scheduled for recording
         elif self.stop > time.time():
             # not in the past, can still be scheduled
             txt = _('Schedule for recording')
             items.append(ActionItem(txt, self, self.schedule))
-        
-        
+
+
         # this items are only shown from inside the TVGuide:
         if self.additional_items:
             # Show all programm on this channel
@@ -236,7 +250,7 @@
             # Search for more of this program
             txt = _('Search for more of this program')
             items.append(ActionItem(txt, self, self.search_similar))
-        
+
         # Add the menu for handling favorites
         if self.favorite:
             txt = _('Edit favorite')
@@ -245,15 +259,15 @@
             items.append(ActionItem(txt, self, self.remove_favorite))
         else:
             txt = _('Add favorite')
-            items.append(ActionItem(txt, self, self.add_favorite))    
-        
-        return items    
-    
-    
+            items.append(ActionItem(txt, self, self.add_favorite))
+
+        return items
+
+
     def submenu(self, additional_items=False):
         """
         show a submenu for this item
-        
+
         There are some items, that are only created if 'additional_items'
         is set to TRUE, this items are useful in the TVGuide.
         """
@@ -261,8 +275,8 @@
         # get the item list
         items = self.get_menuitems()
         # create the menu
-        s = Menu(self, items, 
-                 type = 'tv program menu', 
+        s = Menu(self, items,
+                 type = 'tv program menu',
                  reload_func=self.reload_submenu)
         s.submenu = True
         s.infoitem = self
@@ -287,8 +301,8 @@
             msg = _('Scheduling failed: %s') % result
         MessageWindow(msg).show()
         self.get_menustack().back_one_menu()
-                       
-        
+
+
     @kaa.notifier.yield_execution()
     def remove(self):
         """
@@ -329,16 +343,16 @@
         # FIXME: the percent values need to be calculated
         # cmenu.table = (15, 15, 70)
         self.get_menustack().pushmenu(cmenu)
-   
-   
+
+
     def watch_channel(self):
         MessageWindow('Not implemented yet').show()
-        
+
 
     def watch_recording(self):
         MessageWindow('Not implemented yet').show()
 
-    
+
     @kaa.notifier.yield_execution()
     def search_similar(self):
         """
@@ -348,9 +362,9 @@
             # we need the tvserver for this
             MessageWindow(_('TVServer not running')).show()
             return
-        # time tuple representing the future    
+        # time tuple representing the future
         future = (int(time.time()), sys.maxint)
-        # create an empty list for ProgramItems    
+        # create an empty list for ProgramItems
         items = []
         # query the epg database in background
         query_data = kaa.epg.search(title=self.title, time=future)
@@ -361,30 +375,30 @@
         query_data.sort(lambda a,b:cmp(a.start,b.start))
         for prog in query_data:
             items.append(ProgramItem(prog, self))
-        # create the submenu from this        
+        # create the submenu from this
         resmenu = Menu(self.title, items, type = 'tv program menu')
-        self.get_menustack().pushmenu(resmenu)   
-                
+        self.get_menustack().pushmenu(resmenu)
+
 
     def add_favorite(self):
-        """ 
+        """
         Create a new FavoriteItem and open its submenu
         """
         favorite.FavoriteItem(self, self).submenu()
-        
-        
+
+
     def edit_favorite(self):
-        """ 
+        """
         Create a FavoriteItem for a existing favorite
         and open its submenu to edit this item
         """
         favorite.FavoriteItem(self, self.favorite).submenu()
-            
-    
+
+
     def remove_favorite(self):
         """
-        Create a FavoriteItem for a existing favorite 
+        Create a FavoriteItem for a existing favorite
         and delete this favorite.
         """
         favorite.FavoriteItem(self, self.favorite).remove()
-        
+

Modified: trunk/ui/src/video/fxdhandler.py
==============================================================================
--- trunk/ui/src/video/fxdhandler.py    (original)
+++ trunk/ui/src/video/fxdhandler.py    Sat Oct 20 05:30:35 2007
@@ -111,7 +111,7 @@
         return None
 
     item = VideoItem(files[0], parent)
-    # Bad hack but works. We can't use the tmp: variables in beacon because
+    # Bad hack but works. We can't use the mem: variables in beacon because
     # multiple items based n the same file can have different info. Or maybe
     # we just ignore this. In that case, the fxdinfo code will be replaced by
     # an in beacon solution.

Modified: trunk/ui/src/video/playlist.py
==============================================================================
--- trunk/ui/src/video/playlist.py      (original)
+++ trunk/ui/src/video/playlist.py      Sat Oct 20 05:30:35 2007
@@ -38,9 +38,9 @@
 class VideoPlaylist(Playlist):
     type = 'video'
 
-    def __id__(self):
+    def get_id(self):
         """
         Return a unique id of the item. This id should be the same when the
         item is rebuild later with the same informations
         """
-        return ''.join([ c.__id__() for c in self.choices ])
+        return ''.join([ c.get_id() for c in self.choices ])

Modified: trunk/ui/src/video/videoitem.py
==============================================================================
--- trunk/ui/src/video/videoitem.py     (original)
+++ trunk/ui/src/video/videoitem.py     Sat Oct 20 05:30:35 2007
@@ -67,7 +67,7 @@
 
 class VideoItem(MediaItem):
     type = 'video'
-    
+
     def __init__(self, url, parent):
         MediaItem.__init__(self, parent)
         self.user_stop = False
@@ -98,7 +98,7 @@
             # get informations for recordings
             show_name = (self.name, '', self.info['episode'], \
                          self.info['subtitle'])
-        elif VIDEO_SHOW_REGEXP_MATCH(self.name) and not self.network_play:
+        elif VIDEO_SHOW_REGEXP_MATCH(self.name):
             # split tv show files based on regexp
             show_name = VIDEO_SHOW_REGEXP_SPLIT(self.name)
             if show_name[0] and show_name[1] and show_name[2] and show_name[3]:
@@ -126,11 +126,10 @@
         """
         Sets a new url to the item. Always use this function and not set 'url'
         directly because this functions also changes other attributes, like
-        filename, mode and network_play
+        filename and mode
         """
         MediaItem.set_url(self, url)
         if self.url.startswith('dvd://') or self.url.startswith('vcd://'):
-            self.network_play = False
             if self.info.filename:
                 # dvd on harddisc, add '/' for xine
                 self.url = self.url + '/'
@@ -148,23 +147,28 @@
             # dvd iso
             self.mode     = 'dvd'
             self.url      = 'dvd' + self.url[4:] + '/'
-            
+
         # start name parser by setting name to itself
         self.set_name(self.name)
 
 
-    def __getitem__(self, key):
+    def get_geometry(self):
         """
-        return the specific attribute
+        Return width x height of the image or None
         """
-        if key == 'geometry' and self.info['width'] and self.info['height']:
-            return '%sx%s' % (self.info['width'], self.info['height'])
+        if self.get('width') and self.get('height'):
+            return '%sx%s' % (self.get('width'), self.get('height'))
+        return None
 
-        if key == 'aspect' and self.info['aspect']:
-            aspect = str(self.info['aspect'])
-            return aspect[:aspect.find(' ')].replace('/', ':')
 
-        return MediaItem.__getitem__(self, key)
+    def get_aspect(self):
+        """
+        Return aspect as string or None if unknown
+        """
+        if key == 'aspect' and self.info.get('aspect'):
+            aspect = str(self.info.get('aspect'))
+            return aspect[:aspect.find(' ')].replace('/', ':')
+        return None
 
 
     # ------------------------------------------------------------------------

-------------------------------------------------------------------------
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems?  Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to