示例#1
0
 def nano_command(self, arg):
     oldday = self.day
     if arg == '?':
         self.print_('xs to init nanomode, xd to show day, xd+ to increase day')
     elif arg == 'd':
         self.print_('Day is {}'.format(self.day))
     elif arg == 'd+':
         self.day += 1
         self.print_('Day changed to {}'.format(self.day))
     elif re.match(r'd\d\d?$', arg):
         day = int(arg[1:])
         if day not in range(1,31):
             self.error('Invalid day')
             return
         self.day = day
         self.print_('Day changed to {}'.format(self.day))
     elif arg == 's':
         if not self.activated:
             logfile_path = self.get_logfile_path()
             if os.path.exists(logfile_path):
                 log = read_json(logfile_path)
                 self.offset = log.get('offset', 0)
             self.print_('Nano mode initiated.')
             self.activated = True
             if self.settings['override title wordcount']:
                 self.textarea.wordcount_changed.emit(self.get_wordcount()[0])
         else:
             self.error('Nano mode already running!')
     # Update the config just in case
     if self.day != oldday:
         self.settings = read_json(self.configfile)
         self.settings['day'] = self.day
         write_json(self.configfile, self.settings)
示例#2
0
文件: nomia.py 项目: nycz/nomia
def read_config(configpath, defaultstyle):
    #if configdir:
    #    configpath = configdir
    #else:
    #    configpath = join(getenv('HOME'), '.config', 'nomia')
    configfile = join(configpath, 'settings.json')
    stylefile = join(configpath, 'style.json')
    make_sure_config_exists(configfile, local_path('defaultconfig.json'))
    make_sure_config_exists(stylefile, local_path('defaultstyle.json'))
    # Make sure to update the style with the defaultstyle's values
    newstyle = read_json(stylefile)
    style = defaultstyle.copy()
    style.update({k:v for k,v in newstyle.items() if k in defaultstyle})
    return read_json(configfile), style, stylefile
示例#3
0
def get_updated_css(stylepath, current_style, css_template):
    """
    Return the style json and the complete css if it is valid and has been
    changed since last update, otherwise return None.

    current_style - a dict with keys to format() the template
    css_template - a format()-ready string that matches current_style
    """
    # Copy in the default theme if a customized doesn't exist
    if not os.path.exists(stylepath):
        defaultcss = common.local_path('defaultstyle.json')
        shutil.copyfile(defaultcss, stylepath)
    try:
        style = common.read_json(stylepath)
    except:
        print('Invalid style config: unable to parse it as json')
        return
    # Only update if something's changed
    if style != current_style:
        try:
            css = css_template.format(**style)
        except KeyError:
            print('Invalid style config: key missing')
            return
        else:
            return style, common.parse_stylesheet(css)
    return
示例#4
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', choices=['stats', 'todo', 'update'])
    parser.add_argument('entryname',
                        nargs='?',
                        help='part of the name of the fic to update')
    sortalt = ['name', 'cur', 'mean', 'med', 'max', 'min']
    parser.add_argument('-s',
                        '--sort-stats',
                        choices=sortalt,
                        default=sortalt[0])
    parser.add_argument('-r', '--reverse', action='store_true')
    args = parser.parse_args()
    data = read_json(local_path('medusadata.json'))
    if args.mode == 'stats':
        show_stats(data,
                   sortalt.index(args.sort_stats) if args.sort_stats else None,
                   args.reverse)
    elif args.mode == 'todo':
        show_todo(data)
    elif args.mode == 'update':
        if not args.entryname or not args.entryname.strip():
            print('Error: No entry name specified')
            return
        run_update(data, args.entryname)
示例#5
0
    def __init__(self, path, get_filepath, get_text):
        QtGui.QLineEdit.__init__(self, None)
        self.setVisible(False)
        self.setReadOnly(True)
        self.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        font = QtGui.QFont()
        font.setFamily("Monospace")
        font.setPointSize(10)
        self.setFont(font)

        self.pluginpath = path
        self.get_text = get_text

        self.nano_width = 20 #TODO I think this is width in chars
        char_width = self.fontMetrics().averageCharWidth()
        self.setFixedWidth((self.nano_width + 1)*char_width)

        self.nano_day = 0 
        self.nano_mode = False

        cfg = common.read_json(os.path.join(self.pluginpath, 'cfg.json'))
        self.endpoint = cfg['nano']['endpoint']
        self.chapter_div = '|'.join(cfg['nano']['chapter_division'])
        self.goal = int(cfg['nano']['goal'])
        self.days = int(cfg['nano']['days'])
        self.ideal_chapter = int(cfg['nano']['ideal_chapter'])
        self.cutoff_percent = int(cfg['nano']['cutoff_percent'])
        self.cutoff_minimum = int(cfg['nano']['cutoff_minimum'])
        self.cutoff_days = int(cfg['nano']['cutoff_days'])
        
        self.stats_dir = os.path.join(self.pluginpath, 'stats')
        self.get_filepath = get_filepath 
示例#6
0
文件: nomia.py 项目: nycz/nomia
    def __init__(self, configdir, activation_event, dry_run):
        super().__init__()
        self.setWindowTitle('Nomia')
        if configdir:
            self.configdir = configdir
        else:
            self.configdir = join(getenv('HOME'), '.config', 'nomia')
        activation_event.connect(self.reload_settings)
        self.force_quit_flag = False

        # Create layouts
        self.stack = QtGui.QStackedLayout(self)

        # Index viewer
        self.index_viewer = IndexFrame(self, dry_run, self.configdir)
        self.stack.addWidget(self.index_viewer)

        # Popup viewer
        self.popup_viewer = FileViewer(self)
        self.stack.addWidget(self.popup_viewer)
        self.popuphomekey = QtGui.QShortcut(QtGui.QKeySequence(),
                                            self.popup_viewer,
                                            self.show_index)

        # Load settings
        self.defaultstyle = read_json(local_path('defaultstyle.json'))
        self.css_template = read_file(local_path(join('templates','template.css')))
        self.index_css_template = read_file(local_path(join('templates','index_page.css')))
        self.settings, self.style = {}, {}
        self.reload_settings()
        self.index_viewer.populate_view()

        # Misc
        #self.connect_signals()
        self.show()
示例#7
0
文件: indexframe.py 项目: cefyr/mneme
def index_stories(path):
    """
    Find all files that match the filter, and return a sorted list
    of them with wordcount, paths and all data from the metadata file.
    """
    attributes = (
        ('title', {'filter': 'text', 'parser': 'text'}),
        ('tags', {'filter': 'tags', 'parser': 'tags'}),
        ('description', {'filter': 'text', 'parser': 'text'}),
        ('wordcount', {'filter': 'number'}),
        ('current_page', {'filter': 'number', 'parser': 'text'}),
        ('length', {'filter': 'number', 'parser': 'text'}),
        ('file', {}),
        ('lastmodified', {'filter': 'number'}),
        ('metadatafile', {}),
    )
    metafile = lambda dirpath, fname: join(dirpath, '.'+fname+'.metadata')
    files = ((read_json(metafile(dirpath, fname)), join(dirpath, fname), metafile(dirpath, fname))
             for dirpath, _, filenames in os.walk(path)
             for fname in filenames
             if exists(metafile(dirpath, fname)))
    entries = ((metadata['title'],
                frozenset(metadata['tags']),
                metadata['description'],
                len(re.findall(r'\S+', read_file(fname))),
                int(metadata['current_page']),
                int(metadata['length']),
                fname,
                os.path.getmtime(fname),
                metadatafile)
               for metadata, fname, metadatafile in files)
    return attributes, entries
 def read_config(self):
     # config
     configfile = os.path.join(self.configpath, 'kalpana-chapters.conf')
     make_sure_config_exists(configfile, os.path.join(self.pluginpath, 'default_config.json'))
     self.sidebar.settings = read_json(configfile)
     # stylesheet
     cssfile = os.path.join(self.configpath, 'kalpana-chapters.css')
     make_sure_config_exists(cssfile, os.path.join(self.pluginpath, 'default_theme.css'))
     self.sidebar.setStyleSheet(parse_stylesheet(read_file(cssfile)))
示例#9
0
文件: indexframe.py 项目: nycz/nomia
 def read_data(self, datapath):
     data = read_json(datapath)
     dateattributes = ['airing_started', 'airing_finished', 'watching_started', 'watching_finished']
     for entry in data.values():
         for x in dateattributes:
             if entry[x] is not None:
                 entry[x] = datetime.strptime(entry[x], self.dateformat).date()
         entry['tags'] = set(entry['tags'])
     return data
示例#10
0
 def written_today(self, total_wordcount):
     logfile_path = self.get_logfile_path()
     offset = 0
     if os.path.exists(logfile_path):
         days = read_json(self.get_logfile_path())['days']
         for x in days[::-1]:
             date, day, wc = x.split(';')
             if int(day) < self.day:
                 offset = int(wc)
                 break
     return total_wordcount - offset
示例#11
0
 def set_title(self):
     if not self.settings['use sapfo title']:
         return
     fname = self.textarea.file_path
     metadatafile = join(dirname(fname), '.' + basename(fname) + '.metadata')
     if isfile(metadatafile):
         try:
             metadata = read_json(metadatafile)
             title = metadata['title']
         except:
             title = "##metadata error##"
         self.textarea.filename_changed.emit(title)
示例#12
0
def read_config(config_file_path, default_config):
    """
    Return the config after adding all settings it misses from the default
    config and purgin all settings it has that the default doesn't have.

    Return the default config if the current config is broken or doesn't exist.
    """
    try:
        raw_settings = common.read_json(config_file_path)
    except:
        print('Bad or no config, replacing with default')
        return default_config['automatic'], default_config['manual']
    def generate_settings(type_):
        return {k:raw_settings[type_][k] if k in raw_settings[type_] else v \
                for k,v in default_config[type_].items()}
    return generate_settings('automatic'), generate_settings('manual')
示例#13
0
文件: fckthms.py 项目: nycz/fckthms
def validate_theme(themefile: str, styleconfig: Dict[str, str]) -> None:
    rx = r'color \S+ "[^"]+" "([^"]+)" \S+\s*'
    with open(themefile) as f:
        rawsettings = [
            re.fullmatch(rx, l).group(1) for l in f.readlines()
            if l.startswith('color')
        ]
    settings = set(rawsettings)
    if len(rawsettings) != len(settings):
        print('WARNING: some colors where defined twice')
    styleconfig = common.read_json(styleconfig)
    rest = settings - set(styleconfig.keys())
    if rest:
        print('ERROR: some colors wasn\'t found in the styleconfig:')
        print(*rest, sep='\n')
        sys.exit(1)
示例#14
0
 def on_save(self):
     if not self.activated:
         return
     if self.settings['override title wordcount']:
         self.textarea.wordcount_changed.emit(self.get_wordcount()[0])
     logfile_path = self.get_logfile_path()
     if os.path.exists(logfile_path):
         log = read_json(logfile_path)
     else:
         log = {'days':[], 'chapters':[]}
     wc, chapters = self.get_wordcount()
     log['chapters'] = chapters
     try:
         lastwc = int(log['days'][-1].split(';')[2])
     except IndexError:
         lastwc = 0
     if wc == lastwc:
         return
     log['days'].append('{};{};{}'.format(datetime.now(), self.day, wc))
     write_json(logfile_path, log)
示例#15
0
文件: medusa.py 项目: nycz/medusa
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', choices=['stats', 'todo', 'update'])
    parser.add_argument('entryname', nargs='?',
                        help='part of the name of the fic to update')
    sortalt = ['name', 'cur', 'mean', 'med', 'max', 'min']
    parser.add_argument('-s', '--sort-stats', choices=sortalt, default=sortalt[0])
    parser.add_argument('-r', '--reverse', action='store_true')
    args = parser.parse_args()
    data = read_json(local_path('medusadata.json'))
    if args.mode == 'stats':
        show_stats(data, sortalt.index(args.sort_stats) if args.sort_stats else None,
                   args.reverse)
    elif args.mode == 'todo':
        show_todo(data)
    elif args.mode == 'update':
        if not args.entryname or not args.entryname.strip():
            print('Error: No entry name specified')
            return
        run_update(data, args.entryname)
示例#16
0
文件: nomia.py 项目: nycz/nomia
    def reload_settings(self):
        self.defaultstyle = read_json(local_path('defaultstyle.json'))
        self.css_template = read_file(local_path(join('templates','template.css')))
        self.index_css_template = read_file(local_path(join('templates','index_page.css')))

        settings, style, stylepath = read_config(self.configdir, self.defaultstyle)
        # TODO: FIX THIS UGLY ASS SHIT
        # Something somewhere f***s up and changes the settings dict,
        # therefor the deepcopy(). Fix pls.
        #if settings != self.settings:
        if settings['title']:
            self.setWindowTitle(settings['title'])
        else:
            self.setWindowTitle('Nomia')
        self.settings = copy.deepcopy(settings)
        self.index_viewer.update_settings(settings)
        self.popuphomekey.setKey(QtGui.QKeySequence(settings['hotkey home']))
        #if style != self.style:
        self.style = style.copy()
        self.update_style(style)
        write_json(stylepath, style)
示例#17
0
 def read_config(self):
     configfile = join(self.configpath, 'kalpana-sapfo.conf')
     make_sure_config_exists(configfile, join(self.pluginpath, 'defaultconfig.json'))
     self.settings = read_json(configfile)
 def read_config(self):
     configfile = os.path.join(self.configpath, 'kalpana-export.conf')
     make_sure_config_exists(configfile, os.path.join(self.pluginpath, 'default_config.json'))
     self.settings = read_json(configfile)
示例#19
0
def main():
    template = read_json(os.path.join(local_path('templates'), 'defaultentry-meta.json'))
    malanimelist = ET.parse(local_path('animelist-2016-05-26.xml'))
    htmldata = extract_html_data(local_path('malanimetempcache'))
    entries = parse_animelist_xml(malanimelist.getroot(), htmldata, template)
    write_json(local_path('animelisttest.json'), entries)
 def read_config(self):
     configfile = join(self.configpath, 'kalpana-logger.conf')
     defaultconfigfile = join(self.local_path, 'defaultconfig.json')
     make_sure_config_exists(configfile, defaultconfigfile)
     self.settings = read_json(configfile)
示例#21
0
文件: urd.py 项目: cefyr/urd
def read_config():
    config_file = os.path.join(os.getenv('HOME'), '.config', 'urd', 'urd.conf')
    common.make_sure_config_exists(config_file,
                                   common.local_path('default_config.json'))
    return common.read_json(config_file)
示例#22
0
def load_settings():
    config_file = os.path.join(os.getenv('HOME'), '.config', 'sapfo-dl',
                               'settings.json')
    make_sure_config_exists(config_file, local_path('default_settings.json'))
    return read_json(os.path.join(config_file))
示例#23
0
文件: urd.py 项目: nycz/urd
def read_config():
    config_file = os.path.join(os.getenv("HOME"), ".config", "urd", "urd.conf")
    common.make_sure_config_exists(config_file, common.local_path("default_config.json"))
    return common.read_json(config_file)
示例#24
0
文件: download.py 项目: nycz/sapfo-dl
def load_settings():
    config_file = os.path.join(os.getenv('HOME'), '.config', 'sapfo-dl', 'settings.json')
    make_sure_config_exists(config_file, local_path('default_settings.json'))
    return read_json(os.path.join(config_file))
def get_index(path):
    if exists(path):
        return read_json(path)
    else:
        return {}
示例#26
0
def get_default_config():
    return common.read_json(common.local_path('defaultconfig.json'))
示例#27
0
 def read_data(self):
     # TODO: attribute-specific shit here
     self._entries = read_json(self._datapath)
示例#28
0
 def read_config(self):
     self.configfile = os.path.join(self.configpath, 'kalpanano.conf')
     defaultconfigfile = os.path.join(self.local_path, 'defaultconfig.json')
     make_sure_config_exists(self.configfile, defaultconfigfile)
     self.settings = read_json(self.configfile)
     self.day = self.settings['day']