예제 #1
0
class MessageWindow(Window):

    type = 'message'

    def __init__(self, text, title='', button=False):
        Window.__init__(self)
        self.text = text
        self.title = title
        if button is not False:
            self.button = button
        else:
            self.button = Button(_('OK'))
        self._timeout_timer = None
        self.eventhandler = MessageEventHandler(self)
        return None

    def show(self, timeout=None, timeout_callback=None):
        self.timeout_callback = timeout_callback
        ret = Window.show(self)
        if timeout:

            def _MessageWindow__callback_runner():
                self.hide()
                if self.timeout_callback:
                    self.timeout_callback()
                return None

            self._timeout_timer = Task(_MessageWindow__callback_runner)
            self._timeout_timer.start(timeout)
        return ret

    def hide(self):
        if self._timeout_timer:
            self._timeout_timer.stop()
        return Window.hide(self)
예제 #2
0
파일: core.py 프로젝트: rayman18/wydev
class TimerActivator(object):
    def __init__(self, signals=('on_start', 'on_stop'), delay=2, _check=False):
        self.signals = signals
        self._timer = Task(self.handler)
        self._delay = delay
        self._sender = None
        self._check = _check
        return None

    def handler(self):
        if self._check and not self._sender.could_remove_banner():
            return None
        self._timer.stop()
        louie_send(self.signals[1], sender=self._sender)
        self._sender.tasks['tick'].stop()
        return None

    def __call__(self, func):
        def _exec(menu, *args, **kw):
            ret = None
            try:
                ret = func(menu, *args, **kw)
            except Exception, e:
                log.debug('%s', e)
            self._sender = menu
            if self._timer.running:
                self._timer.start(loop=True, consider_idle=True)
            else:
                self._timer.start(self._delay, loop=True, consider_idle=True)
                self._sender._start_timers()
                louie_send(self.signals[0], sender=self._sender)
            return ret

        return _exec
예제 #3
0
class MonitorConfigurationItem(ParametersSetupItem):
	depth = 3
	def __init__(self, *args, **kw):
		ParametersSetupItem.__init__(self, *args, **kw)
		self.refresh_task = Task(self._refresh_infos)
		Task(self._set_preview_list).start(delay=1,loop=False)
		
	def browse(self, preview=False):
		if self.menu.selected_main.__eq__(self):
			self.refresh_task.start(delay=5, loop=True, init_delay=0, consider_idle=True)
			return self.preview_list

	def _set_preview_list(self):
#		log.debug('_set_preview_list call')
		self.preview_list = [HwMonitoringItem(type_='setupitem', device='Fan'),
			HwMonitoringItem(type_='setupitem', device='Cpu'),
			HwMonitoringItem(type_='setupitem', device='Hdd'),
			CpuLoadMonitoringItem(type_='setupitem'),
			MemLoadMonitoringItem(type_='setupitem')]

	def _refresh_infos(self):
#		log.debug('_refresh_infos call')
		if self.menu.selected_main.__eq__(self):
			for i in range(len(self.preview_list)):
				self.preview_list[i].reset_view()
		else:
			self.refresh_task.stop()
예제 #4
0
 def device_activation_failed(self, dev, ssid):
     log.debug('sig DeviceActivationFailed (%s)', dev)
     for o in self._obs:
         try:
             o.device_activation_failed
         except AttributeError:
             log.debug('%r has not device_activation_failed', o)
         else:
             t = Task(o.device_activation_failed)
             t.args = (dev, ssid)
             t.start(0.5)
     return None
예제 #5
0
class TextScreenSaverMenu(ScreenSaverMenu):

	def __init__(self):
		ScreenSaverMenu.__init__(self, type='text_screensaver')
		if user_config['power']['screensaver_text_type'] == 'time':
			self.text = '%d:%02d:%02d' % tuple(localtime(time())[3:6])
			self.refresh_task = Task(self._refresh_text)
		else:
			self.text = user_config['power']['screensaver_text']
			if len(self.text) > 100:
				self.text = self.text[:100]
		self._getitems_keywords['text'] = self._get_screensaver_text
		return None

	def _get_screensaver_text(self):
		if user_config['power']['screensaver_text_type'] == 'time':
			self.text = '%d:%02d:%02d' % tuple(localtime(time())[3:6])
		return self.text

	def _refresh_text(self):
		louie_send('text', sender=self, value=self._get_screensaver_text())

	def idle(self):
		ScreenSaverMenu.idle(self)
		if user_config['power']['screensaver_text_type'] == 'time':
			self.refresh_task.start(delay=1, loop=True, init_delay=0, consider_idle=True)
		return None

	def busy(self):
		if user_config['power']['screensaver_text_type'] == 'time':
			self.refresh_task.stop()
		ScreenSaverMenu.busy(self)
		return None

	def refresh_metadata(self, title, artist, album):
		return None
예제 #6
0
class ControlModeManager(object):

    __metaclass__ = MetaSingleton

    def __init__(self):
        self._obs = []
        self._wdb = peewee_dbus
        self._wymts = self._wdb.reference('com.wyplay.wymts',
                                          '/com/wyplay/wymts',
                                          'com.wyplay.wymts')
        self._wymts_sig = self._wdb.instance('/com/wyplay/wymts')
        self._wymts_sig.signal('Connected', 's', self.connected, 0)
        self._wymts_sig.signal('Disconnected', 's', self.disconnected, 0)
        self._IsConnected = self._wymts.method('IsConnected', 's', 'b')
        self._current_mode = 'mtp_off'
        self._task_control = Task(self._set_control)
        self.startup()
        return None

    def startup(self):
        try:
            mtp = self._IsConnected('MTP')
        except:
            log.error('Error while calling IsConnected')
            PRINT_EXCEPTION()
            mtp = False
        if mtp:
            self._task_control.args = ('mtp_on', )
            self._task_control.start(0)
        return None

    def register_observer(self, obs):
        log.debug('%s registred', obs)
        self._obs.append(obs)
        return None

    def unregister_observer(self, obj):
        self._obs.remove(obj)
        return None

    def _set_control(self, mode):
        if mode != self._current_mode:
            self._current_mode = mode
            rcu, standby = mode_dict[mode]
            log.debug('setting control: mode=%s rcu=%s standby=%s', mode, rcu,
                      standby)
            for obs in self._obs:
                try:
                    obs(mode, rcu, standby)
                    log.debug('%s called', obs)
                except:
                    log.debug('calling %s failled', obs)
        else:
            log.debug('current_mode == wanted_mode == %s: nothing to do', mode)
        return None

    def connected(self, mode):
        log.debug('sig connected(%s) received', mode)
        handler = '_' + mode.lower() + '_connect'
        ref = getattr(self, handler, None)
        if ref:
            ref()
        else:
            log.warn('no handler for %s', handler)
        return None

    def disconnected(self, mode):
        log.debug('sig disconnected(%s) received', mode)
        handler = '_' + mode.lower() + '_disconnect'
        ref = getattr(self, handler, None)
        if ref:
            ref()
        else:
            log.warn('no handler for %s', handler)
        return None

    def _mtp_connect(self):
        log.debug('MTP connect')
        self._task_control.args = ('mtp_on', )
        self._task_control.start(2)
        return None

    def _mtp_disconnect(self):
        log.debug('MTP disconnect')
        self._task_control.args = ('mtp_off', )
        self._task_control.start(2)
        return None
예제 #7
0
class EpgControlWindowMenu(Menu):

    fields = ['date', 'time_slice', 'favorite_list']

    def __init__(self, grid):
        Menu.__init__(self,
                      name='EPG Control Window',
                      choices=[],
                      type='epg_control_window',
                      universe='tv')
        self.eventhandler = EpgControlWindowEventHandler(self)
        self._getitems_keywords.update({
            'date': self.get_date,
            'time_slice': self.get_time_slice,
            'favorite_list': self.get_favorite_list
        })
        self.grid = grid
        self.favorites = HiddenRoot().get_child('TV Favorites',
                                                self.grid).browse()
        self.acl = TVRootItem().get_acl(self.grid)
        if self.grid.channel_list['index'] is None:
            self.selected_favorite_pos = -1
        else:
            self.selected_favorite_pos = int(self.grid.channel_list['index'])
        self.field_dispatch = [
            self.select_date, self.select_visible_time_slice,
            self.select_favorite_list
        ]
        self.selected_field = 0
        self.start_time, self.end_time = grid.start_time, grid.end_time
        self.commit_task = Task(self._commit_changes)
        return None

    # Change fields.
    def select_field(self, value):
        if 0 <= self.selected_field + value <= len(self.fields):
            self.selected_field += value
            field_name = self.fields[self.selected_field]
            louie_send('on_control_select_%s' % field_name, sender=self)
        return None

    # Change the value of the current field.
    def select_value(self, value):
        self.field_dispatch[self.selected_field](value)
        return None

    # Select the [value]th next day, remaining on the same time slice.
    # value may be negative.
    @selective_gui_updater('date')
    def select_date(self, value):
        delta = timedelta(days=value)
        if self.grid.lower_limit <= self.start_time + delta <= self.grid.upper_limit:
            self.start_time += delta
            self.end_time += delta
            self.commit_task.start(delay=HMI_TV['zap_time'])
        return None

    # Select the [value]th next visible time slice. value may be negative.
    # Attempting to switch to the next time slice while the active one is
    # 'night' will select the 'morning' time slice on the next day.
    @selective_gui_updater('time_slice', 'date')
    def select_visible_time_slice(self, value):
        slice_count = ts.distance_to_visible_slice(self.start_time, value)
        target_start, target_end = ts.timeslice_boundaries(
            self.start_time.slice_count)
        if self.grid.lower_limit <= target_start <= self.grid.upper_limit:
            self.start_time = target_start
            self.end_time = target_end
            self.commit_task.start(delay=HMI_TV['zap_time'])
        return None

    # Return the selected favorite list.
    # (the ACL counts as a favorite list for the intents of this property)
    @property
    def selected_favorite_list(self):
        return (self.acl if self.selected_favorite_pos == -1 else
                self.favorites[self.selected_favorite_pos])

    # Change the active favorite list.
    @selective_gui_updater('favorite_list')
    def select_favorite_list(self, value):
        num_favorites = len(self.favorites)
        if not num_favorites:
            return None
        if self.selected_favorite_pos == -1:
            self.selected_favorite_pos = (0 if value > 0 else num_favorites -
                                          1)
        elif 0 <= self.selected_favorite_pos + value < num_favorites:
            self.selected_favorite_pos += value
        else:
            self.selected_favorite_pos = -1
        self.commit_task.start(delay=HMI_TV['zap_time'])
        return None

    # Commit pending time slice and channel list selections, if any.
    # Those selections are accumulated:
    #     - in (self.start_time, self.end_time) for the time slice changes,
    #     - in self.selected_favorite_list for the channel list changes,
    # and commited by commit_task after HMI_TV['zap_time'] seconds, in order
    # to achieve a quick zap-like behavior.
    def _commit_changes(self):
        grid = self.grid
        if self.selected_favorite_list != grid.channel_list:
            grid.set_channel_list(self.selected_favorite_list)
        if self.start_time != grid.start_time:
            grid.set_boundaries(self.start_time, self.end_time)
            grid.select_current_program()
        return None

    def display_info_banner(self):
        self.grid.display_info_banner()
        return None

    def show(self):
        return Menu.show(self, False)

    def get_date(self):
        return ts.get_epg_day(self.start_time).strftime(get_date_format())

    def get_time_slice(self):
        slice_id = ts.get_visible_slice_id(self.start_time)
        return ts.NAMES[slice_id]

    def get_favorite_list(self):
        return self.selected_favorite_list.name
예제 #8
0
class ZoneEventHandler(object):

    # @arg zone: tuple (xmin , xmax, ymin, ymax) (see compute_zones()).
    # @arg margin: integer representing margin out the zone.
    # 	If the zone is active, it catch mouse event in the
    # 	zone plus the external margin.
    # @arg pick_on_click: boolean: do a pick (select) while handling button0
    def __init__(self,
                 player,
                 zone,
                 margin=DEFAULT_MARGIN,
                 pick_on_click=False):
        self.player = player
        if zone is not None:
            self._zone = zone
        else:
            self._zone = (0, 0, 0, 0)
        self._margin = margin
        self._pick_on_click = pick_on_click
        self._button0_task = Task((lambda: None))
        self._button1_task = Task((lambda: None))
        self._button2_task = Task((lambda: None))
        self._button3_task = Task((lambda: None))
        self._button4_task = Task((lambda: None))
        self.handle_click = do_nothing
        self.handle_pressed = do_nothing
        self.handle_long_click = do_nothing
        return None

    def _check_zone(self, event, handler, xkey, ykey, remap_coord):
        arg = event.arg
        x = arg[xkey]
        y = arg[ykey]
        ret = self._in_zone(x, y)
        if ret:
            if remap_coord:
                zone = self._zone
                arg[xkey] = min(zone[1], max(zone[0], x))
                arg[ykey] = min(zone[3], max(zone[2], y))
            handler(arg)
        return ret

    def _in_zone(self, x, y):
        zone = self._zone
        margin = self._margin
        if zone[0] - margin <= x <= zone[1] - margin and zone[
                2] - margin <= y <= zone[3] - margin:
            return True
        return False

    def event_mouse(self, event):
        if not self._button0_task.running:
            return self._check_zone(event, self._manage_mouse, 'x', 'y', True)
        else:
            log.warn('%s Dropped because button0 task is running', event)
            return True

    def event_button0(self, event):
        return self._check_zone(event, self._manage_button0, 'start_x',
                                'start_y', False)

    def event_button1(self, event):
        if not hasattr(self, 'handle_button1'):
            return False
        self._manage_button1(event.arg)
        return True

    def event_button2(self, event):
        if not hasattr(self, 'handle_button2'):
            return False
        self._manage_button2(event.arg)
        return True

    def event_button3(self, event):
        if not hasattr(self, 'handle_button3'):
            return False
        self._manage_button3(event.arg)
        return True

    def event_button4(self, event):
        if not hasattr(self, 'handle_button4'):
            return False
        self._manage_button4(event.arg)
        return True

    def _manage_button0(self, event_arg):
        count = event_arg['count']
        if self.player._autohide_timeout:
            self.player._autohide_timeout.start()
        if self._pick_on_click:
            self._pick(event_arg)
        task = self._button0_task
        move_detected = self._check_button_move(event_arg)
        self.handle_pressed()
        if count < LONGCLIC_THRESHOLD and not move_detected:
            task.fn = self.handle_click
            task.args = ()
            task.start(BUTTONS_CLICK_TIMEOUT)
        else:
            task.fn = self._manage_long_click
            task.args = (event_arg, )
            task.start(BUTTONS_CLICK_TIMEOUT)
        return None

    def _manage_mouse(self, event_arg):
        if self.player._autohide_timeout:
            self.player._autohide_timeout.start()
        self._pick(event_arg)
        return None

    def _manage_button1(self, event_arg):
        self._button1_task.fn = self.handle_button1
        self._button1_task.start(BUTTONS_REPEAT_TIMEOUT)
        return None

    def _manage_button2(self, event_arg):
        self._button2_task.fn = self.handle_button2
        self._button2_task.start(BUTTONS_REPEAT_TIMEOUT)
        return None

    def _manage_button3(self, event_arg):
        self._button3_task.fn = self.handle_button3
        self._button3_task.start(BUTTONS_REPEAT_TIMEOUT)
        return None

    def _manage_button4(self, event_arg):
        self._button4_task.fn = self.handle_button4
        self._button4_task.start(BUTTONS_REPEAT_TIMEOUT)
        return None

    def _manage_long_click(self, event_arg):
        return None

    def _pick(self, event_arg):
        print 'ERROR: _pick() NOT IMPLEMENTED'
        return None

    # Just check if we move enougth to launch a 'move_click'
    def _check_button_move(self, event_arg):
        if abs(event_arg['x'] - event_arg['start_x']) > EPSILON:
            return True
        return abs(event_arg['y'] - event_arg['start_y']) > EPSILON
예제 #9
0
class Mix(object):

	__metaclass__ = MetaSingleton

	def __init__(self, control='Primary', id=0, card='hw:4'):
		self._mixers = dict()
		self._limiters = dict()
		self._def_control = control
		self._def_id = id
		self._def_card = card
		if architecture == 'pc':
			self._mixers['Fake'] = FakeMixer()
			self._def_control = 'Fake'
		else:
			self.add_control(control)
		events_watch(self.handle)
		self.window = SoundLevelWindow(_('Sound level'))
		self.mute_window = MuteWindow(_('Mute'))
		self._hide_task = Task(self.window.hide)
		self._hide_mute_task = Task(self.mute_window.hide)
		self._save_task = Task(user_config.save)
		self.soft_mute_flag = 0
		self.soft_mute_prev_vol = 0
		self._fill_limiters()
		self._gain = False
		self._vol_id = user_config['sound']['volume']
		self.set_volume(self._vol_id)
		self.set_mute(user_config['sound']['mute'])
		self.set_hdmi_mute(user_config['connections']['hdmi_sound'])
		self._notification()
		return None

	def handle(self, event):
		if event.name in ('VOLUME_DOWN', 'VOLUME_UP', 'MUTE'):
			getattr(self, event.name.lower())()
		return None

	# Mandatory to control sound level.
	def _switch_gain_override(self):
		try:
			gain = Mixer('Gain Override')
			gain.setmute(0)
		except ALSAAudioError:
			gain = Mixer('Gain Override', self._def_id, self._def_card)
			gain.setmute(0)
		return None

	# Should be activated when volume reach 8192 on Primary.
	def _fill_limiters(self):
		for limiter in ('Analog Limiter', 'HDMI Limiter', 'SPDIF Limiter'):
			try:
				self._limiters[limiter] = Mixer(limiter)
			except ALSAAudioError:
				self._limiters[limiter] = Mixer(limiter, self._def_id, self._def_card)
		return None

	def _notification(self):
		self.window.mute = self.get_mute()
		self.window.progress = volume_progress_dict[self._vol_id]['progress']
		if not self._hide_task.running:
			self.window.show()
		self._hide_task.start(HMI_BASE['volumewindow_duration'])
		if self.get_mute():
			self.mute_window.show()
		else:
			self._hide_mute_task.start(0)
		return None

	def add_control(self, control):
		try:
			self._mixers[control] = Mixer(control)
		except ALSAAudioError:
			self._mixers[control] = Mixer(control, self._def_id, self._def_card)
		return None

	def switch_limiters(self, val):
		log.debug('switch limiters to: %s', val)
		for name, mix in self._limiters.iteritems():
			mix.setmute(val)
		return None

	def get_volume(self, control=None):
		if not control:
			ctrl = self._def_control
		else:
			ctrl = control
		try:
			volume = self._mixers[ctrl].getvolume()[0]
			if self.soft_mute_flag:
				volume = self.soft_mute_prev_vol
		except ALSAAudioError:
			volume = 0
		return volume

	def set_volume(self, vol_id, dummy=False, control=None):
		vol_id = min(vol_id, len(volume_progress_dict) - 1)
		vol_id = max(vol_id, 0)
		volume = volume_progress_dict[vol_id]['vol']
		log.debug('vol_id:%s volume=%s', vol_id, volume)
		if volume >= 12.5:
			self._gain = True
			log.debug('gain ON')
			self.switch_limiters(0)
		else:
			self._gain = False
			log.debug('gain OFF')
			self.switch_limiters(1)
		if control:
			self._mixers[control].setvolume(int(volume))
		else:
			for name, mix in self._mixers.iteritems():
				mix.setvolume(int(volume))
		if not dummy:
			self._vol_id = vol_id
			user_config['sound']['volume'] = self._vol_id
			self._save_task.start(1)
		return None

	def get_mute(self, control=None):
		if not control:
			ctrl = self._def_control
		else:
			ctrl = control
		try:
			mute = self._mixers[ctrl].getmute()[0]
		except ALSAAudioError:
			mute = self.soft_mute_flag
		return mute

	def _soft_mute(self, mute):
		if mute and not self.soft_mute_flag:
			self.soft_mute_prev_vol = self._vol_id
			self.set_volume(0, dummy=True)
			self.soft_mute_flag = 1
		elif not mute and self.soft_mute_flag:
			self.set_volume(self.soft_mute_prev_vol)
			self.soft_mute_flag = 0
		return None

	def set_mute(self, mute, control=None):
		def secure_mute(mix, mute):
			try:
				mix.setmute(mute)
			except ALSAAudioError:
				self._soft_mute(mute)
			return None

		if control:
			secure_mute(self._mixers[control], mute)
		else:
			for name, mix in self._mixers.iteritems():
				secure_mute(mix, mute)
		user_config['sound']['mute'] = mute
		self._save_task.start(1)
		return None

	def set_hdmi_mute(self, mute):
		try:
			mix = Mixer('HDMI')
			mix.setmute(mute)
			log.debug('Set HDMI sound control to %s', mute)
			return True
		except ALSAAudioError, e:
			log.error('Impossible to set HDMI sound mute to %s <%s>', mute, e)
			return False
예제 #10
0
class Menu(object):

    _active_list = 'main_list'
    toggleable = False
    groupeable = False
    _grouped_menu = 0
    hold = False
    show_help_banner = True

    def _get_active_list(self):
        return self._active_list

    def _set_active_list(self, val):
        dc = self._active_list
        if dc != val:
            louie_send('on_%s_blur' % dc, self)
            self._active_list = val
            louie_send('on_%s_focus' % val, self)
            self.choices.advertise()
        return None

    active_list = property(_get_active_list, _set_active_list)
    del _get_active_list
    del _set_active_list

    # Set the focus on the next item_list available in available_choices,
    # if this item_list contains some items. Return True in this case
    # Return False if we are already at the end of available_choices,
    # or if no items are in the new item_list
    def focus_next(self):
        dc = self.active_list
        if dc != self.available_choices[-1]:
            idx = self.available_choices.index(dc)
            new_choice = self.available_choices[idx + 1]
            new_item_list = self.get_item_list(new_choice)
            if new_item_list:
                self.active_list = new_choice
                return True
        return False

    # Set the focus on the previous item_list available in available_choices,
    # if this item_list contains some items. Return True in this case
    # Return False if we are already at the begining of available_choices,
    # or if no items are in the new item_list
    def focus_previous(self):
        dc = self.active_list
        if dc != self.available_choices[0]:
            idx = self.available_choices.index(dc)
            new_choice = self.available_choices[idx - 1]
            new_item_list = self.get_item_list(new_choice)
            if new_item_list:
                self.active_list = new_choice
                return True
        return False

    # Set the basic attributes to Menu
    # Parameters :
    #  * name                   : menu name
    #  * choices (optional)     : list of items that will be placed in the main_list
    #  * type (optional)        : menu type (string)
    #  * universe (optional)    : universe where the menu is located (ex: 'tv', 'parameters', ...)
    def __init__(self,
                 name,
                 choices=None,
                 type='undefined',
                 universe=None,
                 timeout=None,
                 parent=None,
                 zone=None):
        self.name = name
        self.type = type
        self.universe = universe
        self.tasks = {
            'show_help': Task(self._show_help),
            'hide_help': Task(self._hide_help),
            'error_timeout': Task(self._error_canceler)
        }
        if not hasattr(self, 'zone'):
            self.zone = zone
        self.item_lists_dict = {}
        if choices is None:
            choices = []
        self.set_items(choices, self.active_list)
        self.available_choices = [self.active_list]
        self.item = None
        self._getitems_keywords = dict(
            menu_name=(lambda: self.name),
            item_name=self._get_item_name,
            main_list=(lambda: self.get_item_list('main_list')),
            menu_type_name=(lambda: self.type),
            parent_item_name=self._get_parent_item_name)
        if not hasattr(self, 'eventhandler'):
            self.eventhandler = MenuEventHandler(self)
        self.children = []
        self.parent = parent
        if timeout is not None:
            self._autohide_timeout = Task(self._autohide)
            self._autohide_timeout.delay = timeout
            self._autohide_timeout.ival = timeout
        else:
            self._autohide_timeout = None
        return None

    # Show the "unauthorized operation" pictogram.
    # It will auto-disappear after HMI_BASE["error_signal_delay"] seconds.
    def _error_spawner(self, prefix=None):
        error_timeout = self.tasks['error_timeout']
        if not error_timeout.running:
            txt = 'error_signal'
            if prefix is not None:
                txt = prefix + '_' + txt
            louie_send(txt, sender=self)
        error_timeout.start(HMI_BASE['error_signal_delay'])
        return None

    # Hide the "unauthorized operation" pictogram.
    def _error_canceler(self):
        louie_send('end_error_signal', sender=self)
        return None

    def __repr__(self):
        return '<%s::%s @%x>' % (self.__class__.__name__, self.type, id(self))

    def _get_item_name(self):
        sel = self.selected
        if sel:
            return sel.name
        return ''

    def _get_parent_item_name(self):
        item = self.item
        if item and item.type != 'main':
            return item.name
        return u''

    # Reload the menu. Feel free to provide your own implementation.
    def reload_func(self):
        self.show_help()
        return None

    # Flush the menu (delete all items), then set items contained in choices,
    # and name, type and universe specified
    # Parameters (same as __init__) :
    #  * name (optional)     : new name for the menu
    #  * choices (optional)  : new items for the menu main_list
    #  * type (optional)     : new type for the menu
    #  * universe (optional) : new universe for the menu
    def reset(self, name='', choices=None, type=None, universe=None):
        self.name = name
        self.item = None
        self.universe = universe
        self._active_list = 'main_list'
        if type is not None:
            self.type = type
        self.item_lists_dict = dict()
        if choices:
            self.set_items(choices, self.active_list)
        else:
            self.set_items([], self.active_list)
        return None

    def __getitem__(self, name):
        return self._getitems_keywords.get(name, (lambda: None))()

    def clear(self):
        if self not in pygui_globs['menustack']:
            for k, v in self.item_lists_dict.iteritems():
                self.item_lists_dict[k].set_items([])
                v.selected = False
                v.menu = None
                v._data = None
        return None

    def get_item_list(self, list_name=None):
        if not list_name:
            return self.item_lists_dict[self.active_list]
        return self.item_lists_dict[list_name]

    # Return a list of items related to 'list_name'. If 'list_name' is not registred, it is added
    def get_create_item_list(self, list_name):
        if list_name not in self.item_lists_dict:
            self.add_item_list(list_name)
        return self.get_item_list(list_name)

    # Helper to easily get the active choices
    choices = property(get_item_list)

    # Add an ItemList item_list to the menu and fill it with items
    # Parameters :
    #  * list_name        : name of the ItemList created
    #  * items (optional) : list of Items to fill item_list
    def add_item_list(self, list_name, items=None):
        if list_name is not None:
            if not items:
                self.item_lists_dict[list_name] = ItemList(self, [], list_name)
            else:
                self.item_lists_dict[list_name] = ItemList(
                    self, items, list_name)
        return None

    def del_item_list(self, list_name):
        del self.item_lists_dict[list_name]
        return None

    # Set/replace the items in this menu.
    # If position is -1, no item is selected
    # Parameters :
    #  * items                : list of items that will be placed in ItemList 'list_name'
    #  * list_name (optional) : name of the ItemList where items will be set
    #  * position (optional)  : selected item's index (integer)
    #                           0 -> begining
    #                           -1 -> end
    def set_items(self, items, list_name='main_list', position=-1):
        item_list = self.get_create_item_list(list_name)
        item_list.set_items(items, position)
        if list_name == self._active_list:
            self._logselected()
        return None

    # Return the Item selected in 'active_list'
    def _get_selected(self):
        return self.get_item_list().selected

    # Set the Item refered to value in 'active_list'
    def _set_selected(self, value):
        self.get_item_list().select(value)
        return None

    selected = property(_get_selected, _set_selected)
    del _get_selected
    del _set_selected

    # Return the Item selected position in 'active_list'
    def _get_selected_pos(self):
        return self.get_item_list().selected_pos

    selected_pos = property(_get_selected_pos)
    del _get_selected_pos

    def _logselected(self):
        global logselected
        try:
            if logselected is not None:
                logselected.write('%s\n' % self.selected.name)
                logselected.flush()
            else:
                if 'logselected' in plugins:
                    logselected = UDPSender()
        except:
            pass
        return None

    # Select item in list_name
    # Parameters :
    #  * item                 : refering to the wanted item
    #                           Can be an Item instance or an integer (1 means the next item in ItemList)
    #  * list_name (optional) : name of the ItemList where item is located.
    #                           If list_name isn't provided, the currently active list is used.
    #  * force_pos (optional) :  select the item at this position (an Item can also be passed, but discouraged)
    #
    # Careful: the display engine uses Items' wymedia IDs or URIs to recognize which is selected.
    def select(self, item, list_name=None, force_pos=False):
        if self._autohide_timeout:
            log.debug('%s autohide postponed', self)
            self._autohide_timeout.start()
        if not list_name:
            val = self.get_item_list(self._active_list).select(item, force_pos)
        else:
            val = self.get_item_list(list_name).select(item, force_pos)
        if val is not False:
            self._logselected()
        return val

    # Delete item located in list_name
    # Parameters :
    #  * item : Item instance
    #  * list_name (optional) : name of the ItemList where item is located
    def delete_item(self, item, list_name=None):
        if not list_name:
            actual_list = self.get_item_list(self.active_list)
        else:
            actual_list = self.get_item_list(list_name)
        actual_list.remove(item)
        return None

    def toggle_menu(self):
        stack = pygui_globs['menustack']
        from pygui.menu.players.core import Player
        for menu in stack.menus_stack:
            if isinstance(menu, Player):
                menu.toggle_menu()
                break
        return None

    def _show_help(self):
        if user_config['base']['help_banner']:
            if not self.tasks['hide_help'].running:
                louie_send('show_help', self)
                self.hide_help()
        return None

    # Show the help banner. Once shown, it will auto-hide after HMI_BASE['helpbanner_duration'] seconds.
    def show_help(self):
        if self.show_help_banner:
            self.tasks['show_help'].start(0.5)
        return None

    def _hide_help(self):
        if user_config['base']['help_banner'] != 1:
            louie_send('hide_help', self)
        return None

    # Hide the help banner.
    def hide_help(self):
        if self.show_help_banner:
            self.tasks['hide_help'].start(HMI_BASE['helpbanner_duration'])
        return None

    def show(self, hide_previous_menu=True, timeout=None):
        pygui_globs['menustack'].push_menu(self, hide_previous_menu)
        self.show_help()
        if self.parent:
            try:
                self.parent.children.append(self)
            except Exception, e:
                log.error('Cannot append %s to %s.children', self, self.parent)
                PRINT_EXCEPTION(e)
        if timeout is not None:
            if self._autohide_timeout is None:
                self._autohide_timeout = Task(self._autohide)
            self._autohide_timeout.delay = timeout
            self._autohide_timeout.ival = timeout
        if self._autohide_timeout:
            self._autohide_timeout.start()
        return None
예제 #11
0
class PSFreedomConfigurationItem(ParametersSetupItem):
    depth = 3

    def __init__(self, *args, **kw):
        global glob_usb_mode_dict, glob_current_usb_mode, glob_ps3_fw_dict, glob_current_ps3_fw, glob_usb_mode_orig
        self._get_psfreedom_conf()
        glob_usb_mode_orig = glob_current_usb_mode
        ParametersSetupItem.__init__(self, *args, **kw)
        self.USBModeItem = PSFreedomCommonSetupItem(name=_(
            'Mode: %s' % (glob_usb_mode_dict[glob_current_usb_mode])),
                                                    type_='setupitem',
                                                    menu=self.menu,
                                                    display_type=None,
                                                    action=self._set_usb_mode)
        self.PS3FwVersionItem = PSFreedomCommonSetupItem(
            name=_('PS3 firmware: v%s' %
                   (glob_ps3_fw_dict[glob_current_ps3_fw])),
            type_='setupitem',
            menu=self.menu,
            display_type=None,
            action=self._set_ps3_fw_version)
        self.PSFreedomStatusItem = PSFreedomCommonSetupItem(name=_(
            'Status: %s' % (self._get_psfreedom_status())),
                                                            type_='setupitem',
                                                            menu=self.menu,
                                                            display_type=None,
                                                            action=None)
        self.SaveSettingsItem = ActionItem(name=_('Save settings'),
                                           type_='setupitem',
                                           display_type=None,
                                           action=self._save_usb_mode)
        self.refresh_task = Task(self._refresh_status)

    def browse(self, preview=False):
        global glob_usb_mode_dict, glob_current_usb_mode, glob_ps3_fw_dict, glob_current_ps3_fw
        if self.menu.selected_main.__eq__(self):
            self.preview_list = [self.USBModeItem]
            if glob_current_usb_mode == 1:
                self.preview_list.append(self.PS3FwVersionItem)
                self.preview_list.append(self.PSFreedomStatusItem)
            self.preview_list.append(self.SaveSettingsItem)
            self.refresh_task.start(delay=5,
                                    loop=True,
                                    init_delay=0,
                                    consider_idle=True)
            return self.preview_list

    def _refresh_status(self):
        try:
            if self.menu.selected_main.__eq__(self):
                if glob_current_usb_mode == 1:
                    self.PSFreedomStatusItem.name = _(
                        'Status: %s' % (self._get_psfreedom_status()))
                    self.PSFreedomStatusItem.reset_view()
            else:
                self.refresh_task.stop()
        except:
            self.refresh_task.stop()

    def _get_psfreedom_status(self):
        Status = 'NONE'
        try:
            if os.path.exists('/proc/psfreedom/status'):
                status_file = os.popen('cat /proc/psfreedom/status')
                line = status_file.readline()
                status_file.close()
                Status = line.replace('\n', '')
        except:
            pass
        return Status

    def _find_key(self, dic, val):
        return [k for k, v in dic.iteritems() if v == val][0]

    def _get_psfreedom_conf(self):
        global glob_current_usb_mode, glob_ps3_fw_dict, glob_current_ps3_fw
        try:
            if not os.path.exists('/wymedia/usr/etc/usbcable.conf'):
                os.system('echo Mode MTP > /wymedia/usr/etc/usbcable.conf')
                os.system('echo %s >> /wymedia/usr/etc/usbcable.conf' %
                          (glob_ps3_fw_dict[0]))
            conf_file = os.popen('cat /wymedia/usr/etc/usbcable.conf')
            lines = conf_file.readlines()
            conf_file.close()
            for line in lines:
                line = line.replace('\n', '')
                if line == '':
                    continue
                elif 'Mode MTP' in line:
                    glob_current_usb_mode = 0
                elif 'Mode PS3' in line:
                    glob_current_usb_mode = 1
                else:
                    glob_current_ps3_fw = self._find_key(
                        glob_ps3_fw_dict, line)
                    if glob_current_ps3_fw is None:
                        glob_current_ps3_fw = 0
        except:
            pass

    def _set_usb_mode(self):
        global glob_usb_mode_dict, glob_current_usb_mode
        if glob_current_usb_mode == 0:
            glob_current_usb_mode = 1
        else:
            glob_current_usb_mode = 0
        self.USBModeItem.name = _('Mode: %s' %
                                  (glob_usb_mode_dict[glob_current_usb_mode]))
        self.USBModeItem.reset_view()
        self.USBModeItem.reload_center_list(True)

    def _set_ps3_fw_version(self):
        global glob_ps3_fw_dict, glob_current_ps3_fw
        glob_current_ps3_fw = glob_current_ps3_fw + 1
        if glob_current_ps3_fw >= 9:
            glob_current_ps3_fw = 0
        if os.path.exists('/proc/psfreedom/fw_version'):
            os.system('echo %s > /proc/psfreedom/fw_version' %
                      (glob_ps3_fw_dict[glob_current_ps3_fw]))
        self.PS3FwVersionItem.name = _('PS3 firmware: v%s' %
                                       (glob_ps3_fw_dict[glob_current_ps3_fw]))
        self.PS3FwVersionItem.reset_view()
        self._refresh_status()

    def _save_usb_mode(self):
        global glob_current_usb_mode, glob_current_ps3_fw, glob_usb_mode_orig
        try:
            if glob_current_usb_mode == 0:
                os.system('echo Mode MTP > /wymedia/usr/etc/usbcable.conf')
                os.system('echo %s >> /wymedia/usr/etc/usbcable.conf' %
                          (glob_ps3_fw_dict[glob_current_ps3_fw]))
                self._update_initng(0)
            else:
                os.system('echo Mode PS3 > /wymedia/usr/etc/usbcable.conf')
                os.system('echo %s >> /wymedia/usr/etc/usbcable.conf' %
                          (glob_ps3_fw_dict[glob_current_ps3_fw]))
                self._update_initng(1)
            if glob_usb_mode_orig != glob_current_usb_mode:
                w = ConfirmWindow(text=_(
                    'Modifications will take effect after reboot.\nDo you want to reboot now ?'
                ),
                                  confirm_action=self._reinit_box,
                                  buttons=[
                                      Button(_('Yes'), False),
                                      Button(_('No'), True)
                                  ])
                w.show()
        except:
            pass

    def _update_initng(self, mode):
        try:
            psfreedom_found = 0
            initng_file = open('/etc/initng/runlevel/default.runlevel', 'rw+')
            lines = initng_file.readlines()
            initng_file.seek(0, 0)
            new_lines = []
            for line in lines:
                if mode == 0:
                    if 'daemon/wymtsd' in line:
                        new_lines.append('daemon/wymtsd\n')
                    elif 'system/psfreedom' in line:
                        psfreedom_found = 1
                        new_lines.append('#system/psfreedom\n')
                    else:
                        new_lines.append(line)
                else:
                    if 'daemon/wymtsd' in line:
                        new_lines.append('#daemon/wymtsd\n')
                    elif 'system/psfreedom' in line:
                        psfreedom_found = 1
                        new_lines.append('system/psfreedom\n')
                    else:
                        new_lines.append(line)
            if psfreedom_found == 0:
                if mode == 0:
                    new_lines.append('#system/psfreedom\n')
                else:
                    new_lines.append('system/psfreedom\n')
            initng_file.writelines(new_lines)
            initng_file.close()
        except:
            pass

    def _reinit_box(self):
        os.system('/sbin/reboot')
예제 #12
0
파일: epg_grid.py 프로젝트: rayman18/wydev
class EpgGridMenu(Menu):
    def __init__(self, player, channel_list, universe='tv', selected_chan=0):
        Menu.__init__(self,
                      name='EPG Grid',
                      choices=[],
                      type='epg_grid',
                      universe=universe)
        self.eventhandler = EpgGridEventHandler(self)
        self.player = player
        self.start_time, self.end_time = ts.current_timeslice()
        self.lower_limit = ts.get_epg_day(self.start_time)
        self.upper_limit = self.start_time + datetime.timedelta(days=7)
        self.displayed_programs = []
        self.selected_program = 0
        self._summarized_info = dict()
        self._getitems_keywords.update({
            'clock': (lambda: None),
            'channel_list': (lambda: self.get_item_list('channel_list')),
            'channel_list_name': (lambda: self.channel_list.name),
            'info_press': (lambda: self._summarized_info['info_press']),
            'info_icon': (lambda: self._summarized_info['info_icon']),
            'selected_program_name':
            (lambda: self._summarized_info['program_name']),
            'selected_program_duration':
            (lambda: self._summarized_info['program_duration']),
            'selected_program_date':
            (lambda: self._summarized_info['program_date']),
            'selected_program_start_time':
            (lambda: self._summarized_info['program_start']),
            'selected_program_maturity_rating':
            (lambda: self._summarized_info['program_maturity_rating']),
            'selected_program_duration_caption': (lambda: _('Duration')),
            'epg_control_window_caption': (lambda: _('EPG Control Window'))
        })
        self.update_channels_timer = Task(self.update_channels)
        self.refresh_timer = Task(self.refresh)
        self.set_channel_list(channel_list)
        self.select(selected_chan, 'main_list')
        self.select(selected_chan, 'channel_list')
        self.update_programs()
        now = time()
        for i, prog in enumerate(self.displayed_programs):
            if prog.start_time <= now and prog.end_time >= now:
                self.selected_program = i
                self.select_program(0)
                break
        self.tick_timer = Task(self.tick_callback)
        self.tick_timer.start(5, loop=True)
        self.refresh_timer.start(AUTO_REFRESH_DELAY,
                                 loop=True,
                                 consider_idle=True)
        return None

    # Display the EPG control window.
    def display_control_window(self):
        EpgControlWindowMenu(self).show()
        return None

    # Display the full program information banner on the currently selected program.
    def display_info_banner(self):
        program = self.displayed_programs[self.selected_program]
        if 'dummy' not in program['class']:
            EpgInfoBanner(program).show()
        return None

    # Zap to the currently selected program if it is being broadcast.
    # Returns True on success.
    def zap_to_selected(self):
        if self.player.can_zap():
            channel = self.get_item_list('main_list').selected
            self.hide()
            channel.execute()
            return True
        else:
            title = _("Can't change channels")
            message = _('A recording is in progress. Stop it before zapping.')
            MessageWindow(message, title, button=None).show(timeout=5)
        return None

    # Schedule the recording of the currently selected program.
    def record_selected(self):
        program = self.displayed_programs[self.selected_program]
        now = int(time())
        if program.end_time > now:
            start_time = max(now, program.start_time)
            end_time = min(program.end_time, start_time + 21600)
            channel = self['channel_list'].selected
            chan_id = int(channel['serviceId'])
            favorite_name = self.channel_list.name
            values = {
                'channel': self['channel_list'].selected.name,
                'title': program.name,
                'date': strftime('%Y/%m/%d', localtime(start_time)),
                'start_time': seconds_to_hhmm(start_time),
                'end_time': seconds_to_hhmm(end_time)
            }
            record_name = EPG_RECORDING_NAME_PATTERN % values
            try:
                WyRecord().scheduler.ScheduleRecording(chan_id,
                                                       start_time,
                                                       end_time,
                                                       record_name,
                                                       program_id=program.id,
                                                       favorite=favorite_name)
                louie_send('update_record')
            except SchedulerConflictWithInstantRecordError, e:
                louie_send('update_record', sender=None)
                conflicting_rec = e.conflict.getAllRecInConflict()[0]
                message_pattern = _(
                    'An instant recording on %(channel)s will be stopped when this recording starts.'
                )
                message = message_pattern % {
                    'name': ellipsize(conflicting_rec.name, 40),
                    'start_time': seconds_to_hhmm(conflicting_rec.start_time),
                    'channel': conflicting_rec.service_name
                }
                title = _('Conflict with an instant recording')
                MessageWindow(message, title, button=None).show(timeout=5)
            except SchedulerConflictError, e:
                conflicting_rec = e.conflict.getAllRecInConflict()[0]
                message_pattern = _(
                    'The recording you are attempting to schedule conflicts with "%(name)s", starting at %(start_time)s on %(channel)s.'
                )
                message = message_pattern % {
                    'name': ellipsize(conflicting_rec.name, 40),
                    'start_time': seconds_to_hhmm(conflicting_rec.start_time),
                    'channel': conflicting_rec.service_name
                }
                title = _('Recording scheduler error')
                MessageWindow(message, title, button=None).show(timeout=5)
            except SchedulerError, e:
                log.error("Can't start recording due to %s", e)
                title = _('Recording scheduler error')
                message = 'Unable to schedule your recording. Sorry.'
                MessageWindow(message, title, button=None).show(timeout=5)