Exemplo n.º 1
0
    def translate_img(self, img_path=None):
        if img_path is None:
            # 读取剪切板
            file_path, is_tempfile = Clipboard.paste()
        else:
            file_path = img_path
            is_tempfile = False

        if file_path and os.path.isfile(file_path):
            # print(file_path)

            resource_url = self.__upload_file(file_path)
            if resource_url is None:
                return None
            print(resource_url)

            url = self.__translate_url(resource_url)
            Clipboard.copy(url)  # 写入剪切板
            print(url)

            if is_tempfile:
                os.remove(file_path)

            return url
        else:
            return None
Exemplo n.º 2
0
    def __init__(self):
        """
            Initialises all the components in the user interface.
        """
        self.root = tk.Tk()
        self.colour_box = tk.Label(self.root)

        self.hex_frame = tk.LabelFrame(self.root, text="Hex")
        self.hex_label = tk.Label(self.hex_frame, text="Hex: #")
        self.hex_input = tk.Entry(self.hex_frame)
        self.hex_input.bind("<KeyRelease>", self.update_hex)

        self.rgb_frame = tk.LabelFrame(self.root, text="RGB")
        self.red_label = tk.Label(self.rgb_frame, text="Red:")
        self.red_input = tk.Entry(self.rgb_frame)
        self.red_input.bind("<KeyRelease>", self.update_rgb)
        self.green_label = tk.Label(self.rgb_frame, text="Green:")
        self.green_input = tk.Entry(self.rgb_frame)
        self.green_input.bind("<KeyRelease>", self.update_rgb)
        self.blue_label = tk.Label(self.rgb_frame, text="Blue:")
        self.blue_input = tk.Entry(self.rgb_frame)
        self.blue_input.bind("<KeyRelease>", self.update_rgb)

        self.clipboard_image = ImageTk.PhotoImage(
            Image.open("./clipboard.png").resize((30, 30)), Image.ANTIALIAS)
        self.input_boxes = {
            "red": self.red_input,
            "green": self.green_input,
            "blue": self.blue_input,
            "hex": self.hex_input
        }

        self.hex_clipboard_button = tk.Button(
            self.hex_frame,
            image=self.clipboard_image,
            command=lambda: Clipboard().copy_to_clipboard(
                self.root, self.input_boxes, "hex"))
        self.rgb_clipboard_button = tk.Button(
            self.rgb_frame,
            image=self.clipboard_image,
            command=lambda: Clipboard().copy_to_clipboard(
                self.root, self.input_boxes, "rgb"))

        self.colours = {
            "invalid input": "#FF726F",
            "default background": "#1D1D1D",
            "secondary": "#FFFFFF",
            "colour box": "#FF0000"
        }

        self.default_font_size = 14
Exemplo n.º 3
0
 def __init__(self, config, args):
     self.config = config
     self.ndb = args['ndb']
     self.key = args['key']
     self.log = args['log']
     self.search_string = ''
     self.search_mode = 'gstyle'
     self.search_direction = ''
     self.note = self.ndb.get_note(self.key) if self.key else None
     self.old_note = None
     self.tabstop = int(self.config.get_config('tabstop'))
     self.clipboard = Clipboard()
     super(ViewNote, self).__init__(
         urwid.SimpleFocusListWalker(self.get_note_content_as_list()))
Exemplo n.º 4
0
    def __init__(self, parent = None):
        QObject.__init__(self, parent = parent)

        # フックマネージャーを生成
        self.hook_manager = pyHook.HookManager()
        # KeyDown, KeyUpで呼ばれる関数を設定
        self.hook_manager.KeyDown = self.on_keyboard_event
        self.hook_manager.KeyUp= self.on_keyboard_event

        self.modifiers_key_state = ModifiersKeyState()

        self.timer = QTimer(self)
        self.timer.setInterval(800)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.on_timeout)
        self.timer_running = False

        self.window_dict = dict()
        self.candidates = deque()

        self.key_sequences = deque()
        self.window_id = None
        self.clipboard = Clipboard()
        self.current_node = None
        self.root_node = KeyDictNode(dict())
        for mode in Mode:
            self.root_node.set_key_dictionary(mode)
        for shortcuts_info in shortcuts_tuple:
            shortcuts_info.set_mode_shortcuts(self.root_node)
        self.current_exe_name = ""
        self._mode = Mode.NORMAL
        self.set_mode_node()
        self.waiting_return_key = ""
        self.func_dict = FuncDictDecorator.func_dict()
Exemplo n.º 5
0
    def _save_record(self):
        """
        Save the details of an uploaded file to the history file and send the link to its destination

        link - The link to the uploaded file
        paths - An array of paths to all the files and folders that were uploaded
        share_to - A string describing the intended destination of the link -
                   either the clipboard, a social network or stdout
        """

        if not self.link:
            return

        # save a record of it to the history,
        for path, filename in zip(self.paths, self.filenames):
            History().add(path, filename, self.link)

        # and then send the link to its destination, be that clipboard or social network.
        if self.share_to == 'clipboard':
            Clipboard().set(self.link)
        elif self.share_to == 'stdout':
            import sys
            sys.stdout.write(self.link)
        else:
            url = URLS[self.share_to] % (SHARE_MESSAGE, self.link)
            webbrowser.open(url, new=2)
Exemplo n.º 6
0
    def __init__(self):
        # Qt application
        self._app = QtWidgets.QApplication([sys.argv[0]])

        # Translation engine (will be set by events)
        self._gtrans = GTransWeb()

        # Clipboard and its handler
        self._clipboard = Clipboard(self._app)
        self._clip_handler = ClipboardHandler(self._clipboard)
        self._clip_handler.set_callback(self._on_clip_changed)
        # Main window
        self._window = Window(self._translate, self._on_clipmode_changed,
                              self._on_backendmode_changed,
                              self._on_headless_changed,
                              self._clipboard.get_mode_strs(),
                              GTransWeb.BACKEND_MODES)
        # Buffer for selection mode
        self._select_buf = CallableBuffer()

        # Exit function should be call at exit
        atexit.register(self.exit)
Exemplo n.º 7
0
 def __init__(self, config, args):
     self.config = config
     self.ndb = args['ndb']
     self.key = args['key']
     self.log = args['log']
     self.search_string = ''
     self.search_mode = 'gstyle'
     self.search_direction = ''
     self.note = self.ndb.get_note(self.key) if self.key else None
     self.old_note = None
     self.tabstop = int(self.config.get_config('tabstop'))
     self.clipboard = Clipboard()
     super(ViewNote, self).__init__(
               urwid.SimpleFocusListWalker(self.get_note_content_as_list()))
Exemplo n.º 8
0
def snippet(args):
    """Upload the contents of the user's clipboard as a text file"""

    # Get the contents of the clipboard
    clipboard = Clipboard().get()
    if clipboard is None:
        return

    if args.text == 'dropbox':
        # Create a unique name for the text file the snippet will be stored in
        # With the extension specified by the user
        filename = 'text_snippet_%d.%s' % (time(), args.extension)
        path = os.path.join(TMP_PATH, filename)

        # Save it
        f = open(path, 'w')
        f.write(clipboard)
        f.close()

        # Upload it
        c.handle_files([path], [filename], args.share)
Exemplo n.º 9
0
 def do_command(self):
     self.__copies = [item.copy() for item in self.items]  # pylint: disable=W0201
     Clipboard().put(self.__copies, self.list)
Exemplo n.º 10
0
 def execute(self):
     # hide quick-console window before cmd is executed
     self.hide()
     cmd = self.text()
     if not cmd:
         cmd = self.lastCmd
     logger.info('executing: {}'.format(cmd))
     # date time in filename format
     if cmd == 'dt':
         copyToClipboard(curDatetime('%Y%m%d%H%M%S'))
     # date time in readable format
     elif cmd == 'dh':
         copyToClipboard(curDatetime('%Y-%m-%d %H:%M:%S'))
     # open cmd in clipboard
     elif cmd == 'cmd':
         path = getTextFromClipboard()
         if not os.path.exists(path):
             path = '.'
         if os.path.isfile(path):
             path = os.path.dirname(path)
         command('start cmd.exe /k cd /d {}'.format(path))
     elif cmd == 'te':
         cur = Windows().current
         if not cur or not cur.path == r'C:\Windows\explorer.exe':
             return
         path = getTextFromClipboard()
         if not os.path.exists(path):
             print('path not exists')
             return
         if os.path.isfile(path):
             print('is not directory')
             return
         command(u'start gvim {}'.format(os.path.join(path, '0txt.txt')))
     # open mintty
     elif cmd == 'mt':
         path = getTextFromClipboard()
         try:
             if not os.path.exists(path):
                 raise Exception()
             if os.path.isfile(path):
                 path = os.path.dirname(path)
             path = path.replace('\\', '/')
             path = path.replace(':', '')
             path = '"/cygdrive/{}"'.format(path)
         except Exception:
             path = '~'
         print(path)
         command(("mintty --title \"mintty\" /bin/bash -lc 'cd {};"
                 + " exec bash'").format(path))
     elif cmd == 'ba' or cmd == 'bs':
         path = getTextFromClipboard()
         try:
             if not os.path.exists(path):
                 raise Exception()
             if os.path.isfile(path):
                 path = os.path.dirname(path)
             path = path.replace('\\', '/')
             path = path.replace(':', '')
             path = '"/cygdrive/{}"'.format(path)
         except Exception:
             path = '~'
         print(path)
         s = 'start bash -c \'cd {}; $SHELL\''.format(path)
         command(s)
     # random music
     elif cmd == 'rm':
         command('start pythonw rand_music.py')
     # secret
     elif cmd == 'av':
         command('start pythonw rand_movie.py')
     elif cmd == 'mav':
         command('start pythonw rand_mmd.py')
     elif cmd == 'yav':
         command('start pythonw rand_av.py')
     # put foreground window to right bottom
     elif cmd == 'put':
         import win32gui
         availGeo = QApplication.desktop().availableGeometry()
         right, bottom = availGeo.width(), availGeo.height()
         hwnd = win32gui.GetForegroundWindow()
         x, y, r, b = win32gui.GetWindowRect(hwnd)
         w = r - x
         h = b - y
         x, y = right - w, bottom - h
         win32gui.MoveWindow(hwnd, x, y, w, h, True)
     elif cmd == 'cl':
         logger.info('cl start')
         try:
             logger.info('cl get_image')
             logger.info(repr(Clipboard))
             fname = Clipboard.get_image()
             if fname:
                 logger.info('cl: ' + fname)
                 copyToClipboard(fname)
             else:
                 logger.info('cl nothing')
         except:
             logger.info(traceback.format_exc())
         logger.info('cl end')
     elif cmd == 'tm':
         run_tmp_script()
     # quit
     elif cmd == 'quit':
         exit()
     # execute in hotkeys directory
     elif cmd in self.cmds:
         logger.info('special cmds: {}'.format(hotkeys))
         logger.info('cmd: {}'.format(cmd))
         ecmd = 'start {}'.format(os.path.join(hotkeys, cmd))
         logger.info('ecmd: {}'.format(ecmd))
         command(ecmd)
     else:
         logger.error('unknown command {}'.format(cmd))
         print('oops')
         return
     self.clear(cmd)
Exemplo n.º 11
0
 def __putItemsOnClipboard(self):
     cb = Clipboard()
     self.__previousClipboardContents = cb.get() # pylint: disable=W0201
     cb.put(self.itemsToCut(), self.sourceOfItemsToCut())
Exemplo n.º 12
0
class ViewNote(urwid.ListBox):
    def __init__(self, config, args):
        self.config = config
        self.ndb = args['ndb']
        self.key = args['key']
        self.log = args['log']
        self.search_string = ''
        self.search_mode = 'gstyle'
        self.search_direction = ''
        self.note = self.ndb.get_note(self.key) if self.key else None
        self.old_note = None
        self.tabstop = int(self.config.get_config('tabstop'))
        self.clipboard = Clipboard()
        super(ViewNote, self).__init__(
            urwid.SimpleFocusListWalker(self.get_note_content_as_list()))

    def get_note_content_as_list(self):
        lines = []
        if not self.key:
            return lines
        if self.old_note:
            for l in self.old_note['content'].split('\n'):
                lines.append(
                    urwid.AttrMap(
                        urwid.Text(l.replace('\t', ' ' * self.tabstop)),
                        'note_content_old', 'note_content_old_focus'))
        else:
            for l in self.note['content'].split('\n'):
                lines.append(
                    urwid.AttrMap(
                        urwid.Text(l.replace('\t', ' ' * self.tabstop)),
                        'note_content', 'note_content_focus'))
        lines.append(urwid.AttrMap(urwid.Divider(u'-'), 'default'))
        return lines

    def update_note_view(self, key=None, version=None):
        if key:  # setting a new note
            self.key = key
            self.note = self.ndb.get_note(self.key)
            self.old_note = None

        if self.key and version:
            # verify version is within range
            if int(version) <= 0 or int(version) >= self.note['version'] + 1:
                self.log(u'Version v{0} is unavailable (key={1})'.format(
                    version, self.key))
                return

        if (not version and self.old_note) or \
           (self.key and version and version == self.note['version']):
            self.log(
                u'Displaying latest version v{0} of note (key={1})'.format(
                    self.note['version'], self.key))
            self.old_note = None
        elif self.key and version:
            # get a previous version of the note
            self.log(u'Fetching version v{0} of note (key={1})'.format(
                version, self.key))
            version_note = self.ndb.get_note_version(self.key, version)
            if not version_note:
                self.log(
                    u'Failed to get version v{0} of note (key={1})'.format(
                        version, self.key))
                # don't do anything, keep current note/version
            else:
                self.old_note = version_note

        self.body[:] = \
            urwid.SimpleFocusListWalker(self.get_note_content_as_list())
        if not self.search_string:
            self.focus_position = 0

    def lines_after_current_position(self):
        lines_after_current_position = range(self.focus_position + 1,
                                             len(self.body.positions()) - 1)
        return lines_after_current_position

    def lines_before_current_position(self):
        lines_before_current_position = range(0, self.focus_position)
        lines_before_current_position.reverse()
        return lines_before_current_position

    def search_note_view_next(self, search_string=None, search_mode=None):
        if search_string:
            self.search_string = search_string
        if search_mode:
            self.search_mode = search_mode
        note_range = self.lines_after_current_position(
        ) if self.search_direction == 'forward' else self.lines_before_current_position(
        )
        self.search_note_range(note_range)

    def search_note_view_prev(self, search_string=None, search_mode=None):
        if search_string:
            self.search_string = search_string
        if search_mode:
            self.search_mode = search_mode
        note_range = self.lines_after_current_position(
        ) if self.search_direction == 'backward' else self.lines_before_current_position(
        )
        self.search_note_range(note_range)

    def search_note_range(self, note_range):
        for line in note_range:
            line_content = self.note['content'].split('\n')[line]
            if (self.is_match(self.search_string, line_content)):
                self.focus_position = line
                break
        self.update_note_view()

    def is_match(self, term, full_text):
        if self.search_mode == 'gstyle':
            return term in full_text
        else:
            results = re.search(term, full_text)
            return (results is not None)

    def get_status_bar(self):
        if not self.key:
            return \
                urwid.AttrMap(urwid.Text(u'No note...'),
                              'status_bar')

        cur = -1
        total = 0
        if len(self.body.positions()) > 0:
            cur = self.focus_position
            total = len(self.body.positions())

        if self.old_note:
            t = time.localtime(float(self.old_note['versiondate']))
            title = utils.get_note_title(self.old_note)
            version = self.old_note['version']
        else:
            t = time.localtime(float(self.note['modifydate']))
            title = utils.get_note_title(self.note)
            flags = utils.get_note_flags(self.note)
            tags = utils.get_note_tags(self.note)
            version = self.note['version']

        mod_time = time.strftime(u'Date: %a, %d %b %Y %H:%M:%S', t)

        status_title = \
            urwid.AttrMap(urwid.Text(u'Title: ' +
                                     title,
                                     wrap='clip'),
                          'status_bar')

        status_key_index = \
            ('pack', urwid.AttrMap(urwid.Text(u' [' +
                                              self.key +
                                              u'] ' +
                                              str(cur + 1) +
                                              u'/' +
                                              str(total)),
                                   'status_bar'))

        status_date = \
            urwid.AttrMap(urwid.Text(mod_time,
                                     wrap='clip'),
                          'status_bar')

        if self.old_note:
            status_tags_flags = \
                ('pack', urwid.AttrMap(urwid.Text(u'[OLD:v' +
                                                  str(version) +
                                                  u']'),
                                       'status_bar'))
        else:
            status_tags_flags = \
                ('pack', urwid.AttrMap(urwid.Text(u'[' +
                                                  tags +
                                                  u'] [v' +
                                                  str(version) +
                                                  u'] [' +
                                                  flags +
                                                  u']'),
                                       'status_bar'))

        pile_top = urwid.Columns([status_title, status_key_index])
        pile_bottom = urwid.Columns([status_date, status_tags_flags])

        if self.old_note or \
           not (utils.note_published(self.note) and 'publishkey' in self.note):
            return urwid.AttrMap(urwid.Pile([pile_top, pile_bottom]),
                                 'status_bar')

        pile_publish = \
            urwid.AttrMap(urwid.Text(u'Published: http://simp.ly/publish/' +
                                     self.note['publishkey']),
                          'status_bar')
        return \
            urwid.AttrMap(urwid.Pile([ pile_top, pile_bottom, pile_publish ]),
                          'status_bar')

    def copy_note_text(self):
        line_content = self.note['content'].split('\n')[self.focus_position]
        self.clipboard.copy(line_content)

    def keypress(self, size, key):
        if key == self.config.get_keybind('tabstop2'):
            self.tabstop = 2
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        elif key == self.config.get_keybind('tabstop4'):
            self.tabstop = 4
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        elif key == self.config.get_keybind('tabstop8'):
            self.tabstop = 8
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        else:
            return key

        return None
Exemplo n.º 13
0
 def restoreItemsToPasteToSource(self):
     Clipboard().put(self.__itemsToPaste, self.__sourceOfItemsToPaste)
Exemplo n.º 14
0
 def clearSourceOfItemsToPaste(self):
     Clipboard().clear()
Exemplo n.º 15
0
    kh = KeyHandler(display)

    if arguments['copy']:
        # Copy from focused window
        copy_from_focused()
    elif arguments['paste']:
        # Paste to focused window
        paste_to_focused()
    elif arguments['focused']:
        # Print focused window id
        print(get_focused().id)
    elif arguments['daemon']:
        # Start daemon
        from clipboard import Clipboard
        Clipboard().run()
    elif arguments['history']:
        # print history?
        pass

# --------- Automate mouse clicks:
# import time
# from Xlib import X
# from Xlib.display import Display
# from Xlib.ext import xtest
# d=Display()
# def click(b):
#     xtest.fake_input(d.get_input_focus().focus, X.ButtonPress, b)
#     d.flush()
#     d.sync()
#     xtest.fake_input(d.get_input_focus().focus, X.ButtonRelease, b)
Exemplo n.º 16
0
 def getItemsToPaste(self):
     return Clipboard().get()
Exemplo n.º 17
0
 def __removeItemsFromClipboard(self):
     cb = Clipboard()
     cb.put(*self.__previousClipboardContents)
Exemplo n.º 18
0
 def getItemsToPaste(self):
     items, source = Clipboard().get()
     return [item.copy() for item in items], source
Exemplo n.º 19
0
 def __putItemsOnClipboard(self):
     cb = Clipboard()
     self.__previousClipboardContents = cb.get()  # pylint: disable=W0201
     cb.put(self.itemsToCut(), self.sourceOfItemsToCut())
Exemplo n.º 20
0
 def undo_command(self):
     Clipboard().clear()
Exemplo n.º 21
0
class GTransWebGui(object):
    def __init__(self):
        # Qt application
        self._app = QtWidgets.QApplication([sys.argv[0]])

        # Translation engine (will be set by events)
        self._gtrans = GTransWeb()

        # Clipboard and its handler
        self._clipboard = Clipboard(self._app)
        self._clip_handler = ClipboardHandler(self._clipboard)
        self._clip_handler.set_callback(self._on_clip_changed)
        # Main window
        self._window = Window(self._translate, self._on_clipmode_changed,
                              self._on_backendmode_changed,
                              self._on_headless_changed,
                              self._clipboard.get_mode_strs(),
                              GTransWeb.BACKEND_MODES)
        # Buffer for selection mode
        self._select_buf = CallableBuffer()

        # Exit function should be call at exit
        atexit.register(self.exit)

    def run(self):
        ''' Run main application '''
        self._app.exec_()

    def exit(self):
        ''' Exit application '''
        self._gtrans.exit()

    def _translate(self, src_text=None):
        ''' Translate passed text. If not passed, it will be get from GUI. '''
        # Get languages from GUI
        src_lang, tgt_lang = self._window.get_langs()
        # Source text
        if src_text is None:
            # Get text from GUI
            src_text = self._window.get_src_text()
        else:
            # Set text to GUI
            self._window.set_src_text(src_text)
        # Start translation
        tgt_text = self._gtrans.translate(src_lang, tgt_lang, src_text)

        # Set to GUI
        self._window.set_tgt_text(tgt_text)
        # Set to clipboard
        if self._window.get_overwrite():
            self._clip_handler.overwrite_clip(tgt_text)

    def _on_clip_changed(self, src_text):
        ''' When clipboard changed, start to translate. '''
        if self._clipboard.get_mode_str() == 'select':
            # Postpone by buffering
            self._select_buf(self._translate, src_text)
        else:
            # Translate right now
            self._translate(src_text)

    def _on_clipmode_changed(self, mode_str):
        ''' When GUI changed, connect to clipboard'''
        self._clipboard.set_mode(mode_str)

    def _on_backendmode_changed(self, mode_str):
        ''' When GUI changed, connect to gtrans '''
        # Restart browser
        self._gtrans.exit()
        headless = self._gtrans.is_headless()
        self._gtrans = GTransWeb(backend_mode=mode_str, headless=headless)

    def _on_headless_changed(self, checked):
        ''' When GUI changed, connect to gtrans '''
        checked = bool(checked)
        # Restart browser
        self._gtrans.exit()
        backend = self._gtrans.get_backend_mode()
        self._gtrans = GTransWeb(backend_mode=backend, headless=checked)
Exemplo n.º 22
0
class EnVimKey(QObject):

    about_to_quit = pyqtSignal()
    changed_mode = pyqtSignal(str, str, int)
    about_to_search = pyqtSignal(object)

    def __init__(self, parent = None):
        QObject.__init__(self, parent = parent)

        # フックマネージャーを生成
        self.hook_manager = pyHook.HookManager()
        # KeyDown, KeyUpで呼ばれる関数を設定
        self.hook_manager.KeyDown = self.on_keyboard_event
        self.hook_manager.KeyUp= self.on_keyboard_event

        self.modifiers_key_state = ModifiersKeyState()

        self.timer = QTimer(self)
        self.timer.setInterval(800)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.on_timeout)
        self.timer_running = False

        self.window_dict = dict()
        self.candidates = deque()

        self.key_sequences = deque()
        self.window_id = None
        self.clipboard = Clipboard()
        self.current_node = None
        self.root_node = KeyDictNode(dict())
        for mode in Mode:
            self.root_node.set_key_dictionary(mode)
        for shortcuts_info in shortcuts_tuple:
            shortcuts_info.set_mode_shortcuts(self.root_node)
        self.current_exe_name = ""
        self._mode = Mode.NORMAL
        self.set_mode_node()
        self.waiting_return_key = ""
        self.func_dict = FuncDictDecorator.func_dict()


    @FuncDictDecorator.inner_func("insert")
    def change_to_insert_mode(self):
        self._mode = Mode.INSERT
        self.set_mode_node()
        self.changed_mode.emit("Mode", "Insert", 500)
        print("insert")

    @FuncDictDecorator.inner_func("normal")
    def change_to_normal_mode(self):
        self._mode = Mode.NORMAL
        self.set_mode_node()
        self.changed_mode.emit("Mode", "Normal", 500)
        print("normal")

    @FuncDictDecorator.inner_func("visual")
    def change_to_visual_mode(self):
        self._mode = Mode.VISUAL
        self.set_mode_node()
        self.changed_mode.emit("Mode", "Visual", 500)
        print("visual")

    @FuncDictDecorator.inner_func("focus")
    def set_window_focus(self, search_window_name):
        def match_window_name(window_handle, dummy):
            window_title = str(win32gui.GetWindowText(window_handle))
            if window_name_pattern.match(window_title):
                self.target_window_handle = window_handle

        self.target_window_handle = None
        window_name_pattern = re.compile(search_window_name)
        win32gui.EnumWindows(match_window_name, "")
        if self.target_window_handle:
            win32gui.SetForegroundWindow(self.target_window_handle)
            win32gui.ShowWindow(self.target_window_handle, win32con.SW_MAXIMIZE)

    @FuncDictDecorator.inner_func("quit")
    def quit_envimkey(self):
        self.about_to_quit.emit()

    @FuncDictDecorator.inner_func("copy")
    def copy_to_clipboard(self,text):
        self.before_text = self.clipboard.get()
        self.clipboard.set(text)

    @FuncDictDecorator.inner_func("rollback")
    def rollback_to_clipboard(self):
        self.clipboard.set(self.before_text)

    def set_mode_node(self):
        self.current_node = self.root_node.dictionary[self._mode]
        # self.print_dict(self.root_node.dictionary)

    def timer_start(self):
        print("start")
        self.timer_running = True
        self.timer.start()

    def timer_stop(self):
        print("stop")
        self.timer.stop()
        self.timer_running = False
        self.set_mode_node()
        if self.waiting_return_key:
            self.emulate_keys(self.waiting_return_key)
            self.waiting_return_key = None
            self.key_sequences.clear()
        if self.key_sequences:
            self.emulate_keys(KeySequences.from_sequences(self.key_sequences).action_atoms)
            self.key_sequences.clear()

    def emulate_keys(self, keys):
        print(keys)
        for action_atom in keys:
            if action_atom.type == ActionType.PRESS:
                if action_atom.extended:
                    win32api.keybd_event(action_atom.info, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0, 0)
                else:
                    win32api.keybd_event(action_atom.info, 0, 0, 0)
                # win32api.keybd_event(action_atom.info, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0)
                win32api.keybd_event(action_atom.info, 0, win32con.KEYEVENTF_KEYUP, 0)
            elif action_atom.type == ActionType.DOWN:
                win32api.keybd_event(action_atom.info, 0, 0, 0)
            elif action_atom.type == ActionType.UP:
                win32api.keybd_event(action_atom.info, 0, win32con.KEYEVENTF_KEYUP, 0)
            else:
                func_arg = action_atom.info.args
                if func_arg is not None:
                    getattr(self, self.func_dict[action_atom.info.text])(func_arg)
                else:
                    getattr(self, self.func_dict[action_atom.info.text])()

    def search(self, key_text, exe_name):
        # self.print_dict(self.current_node.dictionary)
        print(exe_name)
        self.waiting_return_key = ""
        if not(self.timer_running):
            try:
                self.current_node = self.current_node.dictionary[exe_name]
            except KeyError:
                # マッチする実行ファイル名が登録されていない場合
                self.timer_stop()
                return
        try:
            node = self.current_node.dictionary[key_text]
            self.current_node = node
            # ノードの辞書が空で、結果が確定する場合
            if not(node.dictionary):
                self.key_sequences.clear()
                self.timer_stop()
                self.emulate_keys(node.return_key)
                return
            # 結果の候補が存在し、一定時間待機する必要がある場合
            if node.has_return_key:
                self.timer_start()
                self.waiting_return_key = node.return_key
                return
            # マッチしたが次の入力がなければ結果が確定しない場合
            self.timer_start()
            return
        # マッチするキーが存在しない場合
        except KeyError:
            if len(self.key_sequences) == 1:
                self.key_sequences.clear()
                self.timer_stop()
                return SearchResultType.NOT_MATCH_BREAK
            self.timer_stop()
            return

    def on_keyboard_event(self, event):
        # 自分でエミュレートしたイベントならそのままイベントを通す
        if event.Injected:
            # print(event.KeyID)
            return True

        # デバッグ用にescを押したら終了するようにしておく
        if event.KeyID == 27:
            self.timer.stop()
            self.about_to_quit.emit()
            return False

        window_id = event.Window
        # 前回のイベントとwindow_idが異なれば
        if self.window_id != window_id:
            self.window_id = window_id
            # キーイベントを受け取るアプリケーションのexe名を取得
            self.current_exe_name = self.get_exe_name(window_id)
            print(self.current_exe_name)

        code = event.KeyID
        # event.Transitionはpressなら0, releaseなら128
        is_press_event = not(event.Transition)
        # モディファイアーが押されているかチェックし、modifiers_key_stateの状態を更新する
        pressed_modifier = self.modifiers_key_state.pressing(code, is_press_event)

        # モディファイアーが押されていれば以降の処理をしない
        if pressed_modifier:
            print("modifier", code)
            return True

        # キーがReleaseされるイベントなら以降の処理をしない
        if not(is_press_event):
            return True

        # キーコードとモディファイアーの状態をもとにキーシークエンスを生成
        seq = KeySequence.from_code(code, self.modifiers_key_state.presses())

        self.key_sequences.append(seq)

        search_result = self.search(seq.text, self.current_exe_name)

        if search_result == SearchResultType.NOT_MATCH_BREAK:
            return True

        # Falseを返すとイベントを無視し、Trueを返すとイベントを処理する
        return False

    def get_exe_name(self, window_id):
        try:
            base_exe_name = self.window_dict[window_id]
        except KeyError:
            # プロセスIDを取得
            thread_id, process_id = GetWindowThreadProcessId(window_id)
            # プロセスハンドルを取得
            process_handle = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, 0, process_id)
            # キーを受け取るアプリケーションのexe名を取得
            name = GetModuleFileNameEx(process_handle, 0)
            # .exeを除く
            base_exe_name = os.path.basename(name)[:-4]
            self.window_dict[window_id] = base_exe_name
        return base_exe_name

    def _window_enum_callback(self, hwnd, wildcard):
        is_visible = win32gui.IsWindowVisible(hwnd)
        if not(is_visible):
            return

        title = str(win32gui.GetWindowText(hwnd))
        if title != "" and title != "Program Manager":
            try:
                exe_name = self.get_exe_name(hwnd)
            except:
                exe_name = ""
            self.candidates.append((title, exe_name, hwnd))

    def find_window_wildcard(self):
        self.candidates.clear()
        win32gui.EnumWindows(self._window_enum_callback, "")

    @FuncDictDecorator.inner_func("search")
    def search_exe(self):
        self.find_window_wildcard()
        self.about_to_search.emit(self.candidates)

    def key_unlock(self):
        # キーボードフックを解除する
        self.hook_manager.UnhookKeyboard()
        self.thread().quit()

    def keylock(self):
        # キーボードフックを開始する
        self.hook_manager.HookKeyboard()
        pythoncom.PumpWaitingMessages()

    def print_dict(self, d, depth = 0):
        def print_indent(depth, *args, **kwargs):
            print(" "*8*depth, *args, **kwargs)

        for x, y in d.items():
            if len(y.dictionary):
                print_indent(depth, x)
                self.print_dict(y.dictionary, depth + 1)
            if y.has_return_key:
                print_indent(depth, x, y.return_key)

    def on_timeout(self):
        print("timeout")
        self.timer_stop()
Exemplo n.º 23
0
import subprocess
import sys
from clipboard import Clipboard

# def clipboard_test():
#         p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
#         p.stdin.write('copy-text!@#$>>?')
#         p.stdin.close()

# clipboard_test()

clip = Clipboard()

clip.get_clipboard()
clip.print_items()


Exemplo n.º 24
0
 def redo_command(self):
     Clipboard().put(self.__copies, self.list)
Exemplo n.º 25
0
class Wveinterface:
    """
    Create a wave user interface based on Tkinterface to read and modify the waves to play on the DPS

    """
    def __init__(self, prevroot, datawve):
        """
        Create a waveinterface instance.

        :param prevroot: is the main window 
        :param datawve: is the datapoints to play with
        :returns: a new instance of wave interface

        """
        self.root = maketoplevel(prevroot, True)
        self.root.title("Wave editor")

        self.datawve = datawve

        self.dataclpbrd = []
        self.clipboardtime = 0

        row = 0
        col = 0
        self.tablewve = Table(self.root, self.datawve,
                              ('step', 'time [s]', ('voltage [V]', VCOL),
                               ('current [A]', CCOL)), row, col, TABLEROW,
                              TABLECOL)

        SCOPEROWSPAN = 15
        self.scope = Scope(self.root,
                           self.datawve,
                           TABLEROW + 1 + 1,
                           0,
                           rowspan=SCOPEROWSPAN,
                           showpower=False,
                           horizontaljoin=True,
                           buttoncallback=self.buttoncallback)

        row = 1
        rowspan = 1
        colspan = 1
        col = TABLECOL + colspan
        Button(self.root, text="Pick beg",
               command=self.btncmdpckbeg).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)
        col = TABLECOL + colspan
        row += rowspan
        Button(self.root, text="Pick end",
               command=self.btncmdpckend).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        Separator(self.root,
                  orient='horizontal').grid(row=TABLEROW + 1,
                                            column=0,
                                            columnspan=TABLECOL + 2 + 1 + 6,
                                            sticky=E + W,
                                            pady=8)

        Separator(self.root, orient='vertical').grid(row=0,
                                                     column=6,
                                                     rowspan=1 + TABLEROW + 1 +
                                                     SCOPEROWSPAN,
                                                     sticky=N + S,
                                                     padx=8)

        row = 0
        COL1 = TABLECOL + 2 + 1
        col = COL1
        colspan = 1
        insertlabelrow(self.root, row, col, (None, None, ('voltage [V]', VCOL),
                                             ('current [A]', CCOL)))

        row += rowspan
        insertlabelrow(self.root, row, col, ('time [s]:', ))
        self.dvartime = DoubleVar()
        self.dvarvoltage = DoubleVar()
        self.dvarcurrent = DoubleVar()
        insertentryrow(
            self.root, row, col,
            (None, self.dvartime, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Insert",
               command=self.butcmdinsert).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        row += rowspan
        col = COL1
        insertlabelrow(self.root, row, col, ('step :', ))
        self.ivarstep = IntVar()
        insertentryrow(
            self.root, row, col,
            (None, self.ivarstep, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Modify",
               command=self.butcmdmodify).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)
        col += colspan
        Button(self.root, text="Delete",
               command=self.butcmddelete).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        row += rowspan
        col = COL1
        insertlabelrow(self.root, row, col, ('pause [s]:', ))
        self.dvarpause = DoubleVar()
        insertentryrow(
            self.root, row, col,
            (None, self.dvarpause, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Append",
               command=self.butcmdappend).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        self.clipboard = Clipboard(self.root, self.datawve, self.updateview,
                                   TABLEROW + 2, COL1)

        col = COL1 + TABLECOL
        colspan = 1
        row = TABLEROW + 1 + SCOPEROWSPAN
        Button(self.root, text="Help",
               command=self.btncmdhelp).grid(row=row,
                                             column=col,
                                             sticky=E + W,
                                             padx=8)
        col += 1
        Button(self.root, text="Done",
               command=self.butcmddone).grid(row=row,
                                             column=col,
                                             sticky=E + W,
                                             padx=8)

        self.scope.update()
        self.scope.redraw()

    def updateview(self):
        """
        Update scope and table views
        """
        self.tablewve.updateview()
        self.scope.redraw()

    def butcmdmodify(self):
        """
        Modify and item of the table.

        Gets the item to modify and new values from the user interface fields.
        """
        i = self.ivarstep.get()
        if i < len(self.datawve) and i >= 0:
            self.datawve[i] = [self.datawve[self.ivarstep.get()][0]
                               ] + self.getvc(i)
            self.tablewve.updateview()
            self.scope.redraw()
        else:
            tkMessageBox.showinfo('Step not found',
                                  'Step index is not in the points interval')

    def butcmddelete(self):
        """
        Delete a table row.

        Read the index to delete by the interface field.
        """
        i = self.ivarstep.get()
        if i < len(self.datawve) and i >= 0:
            del self.datawve[i]
            self.tablewve.updateview()
            self.scope.redraw()
        else:
            tkMessageBox.showinfo('Step not found',
                                  'Step index is not in the points interval')

    def butcmdinsert(self):
        """
        Insert an item on the data table.

        Gets the item data from the interface fields.
        """
        i = self.tablewve.findtime(self.dvartime.get())

        if len(self.datawve) > 0 and i > 0 and abs(
                self.datawve[i - 1][TPOS] - self.dvartime.get()
        ) < 0.01:  #if the time is the same the insert becomes a modify
            self.datawve[i - 1] = [self.dvartime.get()] + self.getvc(i - 1)
        else:
            self.datawve.insert(i, [self.dvartime.get()] + self.getvc(i - 1))

        self.tablewve.updateview()
        self.scope.redraw()

    def butcmdappend(self):
        """
        Append an item to the data table.

        Gets the item to append values from the user interface fields.
        """
        if self.dvarpause.get() <= 0:
            tkMessageBox.showinfo('Time not monotonic',
                                  'Time pause has to be > 0')
            return

        if len(self.datawve) > 0:
            t0 = self.datawve[-1][TPOS]
        else:
            t0 = 0

        self.datawve.append([self.dvarpause.get() + t0] +
                            self.getvc(len(self.datawve) - 1))
        self.tablewve.updateview()
        self.scope.redraw()

    def btncmdpckbeg(self):
        """
        Gets begin data on the clipboard from the first row visible on the data list. 
        """
        r = self.tablewve.getfistvisiblerow()
        self.ivarstep.set(r)
        self.dvartime.set(self.datawve[r][TPOS])
        self.dvarvoltage.set(self.datawve[r][VPOS])
        self.dvarcurrent.set(self.datawve[r][CPOS])

        self.clipboard.setbegin(r)

    def btncmdpckend(self):
        """
        Gets end data on the clipboard from the second row visible on the data list. 
        """
        r = self.tablewve.getfistvisiblerow() + 1
        if r < len(self.datawve):
            self.ivarstep.set(r)
            self.dvartime.set(self.datawve[r][TPOS])
            self.dvarvoltage.set(self.datawve[r][VPOS])
            self.dvarcurrent.set(self.datawve[r][CPOS])

            self.clipboard.setend(r)

    def butcmddone(self):
        """
        Close the window.
        """
        self.root.destroy()

    def getvc(self, i):
        """
        Gets voltage and current from the interface fields.
        
        If they are negative, the voltage/current at the given position are taken.
        In case of the first point the value 0 is used.

        :param i: the index from which get parameters if something is < 0
        :return: a list containing voltage and current
        """
        v = self.dvarvoltage.get()
        c = self.dvarcurrent.get()

        if i >= 0:
            if v < 0.: v = self.datawve[i][VPOS]
            if c < 0.: c = self.datawve[i][CPOS]
        else:
            if v < 0.: v = 0.
            if c < 0.: c = 0.

        return [v, c]

    def buttoncallback(self, p, action='insert'):
        """
        Insert, modify or delete a point.

        That interface is used by the scopetube to edit the table.
        
        :param p: is a list containing the new value for (t, v, c)
        if v or c are not updated -1 is returned
        :param action: describes the type of action required
        """
        self.dvarvoltage.set(p[1])
        self.dvarcurrent.set(p[2])
        self.dvartime.set(p[0])
        self.ivarstep.set(self.tablewve.findtime(p[0]))

        if action == 'insert':
            self.butcmdinsert()
        elif action == 'modify':
            self.butcmdmodify()
        elif action == 'delete':
            self.butcmddelete()
        else:
            print(
                'Internal error: unexpected button call back in wve interface')

    def btncmdhelp(self):
        """
        Open a window with basic help on the wave interface.
        """
        Txtinterface(
            self.root, 'Help',
            """Wave editor window is designed to create new waveform to play on the DPS supplier.
The wave is visible on two different output formats:
- top-left is text table showing what voltage and current set at give timing
Every line has its step number useful for editing
- bottom-left is the wave graphical picture representing the table above
The wave data can be entered in three ways:
- graphically with mouse clicking on the bottom-left graph
- textually with the commands on top-right input section
- from clipboard on the bottom-right side
The clipboard can copy/cut and paste from the data section. 
Clipboard data can be modified bebore pasting back:
- amplified (or attenuated if the factor is below 1)
- translated (on Y for voltage and current and also on time)
- transformed in a ramp: the give number of steps are inserted between 
the first and last data sample
On the graphical section it is possible to manage the enabled waveforms
with the mouse:
- drage with left button pressed to move the waveform(s)
- rotate wheel to zoom/unzoom the time (x)
- press shift while rotating wheel to zoom/unzoom the amplitude (y)
- press ctrl while rotating wheel to change the enabled waveform(s)
- press wheel to fit waveform(s) on time and y scales 
- press right button to insert a point (on the enabled variables)
- press shift and right button to modify the amplitude of the point(s) at the right 
of the mouse arrow with mouse amplitude on the enabled wave(s)
- press ctrl and right button to delete the point at the right of the mouse pointer
on the enabled wave(s)
- press ctrl and shift to replace the point at the right of the mouse pointer with the 
current mouse arrow place on the enabled wave(s)
On the bottom of the screen the scale, translation and enables are available 
for manual zooming and moving.
On the top-right side it is possible to add new points:
- insert button adds a new point at given time, use -1 on voltage/current to 
keep previous value
- insert button to insert a new point (with absolute time) if the required time 
is already present, that point is modified with new values
- modify and delete buttons can be used to edit or delete the given step
- append is used to add a new point to the tail of current waveform known 
the delta time between last one
On the clipboard the sample time is stored as delta between adiacent points 
while on the main table it is absolute.
On the clipboard are available the following functions:
- Copy and cut from begin/end steps of the data into the clipboard
- Paste clipboard at the given step inserting or overwriteing the data present there
The clipboard can be modified:
- Amplified to stretch in x or y depending on the factors
- Translated on x and y depending on the factors 
- Transform the clipboard in a ramp using first and last points as begin
and end values with given number of steps
The clipboard and the data are showed with following buttons:
- Line up/down to move up or down by 1 line
- Page up/down to move up or dosn by all row available minus 1
- Top/bottom to go to the first or last element
- Goto time/step to move the first line at the given step
- Pick begin/end to read the first/second line and put is in begin/end fields
That is useful for edit purpose without copying by hand.
""")
Exemplo n.º 26
0
 def __removeItemsFromClipboard(self):
     cb = Clipboard()
     cb.put(*self.__previousClipboardContents)
Exemplo n.º 27
0
    def __init__(self, prevroot, datawve):
        """
        Create a waveinterface instance.

        :param prevroot: is the main window 
        :param datawve: is the datapoints to play with
        :returns: a new instance of wave interface

        """
        self.root = maketoplevel(prevroot, True)
        self.root.title("Wave editor")

        self.datawve = datawve

        self.dataclpbrd = []
        self.clipboardtime = 0

        row = 0
        col = 0
        self.tablewve = Table(self.root, self.datawve,
                              ('step', 'time [s]', ('voltage [V]', VCOL),
                               ('current [A]', CCOL)), row, col, TABLEROW,
                              TABLECOL)

        SCOPEROWSPAN = 15
        self.scope = Scope(self.root,
                           self.datawve,
                           TABLEROW + 1 + 1,
                           0,
                           rowspan=SCOPEROWSPAN,
                           showpower=False,
                           horizontaljoin=True,
                           buttoncallback=self.buttoncallback)

        row = 1
        rowspan = 1
        colspan = 1
        col = TABLECOL + colspan
        Button(self.root, text="Pick beg",
               command=self.btncmdpckbeg).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)
        col = TABLECOL + colspan
        row += rowspan
        Button(self.root, text="Pick end",
               command=self.btncmdpckend).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        Separator(self.root,
                  orient='horizontal').grid(row=TABLEROW + 1,
                                            column=0,
                                            columnspan=TABLECOL + 2 + 1 + 6,
                                            sticky=E + W,
                                            pady=8)

        Separator(self.root, orient='vertical').grid(row=0,
                                                     column=6,
                                                     rowspan=1 + TABLEROW + 1 +
                                                     SCOPEROWSPAN,
                                                     sticky=N + S,
                                                     padx=8)

        row = 0
        COL1 = TABLECOL + 2 + 1
        col = COL1
        colspan = 1
        insertlabelrow(self.root, row, col, (None, None, ('voltage [V]', VCOL),
                                             ('current [A]', CCOL)))

        row += rowspan
        insertlabelrow(self.root, row, col, ('time [s]:', ))
        self.dvartime = DoubleVar()
        self.dvarvoltage = DoubleVar()
        self.dvarcurrent = DoubleVar()
        insertentryrow(
            self.root, row, col,
            (None, self.dvartime, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Insert",
               command=self.butcmdinsert).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        row += rowspan
        col = COL1
        insertlabelrow(self.root, row, col, ('step :', ))
        self.ivarstep = IntVar()
        insertentryrow(
            self.root, row, col,
            (None, self.ivarstep, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Modify",
               command=self.butcmdmodify).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)
        col += colspan
        Button(self.root, text="Delete",
               command=self.butcmddelete).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        row += rowspan
        col = COL1
        insertlabelrow(self.root, row, col, ('pause [s]:', ))
        self.dvarpause = DoubleVar()
        insertentryrow(
            self.root, row, col,
            (None, self.dvarpause, self.dvarvoltage, self.dvarcurrent))
        col += TABLECOL
        Button(self.root, text="Append",
               command=self.butcmdappend).grid(row=row,
                                               column=col,
                                               sticky=E + W,
                                               padx=8)

        self.clipboard = Clipboard(self.root, self.datawve, self.updateview,
                                   TABLEROW + 2, COL1)

        col = COL1 + TABLECOL
        colspan = 1
        row = TABLEROW + 1 + SCOPEROWSPAN
        Button(self.root, text="Help",
               command=self.btncmdhelp).grid(row=row,
                                             column=col,
                                             sticky=E + W,
                                             padx=8)
        col += 1
        Button(self.root, text="Done",
               command=self.butcmddone).grid(row=row,
                                             column=col,
                                             sticky=E + W,
                                             padx=8)

        self.scope.update()
        self.scope.redraw()
Exemplo n.º 28
0
 def __putItemsOnClipboard(self):
     cb = Clipboard()
     self.__previousClipboardContents = cb.get() # pylint: disable-msg=W0201
     cb.put(self.items, self.list)
Exemplo n.º 29
0
class ViewNote(urwid.ListBox):

    def __init__(self, config, args):
        self.config = config
        self.ndb = args['ndb']
        self.key = args['key']
        self.log = args['log']
        self.search_string = ''
        self.search_mode = 'gstyle'
        self.search_direction = ''
        self.note = self.ndb.get_note(self.key) if self.key else None
        self.old_note = None
        self.tabstop = int(self.config.get_config('tabstop'))
        self.clipboard = Clipboard()
        super(ViewNote, self).__init__(
                  urwid.SimpleFocusListWalker(self.get_note_content_as_list()))

    def get_note_content_as_list(self):
        lines = []
        if not self.key:
            return lines
        if self.old_note:
            for l in self.old_note['content'].split('\n'):
                lines.append(
                    urwid.AttrMap(urwid.Text(l.replace('\t', ' ' * self.tabstop)),
                                  'note_content_old',
                                  'note_content_old_focus'))
        else:
            for l in self.note['content'].split('\n'):
                lines.append(
                    urwid.AttrMap(urwid.Text(l.replace('\t', ' ' * self.tabstop)),
                                  'note_content',
                                  'note_content_focus'))
        lines.append(urwid.AttrMap(urwid.Divider(u'-'), 'default'))
        return lines

    def update_note_view(self, key=None, version=None):
        if key: # setting a new note
            self.key      = key
            self.note     = self.ndb.get_note(self.key)
            self.old_note = None

        if self.key and version:
            # verify version is within range
            if int(version) <= 0 or int(version) >= self.note['version'] + 1:
                self.log(u'Version v{0} is unavailable (key={1})'.
                         format(version, self.key))
                return

        if (not version and self.old_note) or \
           (self.key and version and version == self.note['version']):
            self.log(u'Displaying latest version v{0} of note (key={1})'.
                     format(self.note['version'], self.key))
            self.old_note = None
        elif self.key and version:
            # get a previous version of the note
            self.log(u'Fetching version v{0} of note (key={1})'.
                     format(version, self.key))
            version_note = self.ndb.get_note_version(self.key, version)
            if not version_note:
                self.log(u'Failed to get version v{0} of note (key={1})'.
                         format(version, self.key))
                # don't do anything, keep current note/version
            else:
                self.old_note = version_note

        self.body[:] = \
            urwid.SimpleFocusListWalker(self.get_note_content_as_list())
        if not self.search_string:
            self.focus_position = 0

    def lines_after_current_position(self):
        lines_after_current_position = range(self.focus_position + 1, len(self.body.positions()) - 1)
        return lines_after_current_position

    def lines_before_current_position(self):
        lines_before_current_position = range(0, self.focus_position)
        lines_before_current_position.reverse()
        return lines_before_current_position

    def search_note_view_next(self, search_string=None, search_mode=None):
        if search_string:
            self.search_string = search_string
        if search_mode:
            self.search_mode = search_mode
        note_range = self.lines_after_current_position() if self.search_direction == 'forward' else self.lines_before_current_position()
        self.search_note_range(note_range)

    def search_note_view_prev(self, search_string=None, search_mode=None):
        if search_string:
            self.search_string = search_string
        if search_mode:
            self.search_mode = search_mode
        note_range = self.lines_after_current_position() if self.search_direction == 'backward' else self.lines_before_current_position()
        self.search_note_range(note_range)

    def search_note_range(self, note_range):
        for line in note_range:
            line_content = self.note['content'].split('\n')[line]
            if (self.is_match(self.search_string, line_content)):
                self.focus_position = line
                break
        self.update_note_view()

    def is_match(self, term, full_text):
        if self.search_mode == 'gstyle':
            return term in full_text
        else:
            results = re.search(term, full_text)
            return ( results is not None )

    def get_status_bar(self):
        if not self.key:
            return \
                urwid.AttrMap(urwid.Text(u'No note...'),
                              'status_bar')

        cur   = -1
        total = 0
        if len(self.body.positions()) > 0:
            cur   = self.focus_position
            total = len(self.body.positions())

        if self.old_note:
            t = time.localtime(float(self.old_note['versiondate']))
            title    = utils.get_note_title(self.old_note)
            version  = self.old_note['version']
        else:
            t = time.localtime(float(self.note['modifydate']))
            title    = utils.get_note_title(self.note)
            flags    = utils.get_note_flags(self.note)
            tags     = utils.get_note_tags(self.note)
            version  = self.note['version']

        mod_time = time.strftime(u'Date: %a, %d %b %Y %H:%M:%S', t)

        status_title = \
            urwid.AttrMap(urwid.Text(u'Title: ' +
                                     title,
                                     wrap='clip'),
                          'status_bar')

        status_key_index = \
            ('pack', urwid.AttrMap(urwid.Text(u' [' + 
                                              self.key + 
                                              u'] ' +
                                              str(cur + 1) +
                                              u'/' +
                                              str(total)),
                                   'status_bar'))

        status_date = \
            urwid.AttrMap(urwid.Text(mod_time,
                                     wrap='clip'),
                          'status_bar')

        if self.old_note:
            status_tags_flags = \
                ('pack', urwid.AttrMap(urwid.Text(u'[OLD:v' + 
                                                  str(version) + 
                                                  u']'),
                                       'status_bar'))
        else:
            status_tags_flags = \
                ('pack', urwid.AttrMap(urwid.Text(u'[' + 
                                                  tags + 
                                                  u'] [v' + 
                                                  str(version) + 
                                                  u'] [' + 
                                                  flags + 
                                                  u']'),
                                       'status_bar'))

        pile_top = urwid.Columns([ status_title, status_key_index ])
        pile_bottom = urwid.Columns([ status_date, status_tags_flags ])

        if self.old_note or \
           not (utils.note_published(self.note) and 'publishkey' in self.note):
            return urwid.AttrMap(urwid.Pile([ pile_top, pile_bottom ]),
                                 'status_bar')

        pile_publish = \
            urwid.AttrMap(urwid.Text(u'Published: http://simp.ly/publish/' +
                                     self.note['publishkey']),
                          'status_bar')
        return \
            urwid.AttrMap(urwid.Pile([ pile_top, pile_bottom, pile_publish ]),
                          'status_bar')

    def copy_note_text(self):
        line_content = self.note['content'].split('\n')[self.focus_position]
        self.clipboard.copy(line_content)

    def keypress(self, size, key):
        if key == self.config.get_keybind('tabstop2'):
            self.tabstop = 2
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        elif key == self.config.get_keybind('tabstop4'):
            self.tabstop = 4
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        elif key == self.config.get_keybind('tabstop8'):
            self.tabstop = 8
            self.body[:] = \
                urwid.SimpleFocusListWalker(self.get_note_content_as_list())

        else:
            return key

        return None
Exemplo n.º 30
0
import cv2
import numpy as np

from vision import Vision
from controller import Controller
from keyboard import Keyboard
from clipboard import Clipboard

from game import Game

vision = Vision()
controller = Controller()
keyboard = Keyboard()
clipboard = Clipboard()
game = Game(vision, controller, keyboard, clipboard)

from pynput.keyboard import Key, Listener


#defining function to print when key is pressed
def on_press(key):
    pass
#print('{0} pressed'.format(key))


#defining function to print when key is released
def on_release(key):
    #print('{0} release'.format(key))
    if key == Key.esc:
        # Stop listener
        return False
Exemplo n.º 31
0
 def __putItemsOnClipboard(self):
     cb = Clipboard()
     self.__previousClipboardContents = cb.get(
     )  # pylint: disable-msg=W0201
     cb.put(self.items, self.list)