Gtk-WARNING gtktreestore.c:1047: Invalid column number 1 added to iter
[LibreOffice.git] / odk / examples / DevelopersGuide / OfficeDev / Clipboard / python / clipboard.py
blob6610f0021b263cd60d8cd7a477012903260c5285
1 # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
3 # This file is part of the LibreOffice project.
5 # This Source Code Form is subject to the terms of the Mozilla Public
6 # License, v. 2.0. If a copy of the MPL was not distributed with this
7 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 import time
11 import traceback
13 import officehelper
15 from clipboard_owner import ClipboardOwner
16 from clipboard_listener import ClipboardListener
17 from text_transferable import TextTransferable
19 from com.sun.star.datatransfer import UnsupportedFlavorException
21 # This example demonstrates the usage of the clipboard service
23 def demonstrate_clipboard():
24 try:
25 # Create a new office context (if needed), and get a reference to it
26 context = officehelper.bootstrap()
27 print("Connected to a running office ...")
29 # Get a reference to the multi component factory/service manager
30 srv_mgr = context.getServiceManager()
32 # Create a new blank document, and write user instructions to it
33 desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
34 doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
35 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 = ")
37 # Get the current controller, and ensure that the document
38 # content is visible to the user by zooming in
39 view_settings_supplier = doc.getCurrentController()
40 view_settings_supplier.getViewSettings() \
41 .setPropertyValue("ZoomType", 0)
43 # Create an instance of systemclipboard that abstracts the
44 # low level system-specific clipboard
45 clipboard = srv_mgr.createInstance("com.sun.star.datatransfer.clipboard.SystemClipboard")
47 # Create a listener for the clipboard
48 print("Registering a clipboard listener...")
49 clip_listener = ClipboardListener()
50 clipboard.addClipboardListener(clip_listener)
52 read_clipboard(clipboard)
54 # Create an owner for the clipboard, and "copy" something to it
55 print("Becoming a clipboard owner...")
56 clip_owner = ClipboardOwner()
57 clipboard.setContents(TextTransferable("Hello World!"), clip_owner)
59 # Show a hint to the user running the example for what to do
60 # as an ellipses style indicator
61 i = 0
62 while clip_owner.isClipboardOwner():
63 if i != 2:
64 if i == 1:
65 print("Change clipboard ownership by putting something into the clipboard!")
66 print("Still clipboard owner...", end='')
67 else:
68 print("Still clipboard owner...", end='')
69 i += 1
70 else:
71 print(".", end='')
72 time.sleep(1)
73 print()
75 read_clipboard(clipboard)
77 # End the clipboard listener
78 print("Unregistering a clipboard listener...")
79 clipboard.removeClipboardListener(clip_listener)
81 # Close the temporary test document
82 doc.close(False)
84 except Exception as e:
85 print(str(e))
86 traceback.print_exc()
89 def read_clipboard(clipboard):
90 # get a list of formats currently on the clipboard
91 transferable = clipboard.getContents()
92 data_flavors_list = transferable.getTransferDataFlavors()
94 # print all available formats
96 print("Reading the clipboard...")
97 print("Available clipboard formats:", data_flavors_list)
99 unicode_flavor = None
101 for flavor in data_flavors_list:
102 print("MimeType:", flavor.MimeType,
103 "HumanPresentableName:", flavor.HumanPresentableName)
105 # Select the flavor that supports utf-16
106 # str.casefold() allows reliable case-insensitive comparison
107 if flavor.MimeType.casefold() == TextTransferable.UNICODE_CONTENT_TYPE.casefold():
108 unicode_flavor = flavor
109 print()
111 try:
112 if unicode_flavor is not None:
113 # Get the clipboard data as unicode
114 data = transferable.getTransferData(unicode_flavor)
116 print("Unicode text on the clipboard ...")
117 print(f"Your selected text \"{data}\" is now in the clipboard.")
119 except UnsupportedFlavorException as ex:
120 print("Requested format is not available on the clipboard!")
121 print(str(ex))
122 traceback.print_exc()
125 if __name__ == "__main__":
126 demonstrate_clipboard()
128 # vim: set shiftwidth=4 softtabstop=4 expandtab: