summaryrefslogtreecommitdiff
path: root/wizards/com/sun/star/wizards/document/OfficeDocument.py
blob: eb6fb0a52736e807a0cd11ceb8e86e926388f46a (plain)
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#
# 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/.
#
# This file incorporates work covered by the following license notice:
#
#   Licensed to the Apache Software Foundation (ASF) under one or more
#   contributor license agreements. See the NOTICE file distributed
#   with this work for additional information regarding copyright
#   ownership. The ASF licenses this file to you under the Apache
#   License, Version 2.0 (the "License"); you may not use this file
#   except in compliance with the License. You may obtain a copy of
#   the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
import uno
import traceback
from unohelper import systemPathToFileUrl, absolutize
from ..ui.event.CommonListener import TerminateListenerProcAdapter
from ..common.Desktop import Desktop

from com.sun.star.awt import WindowDescriptor
from com.sun.star.awt import Rectangle
from com.sun.star.awt.WindowClass import TOP
from com.sun.star.task import ErrorCodeIOException

#Window Constants
com_sun_star_awt_WindowAttribute_BORDER \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.BORDER" )
com_sun_star_awt_WindowAttribute_SIZEABLE \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.SIZEABLE" )
com_sun_star_awt_WindowAttribute_MOVEABLE \
    = uno.getConstantByName( "com.sun.star.awt.WindowAttribute.MOVEABLE" )
com_sun_star_awt_VclWindowPeerAttribute_CLIPCHILDREN \
    = uno.getConstantByName(
        "com.sun.star.awt.VclWindowPeerAttribute.CLIPCHILDREN" )

class OfficeDocument(object):
    '''Creates a new instance of OfficeDocument '''

    def __init__(self, _xMSF):
        self.xMSF = _xMSF

    @classmethod
    def attachEventCall(self, xComponent, EventName, EventType, EventURL):
        try:
            oEventProperties = list(range(2))
            oEventProperties[0] = uno.createUnoStruct(
                'com.sun.star.beans.PropertyValue')
            oEventProperties[0].Name = "EventType"
            oEventProperties[0].Value = EventType
            # "Service", "StarBasic"
            oEventProperties[1] = uno.createUnoStruct(
                'com.sun.star.beans.PropertyValue')
            oEventProperties[1].Name = "Script" #"URL";
            oEventProperties[1].Value = EventURL
            uno.invoke(xComponent.Events, "replaceByName",
                (EventName, uno.Any("[]com.sun.star.beans.PropertyValue",
                    tuple(oEventProperties))))
        except Exception:
            traceback.print_exc()

    def dispose(self, xMSF, xComponent):
        try:
            if xComponent is not None:
                xFrame = xComponent.CurrentController.Frame
                if xComponent.isModified():
                    xComponent.setModified(False)

                Desktop.dispatchURL(xMSF, ".uno:CloseDoc", xFrame)

        except PropertyVetoException:
            traceback.print_exc()

    '''
    Create a new office document, attached to the given frame.
    @param desktop
    @param frame
    @param sDocumentType e.g. swriter, scalc, ( simpress, scalc : not tested)
    @return the document Component
    (implements XComponent) object ( XTextDocument, or XSpreadsheedDocument )
    '''

    @classmethod
    def createNewDocument(self, frame, sDocumentType, preview, readonly):
        loadValues = list(range(2))
        loadValues[0] = uno.createUnoStruct(
            'com.sun.star.beans.PropertyValue')
        loadValues[0].Name = "ReadOnly"
        if readonly:
            loadValues[0].Value = True
        else:
            loadValues[0].Value = False

        loadValues[1] = uno.createUnoStruct(
            'com.sun.star.beans.PropertyValue')
        loadValues[1].Name = "Preview"
        if preview:
            loadValues[1].Value = True
        else:
            loadValues[1].Value = False
        sURL = "private:factory/" + sDocumentType
        xComponent = None
        try:
            xComponent = frame.loadComponentFromURL(
                systemPathToFileUrl(sURL), "_self", 0, tuple(loadValues))

        except Exception:
            traceback.print_exc()

        return xComponent

    @classmethod
    def createNewFrame(self, xMSF, listener, FrameName="_blank"):
        xFrame = None
        if FrameName.lower() == "WIZARD_LIVE_PREVIEW".lower():
            xFrame = self.createNewPreviewFrame(xMSF, listener)
        else:
            xF = Desktop.getDesktop(xMSF)
            xFrame = xF.findFrame(FrameName, 0)
            if listener is not None:
                xFF = xF.getFrames()
                xFF.remove(xFrame)
                xF.addTerminateListener(listener)

        return xFrame

    @classmethod
    def createNewPreviewFrame(self, xMSF, listener):
        xToolkit = None
        try:
            xToolkit = xMSF.createInstance("com.sun.star.awt.Toolkit")
        except Exception:
            # TODO Auto-generated catch block
            traceback.print_exc()

        #describe the window and its properties
        aDescriptor = WindowDescriptor()
        aDescriptor.Type = TOP
        aDescriptor.WindowServiceName = "window"
        aDescriptor.ParentIndex = -1
        aDescriptor.Parent = None
        aDescriptor.Bounds = Rectangle(10, 10, 640, 480)

        #Set Window Attributes
        gnDefaultWindowAttributes = \
            com_sun_star_awt_WindowAttribute_BORDER + \
            com_sun_star_awt_WindowAttribute_MOVEABLE + \
            com_sun_star_awt_WindowAttribute_SIZEABLE + \
            com_sun_star_awt_VclWindowPeerAttribute_CLIPCHILDREN

        aDescriptor.WindowAttributes = gnDefaultWindowAttributes
        #create a new blank container window
        xPeer = None
        try:
            xPeer = xToolkit.createWindow(aDescriptor)
        except IllegalArgumentException:
            traceback.print_exc()

        #define some further properties of the frame window
        #if it's needed .-)
        #xPeer->setBackground(...);
        #create new empty frame and set window on it
        xFrame = None
        try:
            xFrame = xMSF.createInstance("com.sun.star.frame.Frame")
        except Exception:
            traceback.print_exc()

        xFrame.initialize(xPeer)
        #from now this frame is useable ...
        #and not part of the desktop tree.
        #You are alone with him .-)
        if listener is not None:
            Desktop.getDesktop(xMSF).addTerminateListener(listener)

        return xFrame

    @classmethod
    def load(self, xInterface, sURL, sFrame, xValues):
        xComponent = None
        try:
            if not sURL.startswith("file://"):
                sURL = systemPathToFileUrl(sURL)
            xComponent = xInterface.loadComponentFromURL(
                sURL, sFrame, 0, tuple(xValues))
        except Exception:
            traceback.print_exc()

        return xComponent

    @classmethod
    def store(self, xMSF, xComponent, StorePath, FilterName):
        try:
            if len(FilterName):
                oStoreProperties = list(range(2))
                oStoreProperties[0] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[0].Name = "FilterName"
                oStoreProperties[0].Value = FilterName
                oStoreProperties[1] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[1].Name = "InteractionHandler"
                oStoreProperties[1].Value = xMSF.createInstance(
                    "com.sun.star.comp.uui.UUIInteractionHandler")
            else:
                oStoreProperties = list(range(0))      

            StorePath = systemPathToFileUrl(StorePath)
            sPath = StorePath[:(StorePath.rfind("/") + 1)]
            sFile = StorePath[(StorePath.rfind("/") + 1):]
            xComponent.storeToURL(
                absolutize(sPath, sFile), tuple(oStoreProperties))
            return True
        except ErrorCodeIOException:
            #Throw this exception when trying to save a file 
            #which is already opened in Libreoffice
            #TODO: handle it properly
            return True
            pass
        except Exception:
            traceback.print_exc()
            return False

    def close(self, xComponent):
        bState = False
        if xComponent is not None:
            try:
                xComponent.close(True)
                bState = True
            except com.sun.star.util.CloseVetoException:
                print ("could not close doc")
                bState = False

        else:
            xComponent.dispose()
            bState = True

        return bState

    def ArraytoCellRange(self, datalist, oTable, xpos, ypos):
        try:
            rowcount = datalist.length
            if rowcount > 0:
                colcount = datalist[0].length
                if colcount > 0:
                    xNewRange = oTable.getCellRangeByPosition(
                        xpos, ypos, (colcount + xpos) - 1,
                            (rowcount + ypos) - 1)
                    xNewRange.setDataArray(datalist)

        except Exception:
            traceback.print_exc()

    @classmethod
    def getFileMediaDecriptor(self, xmsf, url):
        typeDetect = xmsf.createInstance(
            "com.sun.star.document.TypeDetection")
        mediaDescr = list(range(1))
        mediaDescr[0] = uno.createUnoStruct(
            'com.sun.star.beans.PropertyValue')
        mediaDescr[0].Name = "URL"
        mediaDescr[0].Value = url
        Type = typeDetect.queryTypeByDescriptor(tuple(mediaDescr), True)[0]
        if Type == "":
            return None
        else:
            return typeDetect.getByName(Type)

    @classmethod
    def getTypeMediaDescriptor(self, xmsf, type):
        typeDetect = xmsf.createInstance(
            "com.sun.star.document.TypeDetection")
        return typeDetect.getByName(type)

    def showMessageBox(
        self, xMSF, windowServiceName, windowAttribute, MessageText):

        return SystemDialog.showMessageBox(
            xMSF, windowServiceName, windowAttribute, MessageText)