Merged packages openoffice.interact into openoffice. Renamed package to openoffice...
[openoffice-python:openoffice-python.git] / openoffice / interact.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (c) 2008 by Hartmut Goebel <h.goebel@goebel-consult.de>
5 # Licenced under the GNU General Public License v3 (GPLv3)
6 # see file LICENSE-gpl-3.0.txt
7 #
8
9 __author__ = "Hartmut Goebel <h.goebel@goebel-consult.de>"
10 __copyright__ = "Copyright (c) 2008 by Hartmut Goebel <h.goebel@goebel-consult.de>"
11 __licence__ = "GPLv3 - GNU General Public License v3"
12
13 import unohelper
14 import openoffice.officehelper as officehelper
15 from com.sun.star.beans import PropertyValue
16
17 import openoffice.streams
18
19 import os
20
21 class Context:
22     # Todo:
23     # - Make desktop, unoService and coreRelefection into slots (or such)
24     # - find out which objects are singletons anyway
25     def __init__(self, pipename=None, host=None, port=None):
26         """Start OOo and connect to it"""
27         self.context = officehelper.bootstrap(pipename=pipename,
28                                               host=host, port=port)
29         self._desktop = None
30
31     def desktop(self):
32         if self._desktop is None:
33             self._desktop = Desktop(self)
34         return self._desktop
35
36     def unoService(self, className):
37         return self.context.ServiceManager.createInstanceWithContext(className,
38                                                                      self.context)
39
40     def coreReflection(self):
41         return self.createUnoService("com.sun.star.reflection.CoreReflection")
42
43     def ceateUnoStruct(self, typeName):
44         """
45         Create a UNO struct.
46         Similar to the function of the same name in OOo Basic.
47         """
48         # Get the IDL class for the type name
49         idlClass = self.coreReflection().forName(typeName)
50         rv, struct = idlClass.createObject(None)
51         return struct
52     
53     #----  API helpers ---------------
54
55     def hasUnoInterfaces(self, obj, *interfaceNames):
56         """
57         Similar to Basic's HasUnoInterfaces() function.
58         """
59         wantedInterfaces = set(interfaceNames)
60         # Get the Introspection service and the object info
61         introspect = self.createUnoService("com.sun.star.beans.Introspection")
62         objInfo = introspect.inspect( oObject )
63    
64         # Get List of all methods of the object.
65         methods = objInfo.getMethods(uno.getConstantByName("com.sun.star.beans.MethodConcept.ALL"))
66         # Get the classes (=interfaces) these methods are defined by
67         supportedInterfaces = set([method.getDeclaringClass().getName()
68                                    for method in methods])
69         return wantedInterfaces <= supportedInterfaces
70
71
72 class Desktop:
73     def __init__(self, ctx=None, pipename=None, host=None, port=None):
74         if ctx is None:
75             ctx = Context(pipename=pipename, host=host, port=port)
76         self._ctx = ctx
77         # Verbindung zur Oberflaeche
78         self._desktop = ctx.context.ServiceManager.createInstanceWithContext(
79             "com.sun.star.frame.Desktop", ctx.context)
80         self._ctx._desktop = self._desktop
81
82
83     def newDoc(self, doctype, **kw):
84         """
85         Create a new document.
86
87         ''doctype'' may be one of swriter, scalc, simpress, sdraw,
88         smath or sbase.
89         """
90         return self.openURL("private:factory/" + doctype, **kw)
91
92
93     def openURL(self, url, target='_default', hidden=False,
94                 readonly=False, preview=False, stream=None):
95         """
96         Open a document from it's URL.
97
98         This argumens will be passed to loadComponentFromURL() as
99         Properties:
100
101         - hidden: do not open windows for this document, hide it
102         - readonly: open in read-only mode
103         - preview: open in preview mode
104         - stream: use this stream as "InputStream" (only usefull with
105                   url='private:stream'. You should use openStream() instead.
106         
107         Allowed values for 'target' are:
108
109         :_self: Returns the frame itself. The same as with an empty
110                target frame name. This means to search for a frame you
111                already have, but it is legal.
112         :_top: Returns the top frame of the called frame. The first
113                frame where isTop() returns true when traveling up the
114                hierarchy. If the starting frame does not have a parent
115                frame, the call is treated as a search for "_self".
116                This behavior is compatible to the frame targeting in a
117                web browser.
118         :_parent: Returns the next frame above in the frame hierarchy.
119                If the starting frame does not have a parent frame, the
120                call is treated as a search for "_self". This behavior
121                is compatible to the frame targeting in a web browser.
122         :_blank: Creates a new top-level frame as a child frame of the
123                desktop. If the called frame is not part of the desktop
124                hierarchy, this call fails. Using the "_blank" target
125                loads open documents again that result in a read-only
126                document, depending on the UCB content provider for the
127                component. If loading is done as a result of a user
128                action, this becomes confusing to theusers, therefore
129                the "_default" target is recommended in calls from a
130                user interface, instead of "_blank". Refer to the next
131                section for a discussion about the _default target..
132         :_default: Similar to "_blank", but the implementation defines
133                further behavior that has to be documented by the
134                implementer. The com.sun.star.frame.XComponentLoader
135                implemented at the desktop object shows the following
136                default behavior.
137         """
138         properties = (
139             PropertyValue("Hidden",   0, bool(hidden), 0),
140             PropertyValue("ReadOnly", 0, bool(readonly), 0),
141             PropertyValue("Preview",  0, bool(preview), 0),
142             PropertyValue("InputStream", 0, stream, 0),
143             )
144         return self._desktop.loadComponentFromURL(url, target, 0, properties)
145
146     def openFile(self, filename, **kw):
147         filename = os.path.expanduser(filename)
148         filename = os.path.abspath(filename)
149         url = unohelper.systemPathToFileUrl(filename)
150         return self.openURL(url, **kw)
151
152     def openStream(self, filehandle, **kw):
153         if not isinstance(filehandle, openoffice.streams.InputStream):
154             filehandle = openoffice.streams.InputStream(filehandle)
155         return self.openURL("private:stream", stream=filehandle, **kw)
156
157         
158 if __name__ == '___main__':
159     desktop = Desktop()
160     doc = desktop.newDoc("swriter")