summaryrefslogtreecommitdiffstats
path: root/xpcom/rust/xpcom/src/statics.rs
blob: 27f66fdb4bddc61b3dcc5fcdefba3b45944be096 (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
/* 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/. */

use crate::interfaces::{nsIComponentManager, nsIComponentRegistrar, nsIServiceManager};
use crate::{GetterAddrefs, RefPtr, XpCom};
use std::ffi::CStr;

/// Get a reference to the global `nsIComponentManager`.
///
/// Can return `None` during shutdown.
#[inline]
pub fn component_manager() -> Option<RefPtr<nsIComponentManager>> {
    unsafe { RefPtr::from_raw(Gecko_GetComponentManager()) }
}

/// Get a reference to the global `nsIServiceManager`.
///
/// Can return `None` during shutdown.
#[inline]
pub fn service_manager() -> Option<RefPtr<nsIServiceManager>> {
    unsafe { RefPtr::from_raw(Gecko_GetServiceManager()) }
}

/// Get a reference to the global `nsIComponentRegistrar`
///
/// Can return `None` during shutdown.
#[inline]
pub fn component_registrar() -> Option<RefPtr<nsIComponentRegistrar>> {
    unsafe { RefPtr::from_raw(Gecko_GetComponentRegistrar()) }
}

/// Helper for calling `nsIComponentManager::CreateInstanceByContractID` on the
/// global `nsIComponentRegistrar`.
///
/// This method is similar to `do_CreateInstance` in C++.
#[inline]
pub fn create_instance<T: XpCom>(id: &CStr) -> Option<RefPtr<T>> {
    unsafe {
        let mut ga = GetterAddrefs::<T>::new();
        if component_manager()?
            .CreateInstanceByContractID(id.as_ptr(), &T::IID, ga.void_ptr())
            .succeeded()
        {
            ga.refptr()
        } else {
            None
        }
    }
}

/// Helper for calling `nsIServiceManager::GetServiceByContractID` on the global
/// `nsIServiceManager`.
///
/// This method is similar to `do_GetService` in C++.
#[inline]
pub fn get_service<T: XpCom>(id: &CStr) -> Option<RefPtr<T>> {
    unsafe {
        let mut ga = GetterAddrefs::<T>::new();
        if service_manager()?
            .GetServiceByContractID(id.as_ptr(), &T::IID, ga.void_ptr())
            .succeeded()
        {
            ga.refptr()
        } else {
            None
        }
    }
}

extern "C" {
    fn Gecko_GetComponentManager() -> *const nsIComponentManager;
    fn Gecko_GetServiceManager() -> *const nsIServiceManager;
    fn Gecko_GetComponentRegistrar() -> *const nsIComponentRegistrar;
}