File: clipboard.py

package info (click to toggle)
libreoffice 4%3A25.8.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 3,815,320 kB
  • sloc: cpp: 4,378,739; xml: 454,679; java: 257,215; python: 80,874; ansic: 33,824; perl: 30,304; javascript: 19,722; sh: 11,717; makefile: 10,622; cs: 8,865; yacc: 8,549; objc: 2,131; lex: 1,379; asm: 1,231; awk: 996; pascal: 914; csh: 20; sed: 5
file content (128 lines) | stat: -rw-r--r-- 4,742 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#

import time
import traceback

import officehelper

from clipboard_owner import ClipboardOwner
from clipboard_listener import ClipboardListener
from text_transferable import TextTransferable

from com.sun.star.datatransfer import UnsupportedFlavorException

# This example demonstrates the usage of the clipboard service

def demonstrate_clipboard():
    try:
        # Create a new office context (if needed), and get a reference to it
        context = officehelper.bootstrap()
        print("Connected to a running office ...")

        # Get a reference to the multi component factory/service manager
        srv_mgr = context.getServiceManager()

        # Create a new blank document, and write user instructions to it
        desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
        doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
        doc.getText().setString("In the first step, paste the current content of the clipboard in the document!\nThe text \"Hello world!\" shall be insert at the current cursor position below.\n\nIn the second step, please select some words and put it into the clipboard! ...\n\nCurrent clipboard content = ")

        # Get the current controller, and ensure that the document
        # content is visible to the user by zooming in
        view_settings_supplier = doc.getCurrentController()
        view_settings_supplier.getViewSettings() \
            .setPropertyValue("ZoomType", 0)

        # Create an instance of systemclipboard that abstracts the
        # low level system-specific clipboard
        clipboard = srv_mgr.createInstance("com.sun.star.datatransfer.clipboard.SystemClipboard")

        # Create a listener for the clipboard
        print("Registering a clipboard listener...")
        clip_listener = ClipboardListener()
        clipboard.addClipboardListener(clip_listener)

        read_clipboard(clipboard)

        # Create an owner for the clipboard, and "copy" something to it
        print("Becoming a clipboard owner...")
        clip_owner = ClipboardOwner()
        clipboard.setContents(TextTransferable("Hello World!"), clip_owner)

        # Show a hint to the user running the example for what to do
        # as an ellipses style indicator
        i = 0
        while clip_owner.isClipboardOwner():
            if i != 2:
                if i == 1:
                    print("Change clipboard ownership by putting something into the clipboard!")
                    print("Still clipboard owner...", end='')
                else:
                    print("Still clipboard owner...", end='')
                i += 1
            else:
                print(".", end='')
            time.sleep(1)
        print()

        read_clipboard(clipboard)

        # End the clipboard listener
        print("Unregistering a clipboard listener...")
        clipboard.removeClipboardListener(clip_listener)

        # Close the temporary test document
        doc.close(False)

    except Exception as e:
        print(str(e))
        traceback.print_exc()


def read_clipboard(clipboard):
    # get a list of formats currently on the clipboard
    transferable = clipboard.getContents()
    data_flavors_list = transferable.getTransferDataFlavors()

    # print all available formats

    print("Reading the clipboard...")
    print("Available clipboard formats:", data_flavors_list)

    unicode_flavor = None

    for flavor in data_flavors_list:
        print("MimeType:", flavor.MimeType,
            "HumanPresentableName:", flavor.HumanPresentableName)

        # Select the flavor that supports utf-16
        # str.casefold() allows reliable case-insensitive comparison
        if flavor.MimeType.casefold() == TextTransferable.UNICODE_CONTENT_TYPE.casefold():
            unicode_flavor = flavor
    print()

    try:
        if unicode_flavor is not None:
            # Get the clipboard data as unicode
            data = transferable.getTransferData(unicode_flavor)

            print("Unicode text on the clipboard ...")
            print(f"Your selected text \"{data}\" is now in the clipboard.")

    except UnsupportedFlavorException as ex:
        print("Requested format is not available on the clipboard!")
        print(str(ex))
        traceback.print_exc()


if __name__ == "__main__":
    demonstrate_clipboard()

# vim: set shiftwidth=4 softtabstop=4 expandtab: