From 4c05e43d11430fbfd8a5d86ae0070e24775251b1 Mon Sep 17 00:00:00 2001 From: hut Date: Sun, 13 Dec 2009 16:23:01 +0100 Subject: clean ups, comments --- ranger/__init__.py | 4 +- ranger/actions.py | 2 +- ranger/applications.py | 2 +- ranger/colorschemes/__init__.py | 5 +- ranger/colorschemes/default.py | 3 +- ranger/colorschemes/jungle.py | 3 +- ranger/container/__init__.py | 2 + ranger/container/commandlist.py | 20 ++++--- ranger/container/environment.py | 127 ++++++++++++++++++++++++++++++++++++++++ ranger/container/keybuffer.py | 2 + ranger/defaults/__init__.py | 1 + ranger/environment.py | 127 ---------------------------------------- ranger/ext/__init__.py | 1 + ranger/ext/debug.py | 19 ++++++ ranger/ext/log.py | 15 ----- ranger/ext/relpath.py | 12 +++- ranger/fsobject/__init__.py | 3 + ranger/fsobject/fsobject.py | 3 +- ranger/gui/ui.py | 21 ++++--- ranger/gui/widgets/filelist.py | 6 +- ranger/shared/__init__.py | 2 + ranger/shared/settings.py | 2 +- test/tc_directory.py | 11 ++-- test/tc_history.py | 2 +- 24 files changed, 218 insertions(+), 177 deletions(-) create mode 100644 ranger/container/environment.py delete mode 100644 ranger/environment.py create mode 100644 ranger/ext/debug.py delete mode 100644 ranger/ext/log.py diff --git a/ranger/__init__.py b/ranger/__init__.py index 553e57f5..484ddbdd 100644 --- a/ranger/__init__.py +++ b/ranger/__init__.py @@ -12,7 +12,7 @@ import os import sys # for easier access -from ranger.ext.log import log +from ranger.ext.debug import log, trace CONFDIR = os.path.expanduser('~/.ranger') RANGERDIR = os.path.dirname(__file__) @@ -34,7 +34,7 @@ def main(): from optparse import OptionParser, SUPPRESS_HELP from ranger.fm import FM - from ranger.environment import Environment + from ranger.container.environment import Environment from ranger.gui.defaultui import DefaultUI as UI from ranger.fsobject.file import File diff --git a/ranger/actions.py b/ranger/actions.py index cc013401..4be005bd 100644 --- a/ranger/actions.py +++ b/ranger/actions.py @@ -33,7 +33,7 @@ If CTRL+C is pressed while waiting, the program will be exited""" def enter_dir(self, path): """Enter the directory at the given path""" - self.env.enter_dir(path) + return self.env.enter_dir(path) def enter_bookmark(self, key): """Enter the bookmark with the name """ diff --git a/ranger/applications.py b/ranger/applications.py index 39601e0e..3acf6da5 100644 --- a/ranger/applications.py +++ b/ranger/applications.py @@ -54,7 +54,7 @@ def run(*args, **kw): return process else: - if fm.ui: fm.ui.destroy() + if fm.ui: fm.ui.suspend() p = Popen(args, **popen_kw) waitpid_no_intr(p.pid) if fm.ui: fm.ui.initialize() diff --git a/ranger/colorschemes/__init__.py b/ranger/colorschemes/__init__.py index 6c710bd8..8b543d67 100644 --- a/ranger/colorschemes/__init__.py +++ b/ranger/colorschemes/__init__.py @@ -1,3 +1,5 @@ +"""Colorschemes are required to be located here, +or in the CONFDIR/colorschemes/ directory""" from ranger.ext.get_all_modules import get_all_modules from os.path import expanduser, dirname, exists, join @@ -9,7 +11,8 @@ confpath = expanduser('~/.ranger') if exists(join(confpath, 'colorschemes')): initpy = join(confpath, 'colorschemes/__init__.py') if not exists(initpy): - open(initpy, 'w').write("""from ranger.ext.get_all_modules import get_all_modules + open(initpy, 'w').write("""# Automatically generated: +from ranger.ext.get_all_modules import get_all_modules from os.path import dirname __all__ = get_all_modules(dirname(__file__)) diff --git a/ranger/colorschemes/default.py b/ranger/colorschemes/default.py index ac54bf7f..b35aa8e1 100644 --- a/ranger/colorschemes/default.py +++ b/ranger/colorschemes/default.py @@ -32,7 +32,8 @@ class Default(ColorScheme): if context.directory: fg = blue - elif context.executable and not any((context.media, context.container, context.document)): + elif context.executable and not \ + any((context.media, context.container, context.document)): attr |= bold fg = green diff --git a/ranger/colorschemes/jungle.py b/ranger/colorschemes/jungle.py index eb70e5aa..41e2d912 100644 --- a/ranger/colorschemes/jungle.py +++ b/ranger/colorschemes/jungle.py @@ -26,7 +26,8 @@ class Default(ColorScheme): if context.directory: fg = green # trees =) - elif context.executable and not any((context.media, context.container)): + elif context.executable and not \ + any((context.media, context.container)): fg = yellow # banananas if context.link: diff --git a/ranger/container/__init__.py b/ranger/container/__init__.py index fe8228e9..5a1cd9d8 100644 --- a/ranger/container/__init__.py +++ b/ranger/container/__init__.py @@ -1,3 +1,5 @@ +"""This package includes container-objects which are +used to manage stored data""" from ranger.container.history import History from ranger.container.keybuffer import KeyBuffer from .commandlist import CommandList diff --git a/ranger/container/commandlist.py b/ranger/container/commandlist.py index 9c4c77a0..ab6f1102 100644 --- a/ranger/container/commandlist.py +++ b/ranger/container/commandlist.py @@ -1,11 +1,12 @@ -"""CommandLists are dictionary-like objects which give you a command -for a given key combination. CommandLists must be initialized -before use.""" class CommandList(object): + """CommandLists are dictionary-like objects which give you a command +for a given key combination. CommandLists must be filled before use.""" + dummy_object = None dummies_in_paths = False paths = {} commandlist = [] + def __init__(self): self.commandlist = [] self.paths = {} @@ -25,13 +26,13 @@ and wait.""" for cmd in self.commandlist: for key in cmd.keys: - for path in self.keypath(key): + for path in self._keypath(key): if path not in self.paths: self.paths[path] = self.dummy_object self.dummies_in_paths = True - def keypath(self, tup): + def _keypath(self, tup): """split a tuple like (a,b,c,d) into [(a,), (a,b), (a,b,c)]""" length = len(tup) @@ -56,7 +57,7 @@ and wait.""" self.dummies_in_paths = False - def str_to_tuple(self, obj): + def _str_to_tuple(self, obj): """splits a string into a tuple of integers""" if isinstance(obj, tuple): return obj @@ -71,7 +72,7 @@ and wait.""" """create a Command object and assign it to the given key combinations.""" if len(keys) == 0: return - keys = tuple(map(self.str_to_tuple, keys)) + keys = tuple(map(self._str_to_tuple, keys)) cmd = Command(fnc, keys) @@ -80,11 +81,14 @@ and wait.""" self.paths[key] = cmd class Command(object): + """Command objects store information about a command""" + keys = [] + def __init__(self, fnc, keys): self.keys = keys self.execute = fnc def execute(self, *args): - """Execute the command.""" + """Execute the command""" diff --git a/ranger/container/environment.py b/ranger/container/environment.py new file mode 100644 index 00000000..a6d291cf --- /dev/null +++ b/ranger/container/environment.py @@ -0,0 +1,127 @@ +from os.path import abspath, normpath, join, expanduser +from ranger.fsobject.directory import Directory, NoDirectoryGiven +from ranger.container import KeyBuffer, History +from ranger.shared import SettingsAware + +class Environment(SettingsAware): + # A collection of data which is relevant for more than + # one class. + def __init__(self, path): + self.path = abspath(expanduser(path)) + self.pathway = () + self.last_search = None + self.directories = {} + self.pwd = None # current directory + self.cf = None # current file + self.keybuffer = KeyBuffer() + self.copy = None + self.termsize = None + self.history = History(self.settings.max_history_size) + + from ranger.shared import EnvironmentAware + EnvironmentAware.env = self + + def key_append(self, key): + """Append a key to the keybuffer""" + from ranger import log + self.keybuffer = KeyBuffer(self.keybuffer + (key, )) + + def key_clear(self): + """Clear the keybuffer""" + self.keybuffer = KeyBuffer() + + def at_level(self, level): + """Returns the FileSystemObject at the given level. +level 1 => preview +level 0 => current file/directory +level <0 => parent directories""" + if level <= 0: + try: + return self.pathway[level - 1] + except IndexError: + return None + else: + try: + return self.directories[self.cf.path] + except AttributeError: + return None + except KeyError: + return self.cf + + def garbage_collect(self): + """Delete unused directory objects""" + from ranger.fsobject.fsobject import FileSystemObject + for key in tuple(self.directories.keys()): + value = self.directories[key] + if isinstance(value, FileSystemObject): + if value.is_older_than(1200): + del self.directories[key] + + def get_directory(self, path): + """Get the directory object at the given path""" + path = abspath(path) + try: + return self.directories[path] + except KeyError: + self.directories[path] = Directory(path) + return self.directories[path] + + def assign_correct_cursor_positions(self): + """Assign correct cursor positions for subdirectories""" + last_path = None + for path in reversed(self.pathway): + if last_path is None: + last_path = path + continue + + path.move_pointer_to_file_path(last_path) + last_path = path + + def history_go(self, relative): + """Move relative in history""" + if self.history: +# self.enter_dir(self.history.move(relative)) + self.history.move(relative).go() + + def enter_dir(self, path, history = True): + """Enter given path""" + if path is None: return + path = str(path) + + # get the absolute path + path = normpath(join(self.path, expanduser(path))) + + try: + new_pwd = self.get_directory(path) + except NoDirectoryGiven: + return False + + self.path = path + self.pwd = new_pwd + + self.pwd.load_content_if_outdated() + + # build the pathway, a tuple of directory objects which lie + # on the path to the current directory. + if path == '/': + self.pathway = (self.get_directory('/'), ) + else: + pathway = [] + currentpath = '/' + for dir in path.split('/'): + currentpath = join(currentpath, dir) + pathway.append(self.get_directory(currentpath)) + self.pathway = tuple(pathway) + + self.assign_correct_cursor_positions() + + # set the current file. + self.pwd.directories_first = self.settings.directories_first + self.pwd.sort_if_outdated() + self.cf = self.pwd.pointed_file + + if history: + self.history.add(new_pwd) + + return True + diff --git a/ranger/container/keybuffer.py b/ranger/container/keybuffer.py index 1f6471d8..10c9c40c 100644 --- a/ranger/container/keybuffer.py +++ b/ranger/container/keybuffer.py @@ -1,5 +1,7 @@ class KeyBuffer(tuple): + """Extension of tuple suited to be used as a keybuffer""" def __str__(self): + """returns a concatenation of all characters""" return "".join( map( to_string, self ) ) def to_string(i): diff --git a/ranger/defaults/__init__.py b/ranger/defaults/__init__.py index e69de29b..71df3cb3 100644 --- a/ranger/defaults/__init__.py +++ b/ranger/defaults/__init__.py @@ -0,0 +1 @@ +"""Default options and configration files""" diff --git a/ranger/environment.py b/ranger/environment.py deleted file mode 100644 index 881e25e0..00000000 --- a/ranger/environment.py +++ /dev/null @@ -1,127 +0,0 @@ -from os.path import abspath, normpath, join, expanduser -from ranger.fsobject.directory import Directory, NoDirectoryGiven -from ranger.container import KeyBuffer, History -from ranger.shared import SettingsAware - -class Environment(SettingsAware): - # A collection of data which is relevant for more than - # one class. - def __init__(self, path): - self.path = abspath(expanduser(path)) - self.pathway = () - self.last_search = None - self.directories = {} - self.pwd = None # current directory - self.cf = None # current file - self.keybuffer = KeyBuffer() - self.copy = None - self.termsize = None -# self.termsize = (24, 80) - self.history = History(self.settings.max_history_size) - - from ranger.shared import EnvironmentAware - EnvironmentAware.env = self - - def key_append(self, key): - """Append a key to the keybuffer""" - self.keybuffer = KeyBuffer(self.keybuffer + (key, )) - - def key_clear(self): - """Clear the keybuffer""" - self.keybuffer = KeyBuffer() - - def at_level(self, level): - """Returns the FileSystemObject at the given level. -level 1 => preview -level 0 => current file/directory -level <0 => parent directories""" - if level <= 0: - try: - return self.pathway[level - 1] - except IndexError: - return None - else: - try: - return self.directories[self.cf.path] - except AttributeError: - return None - except KeyError: - return self.cf - - def garbage_collect(self): - """Delete unused directory objects""" - from ranger.fsobject.fsobject import FileSystemObject - for key in tuple(self.directories.keys()): - value = self.directories[key] - if isinstance(value, FileSystemObject): - if value.is_older_than(1200): - del self.directories[key] - - def get_directory(self, path): - """Get the directory object at the given path""" - path = abspath(path) - try: - return self.directories[path] - except KeyError: - self.directories[path] = Directory(path) - return self.directories[path] - - def assign_correct_cursor_positions(self): - """Assign correct cursor positions for subdirectories""" - last_path = None - for path in reversed(self.pathway): - if last_path is None: - last_path = path - continue - - path.move_pointer_to_file_path(last_path) - last_path = path - - def history_go(self, relative): - """Move relative in history""" - if self.history: -# self.enter_dir(self.history.move(relative)) - self.history.move(relative).go() - - def enter_dir(self, path, history = True): - """Enter given path""" - if path is None: return - path = str(path) - - # get the absolute path - path = normpath(join(self.path, expanduser(path))) - - try: - new_pwd = self.get_directory(path) - except NoDirectoryGiven: - return False - - self.path = path - self.pwd = new_pwd - - self.pwd.load_content_if_outdated() - - # build the pathway, a tuple of directory objects which lie - # on the path to the current directory. - if path == '/': - self.pathway = (self.get_directory('/'), ) - else: - pathway = [] - currentpath = '/' - for dir in path.split('/'): - currentpath = join(currentpath, dir) - pathway.append(self.get_directory(currentpath)) - self.pathway = tuple(pathway) - - self.assign_correct_cursor_positions() - - # set the current file. - self.pwd.directories_first = self.settings.directories_first - self.pwd.sort_if_outdated() - self.cf = self.pwd.pointed_file - - if history: - self.history.add(new_pwd) - - return True - diff --git a/ranger/ext/__init__.py b/ranger/ext/__init__.py index e69de29b..9cf2ee50 100644 --- a/ranger/ext/__init__.py +++ b/ranger/ext/__init__.py @@ -0,0 +1 @@ +"""This package includes extensions with broader usability""" diff --git a/ranger/ext/debug.py b/ranger/ext/debug.py new file mode 100644 index 00000000..63a1cfd0 --- /dev/null +++ b/ranger/ext/debug.py @@ -0,0 +1,19 @@ +LOGFILE = '/tmp/errorlog' + +def log(*objects, **keywords): + """Writes objects to a logfile. +Has the same arguments as print() in python3""" + start = 'start' in keywords and keywords['start'] or 'ranger:' + sep = 'sep' in keywords and keywords['sep'] or ' ' + _file = 'file' in keywords and keywords['file'] or open(LOGFILE, 'a') + end = 'end' in keywords and keywords['end'] or '\n' + _file.write(sep.join(map(str, (start, ) + objects)) + end) + +#for python3-only versions, this could be replaced with: +# +#def log(*objects, start='ranger:', sep=' ', end='\n'): +# print(start, *objects, end=end, sep=sep, file=open(LOGFILE, 'a')) + +def trace(): + from traceback import print_stack + print_stack(file=open(LOGFILE, 'a')) diff --git a/ranger/ext/log.py b/ranger/ext/log.py deleted file mode 100644 index c2521e09..00000000 --- a/ranger/ext/log.py +++ /dev/null @@ -1,15 +0,0 @@ -LOGFILE = '/tmp/errorlog' - -def log(*objects, **keywords): - """Writes objects to a logfile. -Has the same arguments as print() in python3""" - start = 'start' in keywords and keywords['start'] or 'ranger:' - sep = 'sep' in keywords and keywords['sep'] or ' ' - _file = 'file' in keywords and keywords['file'] or open(LOGFILE, 'a') - end = 'end' in keywords and keywords['end'] or '\n' - _file.write(sep.join(map(str, (start, ) + objects)) + end) - -#for python3-only versions, this could be replaced with: -# -#def log(*objects, start='ranger:', sep=' ', end='\n'): -# print(start, *objects, end=end, sep=sep, file=open(LOGFILE, 'a')) diff --git a/ranger/ext/relpath.py b/ranger/ext/relpath.py index 46d8018d..2d633e7a 100644 --- a/ranger/ext/relpath.py +++ b/ranger/ext/relpath.py @@ -1,5 +1,11 @@ +import os +import ranger + def relpath(*paths): """returns the path relative to rangers library directory""" - from os.path import join - from ranger import RANGERDIR - return join(RANGERDIR, *paths) + return os.path.join(ranger.RANGERDIR, *paths) + +def relpath_conf(*paths): + """returns the path relative to rangers configuration directory""" + return os.path.join(ranger.CONFDIR, *paths) + diff --git a/ranger/fsobject/__init__.py b/ranger/fsobject/__init__.py index 2d6da282..fde46fc9 100644 --- a/ranger/fsobject/__init__.py +++ b/ranger/fsobject/__init__.py @@ -1,3 +1,6 @@ +"""FileSystemObjects are representation of files and directories +with fast access to their properties through caching""" + T_FILE = 'file' T_DIRECTORY = 'directory' T_UNKNOWN = 'unknown' diff --git a/ranger/fsobject/fsobject.py b/ranger/fsobject/fsobject.py index 20b47813..30261c2c 100644 --- a/ranger/fsobject/fsobject.py +++ b/ranger/fsobject/fsobject.py @@ -137,7 +137,8 @@ and caches it for later use""" def go(self): """enter the directory if the filemanager is running""" if self.fm: - self.fm.enter_dir(self.path) + return self.fm.enter_dir(self.path) + return False def load_if_outdated(self): """calls load() if the currently cached information is outdated or nonexistant""" diff --git a/ranger/gui/ui.py b/ranger/gui/ui.py index eb25d9ca..4b473021 100644 --- a/ranger/gui/ui.py +++ b/ranger/gui/ui.py @@ -37,7 +37,7 @@ class UI(DisplayableContainer): ## this line solves this problem: ## If an action, following a mouse click, includes the - ## destruction and re-initializion of the ui (e.g. running a + ## suspension and re-initializion of the ui (e.g. running a ## file by clicking on its preview) and the next key is another ## mouse click, the bstate of this mouse event will be invalid. ## (atm, invalid bstates are recognized as scroll-down) @@ -48,11 +48,10 @@ class UI(DisplayableContainer): self.setup() self.update_size() - def destroy(self): - """Destroy all widgets and turn off curses""" -# DisplayableContainer.destroy(self) + def suspend(self): + """Turn off curses""" from ranger import log - log("exiting ui!") + log("suspending ui!") self.win.keypad(0) curses.nocbreak() curses.echo() @@ -60,6 +59,11 @@ class UI(DisplayableContainer): curses.mousemask(0) curses.endwin() + def destroy(self): + """Destroy all widgets and turn off curses""" + DisplayableContainer.destroy(self) + self.suspend() + def handle_mouse(self): """Handles mouse input""" try: @@ -67,8 +71,8 @@ class UI(DisplayableContainer): except: return -# from ranger import log -# log('{0:0>28b} ({0})'.format(event.bstate)) + from ranger import log + log('{0:0>28b} ({0})'.format(event.bstate)) if DisplayableContainer.click(self, event): return @@ -116,7 +120,8 @@ Override this!""" def update_size(self): """Update self.env.termsize. -Extend this method to resize all widgets!""" +Extend this method to resize all widgets! +""" self.env.termsize = self.win.getmaxyx() def draw(self): diff --git a/ranger/gui/widgets/filelist.py b/ranger/gui/widgets/filelist.py index e8138e51..60c3e2f9 100644 --- a/ranger/gui/widgets/filelist.py +++ b/ranger/gui/widgets/filelist.py @@ -129,9 +129,11 @@ class FileList(Widget): string = drawed.basename if self.main_display: - self.win.addnstr(self.y + line, self.x+1, drawed.basename, self.wid-2) + self.win.addnstr( + self.y + line, self.x + 1, drawed.basename, self.wid - 2) else: - self.win.addnstr(self.y + line, self.x, drawed.basename, self.wid) + self.win.addnstr( + self.y + line, self.x, drawed.basename, self.wid) if self.display_infostring and drawed.infostring: info = drawed.infostring diff --git a/ranger/shared/__init__.py b/ranger/shared/__init__.py index 4bb09e30..1492eec0 100644 --- a/ranger/shared/__init__.py +++ b/ranger/shared/__init__.py @@ -1,3 +1,5 @@ +"""Shared objects contian singleton variables wich can be +inherited, essentially acting like global variables.""" class Awareness(object): pass diff --git a/ranger/shared/settings.py b/ranger/shared/settings.py index def09c4e..cf1c00c8 100644 --- a/ranger/shared/settings.py +++ b/ranger/shared/settings.py @@ -34,7 +34,7 @@ elif ismodule(options.colorscheme): options.colorscheme = var() break else: - raise Exception("The given colorscheme module contains no valid colorscheme!") + raise Exception("The colorscheme module contains no valid colorscheme!") else: raise Exception("Cannot locate colorscheme!") diff --git a/test/tc_directory.py b/test/tc_directory.py index cb8e747e..676ec0fe 100644 --- a/test/tc_directory.py +++ b/test/tc_directory.py @@ -1,10 +1,11 @@ if __name__ == '__main__': from __init__ import init; init() +from os.path import realpath, join, dirname + from ranger import fsobject from ranger.fsobject.file import File from ranger.fsobject.directory import Directory -from os.path import realpath, join, dirname TESTDIR = realpath(join(dirname(__file__), 'testdir')) TESTFILE = join(TESTDIR, 'testfile5234148') NONEXISTANT_DIR = join(TESTDIR, 'nonexistant') @@ -34,7 +35,8 @@ class Test1(unittest.TestCase): # Get the filenames you expect it to have and sort both before # comparing. I don't expect any order after only loading the filenames. assumed_filenames = os.listdir(TESTDIR) - assumed_filenames = list(map(lambda str: os.path.join(TESTDIR, str), assumed_filenames)) + assumed_filenames = list(map(lambda str: os.path.join(TESTDIR, str), + assumed_filenames)) assumed_filenames.sort() dir.filenames.sort() @@ -67,7 +69,7 @@ class Test1(unittest.TestCase): import os import time # modify the directory. If the time between the last modification - # was within the filesystems resolution of mtime, we should have a re-load. + # was within the filesystems resolution of mtime, we should have a reload def modify_dir(): open(TESTFILE, 'w').close() @@ -90,7 +92,8 @@ class Test1(unittest.TestCase): time.sleep(0.1) else: # fail after 5 seconds of trying - self.fail("Cannot perform test: mtime of TESTDIR is not being updated.") + self.fail( + "Cannot perform test: mtime of TESTDIR is not being updated.") self.assertTrue(dir.load_if_outdated()) diff --git a/test/tc_history.py b/test/tc_history.py index ad340992..e3377532 100644 --- a/test/tc_history.py +++ b/test/tc_history.py @@ -5,7 +5,7 @@ from unittest import TestCase, main import unittest class Test(TestCase): - def test_everything(self): + def test_history(self): hist = History(3) for i in range(6): hist.add(i) -- cgit 1.4.1-2-gfad0