def usage(self): """ Defines the usage information that is presented when a user hits the help option.You should not directly override this method, instead, just override the protected method `_usage_options_example`, created for this purpose. All other stuff will be defined by the `usage_header` and `usage_footer` methods. """ # header self.usage_header() print _("""Screen: %(screen)s Description: %(description)s Usage: %(app_name)s %(screen)s [options]""") % { 'app_name': constants.App.NAME, 'screen': self.name, 'description': self.description, } # any additional info in between (see other classes for reference) self._usage_options_example() #footer self.usage_footer()
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -p, --path Sets the location to search for text-based source files. this option is mandatory. -d, --delay Sets the speed of the displaying characters default is%(default_delay)s of a second -h, --help Displays this help message Examples: $ %(app_name)s %(screen)s -p /path/to/my/code This will trigger the screensaver to read all files in the path selected $ %(app_name)s %(screen)s -p /path/to/my/code -d 0 This will trigger the screensaver to read all files in the path selected with no delay (too fast for a screensaver, but it's your choice that matters!) """) % { 'screen': self.name, 'app_name': constants.App.NAME, 'default_delay': constants.Settings.CHAR_DELAY_SECONDS, }
def _run_cycle(self): """ Executes a cycle of this screen. """ # calculate random position based on screen size self.get_terminal_size() # update info data if self.path: # # run the flow for external path # self.update_stats_extra() if self.geometry["x"] > 16: # just to avoid unexpected exceptions title = "%s: %s" % ( _("Monitoring"), (self.path[: (self.geometry["x"] - 16)] + (self.path[(self.geometry["x"] - 16) :] and "...")), ) else: title = _("Monitoring file") txt = self.get_xy_chart(title, "extra") txt += self.center_text_horizontally( "\n Load: %s%% %s " % (("%02d" % self.info["db"][-1]["extra"]), self.get_chart(self.info["db"][-1]["extra"])) ) else: # # run the flow for CPU/Mem as default # self.update_stats() txt = self.get_xy_chart("CPU Monitor", "cpu") txt += "\n" txt += self.get_xy_chart("MEM Monitor", "mem") txt += self.center_text_horizontally( "\n%s CPU: %s%% %s MEM: %s%% (total %sMB)" % ( self.get_chart(self.info["db"][-1]["cpu"]), ("%.1f" % self.info["db"][-1]["cpu"]), self.get_chart(self.info["db"][-1]["mem"]), self.info["db"][-1]["mem"], int(self.info["total_mem"]), ) ) # # Due to a time delay to calculate CPU usage # we need to clear the screen manually # self.clear_screen() # just print the whole text print txt
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -c, --char Sets the character to be showing up default is X -d, --delay Sets the speed of the displaying characters default is 0.05 of a second (advised to keep between 0.1 and 0.01). -h, --help Displays this help message Example: $ %(app_name)s %(screen)s This will trigger the screensaver to display a dot on screen, with random size increase. $ %(app_name)s %(screen)s -c + Overrides the default dot (.) character to be a plus sign (+) """) % { 'app_name': constants.App.NAME, 'screen': self.name, }
def update_stats_extra(self): """ Updates the info property with latest information on an extra path, defined by --path argument option Note: This also takes care of sleep (defined by delay property) """ f = open(self.path, "r") try: val = int(f.read()) except: raise exception.TermSaverException(_("The file does not contain an integer as expected.")) if val < 0 or val > 100: raise exception.TermSaverException(_("The file contains invalid data (must be between 0 and 100).")) f.close() # cut the data to keep only recent values self.info["db"] = self.info["db"][-(self.geometry["x"] - 5) :] max_extra = 0 for item in self.info["db"]: if item["extra"] > max_extra: max_extra = item["extra"] self.info["max_extra"] = max_extra self.info["db"].append({"time": time.time(), "extra": val}) time.sleep(self.delay)
def update_stats_extra(self): """ Updates the info property with latest information on an extra path, defined by --path argument option Note: This also takes care of sleep (defined by delay property) """ f = open(self.path, 'r') try: val = int(f.read()) except: raise exception.TermSaverException( _('The file does not contain an integer as expected.')) if val < 0 or val > 100: raise exception.TermSaverException( _('The file contains invalid data (must be between 0 and 100).' )) f.close() # cut the data to keep only recent values self.info['db'] = self.info['db'][-(self.geometry['x'] - 5):] max_extra = 0 for item in self.info['db']: if item['extra'] > max_extra: max_extra = item['extra'] self.info['max_extra'] = max_extra self.info['db'].append({ 'time': time.time(), 'extra': val, }) time.sleep(self.delay)
def _run_cycle(self): """ Executes a cycle of this screen. """ # calculate random position based on screen size self.get_terminal_size() # update info data if self.path: # # run the flow for external path # self.update_stats_extra() if self.geometry['x'] > 16: # just to avoid unexpected exceptions title = "%s: %s" % (_('Monitoring'), (self.path[:(self.geometry['x'] - 16)] + (self.path[(self.geometry['x'] - 16):] and '...'))) else: title = _("Monitoring file") txt = self.get_xy_chart(title, 'extra') txt += self.center_text_horizontally( "\n Load: %s%% %s " % ( ("%02d" % self.info['db'][-1]['extra']), self.get_chart(self.info['db'][-1]['extra']), ) ) else: # # run the flow for CPU/Mem as default # self.update_stats() txt = self.get_xy_chart("CPU Monitor", 'cpu') txt += "\n" txt += self.get_xy_chart("MEM Monitor", 'mem') txt += self.center_text_horizontally( "\n%s CPU: %s%% %s MEM: %s%% (total %sMB)" % ( self.get_chart(self.info['db'][-1]['cpu']), ('%.1f' % self.info['db'][-1]['cpu']), self.get_chart(self.info['db'][-1]['mem']), self.info['db'][-1]['mem'], int(self.info['total_mem']) )) # # Due to a time delay to calculate CPU usage # we need to clear the screen manually # self.clear_screen() # just print the whole text print(txt)
def _parse_args(self, prepared_args): for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-i", "--invert"): self.options['invert'] = True elif o in ("-w", "--wide"): try: # makes sure this is a valid integer self.options['wide'] = int(a) except: raise exception.InvalidOptionException("wide") elif o in ("-c", "--contrast"): self.options['contrast'] = True elif o in ("-s", "--set"): self.options['customcharset'] = a elif o in ("-f", "--framedelay"): try: self.option['framedelay'] = int(a) except: raise exception.InvalidOptionException("framedelay") elif o in ("-z", "--scale"): try: self.options['scale'] = int(a) except: raise exception.InvalidOptionException("scale") elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-p", "--path"): # make sure argument is a valid value (existing path) self.path = a if not os.path.exists( self.path) and self.path[0:4].lower() != 'http': raise exception.PathNotFoundException( self.path, _("Make sure the file or directory exists.")) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details.")) # last validations if self.path in (None, ''): raise exception.InvalidOptionException( "path", _("It is mandatory option"), help=self._message_no_path())
def __init__(self): """ Creates a new instance of this class. """ UrlFetcherBase.__init__(self, "urlfetcher", _("displays url contents with typing animation"))
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, __ in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-m", "--ampm"): self.ampm = True elif o in ("-b", "--big"): self.big = True self.lineindigimap = 15 self.digmap = self.digimapbig else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def __init__(self): """ Creates a new instance of this class (used by termsaver script) From its base classes, the functionality provided here bases on the settings defined below: * clean up each cycle: True this will force the screen to be cleaned (cleared) before each new cycle is displayed * clean up each file: True this will force the screen to be cleaned (cleared) before each new file is displayed """ ScreenBase.__init__(self, "img2ascii", _("displays images in typing animation"), cli_opts={ 'opts': 'hicd:p:w:s:z:f:', 'long_opts': [ 'help', 'invert', 'path=', 'wide=', 'contrast', 'set=', 'framedelay=', 'scale=' ], }) self.delay = 0.002 self.frame_delay = 5 # self.path = path self.cleanup_per_cycle = False self.options = {'wide': 2} self.cleanup_per_cycle = True self.cleanup_per_file = True self.options = {}
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-c", "--char"): # make sure argument is a valid value (single char) if len(a) != 1: raise exception.InvalidOptionException("char") else: self.char = a else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def _message_no_url(self): """ Defines a method to be overriden by inheriting classes, with the purpose to display extra help information for specific errors. """ return _(""" You just need to provide the URL of the RSS feed from where %(app_title)s will read and display on screen. If you do not have any idea which RSS to use, check out some examples here: CNN Top Stories - http://rss.cnn.com/rss/edition.rss World - http://rss.cnn.com/rss/edition_world.rss Technology - http://rss.cnn.com/rss/edition_technology.rss See CNN's complete list of RSS syndication here: http://edition.cnn.com/services/rss/ Lifehacker - http://www.lifehacker.com/index.xml Note: Lifehacker uses HTML to deliver "description" contents in the RSS, so you might need to change the format to something like: --format "%%(title)s (%%(pubDate)s)\\n" """) % { 'app_title': constants.App.TITLE, }
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-r", "--raw"): self.clean_html = False elif o in ("-f", "--format"): # remove escaping self.print_format = common.unescape_string(a) elif o in ("-u", "--url"): try: # try to fix the url formatting self.url = self.fix_uri(a) except Exception, e: raise exception.InvalidOptionException("url", e.message) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def _run_cycle(self): """ Executes a cycle of this screen. """ # calculate random position based on screen size self.get_terminal_size() self.build_figlet_text(self.word) # make sure the figlet output can be printed on available screen if len(self.figlet_text.split("\n")) > self.geometry["y"]: raise exception.InvalidOptionException("word", _("The word you are trying to print is just too big.")) if self.position["x"] == self.geometry["x"] + self.figlet_geometry["x"]: self.position["x"] = 1 self.position["y"] = random.randint(1, self.geometry["y"] - self.figlet_geometry["y"]) self.position["x"] += 1 new_text = "" for l in self.figlet_text.split("\n"): # print start/end in pieces if self.position["x"] < self.figlet_geometry["x"]: txt = l[self.figlet_geometry["x"] - self.position["x"] :] elif self.position["x"] > self.geometry["x"]: txt = ( " " * (self.position["x"] - self.figlet_geometry["x"]) + l[: self.geometry["x"] - self.position["x"]] ) else: txt = " " * (self.position["x"] - self.figlet_geometry["x"]) + l new_text += "\n" + txt print "\n" * self.position["y"] + new_text time.sleep(self.delay)
def __init__(self): """ Creates a new instance of this class. """ UrlFetcherBase.__init__( self, "urlfetcher", _("displays url contents with typing animation"))
def __init__(self): """ The constructor of this class, using most default values from its super class, `SimpleRSSFeedScreenBase`. The display of the ascii arts here are basically based on getting the description tag of the RSS feed, that constains a dirty HTML ascii art. NOTE: Maybe NSFW (Not Safe For Work) """ super(AsciArtFartsScreen, self).__init__( "asciiartfarts", _("displays ascii images from asciiartfarts.com (NSFW)"), 'http://www.asciiartfarts.com/farts.rss', ["description"], "%(description)s", ) # set defaults for this screen self.cleanup_per_cycle = True self.sleep_between_items = 5 self.center_vertically = True self.center_horizontally = True self.clean_dirt = ['<pre>', '</pre>'] self.cleanup_per_item = True
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-r", "--raw"): self.clean_html = False elif o in ("-f", "--format"): #remove escaping self.print_format = common.unescape_string(a) elif o in ("-u", "--url"): try: # try to fix the url formatting self.url = self.fix_uri(a) except Exception, e: raise exception.InvalidOptionException("url", e.message) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.freeze_delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-w", "--word"): # make sure argument is a valid value if a in (None, ''): raise exception.InvalidOptionException("word") self.word = a else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ use_kana_only = False for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-k", "--kana"): use_kana_only = True elif o in ("-z", "--zenkaku"): self.use_zenkaku = True elif o in ("-g", "--granularity"): try: # make sure argument is a valid value (int) self.granularity = int(a) except: raise exception.InvalidOptionException("granularity") if self.granularity <= 0: raise exception.InvalidOptionException("granularity", "Must be higher than zero") elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.line_delay = float(a) except: raise exception.InvalidOptionException("delay") if self.line_delay <= 0: raise exception.InvalidOptionException("delay", "Must be higher than zero") else: # this should never happen! raise Exception(_("Unhandled option. See --help for details.")) # fill in other important properties if self.use_zenkaku: digmap_kana = self.digmap_kana_zenkaku digmap_alpha_num = self.digmap_alpha_num_zenkaku self.space = self.space_zenkaku self.proportion = 2 else: digmap_kana = self.digmap_kana_hangaku digmap_alpha_num = self.digmap_alpha_num_hangaku self.space = self.space_hangaku self.proportion = 1 self.digmap.extend(digmap_kana) if not use_kana_only: self.digmap.extend(digmap_alpha_num)
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ use_kana_only = False for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-k", "--kana"): use_kana_only = True elif o in ("-z", "--zenkaku"): self.use_zenkaku = True elif o in ("-g", "--granularity"): try: # make sure argument is a valid value (int) self.granularity = int(a) except: raise exception.InvalidOptionException("granularity") if self.granularity <= 0: raise exception.InvalidOptionException( "granularity", "Must be higher than zero") elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.line_delay = float(a) except: raise exception.InvalidOptionException("delay") if self.line_delay <= 0: raise exception.InvalidOptionException( "delay", "Must be higher than zero") else: # this should never happen! raise Exception(_("Unhandled option. See --help for details.")) # fill in other important properties if self.use_zenkaku: digmap_kana = self.digmap_kana_zenkaku digmap_alpha_num = self.digmap_alpha_num_zenkaku self.space = self.space_zenkaku self.proportion = 2 else: digmap_kana = self.digmap_kana_hangaku digmap_alpha_num = self.digmap_alpha_num_hangaku self.space = self.space_hangaku self.proportion = 1 self.digmap.extend(digmap_kana) if not use_kana_only: self.digmap.extend(digmap_alpha_num)
def help_fonts(self): fonts = self.get_fonts() ScreenBase.usage_header() print _("""Here is the list of all available figlet fonts that are supported in your system: %(fonts)s You may try to use them with the option -f/--font. See --help for details. You may also refer to official figlet documentation for additional details on how to deal with fonts. """) % { 'fonts': "\t" + "\n\t".join(textwrap.wrap(", ".join(fonts), 50)), } ScreenBase.usage_footer()
def __init__(self): """ The constructor of this class, using most default values from its super class, `SimpleUrlFetcherBase`. """ SimpleUrlFetcherBase.__init__(self, "rfc", _("randomly displays RFC contents"), "localhost") # base class require a URL
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__(self, "exampleplugin", _("the example plugin"), { 'opts': 'h', 'long_opts': ['help'] }) self.cleanup_per_cycle = True
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -g, --granularity an integer value to define how dirt should the screen be. Default value is [%(granularity)s]. Use something like [1] for clean style, or a [100] for total dirt. -d, --delay Defines the speed (in seconds) of the character movement Default value is [%(line_delay)s] (in seconds). -k, --kana-only Displays only Japanese characters (excludes alpha numeric). -z, --zenkaku Displays full-width (fattish) Japanese characters. By default it displays half-width characters. -h, --help Displays this help message Examples: $ %(app_name)s %(screen)s -g 100 This will print out random characters in maximum dirt (using almost the entire screen space). Try [1] for very clean results. $ %(app_name)s %(screen)s -g 5 -d 0.001 -k This will give a cleaner print than the default, much faster with only Japanese characters. """) % { 'screen': self.name, 'app_name': constants.App.NAME, 'granularity': self.granularity, 'line_delay': self.line_delay, }
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__(self, "clock", _("displays a digital clock on screen"), {'opts': 'hf', 'long_opts': ['help', 'format']}, ) self.cleanup_per_cycle = True
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -w, --word Sets the word to be displayed default is the name of this application (if you need to use spaces, don't forget to place the word with quotes) -d, --delay Sets how long the word will be displayed before randomized again. Default is %(default_delay)s second(s) -f, --font the figlet font to be used, default is the figlet default (see `figlet -I3` command for details or figler man pages) -h, --help Displays this help message --help-fonts Displays the available fonts that can be used with the -f/--font option. Example: $ %(app_name)s %(screen)s This will trigger the screensaver to display the default word %(app_title)s in random locations of the screen $ %(app_name)s %(screen)s -w FooBar -f lean -d 5 This will trigger the screensaver to display the word FooBar in random locations of the screen, using the "lean" figlet font with a delay of 5 seconds. """) % { 'app_name': constants.App.NAME, 'app_title': constants.App.TITLE, 'screen': self.name, 'default_delay': self.FREEZE_WORD_DELAY, }
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-u", "--url"): try: # try to fix the url formatting self.url = self.fix_uri(a) except Exception as e: error_message = "" if hasattr(e, 'message'): error_message = e.message else: error_message = e raise exception.InvalidOptionException("url", error_message) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details.")) # last validations if self.url in (None, ''): raise exception.InvalidOptionException("url", _("It is mandatory option"), help=self._message_no_url())
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -h, --help Displays this help message -f, --format Shows the clock in 12 hour format """)
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -h, --help Displays this help message -m, --ampm Shows the clock in am/pm 12-hour format, without seconds. """)
def fix_uri(self, text): """ Validates a text as URL format, also adjusting necessary stuff for a clearer URL that will be fetched here. Code based on Django source: https://code.djangoproject.com/browser/django/trunk/django/forms/ fields.py?rev=17430#L610 Arguments: * text: the URL string that is to be validated and fixed """ if not text: raise exception.UrlException(text, _("URL can not be blank")) try: url_fields = list(urlparse.urlsplit(text)) except ValueError: raise exception.UrlException(text, _("URL does not seem valid")) if not url_fields[0]: # If no URL scheme given, assume http:// url_fields[0] = 'http' if not url_fields[1]: # Assume that if no domain is provided, that the path segment # contains the domain. url_fields[1] = url_fields[2] url_fields[2] = '' # Rebuild the url_fields list, since the domain segment may now # contain the path too. try: url_fields = list(urlparse.urlsplit( urlparse.urlunsplit(url_fields))) except ValueError: raise exception.UrlException(text, _("URL does not seem valid")) if not url_fields[2]: # the path portion may need to be added before query params url_fields[2] = '/' return urlparse.urlunsplit(url_fields)
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print( _(""" Options: -p, --path Sets the location to search for text-based source files. This option is mandatory. -d, --delay Sets the speed at which the image is typed out. Default is 1 second. -w, --wide The width of each 'character' of the image. Default is 2 units. (Recommended left at default) -c, --contrast Displays image using a contrast based character set. -i, --invert Displays the image with inverted colors. -s, --set Allows the use of a custom character set. Default is ' .:;+=xX$&'. -z, --scale Scales the image. Default is 1. -f, --framedelay Sets the amount of time between image shifts. Default is 5 seconds -h, --help Displays this help message. Examples: $ %(app_name)s %(screen)s -p /path/to/my/images This will trigger the screensaver to read all files in the path selected $ %(app_name)s %(screen)s -p /path/to/my/image.jpg This will trigger the screensaver to read just one image, refreshing at the preset interval. $ %(app_name)s %(screen)s -p /path/to/my/images -c -i This will trigger the screensaver to read all files in the path selected using a contrast characterset and inverted colors. $ %(app_name)s %(screen)s -p /path/to/my/images -s "1234567890_." This will trigger the screensaver to read all files in the path selected rendering them using only the characters provided. """) % { 'screen': self.name, 'app_name': constants.App.NAME, 'default_delay': constants.Settings.CHAR_DELAY_SECONDS, })
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o == "--help-fonts": self.help_fonts() self.screen_exit() elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.freeze_delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-w", "--word"): # make sure argument is a valid value if a in (None, ''): raise exception.InvalidOptionException("word") self.word = a elif o in ("-f", "--font"): # make sure argument is a valid value (exists) self.font = str(a) if self.font not in self.get_fonts(): raise exception.InvalidOptionException("font", _("Font does not exist")) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -h, --help Displays this help message -u, --url The URL path of the RSS feed (text) to be displayed -r, --raw Shows all text available (with HTML if any) -f, --format The printing format according to values available in RSS feed: * pubDate * title * link * description You must use python dictionary based formatting style (see examples for details) Example: $ %(app_name)s %(screen)s -u http://rss.cnn.com/rss/edition.rss This will trigger the screensaver to fetch the contents from the CNN feed and display it in default formatting: '%%(title)s (%%(pubDate)s)\\n' $ %(app_name)s %(screen)s -u http://rss.cnn.com/rss/edition.rss \\ -f '%%(title)s (%%(pubDate)s)\\n%%(description)s\\n%%(link)s' This will trigger the screensaver to fetch the contents from the CNN feed and display all contents as specified in the formatting. """) % { 'app_name': constants.App.NAME, 'screen': self.name, 'description': self.description, }
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print( _(""" Options: -p, --path Sets the location to search for text-based source files. This option is mandatory. -d, --delay Sets the speed of the displaying characters. Default is 2/1000th of a second -w, --wide The width of each 'character' of the image. Default is 2 units. (Recommended left at default) -c, --contrast Displays image using a contrast based character set. -i, --invert Displays the image with inverted colors. -s, --set Allows the use of a custom character set. Default is ' .:;+=xX$&'. -z, --scale Scales the image. Default is 1. -f, --framedelay Sets the amount of time between image shifts. Default is 5 seconds -h, --help Displays this help message. Examples: $ %(app_name)s %(screen)s -p /path/to/images/ This will trigger the screensaver to read all files in the path selected $ %(app_name)s %(screen)s -p /path/to/images/image.jpg -d 0 This will trigger the screensaver to read all files in the path selected with no delay (too fast for a screensaver, but it's your choice that matters!) $ %(app_name)s %(screen)s -p /path/to/images/image.jpg -i -c This will trigger the screensaver to read the image from the internet and the image will be displayed in contrast mode and inverted. $ %(app_name)s %(screen)s -p http://website.com/image.jpg -d 5 This will trigger the screensaver to read the image from the internet and display it extremely slowly """) % { 'screen': self.name, 'app_name': constants.App.NAME, })
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _( """ Options: -w, --word Sets the word to be displayed default is the name of this application (if you need to use spaces, don't forget to place the word with quotes) -d, --delay Sets the speed of the displaying characters default is 0.05 of a second (advised to keep between 0.1 and 0.01). -f, --font the figlet font to be used, default is the figlet default (see `figlet -I3` command for details or figler man pages) -h, --help Displays this help message --help-fonts Displays the available fonts that can be used with the -f/--font option. Example: $ %(app_name)s %(screen)s This will trigger the screensaver to display the default word %(app_title)s in random locations of the screen $ %(app_name)s %(screen)s -w FooBar -f lean -d 0.005 This will trigger the screensaver to display the word FooBar in random locations of the screen, using the "lean" figlet font with a delay of 0.005 seconds (fast). """ ) % {"app_name": constants.App.NAME, "screen": self.name}
def _message_no_path(self): """ The specific helper message in case there is no path informed in the command-line arguments. """ return _(""" You just need to provide the path to the image from where %(app_title)s will read and display on screen. You may also use online images by sending a url instead of image path. """) % { 'app_title': constants.App.TITLE, }
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__( self, "figlet-fly", _("displays flying text"), {"opts": "hw:d:f:", "long_opts": ["help", "word=", "delay=", "help-fonts", "font="]}, ) self.word = constants.App.TITLE self.delay = 0.05 self.cleanup_per_cycle = True
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _( """ Options: -h, --help Displays this help message -u, --url The URL path of the RSS feed (text) to be displayed -r, --raw Shows all text available (with HTML if any) -f, --format The printing format according to values available in RSS feed: * pubDate * title * link * description You must use python dictionary based formatting style (see examples for details) Example: $ %(app_name)s %(screen)s -u http://rss.cnn.com/rss/edition.rss This will trigger the screensaver to fetch the contents from the CNN feed and display it in default formatting: '%%(title)s (%%(pubDate)s)\\n' $ %(app_name)s %(screen)s -u http://rss.cnn.com/rss/edition.rss \\ -f '%%(title)s (%%(pubDate)s)\\n%%(description)s\\n%%(link)s' This will trigger the screensaver to fetch the contents from the CNN feed and display all contents as specified in the formatting. """ ) % {"app_name": constants.App.NAME, "screen": self.name, "description": self.description}
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-n", "--no-adjust"): self.adjust = False elif o in ("-p", "--path"): # make sure argument is a valid value (existing path) self.path = a if not os.path.exists(self.path): raise exception.PathNotFoundException( self.path, _("Make sure the file exists.")) if not os.path.isfile(self.path): raise exception.InvalidOptionException( "--path", _("Make sure it is a file")) elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.delay = float(a) except: raise exception.InvalidOptionException("delay") else: # this should never happen! raise Exception(_("Unhandled option. See --help for details."))
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__( self, "clock", _("displays a digital clock on screen"), { 'opts': 'hmb', 'long_opts': ['help', 'ampm', "big"] }, ) self.cleanup_per_cycle = True
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__(self, "dot", _("displays a random running dot"), {'opts': 'hc:d:', 'long_opts': ['help', 'char=', 'delay=']}, ) self.char = "*" self.text = "" self.size = 1 self.delay = 0.05 self.cleanup_per_cycle = True
def __init__(self): """ Creates a new instance of this class. """ ScreenBase.__init__(self, "randtxt", _("displays word in random places on screen"), {'opts': 'hw:d:', 'long_opts': ['help', 'word=', 'delay=']}, ) self.word = constants.App.TITLE self.delay = 0.01 self.line_delay = 0 self.cleanup_per_cycle = True self.freeze_delay = self.FREEZE_WORD_DELAY
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -d, --delay Sets the speed of the displaying characters default is 0.5 seconds (advised to keep at least above 0.1). -n, --no-adjust Forces the charts to displays 0 ~ 100%% values, instead of dynamically adjusted values based on current maximum. -p, --path Sets the location of a file to be monitored. The file must only contain a number from 0 to 100, or the screen will not start. This option is optional. -h, --help Displays this help message Example: $ %(app_name)s %(screen)s This will trigger the screensaver to display a dot on screen, with random size increase. $ %(app_name)s %(screen)s -d 5 Overrides the default delay to 5 seconds """) % { 'app_name': constants.App.NAME, 'screen': self.name, }
def _parse_args(self, prepared_args): """ Handles the special command-line arguments available for this screen. Although this is a base screen, having these options prepared here can save coding for screens that will not change the default options. See `_usage_options_example` method for documentation on each of the options being parsed here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ for o, a in prepared_args[0]: # optlist, args if o in ("-h", "--help"): self.usage() self.screen_exit() elif o in ("-d", "--delay"): try: # make sure argument is a valid value (float) self.delay = float(a) except: raise exception.InvalidOptionException("delay") elif o in ("-p", "--path"): # make sure argument is a valid value (existing path) self.path = a if not os.path.exists(self.path): raise exception.PathNotFoundException(self.path, _("Make sure the file or directory exists.")) else: # this should never happen! raise Exception(_("Unhandled option. See --help for details.")) # last validations if self.path in (None, ''): raise exception.InvalidOptionException("path", _("It is mandatory option"), help=self._message_no_path())
def fetch(self, uri): """ Executes the fetch action toward a specified URI. This will also try to avoid unnecessary calls to the Internet by setting the flag `__last_fetched`. If it can not fetch again, it will simply return the `raw` data that was previously created by a previous fetch. Arguments: * uri: the path to be fetched """ # check if we can fetch again if self.__last_fetched and not self.raw and \ time.time() - self.__last_fetched < \ constants.Settings.FETCH_INTERVAL_SECONDS: return self.raw headers = {'User-Agent': "%s/%s" % (constants.App.NAME, constants.App.VERSION)} # separate possible querystring data from plain URL temp = uri.split('?') url = temp[0] if len(temp) > 1: # old style condition for old python compatibility data = temp[1] else: data = None self.log(_("Connecting to %s ... (this could take a while)") % uri) # execute URL fetch req = Request(url, data, headers) resp = None try: resp = urlopen(req) except HTTPError, e: raise exception.UrlException(uri, _("Fetched URL returned error %d.") % e.code)
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -w, --word Sets the word to be displayed default is the name of this application (if you need to use spaces, don't forget to place the word with quotes) -d, --delay Sets how long the word will be displayed before randomized again. Default is %(default_delay)s second(s) -h, --help Displays this help message Example: $ %(app_name)s %(screen)s This will trigger the screensaver to display the default word %(app_title)s in random locations of the screen $ %(app_name)s %(screen)s -w FooBar This will trigger the screensaver to display the default word FooBar in random locations of the screen """) % { 'app_name': constants.App.NAME, 'app_title': constants.App.TITLE, 'screen': self.name, 'default_delay': self.FREEZE_WORD_DELAY, }
def _usage_options_example(self): """ Describe here the options and examples of this screen. The method `_parse_args` will be handling the parsing of the options documented here. Additionally, this is dependent on the values exposed in `cli_opts`, passed to this class during its instantiation. Only values properly configured there will be accepted here. """ print _(""" Options: -u, --url Defines the URL location from where the information should be fetched, then displayed. This option is MANDATORY. -d, --delay Sets the speed of the displaying characters default is 0.003 of a second (advised to keep between 0.01 and 0.001). -h, --help Displays this help message Examples: $ %(app_name)s %(screen)s -u www.google.com This will trigger the screensaver to fetch the HTML contents of this web site and display progressively. $ %(app_name)s %(screen)s -u www.google.com -d 0 This will trigger the screensaver to fetch the HTML contents of this web site with no delay (too fast for a screensaver, but it's your choice that matters!) """) % { 'screen': self.name, 'app_name': constants.App.NAME, }
def execute_shell(self, cmd): """ Simple routine to execute shell commands """ try: return common.execute_shell(cmd, False) except Exception, e: raise exception.TermSaverException(help=_( """Could not execute the command [%(cmd)s] properly. %(message)s \nError details: %(error)s""") % { "cmd": " ".join(cmd), "message": "Make sure you have figlet installed!", "error": str(e) } )
def __init__(self): """ The constructor of this class. """ ScreenBase.__init__(self, "sysmon", _("displays a graphical system monitor"), {'opts': 'hd:np:', 'long_opts': ['help', 'delay=', 'no-adjust', 'path=']}, ) if self.delay is None: self.delay = 0.5 # # Due to a time delay to calculate CPU usage # we need to clear the screen manually # self.cleanup_per_cycle = False