Skip to content

Commit

Permalink
Merge pull request AnthonyDiGirolamo#1 from andyoakley/filewatcher
Browse files Browse the repository at this point in the history
  Filewatcher
  • Loading branch information
andyoakley authored Sep 10, 2017
2 parents 04a0306 + eaef110 commit 02ddad1
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 39 deletions.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
docopt==0.6.2
urwid==1.3.0
watchdog==0.8.3
46 changes: 18 additions & 28 deletions todotxt_machine/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
from todotxt_machine.colorscheme import ColorScheme
from todotxt_machine.keys import KeyBindings

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

# Import the correct version of configparser
if sys.version_info[0] >= 3:
Expand All @@ -40,28 +42,13 @@
config_parser_module = ConfigParser


autosave_lock = threading.Lock()


def autosave():
if not enable_autosave:
return

# print "autosaving..."
with autosave_lock:
# view.save_todos() # TODO: Saved message isn't displayed, need to force redraw urwid ui?
view.todos.save()

# Check the flag once again, as the flag may have been set
# after the last check but before this statement is executed.
if enable_autosave:
global timer
timer = threading.Timer(30.0, autosave)
timer.start()


timer = threading.Timer(30.0, autosave)

class AutoLoad(PatternMatchingEventHandler):
def on_modified(self, event):
view.reload_todos_from_file()
view.loop.draw_screen()

def exit_with_error(message):
sys.stderr.write(message.strip(' \n') + '\n')
Expand Down Expand Up @@ -162,6 +149,13 @@ def main():
exit_with_error("ERROR: unable to open {0}\n\nEither specify one as an argument on the command line or set it in your configuration file ({0}).".format(todotxt_file_path, arguments['--config']))
todos = Todos([], todotxt_file_path, donetxt_file_path)

todos.autosave = enable_autosave

observer = Observer()
observer.schedule(AutoLoad(patterns=['*/'+os.path.split(todotxt_file_path)[1]]),
os.path.split(todotxt_file_path)[0], recursive=False)
observer.start()

show_toolbar = get_boolean_config_option(cfg, 'settings', 'show-toolbar')
show_filter_panel = get_boolean_config_option(cfg, 'settings', 'show-filter-panel')
enable_borders = get_boolean_config_option(cfg, 'settings', 'enable-borders')
Expand All @@ -170,8 +164,6 @@ def main():
global view
view = UrwidUI(todos, keyBindings, colorscheme)

timer.start()

view.main( # start up the urwid UI event loop
enable_borders,
enable_word_wrap,
Expand All @@ -180,14 +172,12 @@ def main():

# UI is now shut down

# Shut down the auto-saving thread.
enable_autosave = False
timer.cancel()
observer.stop()
observer.join()


# Final save
with autosave_lock:
# print("Writing: {0}".format(todotxt_file_path))
view.todos.save()
# final save
view.todos.save()

exit(0)

Expand Down
27 changes: 23 additions & 4 deletions todotxt_machine/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
import random
from datetime import date


class Todo:
"""Single Todo item"""
_priority_regex = re.compile(r'\(([A-Z])\) ')

def __init__(self, item, index,
def __init__(self, item, index, parent,
colored="", priority="", contexts=[], projects=[],
creation_date="", due_date="", completed_date=""):
self.raw = item.strip()
Expand All @@ -21,6 +20,7 @@ def __init__(self, item, index,
self.due_date = due_date
self.completed_date = completed_date
self.colored = self.highlight()
self.parent = parent
# self.colored_length = TerminalOperations.length_ignoring_escapes(self.colored)

def update(self, item):
Expand All @@ -32,6 +32,8 @@ def update(self, item):
self.due_date = Todos.due_date(item)
self.completed_date = Todos.completed_date(item)
self.colored = self.highlight()
if self.parent.autosave:
self.parent.save()
# self.colored_length = TerminalOperations.length_ignoring_escapes(self.colored)

def __repr__(self):
Expand Down Expand Up @@ -142,11 +144,19 @@ class Todos:
def __init__(self, todo_items, file_path, archive_path):
self.file_path = file_path
self.archive_path = archive_path
self.autosave = True
self.update(todo_items)

def reload_from_file(self):
current=[t.raw + '\n' for t in self.todo_items]
with open(self.file_path, "r") as todotxt_file:
self.update(todotxt_file.readlines())
loaded=todotxt_file.readlines()

if loaded != current:
self.update(loaded)
return True
else:
return False

def save(self):
with open(self.file_path, "w") as todotxt_file:
Expand All @@ -168,6 +178,8 @@ def archive_done(self):

def update(self, todo_items):
self.parse_raw_entries(todo_items)
if self.autosave:
self.save()

def append(self, item, add_creation_date=True):
self.insert(len(self.todo_items), item, add_creation_date)
Expand All @@ -179,11 +191,15 @@ def insert(self, index, item, add_creation_date=True):
newtodo = self.todo_items[index]
if add_creation_date and newtodo.creation_date == "":
newtodo.add_creation_date()
if self.autosave:
self.save()
return index

def delete(self, index):
del self.todo_items[index]
self.update_raw_indices()
if self.autosave:
self.save()

def __iter__(self):
self.index = -1
Expand Down Expand Up @@ -223,7 +239,7 @@ def __repr__(self):
return repr([i for i in self.todo_items])

def create_todo(self, todo, index):
return Todo(todo, index,
return Todo(todo, index, self,
contexts=Todos.contexts(todo),
projects=Todos.projects(todo),
priority=Todos.priority(todo),
Expand Down Expand Up @@ -322,6 +338,9 @@ def swap(self, first, second):

self.todo_items[first], self.todo_items[second] = self.todo_items[second], self.todo_items[first]

if self.autosave:
self.save()

def filter_context(self, context):
return [item for item in self.todo_items if context in item.contexts]

Expand Down
16 changes: 9 additions & 7 deletions todotxt_machine/urwid_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,9 @@ def save_item(self):
self.parent_ui.update_filters(new_contexts=self.todo.contexts, new_projects=self.todo.projects)
self.editing = False

if self.parent_ui.todos.autosave:
self.parent_ui.todos.save()

def keypress(self, size, key):
if self.editing:
if key in ['down', 'up']:
Expand Down Expand Up @@ -453,14 +456,13 @@ def archive_done_todos(self):
self.update_header()

def reload_todos_from_file(self, button=None):
self.delete_todo_widgets()

self.todos.reload_from_file()

for t in self.todos.todo_items:
self.listbox.body.append(TodoWidget(t, self.key_bindings, self.colorscheme, self, wrapping=self.wrapping[0], border=self.border[0]))
if self.todos.reload_from_file():
self.delete_todo_widgets()

for t in self.todos.todo_items:
self.listbox.body.append(TodoWidget(t, self.key_bindings, self.colorscheme, self, wrapping=self.wrapping[0], border=self.border[0]))

self.update_header("Reloaded")
self.update_header("Reloaded")

def keystroke(self, input):
focus, focus_index = self.listbox.get_focus()
Expand Down

0 comments on commit 02ddad1

Please sign in to comment.