Source

gadgets / gadgets / ui / dialogs / notes.py

Full commit
import curses, time, datetime
from gadgets.ui.window import Window

class Notes(Window):
    """notes"""

    _table = '''CREATE TABLE if not exists notes
             (host text, method_id integer, timestamp integer, notes text)'''

    _insert = '''INSERT INTO notes VALUES(?, ?, ?, ?)'''
    _notes_query = '''SELECT * FROM notes WHERE host = ? ORDER BY timestamp DESC LIMIT 10'''

    def __init__(self, socket, lock, db):
        self._name = None
        self._socket = socket
        self._lock = lock
        db.ensure_table(self._table)
        self._db = db
        self._width = 40
        self._height = 18

    def _save(self, notes, method_id):
        timestamp=datetime.datetime.now()
        self._db.save(self._insert, (self._name, method_id, int(timestamp.strftime('%s')), notes))

    def _get_notes(self, win, method_id):
        curses.echo()
        curses.curs_set(1)
        notes = ''
        row = 2
        while not notes.endswith('\n\n'):
            win.move(row ,1)
            notes += win.getstr() + '\n'
            row += 1
        curses.noecho()
        curses.curs_set(0)
        if notes != '':
            notes = notes.strip()
            self._save(notes, method_id)

    def _show_notes(self, win, screen):
        notes = [note for note in self._db.query(self._notes_query, [self._name])]
        row = 2
        for i, note in enumerate(notes):
            d = datetime.datetime.fromtimestamp(note[2])
            win.addstr(row, 2, '{0}: {1}'.format(i + 1, d))
            row += 1
        x = win.getch()
        i = int(chr(x)) - 1
        try:
            note = notes[i]
        except IndexError:
            pass
        else:
            win = self._get_subwin(screen)
            win.addstr(2, 2, note[3])
        win.getch()

    def __call__(self, screen, data, method_id=None, command=None, name=None):
        self._name = name
        self._lock.acquire()
        win = self._get_subwin(screen)
        self._add_title(win, self.__doc__)
        if command == ord('n'):
            self._get_notes(win, method_id)
        elif command == ord('N'):
            self._show_notes(win, screen)
        self._lock.release()