summaryrefslogtreecommitdiff
path: root/ios/LibreOfficeLight/LibreOfficeLight/LOKit/LOKitThread.swift
blob: c7573e63b8b373030a1825ff856e64a12f459ac8 (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
283
284
285
286
287
//
// 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 Foundation
import UIKit




/// Serves the same purpose as the LOKitThread in the Android project - sequentialises all access to LOKit on a background thread, off the UI thread.
/// It's a singleton, and keeps a single instance of LibreOfficeKit
/// Public methods may be called from any thread, and will dispatch their work onto the held sequential queue.
/// TODO: move me to framework
public class LOKitThread
{
    public static let instance = LOKitThread() // statics are lazy and thread safe in swift, so no need for anything more complex


    fileprivate let queue = SingleThreadedQueue(name: "LOKitThread.queue")

    /// singleton LibreOffice instance. Can only be accessed through the queue.
    var libreOffice: LibreOffice! = nil // initialised in didFinishLaunchingWithOptions

    public weak var delegate: LOKitUIDelegate? = nil
    public weak var progressDelegate: ProgressDelegate? = nil

    private init()
    {

        async {
            self.libreOffice = try! LibreOffice() // will blow up the app if it throws, but fair enough

            // hook up event handler
            self.libreOffice.registerCallback(callback: self.onLOKEvent)

        }
    }

    private func onLOKEvent(type: LibreOfficeKitCallbackType, payload: String?)
    {
        //LibreOfficeLight.LibreOfficeKitKeyEventType.
        print("onLOKEvent type:\(type) payload:\(payload ?? "")")

        switch type
        {
        case LOK_CALLBACK_STATUS_INDICATOR_START:
            runOnMain {
                self.progressDelegate?.statusIndicatorStart()
            }

        case LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE:
            runOnMain {
                if let doub = Double(payload ?? "")
                {
                    self.progressDelegate?.statusIndicatorSetValue(value: doub)
                }
            }

        case LOK_CALLBACK_STATUS_INDICATOR_FINISH:
            runOnMain {
                self.progressDelegate?.statusIndicatorFinish()
            }
        default:
             print("onLOKEvent type:\(type) not handled!")
        }
    }

    /// Run the task on the serial queue, and return immediately
    public func async(_ runnable: @escaping Runnable)
    {
        queue.async( runnable)
    }

    /// Run the task on the serial queue, and block to get the result
    /// Careful of deadlocking!
    public func sync<R>( _ closure: @escaping () -> R ) -> R
    {
        let ret = queue.sync( closure )
        return ret
    }

    public func withLibreOffice( _ closure: @escaping (LibreOffice) -> ())
    {
        async {
            closure(self.libreOffice)
        }
    }

    /// Loads a document, and calls the callback with a wrapper if successful, or an error if not.
    public func documentLoad(url: String, callback: @escaping (DocumentHolder?, Error?) -> ())
    {
        withLibreOffice
        {
            lo in

            do
            {
                // this is trying to avoid null context errors which pop up on doc init
                // doesn't seem to fix
                UIGraphicsBeginImageContext(CGSize(width:1,height:1))
                let doc = try lo.documentLoad(url: url)
                print("Opened document: \(url)")
                doc.initializeForRendering()
                UIGraphicsEndImageContext()

                callback(DocumentHolder(doc: doc), nil)
            }
            catch
            {
                print("Failed to load document: \(error)")
                callback(nil, error)
            }
        }
    }
}

/**
 * Holds the document object so to enforce access in a thread safe way.
 */
public class DocumentHolder
{
    private let doc: Document

    public weak var delegate: DocumentUIDelegate? = nil

    init(doc: Document)
    {
        self.doc = doc
        doc.registerCallback() {
            [weak self] typ, payload in
            self?.onDocumentEvent(type: typ, payload: payload)
        }
    }

    /// Gives async access to the document
    public func async(_ closure: @escaping (Document) -> ())
    {
        LOKitThread.instance.async
        {
            closure(self.doc)
        }
    }

    /// Gives sync access to the document - blocks until the closure runs.
    /// Careful of deadlocks.
    public func sync<R>( _ closure: @escaping (Document) -> R ) -> R
    {
        return LOKitThread.instance.sync
        {
            return closure(self.doc)
        }
    }

    private func onDocumentEvent(type: LibreOfficeKitCallbackType, payload: String?)
    {
        print("onDocumentEvent type:\(type) payload:\(payload ?? "")")

        switch type
        {
        case LOK_CALLBACK_INVALIDATE_TILES:
            runOnMain {
                self.delegate?.invalidateTiles( rects: decodeRects(payload) )
            }
        case LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR:
            runOnMain {
                self.delegate?.invalidateVisibleCursor( rects: decodeRects(payload) )
            }
        case LOK_CALLBACK_TEXT_SELECTION:
            runOnMain {
                self.delegate?.textSelection( rects: decodeRects(payload) )
            }
        case LOK_CALLBACK_TEXT_SELECTION_START:
            runOnMain {
                self.delegate?.textSelectionStart( rects: decodeRects(payload) )
            }
        case LOK_CALLBACK_TEXT_SELECTION_END:
            runOnMain {
                self.delegate?.textSelectionEnd( rects: decodeRects(payload) )
            }
        default:
            print("onDocumentEvent type:\(type) not handled!")
        }
    }

    public func search(searchString: String, forwardDirection: Bool = true, from: CGPoint)
    {
        var rootJson = JSONObject()

        addProperty(&rootJson, "SearchItem.SearchString", "string", searchString);
        addProperty(&rootJson, "SearchItem.Backward", "boolean", String(forwardDirection) );
        addProperty(&rootJson, "SearchItem.SearchStartPointX", "long", String(describing: from.x) );
        addProperty(&rootJson, "SearchItem.SearchStartPointY", "long", String(describing: from.y) );
        addProperty(&rootJson, "SearchItem.Command", "long", "1") // String.valueOf(0)); // search all == 1

        if let jsonStr = encode(json: rootJson)
        {
            async {
                $0.postUnoCommand(command: ".uno:ExecuteSearch", arguments: jsonStr, notifyWhenFinished: true)
            }
        }
    }


}

public typealias JSONObject = Dictionary<String, AnyObject>
public func addProperty( _ json: inout JSONObject, _ parentValue: String, _ type: String, _ value: String)
{
    var child = JSONObject();
    child["type"] = type as AnyObject
    child["value"] = value as AnyObject
    json[parentValue] = child as AnyObject
}

func encode(json: JSONObject) -> String?
{
    //let encoder = JSONEncoder()

    if let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    {
        return String(data: data, encoding: String.Encoding.utf8)
    }
    return nil
}

/// Decodes a series of rectangles in the form: "x, y, width, height; x, y, width, height"
public func decodeRects(_ payload: String?) -> [CGRect]?
{
    guard var pl = payload else { return nil }
    pl = pl.trimmingCharacters(in: .whitespacesAndNewlines )
    if pl == "EMPTY" || pl.count == 0
    {
        return nil
    }
    var ret = [CGRect]()
    for rectStr in pl.split(separator: ";")
    {
        let coords = rectStr.split(separator: ",").flatMap { Double($0) }
        if coords.count == 4
        {
            let rect = CGRect(x: coords[0],
                              y: coords[1],
                              width: coords[2],
                              height: coords[3])
            ret.append( rect )
        }
    }
    return ret
}

/**
 * Delegate methods for global events emitted from LOKit.
 * Mostly dispatched on the main thread unless noted.
 */
public protocol LOKitUIDelegate: class
{
    // Nothing ATM..
}

public protocol ProgressDelegate: class
{
    func statusIndicatorStart()

    func statusIndicatorFinish()

    func statusIndicatorSetValue(value: Double)
}


public protocol DocumentUIDelegate: class
{
    func invalidateTiles(rects: [CGRect]? )

    func invalidateVisibleCursor(rects: [CGRect]? )

    func textSelection(rects: [CGRect]? )
    func textSelectionStart(rects: [CGRect]? )
    func textSelectionEnd(rects: [CGRect]? )



}