Exemple #1
0
    def set_system_text(cls, content):
        """set text to the clipboard
        
        First the clipboard is emptied. 
        
        This method fails when not in elevated mode.
        
        As alias, you can also call: Clipboard.Set_text("abacadabra")
        """
        print 'set to clipboard: %s' % content
        # content = unicode(content)
        if not OpenClipboardCautious():
            print 'Clipboard, set_system_text: could not open clipboard'
            return
        clipNum = win32clipboard.GetClipboardSequenceNumber()
        # print 'clipboard number: %s'% clipNum
        try:
            win32clipboard.EmptyClipboard()
            if type(content) == six.binary_type:
                format = cls.format_text
            elif type(content) == six.text_type:
                format = cls.format_unicode

            win32clipboard.SetClipboardData(format, content)
        except:
            print 'Clipboard, cannot set text to clipboard: %s' % content
        finally:
            clipNum2 = win32clipboard.GetClipboardSequenceNumber()
            if clipNum2 == clipNum:
                print 'Clipboard, did not increment clipboard number: %s' % clipNum
            win32clipboard.CloseClipboard()
Exemple #2
0
 def save_sequence_number(self):
     """get the Clipboard Sequence Number and store in instance
     
     It is set in self.current_sequence_number, no return
     """
     self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
     )
    def clear_clipboard(self):
        """Empty the clipboard and clear the internal clipboard data
        
        assume the clipboard is open
        
        this will be done at init phase with save_clear == True
        """
        if self.debug > 1:
            print("clear_clipboard, before start, sequence number: %s" %
                  self.current_sequence_number)

        if not OpenClipboardCautious():
            print('copy_to_system, could not open clipboard')
            return
        try:
            win32clipboard.EmptyClipboard()
            self._contents = None
        except:
            print("clipboard, clear_clipboard, could not clear the clipboard")
        finally:
            self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
            )
            if self.debug > 1:
                print("clear_clipboard, new sequence number: %s" %
                      self.current_sequence_number)
            win32clipboard.CloseClipboard()
    def copy_from_system(self,
                         formats=None,
                         save_clear=False,
                         waiting_interval=None,
                         waiting_iterations=None):
        """Copy the Windows system clipboard contents into this instance.

            Arguments:
             - *formats* (iterable, default: None) -- if not None, only the
               given content formats will be retrieved.  If None, all
               available formats will be retrieved.
             - *save_clear* (boolean, default: False) -- if true, the Windows
               system clipboard will be saved in self._backup, and
               cleared after its contents have been retrieved.
               Will be restored from self._backup when the instance is destroyed.
               If false contents are retrieved in self._contents
        """
        if waiting_interval or waiting_iterations:
            waiting_interval = waiting_interval or 0.1
            waiting_iterations = waiting_iterations or 10
            result = self._wait_for_clipboard_change(waiting_interval,
                                                     waiting_iterations)
            if result is None:
                print("no clipboard change")
                return
            if result:
                print('did have to wait %s steps of %s' %
                      (result, waiting_iterations))
        if not OpenClipboardCautious():
            if self.debug:
                print('Clipboard copy_from_system, could not open clipboard')
            return

        try:
            # Determine which formats to retrieve.
            contents = self._get_clipboard_data_from_system(formats=formats)

            # Retrieve Windows system clipboard content.
            if save_clear:
                if contents:
                    self._backup = copy.copy(contents)
                    if self.debug > 1:
                        print('Clipboard, set backup to: %s' %
                              repr(self._backup))
                else:
                    self._backup = None
                self._contents = None
                win32clipboard.EmptyClipboard()
            else:
                if contents:
                    self._contents = copy.copy(contents)
                else:
                    self._contents = None
        finally:
            # Clear the system clipboard, if requested, and close it.
            self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
            )
            win32clipboard.CloseClipboard()
            pass
Exemple #5
0
 def watch_clip(top):
     import win32clipboard
     import time
     lastid = None
     while True:
         time.sleep(0.01)
         nowid = win32clipboard.GetClipboardSequenceNumber()
         if lastid is None or (lastid != nowid):
             if lastid is not None:
                 top.event_generate("<<clipUpdateEvent>>",
                                    when="tail")
             lastid = nowid
Exemple #6
0
 def wait_for_change(cls,
                     timeout,
                     step=0.001,
                     formats=None,
                     initial_clipboard=None):
     # Save the current clipboard sequence number and clipboard contents,
     #  as necessary. The latter is not required unless formats are
     #  specified.
     seq_no = win32clipboard.GetClipboardSequenceNumber()
     if formats and not initial_clipboard:
         initial_clipboard = cls(from_system=True)
     return cls._wait_for_change(timeout, step, formats, initial_clipboard,
                                 seq_no)
Exemple #7
0
    def _wait_for_change(cls, timeout, step, formats, initial_clipboard,
                         seq_no):
        # This method determines if the system clipboard has changed by
        #  repeatedly checking the current sequence number.  Contents are
        #  compared if specific clipboard formats are given.
        timeout = time.time() + float(timeout)
        step = float(step)
        if isinstance(formats, integer_types):
            formats = (formats, )
        elif formats:
            for format in formats:
                if not isinstance(format, integer_types):
                    raise TypeError("Invalid clipboard format: %r" % format)
        clipboard2 = cls() if formats or initial_clipboard else None
        result = False
        while time.time() < timeout:
            seq_no_change = (win32clipboard.GetClipboardSequenceNumber() !=
                             seq_no)
            if seq_no_change and initial_clipboard:
                # Check if the content of any relevant format has changed.
                clipboard2.copy_from_system()
                formats_to_compare = formats if formats else "all"
                result = cls._clipboard_formats_changed(
                    formats_to_compare, initial_clipboard, clipboard2)

                # Reset the sequence number if the clipboard change is not
                #  related.
                if not result:
                    seq_no = win32clipboard.GetClipboardSequenceNumber()
            elif seq_no_change:
                result = True

            if result:
                break

            # Failure. Try again after *step* seconds.
            time.sleep(step)
        return result
    def _wait_for_clipboard_change(self, waiting_time, waiting_iterations):
        """wait a few steps until the clipboard is not changed.
        
        The previous Clipboard Sequence Number should be in
        the instance variable self.current_sequence_number
        
        This value is set when opening the clipboard, or in this internal function.
        
        When in doubt, call _set_sequence_number, before doing a copy!
        
        return True if changed
        """
        try:
            w_time = float(waiting_time)
        except ValueError:
            w_time = 0.001
        if w_time > 0.55:
            print(
                'Clipboard, _wait_for_clipboard_change, waiting time too long, set to 0.1'
                % w_time)
            w_time = 0.001
        try:
            n_wait = int(waiting_iterations)
        except ValueError:
            n_wait = 4
        if n_wait <= 0:
            n_wait = 4

        for i in range(n_wait):
            new_sequence_number = win32clipboard.GetClipboardSequenceNumber()
            if new_sequence_number > self.current_sequence_number:
                self.current_sequence_number = new_sequence_number
                if i:
                    if self.debug:
                        print(
                            '---Clipboard changed after %s steps of %.4fs (%.4f)'
                            % (i, w_time, i * w_time))
                else:
                    if self.debug > 1:
                        print(
                            '_wait_for_clipboard_change, clipboard changed immediately'
                        )
                # time.sleep(w_time)
                return i
            time.sleep(w_time)
        # no result:
        time_waited = n_wait * w_time
        if self.debug:
            print('Clipboard, no change in clipboard in %.4f seconds' %
                  time_waited)
Exemple #9
0
 def synchronized_changes(cls,
                          timeout,
                          step=0.001,
                          formats=None,
                          initial_clipboard=None):
     seq_no = win32clipboard.GetClipboardSequenceNumber()
     if formats and not initial_clipboard:
         initial_clipboard = cls(from_system=True)
     try:
         # Yield for clipboard operations.
         yield
     finally:
         # Wait for the system clipboard to change.
         cls._wait_for_change(timeout, step, formats, initial_clipboard,
                              seq_no)
    def __init__(self,
                 contents=None,
                 text=None,
                 from_system=False,
                 save_clear=False,
                 debug=None):
        """initialisation of clipboard instance.
        
        save_clear can be set to True, current clipboard contents is saved and cleared
               saved contents are kept in self._backup and will be retrieved
               when instance is destroyed.
        from_system: obsolete option
        contents: can be set as initial contents of the clipboard (not tested, 2019)
        text: can be set as initial text contents of the clipboard (not tested, 2019)
        debug: default off, 1: important messages are printed, > 1 more messages are printed
        
        """
        self._contents = {}
        self._backup = None
        self.debug = debug or 0
        if not OpenClipboardCautious():
            if self.debug:
                print(
                    'Warning Clipboard: at initialisation could not open the clipboard'
                )
            return
        self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
        )
        if self.debug > 1:
            print('current_sequence_number: %s' % self.current_sequence_number)

        # If requested, retrieve current system clipboard contents.
        if from_system:
            self.copy_from_system(save_clear=save_clear)
        elif save_clear:
            self.copy_from_system(save_clear=save_clear)

        # Process given contents for this Clipboard instance.
        if contents:
            try:
                self._contents = dict(contents)
            except Exception as e:
                raise TypeError("Clipboard: Invalid contents: %s (%r)" %
                                (e, contents))

        # Handle special case of text content.
        if not text is None:
            self._contents[self.format_unicode] = str(text)
    def copy_to_system(self, data=None, clear=True):
        """Copy the contents of this instance to the Windows clipboard

            Arguments:
            - data: text or dict of clipboard items (format, content) pairs
             - *clear* (boolean, default: True) -- if true, the Windows
               system clipboard will be cleared before this instance's
               contents are transferred.

        """
        if not OpenClipboardCautious():
            print('copy_to_system, could not open clipboard')
            return
        try:
            # Clear the system clipboard, if requested.
            if clear:
                try:
                    win32clipboard.EmptyClipboard()
                except:
                    if self.debug > 1:
                        print(
                            'Clipboard, cannot EmptyClipboard, need more rights, can also not restore backup of clipboard'
                        )

            # Transfer content to Windows system clipboard.
            data = data or self._contents
            if data is None:
                return
            elif isinstance(data, str):
                self.get_text(data)
            elif type(data) == dict:
                for format, content in list(data.items()):
                    win32clipboard.SetClipboardData(format, content)
            else:

                if self.debug:
                    print(
                        "Clipboard, copy_to_system, invalid type of data: %s" %
                        type(data))
                if self.debug > 1: print("data: %s\n========" % repr(data))
                return
        finally:
            self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
            )
            win32clipboard.CloseClipboard()
    def listen(self):
        while self.allow_listen:  # 是否允许监听,可通过 allow_listen 控制是否开启监听
            if not self.pause_listen:  # 是否暂停监听,可通过 pause_listen 控制是否暂停监听
                clip_sn = clip.GetClipboardSequenceNumber()  # 获取剪贴板序列号
                if clip_sn != self.last_clip_sn:  # 如果序列号和上次不一样,则代表剪贴板内容发生了变化

                    try:
                        data = self.get_data(dir_img=self.dir_img)  # 获取剪贴板内容
                        if data[1] and len(
                                data[1]) > self.max:  # 如果剪贴板内容太长,则直接跳过
                            pass
                        else:
                            self.print(data)  # 输出剪贴板内容
                            self.data.append(data)  # 将剪贴板内容存入列表
                            if len(self.data
                                   ) > self.num:  # 如果列表中储存的内容超过限定个数,则删除最早的
                                del self.data[0]
                        self.last_clip_sn = clip_sn  # 记录剪贴板序列号
                    except Exception as e:  # 如果发生异常,则打印异常信息
                        print_exc()
                        self.print(e)

                time.sleep(self.listen_invl)  # 休眠指定时间,一般设为0.5秒就可以了
Exemple #13
0
    def copy_from_system(self,
                         formats=None,
                         save_clear=False,
                         waiting_interval=None,
                         waiting_iterations=10):
        """Copy the Windows system clipboard contents into this instance.

            Arguments:
             - *formats* (iterable, default: None) -- if not None, only the
               given content formats will be retrieved.  If None, all
               available formats will be retrieved.
             - *save_clear* (boolean, default: False) -- if true, the Windows
               system clipboard will be saved in self._backup, and
               cleared after its contents have been retrieved.
               Will be restored from self._backup when the instance is destroyed.
               If false contents are retrieved in self._contents
        """
        if not OpenClipboardCautious():
            if self.debug:
                print 'Clipboard copy_from_system, could not open clipboard'
            return

        try:
            # Determine which formats to retrieve.
            if waiting_interval:
                if not self._check_clipboard_changes(waiting_interval,
                                                     waiting_iterations):
                    if self.debug:
                        print 'Clipboard, copy_from_system, clipboard did not change, no return value'
                    return
            contents = {}

            if waiting_interval:
                for i in range(waiting_iterations):
                    contents = self._get_clipboard_data_from_system(
                        formats=formats)
                    if contents: break
                    time.sleep(waiting_interval)
                else:
                    waiting_time = waiting_interval * waiting_iterations
                    if self.debug:
                        print 'did not get contents from clipboard after %.3f seconds ' % waiting_time
                    return contents
            else:
                contents = self._get_clipboard_data_from_system(
                    formats=formats)

            # Retrieve Windows system clipboard content.
            if save_clear:
                if contents:
                    self._backup = copy.copy(contents)
                    if self.debug > 1:
                        print 'Clipboard, set backup to: %s' % repr(
                            self._backup)
                else:
                    self._backup = None
                self._contents = None
                win32clipboard.EmptyClipboard()
            else:
                if contents:
                    self._contents = copy.copy(contents)
                else:
                    self._contents = None
        finally:
            # Clear the system clipboard, if requested, and close it.
            self.current_sequence_number = win32clipboard.GetClipboardSequenceNumber(
            )
            win32clipboard.CloseClipboard()
            pass