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
/// This macro will set up your plugin's actual callability from HexChat.
///
/// # Example
///
/// ```rust
/// use hexchat::{Plugin, plugin}
/// struct MyPlugin;
/// impl Plugin for MyPlugin {
///     //...
/// #    const NAME: &'static str = "myplugin";
/// #    fn new(context: &Context) -> Self {
/// #        Self
/// #    }
/// }
/// plugin!(MyPlugin);
/// ```
///
#[macro_export]
macro_rules! plugin {
    ($x:ty) => {
        #[no_mangle]
        pub unsafe extern "C" fn hexchat_plugin_init(
            plugin_handle: *mut $crate::c::hexchat_plugin,
            plugin_name: *mut *const ::std::os::raw::c_char,
            plugin_desc: *mut *const ::std::os::raw::c_char,
            plugin_version: *mut *const ::std::os::raw::c_char,
            arg: *mut ::std::os::raw::c_char,
        ) -> ::std::os::raw::c_int {
            $crate::call::hexchat_plugin_init::<$x>(
                plugin_handle,
                plugin_name,
                plugin_desc,
                plugin_version,
                arg,
            )
        }

        #[no_mangle]
        pub unsafe extern "C" fn hexchat_plugin_deinit(
            plugin_handle: *mut $crate::c::hexchat_plugin,
        ) -> ::std::os::raw::c_int {
            $crate::call::hexchat_plugin_deinit::<$x>(plugin_handle)
        }
    };
}

use lazy_static::lazy_static;
use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::os::raw::{c_char, c_int};
use std::panic;
use std::sync::Mutex;

use crate::{
    c, to_cstring, Command, Context, Plugin, PrintEventListener, RawServerEventListener, TimerTask,
    WindowEventListener,
};

lazy_static! {
    pub(crate) static ref PLUGINS: Mutex<HashMap<PhWrapper, PluginDef>> =
        Mutex::new(HashMap::new());
    pub(crate) static ref TYPES: Mutex<HashMap<TypeId, PhWrapper>> = Mutex::new(HashMap::new());
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct PhWrapper(pub(crate) *mut c::hexchat_plugin);
unsafe impl Send for PhWrapper {}

pub(crate) struct PluginDef {
    pub(crate) commands: HashSet<Command>,
    pub(crate) print_events: HashSet<PrintEventListener>,
    pub(crate) window_events: HashSet<WindowEventListener>,
    pub(crate) server_events: HashSet<RawServerEventListener>,
    pub(crate) timer_tasks: HashSet<TimerTask>,
    pub(crate) instance: Box<dyn Any>,
}
unsafe impl Send for PluginDef {}

pub unsafe fn hexchat_plugin_init<T>(
    plugin_handle: *mut c::hexchat_plugin,
    plugin_name: *mut *const c_char,
    plugin_desc: *mut *const c_char,
    plugin_version: *mut *const c_char,
    _arg: *mut c_char,
) -> c_int
where
    T: Plugin + 'static,
{
    let name = to_cstring(T::NAME);
    *plugin_name = name.into_raw();
    let desc = to_cstring(T::DESC);
    *plugin_desc = desc.into_raw();
    let version = to_cstring(T::VERSION);
    *plugin_version = version.into_raw();
    let t = panic::catch_unwind(|| {
        T::new(&Context {
            handle: plugin_handle,
        })
    });
    let t = match t {
        Ok(t) => t,
        Err(e) => {
            Context {
                handle: plugin_handle,
            }
            .send_command(&if let Some(string) = (*e).downcast_ref::<&str>() {
                format!(
                    "GUI MSGBOX Plugin '{} {}' failed to load. Panic message: {}",
                    T::NAME,
                    T::VERSION,
                    string
                )
            } else {
                format!(
                    "GUI MSGBOX Plugin '{} {}' failed to load.",
                    T::NAME,
                    T::VERSION
                )
            });
            return -4;
        }
    };
    let type_id = t.type_id();
    let plugin_def = PluginDef {
        commands: HashSet::new(),
        print_events: HashSet::new(),
        window_events: HashSet::new(),
        server_events: HashSet::new(),
        timer_tasks: HashSet::new(),
        instance: Box::new(t),
    };
    if let Ok(mut types) = TYPES.lock() {
        types.insert(type_id, PhWrapper(plugin_handle));
    } else {
        return -2;
    }
    if let Ok(mut plugins) = PLUGINS.lock() {
        plugins.insert(PhWrapper(plugin_handle), plugin_def);
        1
    } else {
        -1
    }
}

pub unsafe fn hexchat_plugin_deinit<T>(plugin_handle: *mut c::hexchat_plugin) -> c_int
where
    T: Plugin,
{
    let context = Context {
        handle: plugin_handle,
    };
    if let Ok(mut plugins) = PLUGINS.lock() {
        if let Some(plugin_def) = plugins.remove(&PhWrapper(plugin_handle)) {
            let PluginDef {
                instance,
                server_events,
                window_events,
                print_events,
                commands,
                timer_tasks,
            } = plugin_def;
            for event in server_events {
                context.dealloc_raw_server_event_listener(event.0);
            }
            for event in window_events {
                context.dealloc_window_event_listener(event.0);
            }
            for event in print_events {
                context.dealloc_print_event_listener(event.0);
            }
            for command in commands {
                context.dealloc_command(command.0);
            }
            for timer_task in timer_tasks {
                context.dealloc_timer_task(timer_task.0);
            }
            if let Ok(mut types) = TYPES.lock() {
                types.remove(&instance.type_id());
                1
            } else {
                -2
            }
        } else {
            -3
        }
    } else {
        -1
    }
}