libreofficekit 0.5.0

LibreOfficeKit implementation in Rust
Documentation
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use std::{
    ffi::{CStr, CString},
    os::raw::{c_char, c_int, c_ulonglong, c_void},
    path::Path,
    ptr::null_mut,
    sync::atomic::{AtomicBool, Ordering},
};

use crate::bindings::{LibreOfficeKit, LibreOfficeKitClass, LibreOfficeKitDocument};
use dlopen2::wrapper::{Container, WrapperApi};
use once_cell::sync::OnceCell;
use parking_lot::Mutex;

use crate::{error::OfficeError, urls::DocUrl};

// Global instance of the LOK library container
static LOK_CONTAINER: OnceCell<Container<LibreOfficeApi>> = OnceCell::new();

/// Global lock to prevent creating multiple office instances
/// at one time, all other instances must be dropped before
/// a new one can be created
pub(crate) static GLOBAL_OFFICE_LOCK: AtomicBool = AtomicBool::new(false);

/// Type used for the callback data
pub type CallbackData = *mut Box<dyn FnMut(c_int, *const c_char)>;

#[cfg(target_os = "windows")]
const TARGET_LIB: &str = "sofficeapp.dll";
#[cfg(target_os = "windows")]
const TARGET_MERGED_LIB: &str = "mergedlo.dll";

#[cfg(target_os = "linux")]
const TARGET_LIB: &str = "libsofficeapp.so";
#[cfg(target_os = "linux")]
const TARGET_MERGED_LIB: &str = "libmergedlo.so";

#[cfg(target_os = "macos")]
const TARGET_LIB: &str = "libsofficeapp.dylib";
#[cfg(target_os = "macos")]
const TARGET_MERGED_LIB: &str = "libmergedlo.dylib";

#[derive(WrapperApi)]
struct LibreOfficeApi {
    /// Pre initialization hook
    lok_preinit: Option<
        fn(
            install_path: *const std::os::raw::c_char,
            user_profile_url: *const std::os::raw::c_char,
        ) -> std::os::raw::c_int,
    >,

    libreofficekit_hook:
        Option<fn(install_path: *const std::os::raw::c_char) -> *mut LibreOfficeKit>,

    libreofficekit_hook_2: Option<
        fn(
            install_path: *const std::os::raw::c_char,
            user_profile_url: *const std::os::raw::c_char,
        ) -> *mut LibreOfficeKit,
    >,
}

/// Loads the LOK functions from the dynamic link library
fn lok_open(install_path: &Path) -> Result<Container<LibreOfficeApi>, OfficeError> {
    // Append program folder to PATH environment for windows DLL loading
    if let Ok(path) = std::env::var("PATH") {
        let install_path = install_path.to_string_lossy();
        let install_path = install_path.as_ref();

        if !path.contains(install_path) {
            std::env::set_var("PATH", format!("{};{}", install_path, path));
        }
    }

    let target_lib_path = install_path.join(TARGET_LIB);
    if target_lib_path.exists() {
        // Check target library
        let err = match unsafe { Container::load(&target_lib_path) } {
            Ok(value) => return Ok(value),
            Err(err) => err,
        };

        // If the file can be opened and is likely a real library we fail here
        // instead of trying TARGET_MERGED_LIB same as standard LOK
        if std::fs::File::open(target_lib_path)
            .and_then(|file| file.metadata())
            .is_ok_and(|value| value.len() > 100)
        {
            return Err(OfficeError::LoadLibrary(err));
        }
    }

    let target_merged_lib_path = install_path.join(TARGET_MERGED_LIB);
    if target_merged_lib_path.exists() {
        // Check merged target library
        let err = match unsafe { Container::load_with_flags(target_merged_lib_path, Some(2)) } {
            Ok(value) => return Ok(value),
            Err(err) => err,
        };

        return Err(OfficeError::LoadLibrary(err));
    }

    Err(OfficeError::MissingLibrary)
}

fn lok_init(install_path: &Path) -> Result<*mut LibreOfficeKit, OfficeError> {
    // Try initialize the container (If not already initialized)
    let container = LOK_CONTAINER.get_or_try_init(|| lok_open(install_path))?;

    // Get the hook function
    let lok_hook = container
        .libreofficekit_hook
        .ok_or(OfficeError::MissingLibraryHook)?;

    let install_path = install_path.to_str().ok_or(OfficeError::InvalidPath)?;
    let install_path = CString::new(install_path)?;

    let lok = lok_hook(install_path.as_ptr());

    Ok(lok)
}

/// Raw office pointer access
pub struct OfficeRaw {
    /// This pointer for LOK
    this: *mut LibreOfficeKit,
    /// Class pointer for LOK
    class: *mut LibreOfficeKitClass,
    /// Callback data if specified
    callback_data: Mutex<CallbackData>,
}

impl OfficeRaw {
    /// Initializes a new instance of LOK
    pub unsafe fn init(install_path: &Path) -> Result<Self, OfficeError> {
        let lok = lok_init(install_path)?;

        if lok.is_null() {
            return Err(OfficeError::UnknownInit);
        }

        let lok_class = (*lok).pClass;

        let instance = Self {
            this: lok,
            class: lok_class,
            callback_data: Mutex::new(null_mut()),
        };

        Ok(instance)
    }

    /// Gets a [CString] containing the JSON for the available LibreOffice filter types
    pub unsafe fn get_filter_types(&self) -> Result<CString, OfficeError> {
        let get_filter_types = (*self.class)
            .getFilterTypes
            .ok_or(OfficeError::MissingFunction("getFilterTypes"))?;

        let value = get_filter_types(self.this);

        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(CString::from_raw(value))
    }

    /// Gets a [CString] containing the JSON for the current LibreOffice version details
    pub unsafe fn get_version_info(&self) -> Result<CString, OfficeError> {
        let get_version_info = (*self.class)
            .getVersionInfo
            .ok_or(OfficeError::MissingFunction("getVersionInfo"))?;

        let value = get_version_info(self.this);

        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(CString::from_raw(value))
    }

    /// Gets a [CString] containing a dump of the current LibreOffice state
    pub unsafe fn dump_state(&self) -> Result<CString, OfficeError> {
        let mut state: *mut c_char = null_mut();
        let dump_state = (*self.class)
            .dumpState
            .ok_or(OfficeError::MissingFunction("dumpState"))?;
        dump_state(self.this, std::ptr::null(), &mut state);

        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(CString::from_raw(state))
    }

    /// Trims memory from LibreOffice
    pub unsafe fn trim_memory(&self, target: c_int) -> Result<(), OfficeError> {
        let trim_memory = (*self.class)
            .trimMemory
            .ok_or(OfficeError::MissingFunction("trimMemory"))?;
        trim_memory(self.this, target);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(())
    }

    /// Sets an office option
    pub unsafe fn set_option(
        &self,
        option: *const c_char,
        value: *const c_char,
    ) -> Result<(), OfficeError> {
        let set_option = (*self.class)
            .setOption
            .ok_or(OfficeError::MissingFunction("setOption"))?;
        set_option(self.this, option, value);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(())
    }

    /// Exports the provided document and signs the content
    pub unsafe fn sign_document(
        &self,
        url: &DocUrl,
        certificate: *const u8,
        certificate_len: i32,
        private_key: *const u8,
        private_key_len: i32,
    ) -> Result<bool, OfficeError> {
        let sign_document = (*self.class)
            .signDocument
            .ok_or(OfficeError::MissingFunction("signDocument"))?;
        let result = sign_document(
            self.this,
            url.as_ptr(),
            certificate,
            certificate_len,
            private_key,
            private_key_len,
        );

        Ok(result)
    }

    /// Loads a document without any options
    pub unsafe fn document_load(&self, url: &DocUrl) -> Result<DocumentRaw, OfficeError> {
        let document_load = (*self.class)
            .documentLoad
            .ok_or(OfficeError::MissingFunction("documentLoad"))?;
        let this = document_load(self.this, url.as_ptr());

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        debug_assert!(!this.is_null());

        Ok(DocumentRaw { this })
    }

    /// Loads a document with additional options
    pub unsafe fn document_load_with_options(
        &self,
        url: &DocUrl,
        options: *const c_char,
    ) -> Result<DocumentRaw, OfficeError> {
        let document_load_with_options = (*self.class)
            .documentLoadWithOptions
            .ok_or(OfficeError::MissingFunction("documentLoadWithOptions"))?;
        let this = document_load_with_options(self.this, url.as_ptr(), options);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        debug_assert!(!this.is_null());

        Ok(DocumentRaw { this })
    }

    /// Sets the current document password
    ///
    /// Can ONLY be used in [OfficeRaw::register_callback] when used outside
    /// a callback LOK will throw an error
    pub unsafe fn set_document_password(
        &self,
        url: &DocUrl,
        password: *const c_char,
    ) -> Result<(), OfficeError> {
        let set_document_password = (*self.class)
            .setDocumentPassword
            .ok_or(OfficeError::MissingFunction("setDocumentPassword"))?;

        set_document_password(self.this, url.as_ptr(), password);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(())
    }

    /// Sets the optional features bitset
    pub unsafe fn set_optional_features(&self, features: u64) -> Result<(), OfficeError> {
        let set_optional_features = (*self.class)
            .setOptionalFeatures
            .ok_or(OfficeError::MissingFunction("setOptionalFeatures"))?;
        set_optional_features(self.this, features);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(())
    }

    pub unsafe fn send_dialog_event(
        &self,
        window_id: c_ulonglong,
        arguments: *const c_char,
    ) -> Result<(), OfficeError> {
        let send_dialog_event = (*self.class)
            .sendDialogEvent
            .ok_or(OfficeError::MissingFunction("sendDialogEvent"))?;

        send_dialog_event(self.this, window_id, arguments);

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        Ok(())
    }

    pub unsafe fn run_macro(&self, url: *const c_char) -> Result<bool, OfficeError> {
        let run_macro = (*self.class)
            .runMacro
            .ok_or(OfficeError::MissingFunction("runMacro"))?;

        let result = run_macro(self.this, url);

        if result == 0 {
            // Check for errors
            if let Some(error) = self.get_error() {
                return Err(OfficeError::OfficeError(error));
            }
        }

        Ok(result != 0)
    }

    /// Clears the currently registered callback
    pub unsafe fn clear_callback(&self) -> Result<(), OfficeError> {
        let register_callback = (*self.class)
            .registerCallback
            .ok_or(OfficeError::MissingFunction("registerCallback"))?;

        register_callback(self.this, None, null_mut());

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        self.free_callback();

        Ok(())
    }

    pub unsafe fn register_callback<F>(&self, callback: F) -> Result<(), OfficeError>
    where
        F: FnMut(c_int, *const c_char) + 'static,
    {
        /// Create a shim to wrap the callback function so it can be invoked
        unsafe extern "C" fn callback_shim(ty: c_int, payload: *const c_char, data: *mut c_void) {
            // Get the callback function from the data argument
            let callback: *mut Box<dyn FnMut(c_int, *const c_char)> = data.cast();

            // Catch panics from calling the callback
            _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
                // Invoke the callback
                (**callback)(ty, payload);
            }));
        }

        // Callback is double boxed then leaked
        let callback_ptr: *mut Box<dyn FnMut(c_int, *const c_char)> =
            Box::into_raw(Box::new(Box::new(callback)));

        let register_callback = (*self.class)
            .registerCallback
            .ok_or(OfficeError::MissingFunction("registerCallback"))?;

        register_callback(self.this, Some(callback_shim), callback_ptr.cast());

        // Check for errors
        if let Some(error) = self.get_error() {
            return Err(OfficeError::OfficeError(error));
        }

        // Free any existing callbacks
        self.free_callback();

        // Store the new callback
        *self.callback_data.lock() = callback_ptr;

        Ok(())
    }

    /// Frees the current allocated callback data memory if
    /// a callback has been set
    unsafe fn free_callback(&self) {
        let callback = &mut *self.callback_data.lock();

        // Callback has not been set
        if callback.is_null() {
            return;
        }

        let mut callback_ptr: CallbackData = null_mut();

        // Obtain the callback pointer
        std::mem::swap(callback, &mut callback_ptr);

        // Reclaim the raw memory
        _ = Box::from_raw(callback_ptr);
    }

    /// Requests the latest error from LOK if one is available
    pub unsafe fn get_error(&self) -> Option<String> {
        let get_error = (*self.class).getError.expect("missing getError function");
        let raw_error = get_error(self.this);

        // Empty error is considered to be no error
        if *raw_error == 0 {
            return None;
        }

        // Create rust copy of the error message
        let value = CStr::from_ptr(raw_error).to_string_lossy().into_owned();

        // Free error memory
        self.free_error(raw_error);

        Some(value)
    }

    /// Frees the memory allocated for an error by LOK
    ///
    /// Used when we've obtained the error as we clone
    /// our own copy of the error
    unsafe fn free_error(&self, error: *mut c_char) {
        // Only available LibreOffice >=5.2
        if let Some(free_error) = (*self.class).freeError {
            free_error(error);
        }
    }

    /// Destroys the LOK instance and frees any other
    /// allocated memory
    pub unsafe fn destroy(&self) {
        let destroy = (*self.class).destroy.expect("missing destroy function");
        destroy(self.this);

        // Free the callback if allocated
        self.free_callback();
    }
}

impl Drop for OfficeRaw {
    fn drop(&mut self) {
        unsafe { self.destroy() }

        // Unlock the global office lock
        GLOBAL_OFFICE_LOCK.store(false, Ordering::SeqCst)
    }
}

pub struct DocumentRaw {
    /// This pointer for the document
    this: *mut LibreOfficeKitDocument,
}

impl DocumentRaw {
    /// Saves the document as another format
    pub unsafe fn save_as(
        &mut self,
        url: &DocUrl,
        format: *const c_char,
        filter: *const c_char,
    ) -> Result<i32, OfficeError> {
        let class = (*self.this).pClass;
        let save_as = (*class)
            .saveAs
            .ok_or(OfficeError::MissingFunction("saveAs"))?;

        Ok(save_as(self.this, url.as_ptr(), format, filter))
    }

    /// Get the type of document
    pub unsafe fn get_document_type(&mut self) -> Result<i32, OfficeError> {
        let class = (*self.this).pClass;
        let get_document_type = (*class)
            .getDocumentType
            .ok_or(OfficeError::MissingFunction("getDocumentType"))?;

        Ok(get_document_type(self.this))
    }

    pub unsafe fn destroy(&mut self) {
        let class = (*self.this).pClass;
        let destroy = (*class).destroy.expect("missing destroy function");
        destroy(self.this);
    }
}

impl Drop for DocumentRaw {
    fn drop(&mut self) {
        unsafe { self.destroy() }
    }
}