Write hexchat plugins in Rust!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib.rs 58KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. /*
  2. * Hexchat Plugin API Bindings for Rust
  3. * Copyright (C) 2018 Soni L.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! Write hexchat plugins in Rust!
  19. //!
  20. //! This library provides safe API bindings for hexchat, but doesn't attempt to fix hexchat's own
  21. //! bugs. It makes no effort to stop you from unloading your own code while it's still running, for
  22. //! example.
  23. //!
  24. //! When using this library, it's strongly recommended to avoid heap-allocated statics (static
  25. //! mutexes, lazy_static, etc). This is because it's currently impossible to deallocate those on
  26. //! plugin unload. This can be worked around by placing those statics as fields in your plugin
  27. //! struct.
  28. //!
  29. //! This caveat does not apply to static assets (`static FOO: &'static str`, for example), but it
  30. //! does apply to thread-local storage.
  31. //!
  32. //! # Examples
  33. //!
  34. //! ```
  35. //! #[macro_use]
  36. //! extern crate hexchat_plugin;
  37. //!
  38. //! use std::sync::Mutex;
  39. //! use hexchat_plugin::{Plugin, PluginHandle, CommandHookHandle};
  40. //!
  41. //! #[derive(Default)]
  42. //! struct MyPlugin {
  43. //! cmd: Mutex<Option<CommandHookHandle>>
  44. //! }
  45. //!
  46. //! impl Plugin for MyPlugin {
  47. //! fn init(&self, ph: &mut PluginHandle, arg: Option<&str>) -> bool {
  48. //! ph.register("myplugin", "0.1.0", "my simple plugin");
  49. //! *self.cmd.lock().unwrap() = Some(ph.hook_command("hello-world", |ph, arg, arg_eol| {
  50. //! ph.print("Hello, World!");
  51. //! hexchat_plugin::EAT_ALL
  52. //! }, hexchat_plugin::PRI_NORM, Some("prints 'Hello, World!'")));
  53. //! true
  54. //! }
  55. //! }
  56. //!
  57. //! hexchat_plugin!(MyPlugin);
  58. //!
  59. //! # fn main() { } // satisfy the compiler, we can't actually run the code
  60. //! ```
  61. /*
  62. * Some info about how HexChat does things:
  63. *
  64. * All strings passed across the C API are UTF-8.
  65. * - Except `hexchat_get_info(ph, "libdirfs")`, so we need to be careful with that one.
  66. *
  67. * The pointers `name: *mut *const char, desc: *mut *const char, vers: *mut *const char` point to
  68. * inside the ph - that is, they're aliased. Thus, we must never convert a ph to an & or &mut
  69. * except as part of retrieving or setting values in it (e.g. `(*ph).hexchat_get_info` or
  70. * `(*ph).userdata = value`).
  71. *
  72. * `hexchat_plugin_get_info` is never used, so we omit it. It would be impractical not to.
  73. *
  74. * These cause UB:
  75. * `hexchat_command` may invalidate the plugin context.
  76. * `hexchat_find_context` and `hexchat_nickcmp` use the plugin context without checking it.
  77. * `hexchat_get_prefs` uses the plugin context if name == "state_cursor" or "id" (or anything with
  78. * the same hash).
  79. * `hexchat_list_get` uses the plugin context if name == "notify" (or anything with the same hash).
  80. * `hexchat_list_str`, `hexchat_list_int`,
  81. * `hexchat_emit_print`, `hexchat_emit_print_attrs` use the plugin context.
  82. * `hexchat_send_modes` uses the plugin context.
  83. * We need to wrap them (or, alternatively, hexchat_command). However, there's no (safe) way to get
  84. * a valid context afterwards.
  85. * - Actually that's a lie. Hexchat does a trick to give you a context as part of the channel list.
  86. * We can use that to our advantage. I'm not sure if it's better to wrap hexchat_command or the
  87. * other functions, tho.
  88. * (Do we want to walk a linked list every time we use hexchat_command? I'd think
  89. * hexchat_command is the most used API function... Plus, emit_print could indirectly
  90. * invalidate the context as well.)
  91. *
  92. * `hexchat_send_modes` should only be used with channels; however, it doesn't cause UB - it just
  93. * doesn't work.
  94. *
  95. * `hexchat_pluginpref_get_int`, `hexchat_pluginpref_get_str`, `hexchat_pluginpref_set_int`,
  96. * `hexchat_pluginpref_set_str` cannot be used while `name`, `desc`, `vers` are null.
  97. *
  98. * `hexchat_plugin_init` receives an arg string. it may be null. this isn't documented anywhere.
  99. */
  100. /*
  101. * Some info about how we do things:
  102. *
  103. * DO NOT CALL printf/commandf/etc FAMILY OF FUNCTIONS. You can't avoid allocations, so just
  104. * allocate some CStrings on the Rust side. It has the exact same effect, since those functions
  105. * allocate internally anyway.
  106. */
  107. /*
  108. * Big list o' TODO:
  109. * -[ ] Finish API support. [PRI-HIGH]
  110. * -[x] word
  111. * -[x] word_eol
  112. * -[#] HEXCHAT_PRI_{HIGHEST, HIGH, NORM, LOW, LOWEST}
  113. * -[x] HEXCHAT_EAT_{NONE, HEXCHAT, PLUGIN, ALL}
  114. * -[ ] HEXCHAT_FD_{READ, WRITE, EXCEPTION, NOTSOCKET}
  115. * -[x] hexchat_command (for commandf, use command(&format!("...")), it is equivalent.)
  116. * -[x] hexchat_print (for printf, use print(&format!("...")), it is equivalent.)
  117. * -[ ] hexchat_emit_print
  118. * -[ ] hexchat_emit_print_attrs
  119. * -[ ] hexchat_send_modes
  120. * -[ ] hexchat_nickcmp
  121. * -[ ] hexchat_strip
  122. * -[x] ~~hexchat_free~~ not available - use Drop impls.
  123. * -[x] ~~hexchat_event_attrs_create~~ not available - converted as needed
  124. * -[x] ~~hexchat_event_attrs_free~~ not available - use Drop impls.
  125. * -[x] hexchat_get_info
  126. * -[ ] hexchat_get_prefs
  127. * -[ ] hexchat_list_get, hexchat_list_fields, hexchat_list_next, hexchat_list_str,
  128. * hexchat_list_int, hexchat_list_time, hexchat_list_free
  129. * -[x] hexchat_hook_command
  130. * -[ ] hexchat_hook_fd
  131. * -[x] hexchat_hook_print
  132. * -[x] hexchat_hook_print_attrs
  133. * -[#] hexchat_hook_server (implemented through _attrs)
  134. * -[x] hexchat_hook_server_attrs
  135. * -[x] hexchat_hook_timer
  136. * -[x] ~~hexchat_unhook~~ not available - use Drop impls
  137. * -[x] hexchat_find_context
  138. * -[x] hexchat_get_context
  139. * -[x] hexchat_set_context
  140. * -[ ] hexchat_pluginpref_set_str
  141. * -[ ] hexchat_pluginpref_get_str
  142. * -[ ] hexchat_pluginpref_set_int
  143. * -[ ] hexchat_pluginpref_get_int
  144. * -[ ] hexchat_pluginpref_delete
  145. * -[ ] hexchat_pluginpref_list
  146. * -[ ] hexchat_plugingui_add
  147. * -[x] ~~hexchat_plugingui_remove~~ not available - use Drop impls.
  148. * -[ ] Wrap contexts within something we keep track of. Mark them invalid when contexts are
  149. * closed. [PRI-MAYBE]
  150. * -[x] Anchor closures on the stack using Rc<T>. Many (most?) hooks are reentrant. As far as I
  151. * know, all of them need this.
  152. * -[x] Additionally, use a Cell<bool> for timers.
  153. * -[ ] ???
  154. */
  155. #[doc(hidden)]
  156. pub extern crate libc;
  157. mod internals;
  158. use std::borrow::Cow;
  159. use std::cell::Cell;
  160. use std::ffi::{CString, CStr};
  161. use std::marker::PhantomData;
  162. use std::mem;
  163. use std::ops;
  164. use std::panic::catch_unwind;
  165. use std::ptr;
  166. use std::rc::Rc;
  167. use std::rc::Weak as RcWeak;
  168. use std::str::FromStr;
  169. use std::thread;
  170. use std::time::{SystemTime, UNIX_EPOCH, Duration};
  171. // ****** //
  172. // PUBLIC //
  173. // ****** //
  174. // Consts
  175. // EAT_*
  176. /// Equivalent to HEXCHAT_EAT_NONE.
  177. pub const EAT_NONE: Eat = Eat { do_eat: 0 };
  178. /// Equivalent to HEXCHAT_EAT_HEXCHAT.
  179. pub const EAT_HEXCHAT: Eat = Eat { do_eat: 1 };
  180. /// Equivalent to HEXCHAT_EAT_PLUGIN.
  181. pub const EAT_PLUGIN: Eat = Eat { do_eat: 2 };
  182. /// Equivalent to HEXCHAT_EAT_ALL.
  183. pub const EAT_ALL: Eat = Eat { do_eat: 1 | 2 };
  184. // PRI_*
  185. /// Equivalent to HEXCHAT_PRI_HIGHEST
  186. pub const PRI_HIGHEST: i32 = 127;
  187. /// Equivalent to HEXCHAT_PRI_HIGH
  188. pub const PRI_HIGH: i32 = 64;
  189. /// Equivalent to HEXCHAT_PRI_NORM
  190. pub const PRI_NORM: i32 = 0;
  191. /// Equivalent to HEXCHAT_PRI_LOW
  192. pub const PRI_LOW: i32 = -64;
  193. /// Equivalent to HEXCHAT_PRI_LOWEST
  194. pub const PRI_LOWEST: i32 = -128;
  195. // Traits
  196. /// A hexchat plugin.
  197. pub trait Plugin {
  198. /// Called to initialize the plugin.
  199. fn init(&self, ph: &mut PluginHandle, arg: Option<&str>) -> bool;
  200. /// Called to deinitialize the plugin.
  201. ///
  202. /// This is always called immediately prior to Drop::drop.
  203. fn deinit(&self, _ph: &mut PluginHandle) {
  204. }
  205. }
  206. // Structs
  207. /// A hexchat plugin handle, used to register hooks and interact with hexchat.
  208. ///
  209. /// # Examples
  210. ///
  211. /// ```
  212. /// use hexchat_plugin::{PluginHandle};
  213. ///
  214. /// fn init(ph: &mut PluginHandle) {
  215. /// ph.register("myplug", "0.1.0", "my awesome plug");
  216. /// }
  217. /// ```
  218. pub struct PluginHandle {
  219. ph: *mut internals::Ph,
  220. skip_pri_ck: bool,
  221. // Used for registration
  222. info: PluginInfo,
  223. }
  224. /// Arguments passed to a hook, until the next argument.
  225. ///
  226. /// # Examples
  227. ///
  228. /// ```
  229. /// use hexchat_plugin::{PluginHandle, Word, WordEol, Eat};
  230. ///
  231. /// fn cmd_foo(ph: &mut PluginHandle, arg: Word, arg_eol: WordEol) -> Eat {
  232. /// if arg.len() < 3 {
  233. /// ph.print("Not enough arguments");
  234. /// } else {
  235. /// ph.print(&format!("{} {} {}", arg[0], arg[1], arg[2]));
  236. /// }
  237. /// hexchat_plugin::EAT_ALL
  238. /// }
  239. ///
  240. /// fn on_privmsg(ph: &mut PluginHandle, word: Word, word_eol: WordEol) -> Eat {
  241. /// if word.len() > 0 && word[0].starts_with('@') {
  242. /// ph.print("We have message tags!?");
  243. /// }
  244. /// hexchat_plugin::EAT_NONE
  245. /// }
  246. /// ```
  247. pub struct Word<'a> {
  248. word: Vec<&'a str>
  249. }
  250. /// Arguments passed to a hook, until the end of the line.
  251. ///
  252. /// # Examples
  253. ///
  254. /// ```
  255. /// use hexchat_plugin::{PluginHandle, Word, WordEol, Eat};
  256. ///
  257. /// fn cmd_foo(ph: &mut PluginHandle, arg: Word, arg_eol: WordEol) -> Eat {
  258. /// if arg.len() < 3 {
  259. /// ph.print("Not enough arguments");
  260. /// } else {
  261. /// ph.print(&format!("{} {} {}", arg[0], arg[1], arg_eol[2]));
  262. /// }
  263. /// hexchat_plugin::EAT_ALL
  264. /// }
  265. ///
  266. /// fn on_privmsg(ph: &mut PluginHandle, word: Word, word_eol: WordEol) -> Eat {
  267. /// if word_eol.len() > 0 && word[0].starts_with('@') {
  268. /// ph.print("We have message tags!?");
  269. /// }
  270. /// hexchat_plugin::EAT_NONE
  271. /// }
  272. /// ```
  273. pub struct WordEol<'a> {
  274. word_eol: Vec<&'a str>
  275. }
  276. /// A safety wrapper to ensure you're working with a valid context.
  277. ///
  278. /// This mechanism attempts to reduce the likelihood of segfaults.
  279. pub struct EnsureValidContext<'a> {
  280. ph: &'a mut PluginHandle,
  281. }
  282. /// Event attributes.
  283. #[derive(Clone)]
  284. pub struct EventAttrs<'a> {
  285. /// Server time.
  286. pub server_time: Option<SystemTime>,
  287. _dummy: PhantomData<&'a ()>,
  288. }
  289. /// A status indicator for event callbacks. Indicates whether to continue processing, eat hexchat,
  290. /// eat plugin, or eat all.
  291. ///
  292. /// Returned by most hooks.
  293. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
  294. pub struct Eat {
  295. do_eat: i32,
  296. }
  297. /// A command hook handle.
  298. #[must_use = "Hooks must be stored somewhere and are automatically unhooked on Drop"]
  299. pub struct CommandHookHandle {
  300. ph: *mut internals::Ph,
  301. hh: *const internals::HexchatHook,
  302. // this does actually store an Rc<...>, but on the other side of the FFI.
  303. _f: PhantomData<Rc<CommandHookUd>>,
  304. }
  305. /// A server hook handle.
  306. #[must_use = "Hooks must be stored somewhere and are automatically unhooked on Drop"]
  307. pub struct ServerHookHandle {
  308. ph: *mut internals::Ph,
  309. hh: *const internals::HexchatHook,
  310. // this does actually store an Rc<...>, but on the other side of the FFI.
  311. _f: PhantomData<Rc<ServerHookUd>>,
  312. }
  313. /// A print hook handle.
  314. #[must_use = "Hooks must be stored somewhere and are automatically unhooked on Drop"]
  315. pub struct PrintHookHandle {
  316. ph: *mut internals::Ph,
  317. hh: *const internals::HexchatHook,
  318. // this does actually store an Rc<...>, but on the other side of the FFI.
  319. _f: PhantomData<Rc<PrintHookUd>>,
  320. }
  321. /// A timer hook handle.
  322. #[must_use = "Hooks must be stored somewhere and are automatically unhooked on Drop"]
  323. pub struct TimerHookHandle {
  324. ph: *mut internals::Ph,
  325. hh: *const internals::HexchatHook,
  326. // avoids issues
  327. alive: Rc<Cell<bool>>,
  328. // this does actually store an Rc<...>, but on the other side of the FFI.
  329. _f: PhantomData<Rc<TimerHookUd>>,
  330. }
  331. /// A context.
  332. #[derive(Clone)]
  333. pub struct Context {
  334. ctx: RcWeak<*const internals::HexchatContext>, // may be null
  335. closure: Rc<Cell<Option<PrintHookHandle>>>,
  336. }
  337. // #[derive(Debug)] // doesn't work
  338. pub struct InvalidContextError<F: FnOnce(EnsureValidContext) -> R, R>(F);
  339. // Enums
  340. /// A hexchat_get_info key.
  341. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Copy, Clone)]
  342. pub enum InfoId<'a> {
  343. /// Returns the away message, or `None` if the user is not away.
  344. Away,
  345. /// Returns the current channel name.
  346. Channel,
  347. /// Returns the current charset.
  348. Charset,
  349. /// Returns the hexchat configuration directory, e.g. `/home/user/.config/hexchat`.
  350. Configdir,
  351. /// Returns the text event format string for the given text event name.
  352. EventText(&'a str),
  353. /// Returns the (real) hostname of the current server.
  354. Host,
  355. /// Returns the contents of the input box.
  356. Inputbox,
  357. /// Returns the library directory, e.g. `/usr/lib/hexchat`.
  358. ///
  359. /// May not always work, as this string isn't necessarily UTF-8, but local file system
  360. /// encoding.
  361. Libdirfs,
  362. /// Returns the channel modes, if known, or `None`.
  363. Modes,
  364. /// Returns the current network name, or `None`.
  365. Network,
  366. /// Returns the user's current nick.
  367. Nick,
  368. /// Returns the user's nickserv password, if any, or `None`
  369. Nickserv,
  370. /// Returns the current server name, or `None` if you are not connected.
  371. Server,
  372. /// Returns the current channel topic.
  373. Topic,
  374. /// Returns the HexChat version string.
  375. Version,
  376. /// Returns the window status: "active", "hidden" or "normal".
  377. WinStatus,
  378. }
  379. // ***** //
  380. // impls //
  381. // ***** //
  382. impl<'a> InfoId<'a> {
  383. pub fn name(&self) -> Cow<'static, str> {
  384. match *self {
  385. InfoId::EventText(s) => {
  386. let mut eventtext: String = "event_text ".into();
  387. eventtext.push_str(&s);
  388. eventtext.into()
  389. },
  390. InfoId::Away => "away".into(),
  391. InfoId::Channel => "channel".into(),
  392. InfoId::Charset => "charset".into(),
  393. InfoId::Configdir => "configdir".into(),
  394. InfoId::Host => "host".into(),
  395. InfoId::Inputbox => "inputbox".into(),
  396. InfoId::Libdirfs => "libdirfs".into(),
  397. InfoId::Modes => "modes".into(),
  398. InfoId::Network => "network".into(),
  399. InfoId::Nick => "nick".into(),
  400. InfoId::Nickserv => "nickserv".into(),
  401. InfoId::Server => "server".into(),
  402. InfoId::Topic => "topic".into(),
  403. InfoId::Version => "version".into(),
  404. InfoId::WinStatus => "win_status".into(),
  405. }
  406. }
  407. }
  408. impl<F: FnOnce(EnsureValidContext) -> R, R> InvalidContextError<F, R> {
  409. pub fn get_closure(self) -> F {
  410. self.0
  411. }
  412. }
  413. impl Drop for CommandHookHandle {
  414. fn drop(&mut self) {
  415. unsafe {
  416. let b = ((*self.ph).hexchat_unhook)(self.ph, self.hh) as *mut CommandHookUd;
  417. // we assume b is not null. this should be safe.
  418. // just drop it
  419. mem::drop(Rc::from_raw(b));
  420. }
  421. }
  422. }
  423. impl Drop for ServerHookHandle {
  424. fn drop(&mut self) {
  425. unsafe {
  426. let b = ((*self.ph).hexchat_unhook)(self.ph, self.hh) as *mut ServerHookUd;
  427. // we assume b is not null. this should be safe.
  428. // just drop it
  429. mem::drop(Rc::from_raw(b));
  430. }
  431. }
  432. }
  433. impl Drop for PrintHookHandle {
  434. fn drop(&mut self) {
  435. unsafe {
  436. let b = ((*self.ph).hexchat_unhook)(self.ph, self.hh) as *mut PrintHookUd;
  437. // we assume b is not null. this should be safe.
  438. // just drop it
  439. mem::drop(Rc::from_raw(b));
  440. }
  441. }
  442. }
  443. impl Drop for TimerHookHandle {
  444. fn drop(&mut self) {
  445. if !self.alive.get() {
  446. // already free'd.
  447. return;
  448. }
  449. self.alive.set(false);
  450. unsafe {
  451. let b = ((*self.ph).hexchat_unhook)(self.ph, self.hh) as *mut TimerHookUd;
  452. // we assume b is not null. this should be safe.
  453. // just drop it
  454. mem::drop(Rc::from_raw(b));
  455. }
  456. }
  457. }
  458. impl<'a> Word<'a> {
  459. unsafe fn new(word: *const *const libc::c_char) -> Word<'a> {
  460. let mut vec = vec![];
  461. for i in 1..32 {
  462. let w = *word.offset(i);
  463. if !w.is_null() {
  464. vec.push(CStr::from_ptr(w).to_str().expect("non-utf8 word - broken hexchat"))
  465. }
  466. }
  467. while let Some(&"") = vec.last() {
  468. vec.pop();
  469. }
  470. Word { word: vec }
  471. }
  472. }
  473. impl<'a> ops::Deref for Word<'a> {
  474. type Target = [&'a str];
  475. fn deref(&self) -> &[&'a str] {
  476. &self.word
  477. }
  478. }
  479. impl<'a> WordEol<'a> {
  480. unsafe fn new(word_eol: *const *const libc::c_char) -> WordEol<'a> {
  481. let mut vec = vec![];
  482. for i in 1..32 {
  483. let w = *word_eol.offset(i);
  484. if !w.is_null() {
  485. vec.push(CStr::from_ptr(w).to_str().expect("non-utf8 word_eol - broken hexchat"))
  486. }
  487. }
  488. while let Some(&"") = vec.last() {
  489. vec.pop();
  490. }
  491. WordEol { word_eol: vec }
  492. }
  493. }
  494. impl<'a> ops::Deref for WordEol<'a> {
  495. type Target = [&'a str];
  496. fn deref(&self) -> &[&'a str] {
  497. &self.word_eol
  498. }
  499. }
  500. impl PluginHandle {
  501. fn new(ph: *mut internals::Ph, info: PluginInfo) -> PluginHandle {
  502. PluginHandle {
  503. ph, info, skip_pri_ck: false,
  504. }
  505. }
  506. /// Registers this hexchat plugin. This must be called exactly once when the plugin is loaded.
  507. ///
  508. /// # Panics
  509. ///
  510. /// This function panics if this plugin is already registered.
  511. ///
  512. /// # Examples
  513. ///
  514. /// ```
  515. /// use hexchat_plugin::PluginHandle;
  516. ///
  517. /// fn init(ph: &mut PluginHandle) {
  518. /// ph.register("foo", "0.1.0", "my foo plugin");
  519. /// }
  520. /// ```
  521. pub fn register(&mut self, name: &str, desc: &str, ver: &str) {
  522. unsafe {
  523. let info = self.info;
  524. if !(*info.name).is_null() || !(*info.desc).is_null() || !(*info.vers).is_null() {
  525. panic!("Attempt to re-register a plugin");
  526. }
  527. let name = CString::new(name).unwrap();
  528. let desc = CString::new(desc).unwrap();
  529. let ver = CString::new(ver).unwrap();
  530. // these shouldn't panic. if they do, we'll need to free them afterwards.
  531. (*info.name) = name.into_raw();
  532. (*info.desc) = desc.into_raw();
  533. (*info.vers) = ver.into_raw();
  534. }
  535. }
  536. /// Returns this plugin's registered name.
  537. ///
  538. /// # Panics
  539. ///
  540. /// This function panics if this plugin is not registered.
  541. pub fn get_name(&self) -> &str {
  542. unsafe {
  543. let info = self.info;
  544. if !(*info.name).is_null() || !(*info.desc).is_null() || !(*info.vers).is_null() {
  545. std::str::from_utf8_unchecked(CStr::from_ptr(*info.name).to_bytes())
  546. } else {
  547. panic!("Attempt to get the name of a plugin that was not yet registered.");
  548. }
  549. }
  550. }
  551. /// Returns this plugin's registered description.
  552. ///
  553. /// # Panics
  554. ///
  555. /// This function panics if this plugin is not registered.
  556. pub fn get_description(&self) -> &str {
  557. unsafe {
  558. let info = self.info;
  559. if !(*info.name).is_null() || !(*info.desc).is_null() || !(*info.vers).is_null() {
  560. std::str::from_utf8_unchecked(CStr::from_ptr(*info.desc).to_bytes())
  561. } else {
  562. panic!("Attempt to get the description of a plugin that was not yet registered.");
  563. }
  564. }
  565. }
  566. /// Returns this plugin's registered version.
  567. ///
  568. /// # Panics
  569. ///
  570. /// This function panics if this plugin is not registered.
  571. pub fn get_version(&self) -> &str {
  572. unsafe {
  573. let info = self.info;
  574. if !(*info.name).is_null() || !(*info.desc).is_null() || !(*info.vers).is_null() {
  575. std::str::from_utf8_unchecked(CStr::from_ptr(*info.vers).to_bytes())
  576. } else {
  577. panic!("Attempt to get the version of a plugin that was not yet registered.");
  578. }
  579. }
  580. }
  581. /// Ensures the current context is valid.
  582. ///
  583. /// # Panics
  584. ///
  585. /// This function may panic if it's called while hexchat is closing.
  586. // NOTE: using a closure is nicer.
  587. // TODO check if this is actually safe
  588. pub fn ensure_valid_context<F, R>(&mut self, f: F) -> R where F: FnOnce(EnsureValidContext) -> R {
  589. // let ctx = self.get_context();
  590. // if !self.set_context(ctx) {
  591. // // invalid context
  592. // // TODO fix up the context
  593. // unimplemented!()
  594. // }
  595. // f(EnsureValidContext { ph: self })
  596. let ctx = self.get_context();
  597. // need this here because we don't have NLL yet
  598. let res = self.with_context(&ctx, f);
  599. match res {
  600. Result::Ok(r @ _) => r,
  601. Result::Err(e @ _) => {
  602. let nctx = self.find_valid_context().expect("ensure_valid_context failed (find_valid_context failed), was hexchat closing?");
  603. self.with_context(&nctx, e.get_closure()).ok().expect("ensure_valid_context failed, was hexchat closing?")
  604. }
  605. }
  606. }
  607. /// Returns the current context.
  608. ///
  609. /// Note: The returned context may be invalid. Use [`set_context`] to check.
  610. ///
  611. /// [`set_context`]: #method.set_context
  612. // This needs to be fixed by hexchat. I cannot make the value become null when it's invalid
  613. // without invoking UB. This is because I can't set_context to null.
  614. pub fn get_context(&mut self) -> Context {
  615. let ctxp = unsafe { ((*self.ph).hexchat_get_context)(self.ph) };
  616. unsafe { wrap_context(self, ctxp) }
  617. // let ctxp = std::panic::AssertUnwindSafe(Rc::new(unsafe { ((*self.ph).hexchat_get_context)(self.ph) }));
  618. // let weak_ctxp = Rc::downgrade(&ctxp); // calling the Closure should drop the Context (sort of)
  619. // let closure: Rc<Cell<Option<PrintHookHandle>>> = Rc::new(Cell::new(None));
  620. // let hook = std::panic::AssertUnwindSafe(Rc::downgrade(&closure)); // dropping the Context should drop the Closure
  621. // self.skip_pri_ck = true;
  622. // closure.set(Some(self.hook_print("Close Context", move |ph, _| {
  623. // let _ = &ctxp;
  624. // let _: Option<PrintHookHandle> = hook.upgrade().unwrap().replace(None);
  625. // EAT_NONE
  626. // }, libc::c_int::min_value())));
  627. // self.skip_pri_ck = false;
  628. // Context { ctx: weak_ctxp, closure }
  629. }
  630. /// Sets the current context.
  631. ///
  632. /// Returns `true` if the context is valid, `false` otherwise.
  633. pub fn set_context(&mut self, ctx: &Context) -> bool {
  634. if let Some(ctx) = ctx.ctx.upgrade() {
  635. unsafe {
  636. ((*self.ph).hexchat_set_context)(self.ph, *ctx) != 0
  637. }
  638. } else {
  639. false
  640. }
  641. }
  642. /// Do something in a valid context.
  643. ///
  644. /// Note that this changes the active context and doesn't change it back.
  645. ///
  646. /// # Errors
  647. ///
  648. /// Returns `Err(InvalidContextError(f))` if the context is invalid. See [`set_context`]. Otherwise,
  649. /// calls `f` and returns `Ok(its result)`.
  650. ///
  651. /// Note that `InvalidContextError` contains the original closure. This allows you to retry.
  652. ///
  653. /// [`set_context`]: #method.set_context
  654. // this is probably safe to inline, and actually a good idea for ensure_valid_context
  655. #[inline]
  656. pub fn with_context<F, R>(&mut self, ctx: &Context, f: F) -> Result<R, InvalidContextError<F, R>> where F: FnOnce(EnsureValidContext) -> R {
  657. if !self.set_context(ctx) {
  658. Err(InvalidContextError(f))
  659. } else {
  660. Ok(f(EnsureValidContext { ph: self }))
  661. }
  662. }
  663. /// Sets a command hook.
  664. ///
  665. /// # Examples
  666. ///
  667. /// ```
  668. /// use hexchat_plugin::{PluginHandle, CommandHookHandle};
  669. ///
  670. /// fn register_commands(ph: &mut PluginHandle) -> Vec<CommandHookHandle> {
  671. /// vec![
  672. /// ph.hook_command("hello-world", |ph, arg, arg_eol| {
  673. /// ph.print("Hello, World!");
  674. /// hexchat_plugin::EAT_ALL
  675. /// }, hexchat_plugin::PRI_NORM, Some("prints 'Hello, World!'")),
  676. /// ]
  677. /// }
  678. /// ```
  679. pub fn hook_command<F>(&mut self, cmd: &str, cb: F, pri: i32, help: Option<&str>) -> CommandHookHandle where F: Fn(&mut PluginHandle, Word, WordEol) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  680. unsafe extern "C" fn callback(word: *const *const libc::c_char, word_eol: *const *const libc::c_char, ud: *mut libc::c_void) -> libc::c_int {
  681. // hook may unhook itself.
  682. // however, we don't wanna free it until it has returned.
  683. let f: Rc<CommandHookUd> = rc_clone_from_raw(ud as *const CommandHookUd);
  684. let ph = f.1;
  685. match catch_unwind(move || {
  686. let word = Word::new(word);
  687. let word_eol = WordEol::new(word_eol);
  688. (f.0)(&mut PluginHandle::new(f.1, f.2), word, word_eol).do_eat as libc::c_int
  689. }) {
  690. Result::Ok(v @ _) => v,
  691. Result::Err(e @ _) => {
  692. // if it's a &str or String, just print it
  693. if let Some(estr) = e.downcast_ref::<&str>() {
  694. hexchat_print_str(ph, estr, false);
  695. } else if let Some(estring) = e.downcast_ref::<String>() {
  696. hexchat_print_str(ph, &estring, false);
  697. }
  698. 0 // EAT_NONE
  699. }
  700. }
  701. }
  702. let b: Rc<CommandHookUd> = Rc::new((Box::new(cb), self.ph, self.info));
  703. let name = CString::new(cmd).unwrap();
  704. let help_text = help.map(CString::new).map(Result::unwrap);
  705. let bp = Rc::into_raw(b);
  706. unsafe {
  707. let res = ((*self.ph).hexchat_hook_command)(self.ph, name.as_ptr(), pri as libc::c_int, callback, help_text.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()), bp as *mut _);
  708. assert!(!res.is_null());
  709. CommandHookHandle { ph: self.ph, hh: res, _f: PhantomData }
  710. }
  711. }
  712. /// Sets a server hook.
  713. ///
  714. /// # Examples
  715. ///
  716. /// ```
  717. /// use hexchat_plugin::{PluginHandle, ServerHookHandle};
  718. ///
  719. /// fn register_server_hooks(ph: &mut PluginHandle) -> Vec<ServerHookHandle> {
  720. /// vec![
  721. /// ph.hook_server("PRIVMSG", |ph, word, word_eol| {
  722. /// if word.len() > 0 && word[0].starts_with('@') {
  723. /// ph.print("We have message tags!?");
  724. /// }
  725. /// hexchat_plugin::EAT_NONE
  726. /// }, hexchat_plugin::PRI_NORM),
  727. /// ]
  728. /// }
  729. /// ```
  730. pub fn hook_server<F>(&mut self, cmd: &str, cb: F, pri: i32) -> ServerHookHandle where F: Fn(&mut PluginHandle, Word, WordEol) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  731. self.hook_server_attrs(cmd, move |ph, w, we, _| cb(ph, w, we), pri)
  732. }
  733. /// Sets a server hook, with attributes.
  734. pub fn hook_server_attrs<F>(&mut self, cmd: &str, cb: F, pri: i32) -> ServerHookHandle where F: Fn(&mut PluginHandle, Word, WordEol, EventAttrs) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  735. unsafe extern "C" fn callback(word: *const *const libc::c_char, word_eol: *const *const libc::c_char, attrs: *const internals::HexchatEventAttrs, ud: *mut libc::c_void) -> libc::c_int {
  736. // hook may unhook itself.
  737. // however, we don't wanna free it until it has returned.
  738. let f: Rc<ServerHookUd> = rc_clone_from_raw(ud as *const ServerHookUd);
  739. let ph = f.1;
  740. match catch_unwind(move || {
  741. let word = Word::new(word);
  742. let word_eol = WordEol::new(word_eol);
  743. (f.0)(&mut PluginHandle::new(f.1, f.2), word, word_eol, (&*attrs).into()).do_eat as libc::c_int
  744. }) {
  745. Result::Ok(v @ _) => v,
  746. Result::Err(e @ _) => {
  747. // if it's a &str or String, just print it
  748. if let Some(estr) = e.downcast_ref::<&str>() {
  749. hexchat_print_str(ph, estr, false);
  750. } else if let Some(estring) = e.downcast_ref::<String>() {
  751. hexchat_print_str(ph, &estring, false);
  752. }
  753. 0 // EAT_NONE
  754. }
  755. }
  756. }
  757. let b: Rc<ServerHookUd> = Rc::new((Box::new(cb), self.ph, self.info));
  758. let name = CString::new(cmd).unwrap();
  759. let bp = Rc::into_raw(b);
  760. unsafe {
  761. let res = ((*self.ph).hexchat_hook_server_attrs)(self.ph, name.as_ptr(), pri as libc::c_int, callback, bp as *mut _);
  762. assert!(!res.is_null());
  763. ServerHookHandle { ph: self.ph, hh: res, _f: PhantomData }
  764. }
  765. }
  766. /// Sets a print hook.
  767. ///
  768. /// # Examples
  769. ///
  770. /// ```
  771. /// use hexchat_plugin::{PluginHandle, PrintHookHandle};
  772. ///
  773. /// fn register_print_hooks(ph: &mut PluginHandle) -> Vec<PrintHookHandle> {
  774. /// vec![
  775. /// ph.hook_print("Channel Message", |ph, arg| {
  776. /// if let Some(nick) = arg.get(0) {
  777. /// if *nick == "KnOwN_SpAmMeR" {
  778. /// return hexchat_plugin::EAT_ALL
  779. /// }
  780. /// }
  781. /// hexchat_plugin::EAT_NONE
  782. /// }, hexchat_plugin::PRI_NORM),
  783. /// ]
  784. /// }
  785. /// ```
  786. pub fn hook_print<F>(&mut self, name: &str, cb: F, mut pri: i32) -> PrintHookHandle where F: Fn(&mut PluginHandle, Word) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  787. // hmm, is there any way to avoid this code duplication?
  788. // hook_print is special because dummy prints (keypresses, Close Context) are handled
  789. // through here, but never through hook_print_attrs. :/
  790. unsafe extern "C" fn callback(word: *const *const libc::c_char, ud: *mut libc::c_void) -> libc::c_int {
  791. // hook may unhook itself.
  792. // however, we don't wanna free it until it has returned.
  793. let f: Rc<PrintHookUd> = rc_clone_from_raw(ud as *const PrintHookUd);
  794. let ph = f.1;
  795. match catch_unwind(move || {
  796. let word = Word::new(word);
  797. (f.0)(&mut PluginHandle::new(f.1, f.2), word, EventAttrs::new()).do_eat as libc::c_int
  798. }) {
  799. Result::Ok(v @ _) => v,
  800. Result::Err(e @ _) => {
  801. // if it's a &str or String, just print it
  802. if let Some(estr) = e.downcast_ref::<&str>() {
  803. hexchat_print_str(ph, estr, false);
  804. } else if let Some(estring) = e.downcast_ref::<String>() {
  805. hexchat_print_str(ph, &estring, false);
  806. }
  807. 0 // EAT_NONE
  808. }
  809. }
  810. }
  811. if name == "Close Context" && (pri as libc::c_int == libc::c_int::min_value()) && !self.skip_pri_ck {
  812. self.print("Warning: Attempted to hook Close Context with priority INT_MIN. Adjusting to INT_MIN+1.");
  813. pri = (libc::c_int::min_value() + 1) as i32;
  814. }
  815. let b: Rc<PrintHookUd> = Rc::new((Box::new(move |ph, w, _| cb(ph, w)), self.ph, self.info));
  816. let name = CString::new(name).unwrap();
  817. let bp = Rc::into_raw(b);
  818. unsafe {
  819. let res = ((*self.ph).hexchat_hook_print)(self.ph, name.as_ptr(), pri as libc::c_int, callback, bp as *mut _);
  820. assert!(!res.is_null());
  821. PrintHookHandle { ph: self.ph, hh: res, _f: PhantomData }
  822. }
  823. }
  824. /// Sets a print hook, with attributes.
  825. pub fn hook_print_attrs<F>(&mut self, name: &str, cb: F, pri: i32) -> PrintHookHandle where F: Fn(&mut PluginHandle, Word, EventAttrs) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  826. unsafe extern "C" fn callback(word: *const *const libc::c_char, attrs: *const internals::HexchatEventAttrs, ud: *mut libc::c_void) -> libc::c_int {
  827. // hook may unhook itself.
  828. // however, we don't wanna free it until it has returned.
  829. let f: Rc<PrintHookUd> = rc_clone_from_raw(ud as *const PrintHookUd);
  830. let ph = f.1;
  831. match catch_unwind(move || {
  832. let word = Word::new(word);
  833. (f.0)(&mut PluginHandle::new(f.1, f.2), word, (&*attrs).into()).do_eat as libc::c_int
  834. }) {
  835. Result::Ok(v @ _) => v,
  836. Result::Err(e @ _) => {
  837. // if it's a &str or String, just print it
  838. if let Some(estr) = e.downcast_ref::<&str>() {
  839. hexchat_print_str(ph, estr, false);
  840. } else if let Some(estring) = e.downcast_ref::<String>() {
  841. hexchat_print_str(ph, &estring, false);
  842. }
  843. 0 // EAT_NONE
  844. }
  845. }
  846. }
  847. let b: Rc<PrintHookUd> = Rc::new((Box::new(cb), self.ph, self.info));
  848. let name = CString::new(name).unwrap();
  849. let bp = Rc::into_raw(b);
  850. unsafe {
  851. let res = ((*self.ph).hexchat_hook_print_attrs)(self.ph, name.as_ptr(), pri as libc::c_int, callback, bp as *mut _);
  852. assert!(!res.is_null());
  853. PrintHookHandle { ph: self.ph, hh: res, _f: PhantomData }
  854. }
  855. }
  856. /// Sets a timer hook
  857. ///
  858. /// # Examples
  859. ///
  860. /// ```
  861. /// use hexchat_plugin::{PluginHandle, TimerHookHandle};
  862. ///
  863. /// fn register_timers(ph: &mut PluginHandle) -> Vec<TimerHookHandle> {
  864. /// vec![
  865. /// ph.hook_timer(2000, |ph| {
  866. /// ph.print("timer up!");
  867. /// false
  868. /// }),
  869. /// ]
  870. /// }
  871. /// ```
  872. pub fn hook_timer<F>(&mut self, timeout: i32, cb: F) -> TimerHookHandle where F: Fn(&mut PluginHandle) -> bool + 'static + ::std::panic::RefUnwindSafe {
  873. unsafe extern "C" fn callback(ud: *mut libc::c_void) -> libc::c_int {
  874. // hook may unhook itself.
  875. // however, we don't wanna free it until it has returned.
  876. let f: Rc<TimerHookUd> = rc_clone_from_raw(ud as *const TimerHookUd);
  877. let alive = f.1.clone(); // clone the alive because why not
  878. let f = f.0.clone();
  879. let ph = f.1;
  880. // we could technically free the Rc<TimerHookUd> here, I guess
  881. match catch_unwind(move || {
  882. (f.0)(&mut PluginHandle::new(f.1, f.2))
  883. }) {
  884. Result::Ok(true) => 1,
  885. Result::Ok(false) => {
  886. // avoid double-free
  887. if !alive.get() {
  888. return 0;
  889. }
  890. // mark it no longer alive
  891. alive.set(false);
  892. // HexChat will automatically free the hook.
  893. // we just need to free the userdata.
  894. mem::drop(Rc::from_raw(ud as *const TimerHookUd));
  895. 0
  896. },
  897. Result::Err(e @ _) => {
  898. // if it's a &str or String, just print it
  899. if let Some(estr) = e.downcast_ref::<&str>() {
  900. hexchat_print_str(ph, estr, false);
  901. } else if let Some(estring) = e.downcast_ref::<String>() {
  902. hexchat_print_str(ph, &estring, false);
  903. }
  904. // avoid double-free
  905. if !alive.get() {
  906. return 0;
  907. }
  908. // mark it no longer alive
  909. alive.set(false);
  910. // HexChat will automatically free the hook.
  911. // we just need to free the userdata.
  912. mem::drop(Rc::from_raw(ud as *const TimerHookUd));
  913. 0
  914. }
  915. }
  916. }
  917. let alive = Rc::new(Cell::new(true));
  918. let b: Rc<TimerHookUd> = Rc::new((Rc::new((Box::new(cb), self.ph, self.info)), alive.clone()));
  919. let bp = Rc::into_raw(b);
  920. unsafe {
  921. let res = ((*self.ph).hexchat_hook_timer)(self.ph, timeout as libc::c_int, callback, bp as *mut _);
  922. assert!(!res.is_null());
  923. TimerHookHandle { ph: self.ph, hh: res, alive, _f: PhantomData }
  924. }
  925. }
  926. /// Prints to the hexchat buffer.
  927. // this checks the context internally. if it didn't, it wouldn't be safe to have here.
  928. pub fn print(&mut self, s: &str) {
  929. unsafe {
  930. hexchat_print_str(self.ph, s, true);
  931. }
  932. }
  933. /// Returns information on the current context.
  934. ///
  935. /// Note: `InfoId::Libdirfs` may return `None` or broken results if the result wouldn't be (valid) UTF-8.
  936. // TODO this should be `id: InfoId`. fix in 0.3
  937. pub fn get_info(&mut self, id: &InfoId) -> Option<String> {
  938. let ph = self.ph;
  939. let id_cstring = CString::new(&*id.name()).unwrap();
  940. unsafe {
  941. let res = ((*ph).hexchat_get_info)(ph, id_cstring.as_ptr());
  942. if res.is_null() {
  943. None
  944. } else {
  945. let s = CStr::from_ptr(res).to_owned().into_string();
  946. if *id != InfoId::Libdirfs {
  947. Some(s.expect("non-utf8 word - broken hexchat"))
  948. } else {
  949. s.ok()
  950. }
  951. }
  952. }
  953. }
  954. // ******* //
  955. // PRIVATE //
  956. // ******* //
  957. fn find_valid_context(&mut self) -> Option<Context> {
  958. unsafe {
  959. let ph = self.ph;
  960. // TODO wrap this in a safer API, with proper Drop
  961. #[allow(unused_mut)]
  962. let mut list = ((*ph).hexchat_list_get)(ph, cstr(b"channels\0"));
  963. // hexchat does this thing where it puts a context in a list_str.
  964. // this *is* the proper way to do this
  965. if ((*ph).hexchat_list_next)(ph, list) != 0 {
  966. // if this panics we may leak some memory. it's not a big deal tho, as it indicates
  967. // a bug in hexchat-plugin.rs.
  968. let ctx = ((*ph).hexchat_list_str)(ph, list, cstr(b"context\0")) as *const internals::HexchatContext;
  969. ((*ph).hexchat_list_free)(ph, list);
  970. Some(wrap_context(self, ctx))
  971. } else {
  972. ((*ph).hexchat_list_free)(ph, list);
  973. None
  974. }
  975. }
  976. }
  977. }
  978. impl<'a> EventAttrs<'a> {
  979. fn new() -> EventAttrs<'a> {
  980. EventAttrs {
  981. server_time: None,
  982. _dummy: PhantomData,
  983. }
  984. }
  985. }
  986. impl<'a> From<&'a internals::HexchatEventAttrs> for EventAttrs<'a> {
  987. fn from(other: &'a internals::HexchatEventAttrs) -> EventAttrs<'a> {
  988. EventAttrs {
  989. server_time: if other.server_time_utc > 0 { Some(UNIX_EPOCH + Duration::from_secs(other.server_time_utc as u64)) } else { None },
  990. _dummy: PhantomData,
  991. }
  992. }
  993. }
  994. impl<'a> EnsureValidContext<'a> {
  995. /*
  996. * These cause UB:
  997. * `hexchat_command` may invalidate the plugin context.
  998. * `hexchat_find_context` and `hexchat_nickcmp` use the plugin context without checking it.
  999. * `hexchat_get_prefs` uses the plugin context if name == "state_cursor" or "id" (or anything with
  1000. * the same hash).
  1001. * `hexchat_list_get` uses the plugin context if name == "notify" (or anything with the same hash).
  1002. * `hexchat_list_str`, `hexchat_list_int`,
  1003. * `hexchat_emit_print`, `hexchat_emit_print_attrs` use the plugin context.
  1004. * `hexchat_send_modes` uses the plugin context.
  1005. * We need to wrap them (or, alternatively, hexchat_command). However, there's no (safe) way to get
  1006. * a valid context afterwards.
  1007. * - Actually that's a lie. Hexchat does a trick to give you a context as part of the channel list.
  1008. * We can use that to our advantage. I'm not sure if it's better to wrap hexchat_command or the
  1009. * other functions, tho.
  1010. * (Do we want to walk a linked list every time we use hexchat_command? I'd think
  1011. * hexchat_command is the most used API function... Plus, emit_print could indirectly
  1012. * invalidate the context as well.)
  1013. *
  1014. * For performance we put them behind an EnsureValidContext - things that don't invalidate the
  1015. * context take an `&mut self`, things that do take an `self`.
  1016. */
  1017. /// Finds an open context for the given servname and channel.
  1018. pub fn find_context(&mut self, servname: Option<&str>, channel: Option<&str>) -> Option<Context> {
  1019. // this was a mistake but oh well
  1020. let ph = self.ph.ph;
  1021. let servname = servname.map(|x| CString::new(x).unwrap());
  1022. let channel = channel.map(|x| CString::new(x).unwrap());
  1023. let ctx = unsafe {
  1024. let sptr = servname.map(|x| x.as_ptr()).unwrap_or(ptr::null());
  1025. let cptr = channel.map(|x| x.as_ptr()).unwrap_or(ptr::null());
  1026. ((*ph).hexchat_find_context)(ph, sptr, cptr)
  1027. };
  1028. if ctx.is_null() {
  1029. None
  1030. } else {
  1031. Some(unsafe { wrap_context(self.ph, ctx) })
  1032. }
  1033. }
  1034. /// Compares two nicks based on the server's case mapping.
  1035. pub fn nickcmp(&mut self, nick1: &str, nick2: &str) -> ::std::cmp::Ordering {
  1036. use std::cmp::Ordering;
  1037. // this was a mistake but oh well
  1038. let ph = self.ph.ph;
  1039. // need to put this in a more permanent position than temporaries
  1040. let nick1 = CString::new(nick1).unwrap();
  1041. let nick2 = CString::new(nick2).unwrap();
  1042. let res = unsafe {
  1043. ((*ph).hexchat_nickcmp)(ph, nick1.as_ptr(), nick2.as_ptr())
  1044. };
  1045. if res < 0 {
  1046. Ordering::Less
  1047. } else if res > 0 {
  1048. Ordering::Greater
  1049. } else {
  1050. Ordering::Equal
  1051. }
  1052. }
  1053. pub fn send_modes<'b, I: IntoIterator<Item=&'b str>>(&mut self, iter: I, mpl: i32, sign: char, mode: char) {
  1054. // this was a mistake but oh well
  1055. let ph = self.ph.ph;
  1056. assert!(sign == '+' || sign == '-', "sign must be + or -");
  1057. assert!(mode.is_ascii(), "mode must be ascii");
  1058. assert!(mpl >= 0, "mpl must be non-negative");
  1059. let v: Vec<CString> = iter.into_iter().map(|s| CString::new(s).unwrap()).collect();
  1060. let mut v2: Vec<*const libc::c_char> = (&v).iter().map(|x| x.as_ptr()).collect();
  1061. let arr: &mut [*const libc::c_char] = &mut *v2;
  1062. unsafe {
  1063. ((*ph).hexchat_send_modes)(ph, arr.as_mut_ptr(), arr.len() as libc::c_int,
  1064. mpl as libc::c_int, sign as libc::c_char, mode as libc::c_char)
  1065. }
  1066. }
  1067. /// Executes a command.
  1068. pub fn command(self, cmd: &str) {
  1069. // this was a mistake but oh well
  1070. let ph = self.ph.ph;
  1071. // need to put this in a more permanent position than temporaries
  1072. let cmd = CString::new(cmd).unwrap();
  1073. unsafe {
  1074. ((*ph).hexchat_command)(ph, cmd.as_ptr())
  1075. }
  1076. }
  1077. pub fn emit_print(self) {
  1078. // TODO
  1079. unimplemented!()
  1080. }
  1081. pub fn emit_print_attrs(self) {
  1082. // TODO
  1083. unimplemented!()
  1084. }
  1085. // ******** //
  1086. // FORWARDS //
  1087. // ******** //
  1088. // We can't just deref because then you could recursively ensure valid context and then it'd no
  1089. // longer work.
  1090. pub fn get_context(&mut self) -> Context {
  1091. self.ph.get_context()
  1092. }
  1093. /// Sets the current context.
  1094. ///
  1095. /// Returns `true` if the context is valid, `false` otherwise.
  1096. pub fn set_context(&mut self, ctx: &Context) -> bool {
  1097. self.ph.set_context(ctx)
  1098. }
  1099. /// Prints to the hexchat buffer.
  1100. // as of hexchat 2.14.1, this does not call hooks.
  1101. pub fn print(&mut self, s: &str) {
  1102. self.ph.print(s)
  1103. }
  1104. /// Sets a command hook
  1105. pub fn hook_command<F>(&mut self, cmd: &str, cb: F, pri: i32, help: Option<&str>) -> CommandHookHandle where F: Fn(&mut PluginHandle, Word, WordEol) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  1106. self.ph.hook_command(cmd, cb, pri, help)
  1107. }
  1108. /// Sets a server hook
  1109. pub fn hook_server<F>(&mut self, cmd: &str, cb: F, pri: i32) -> ServerHookHandle where F: Fn(&mut PluginHandle, Word, WordEol) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  1110. self.ph.hook_server(cmd, cb, pri)
  1111. }
  1112. /// Sets a print hook
  1113. pub fn hook_print<F>(&mut self, name: &str, cb: F, pri: i32) -> PrintHookHandle where F: Fn(&mut PluginHandle, Word) -> Eat + 'static + ::std::panic::RefUnwindSafe {
  1114. self.ph.hook_print(name, cb, pri)
  1115. }
  1116. /// Sets a timer hook
  1117. pub fn hook_timer<F>(&mut self, timeout: i32, cb: F) -> TimerHookHandle where F: Fn(&mut PluginHandle) -> bool + 'static + ::std::panic::RefUnwindSafe {
  1118. self.ph.hook_timer(timeout, cb)
  1119. }
  1120. pub fn get_info(&mut self, id: &InfoId) -> Option<String> {
  1121. self.ph.get_info(id)
  1122. }
  1123. }
  1124. // ******* //
  1125. // PRIVATE //
  1126. // ******* //
  1127. // Type aliases, used for safety type checking.
  1128. /// Userdata type used by a command hook.
  1129. // We actually do want RefUnwindSafe. This function may be called multiple times, and it's not
  1130. // automatically invalidated if it panics, so it may be called again after it panics. If you need
  1131. // mutable state, std provides std::sync::Mutex which has poisoning. Other interior mutability with
  1132. // poisoning could also be used. std doesn't have anything for single-threaded performance (yet),
  1133. // but hexchat isn't particularly performance-critical.
  1134. type CommandHookUd = (Box<Fn(&mut PluginHandle, Word, WordEol) -> Eat + ::std::panic::RefUnwindSafe>, *mut internals::Ph, PluginInfo);
  1135. /// Userdata type used by a server hook.
  1136. type ServerHookUd = (Box<Fn(&mut PluginHandle, Word, WordEol, EventAttrs) -> Eat + ::std::panic::RefUnwindSafe>, *mut internals::Ph, PluginInfo);
  1137. /// Userdata type used by a print hook.
  1138. type PrintHookUd = (Box<Fn(&mut PluginHandle, Word, EventAttrs) -> Eat + ::std::panic::RefUnwindSafe>, *mut internals::Ph, PluginInfo);
  1139. /// Userdata type used by a timer hook.
  1140. type TimerHookUd = (Rc<(Box<Fn(&mut PluginHandle) -> bool + ::std::panic::RefUnwindSafe>, *mut internals::Ph, PluginInfo)>, Rc<Cell<bool>>);
  1141. /// The contents of an empty CStr.
  1142. ///
  1143. /// This is useful where you need a non-null CStr.
  1144. // NOTE: MUST BE b"\0"!
  1145. const EMPTY_CSTRING_DATA: &[u8] = b"\0";
  1146. /// Converts a nul-terminated const bstring to a C string.
  1147. ///
  1148. /// # Panics
  1149. ///
  1150. /// Panics if b contains embedded nuls.
  1151. // TODO const fn, once that's possible
  1152. fn cstr(b: &'static [u8]) -> *const libc::c_char {
  1153. CStr::from_bytes_with_nul(b).unwrap().as_ptr()
  1154. }
  1155. /// Clones an Rc straight from a raw pointer.
  1156. ///
  1157. /// # Safety
  1158. ///
  1159. /// This function is unsafe because `ptr` must hame come from `Rc::into_raw`.
  1160. unsafe fn rc_clone_from_raw<T>(ptr: *const T) -> Rc<T> {
  1161. // this is a bit confusing to read, but basically, we get an Rc from the raw ptr, and increment
  1162. // the refcount.
  1163. // The construct mem::forget(rc.clone()) increments the refcount.
  1164. let rc = Rc::from_raw(ptr);
  1165. mem::forget(rc.clone());
  1166. rc
  1167. }
  1168. /// Converts a **valid** context pointer into a Context (Rust-managed) struct.
  1169. ///
  1170. /// # Safety
  1171. ///
  1172. /// This function doesn't validate the context.
  1173. unsafe fn wrap_context(ph: &mut PluginHandle, ctx: *const internals::HexchatContext) -> Context {
  1174. let ctxp = std::panic::AssertUnwindSafe(Rc::new(ctx));
  1175. let weak_ctxp = Rc::downgrade(&ctxp); // calling the Closure should drop the Context (sort of)
  1176. let closure: Rc<Cell<Option<PrintHookHandle>>> = Rc::new(Cell::new(None));
  1177. let hook = std::panic::AssertUnwindSafe(Rc::downgrade(&closure)); // dropping the Context should drop the Closure
  1178. ph.skip_pri_ck = true;
  1179. closure.set(Some(ph.hook_print("Close Context", move |ph, _| {
  1180. let _ = &ctxp;
  1181. let _: Option<PrintHookHandle> = hook.upgrade().unwrap().replace(None);
  1182. EAT_NONE
  1183. }, libc::c_int::min_value())));
  1184. ph.skip_pri_ck = false;
  1185. Context { ctx: weak_ctxp, closure }
  1186. }
  1187. /// Prints an &str to hexchat, trying to avoid allocations.
  1188. ///
  1189. /// # Safety
  1190. ///
  1191. /// This function does not check the passed in argument.
  1192. ///
  1193. /// # Panics
  1194. ///
  1195. /// Panics if panic_on_nul is true and the string contains embedded nuls.
  1196. unsafe fn hexchat_print_str(ph: *mut internals::Ph, s: &str, panic_on_nul: bool) {
  1197. match CString::new(s) {
  1198. Result::Ok(cs @ _) => {
  1199. let csr: &CStr = &cs;
  1200. ((*ph).hexchat_print)(ph, csr.as_ptr())
  1201. },
  1202. e @ _ => if panic_on_nul {e.unwrap();}, // TODO nul_position?
  1203. }
  1204. }
  1205. /// Helper to manage owned internals::HexchatEventAttrs
  1206. struct HexchatEventAttrsHelper(*mut internals::HexchatEventAttrs, *mut internals::Ph);
  1207. impl HexchatEventAttrsHelper {
  1208. fn new(ph: *mut internals::Ph) -> Self {
  1209. HexchatEventAttrsHelper(unsafe { ((*ph).hexchat_event_attrs_create)(ph) }, ph)
  1210. }
  1211. fn new_with(ph: *mut internals::Ph, attrs: EventAttrs) -> Self {
  1212. let helper = Self::new(ph);
  1213. let v = attrs.server_time.or(Some(UNIX_EPOCH)).map(|st| match st.duration_since(UNIX_EPOCH) {
  1214. Ok(n) => n.as_secs(),
  1215. Err(_) => 0
  1216. }).filter(|&st| st < (libc::time_t::max_value() as u64)).unwrap() as libc::time_t;
  1217. unsafe { (*helper.0).server_time_utc = v; }
  1218. helper
  1219. }
  1220. }
  1221. impl Drop for HexchatEventAttrsHelper {
  1222. fn drop(&mut self) {
  1223. unsafe {
  1224. ((*self.1).hexchat_event_attrs_free)(self.1, self.0)
  1225. }
  1226. }
  1227. }
  1228. /// Holds name, desc, vers
  1229. // This is kinda naughty - we modify these values after returning from hexchat_plugin_init, during
  1230. // the deinitialization.
  1231. // However, if my reading of the HexChat code is correct, this is "ok".
  1232. #[derive(Copy, Clone)]
  1233. struct PluginInfo {
  1234. name: *mut *const libc::c_char,
  1235. desc: *mut *const libc::c_char,
  1236. vers: *mut *const libc::c_char,
  1237. }
  1238. impl PluginInfo {
  1239. /// Creates a PluginInfo.
  1240. ///
  1241. /// # Panics
  1242. ///
  1243. /// This function explicitly doesn't panic. Call unwrap() on the result instead.
  1244. fn new(name: *mut *const libc::c_char, desc: *mut *const libc::c_char, vers: *mut *const libc::c_char) -> Option<PluginInfo> {
  1245. if name.is_null() || desc.is_null() || vers.is_null() || name == desc || desc == vers || name == vers {
  1246. None
  1247. } else {
  1248. Some(unsafe { PluginInfo::new_unchecked(name, desc, vers) })
  1249. }
  1250. }
  1251. /// Creates a PluginInfo without checking the arguments.
  1252. ///
  1253. /// # Safety
  1254. ///
  1255. /// This function is unsafe, as it doesn't check the validity of the arguments. You're expected
  1256. /// to only pass in non-aliased non-null pointers. Use new if unsure.
  1257. unsafe fn new_unchecked(name: *mut *const libc::c_char, desc: *mut *const libc::c_char, vers: *mut *const libc::c_char) -> PluginInfo {
  1258. PluginInfo {
  1259. name, desc, vers
  1260. }
  1261. }
  1262. /// Drop relevant CStrings.
  1263. ///
  1264. /// # Safety
  1265. ///
  1266. /// This function is unsafe because calling it may trigger Undefined Behaviour. See also
  1267. /// [CString::from_raw].
  1268. ///
  1269. /// [from_raw]: https://doc.rust-lang.org/std/ffi/struct.CString.html#method.from_raw
  1270. unsafe fn drop_info(&mut self) {
  1271. if !(*self.name).is_null() {
  1272. mem::drop(CString::from_raw(*self.name as *mut _));
  1273. *self.name = cstr(EMPTY_CSTRING_DATA);
  1274. }
  1275. if !(*self.desc).is_null() {
  1276. mem::drop(CString::from_raw(*self.desc as *mut _));
  1277. *self.desc = cstr(EMPTY_CSTRING_DATA);
  1278. }
  1279. if !(*self.vers).is_null() {
  1280. mem::drop(CString::from_raw(*self.vers as *mut _));
  1281. *self.vers = cstr(EMPTY_CSTRING_DATA);
  1282. }
  1283. }
  1284. }
  1285. /// Plugin data stored in the hexchat plugin_handle.
  1286. struct PhUserdata {
  1287. plug: Box<Plugin>,
  1288. pluginfo: PluginInfo,
  1289. }
  1290. /// Puts the userdata in the plugin handle.
  1291. ///
  1292. /// # Safety
  1293. ///
  1294. /// This function is unsafe because it doesn't check if the pointer is valid.
  1295. ///
  1296. /// Improper use of this function can leak memory.
  1297. unsafe fn put_userdata(ph: *mut internals::Ph, ud: Box<PhUserdata>) {
  1298. (*ph).userdata = Box::into_raw(ud) as *mut libc::c_void;
  1299. }
  1300. // unsafe fn get_userdata(ph: *mut internals::Ph) -> *const PhUserdata {
  1301. // (*ph).userdata as *const _
  1302. // }
  1303. /// Pops the userdata from the plugin handle.
  1304. ///
  1305. /// # Safety
  1306. ///
  1307. /// This function is unsafe because it doesn't check if the pointer is valid.
  1308. unsafe fn pop_userdata(ph: *mut internals::Ph) -> Box<PhUserdata> {
  1309. Box::from_raw(mem::replace(&mut (*ph).userdata, ptr::null_mut()) as *mut PhUserdata)
  1310. }
  1311. // *********************** //
  1312. // PUBLIC OUT OF NECESSITY //
  1313. // *********************** //
  1314. #[doc(hidden)]
  1315. pub unsafe fn hexchat_plugin_init<T>(plugin_handle: *mut libc::c_void,
  1316. plugin_name: *mut *const libc::c_char,
  1317. plugin_desc: *mut *const libc::c_char,
  1318. plugin_version: *mut *const libc::c_char,
  1319. arg: *const libc::c_char) -> libc::c_int
  1320. where T: Plugin + Default + 'static {
  1321. if plugin_handle.is_null() || plugin_name.is_null() || plugin_desc.is_null() || plugin_version.is_null() {
  1322. // we can't really do anything here.
  1323. eprintln!("hexchat_plugin_init called with a null pointer that shouldn't be null - broken hexchat");
  1324. // TODO maybe call abort.
  1325. return 0;
  1326. }
  1327. let ph = plugin_handle as *mut internals::Ph;
  1328. // clear the "userdata" field first thing - if the deinit function gets called (wrong hexchat
  1329. // version, other issues), we don't wanna try to drop the hexchat_dummy or hexchat_read_fd
  1330. // function as if it were a Box!
  1331. (*ph).userdata = ptr::null_mut();
  1332. // read the filename so we can pass it on later.
  1333. let filename = if !(*plugin_name).is_null() {
  1334. if let Ok(fname) = CStr::from_ptr(*plugin_name).to_owned().into_string() {
  1335. fname
  1336. } else {
  1337. eprintln!("failed to convert filename to utf8 - broken hexchat");
  1338. return 0;
  1339. }
  1340. } else {
  1341. // no filename specified for some reason, but we can still load
  1342. String::new() // empty string
  1343. };
  1344. // these may be null, unless initialization is successful.
  1345. // we set them to null as markers.
  1346. *plugin_name = ptr::null();
  1347. *plugin_desc = ptr::null();
  1348. *plugin_version = ptr::null();
  1349. // do some version checks for safety
  1350. // NOTE: calling hexchat functions with null plugin_name, plugin_desc, plugin_version is a bit
  1351. // dangerous. this particular case is "ok".
  1352. {
  1353. let ver = ((*ph).hexchat_get_info)(ph, cstr(b"version\0")); // this shouldn't panic
  1354. let cstr = CStr::from_ptr(ver);
  1355. if let Ok(ver) = cstr.to_str() {
  1356. let mut iter = ver.split('.');
  1357. let a = iter.next().map(i32::from_str).and_then(Result::ok).unwrap_or(0);
  1358. let b = iter.next().map(i32::from_str).and_then(Result::ok).unwrap_or(0);
  1359. let c = iter.next().map(i32::from_str).and_then(Result::ok).unwrap_or(0);
  1360. // 2.9.6 or greater
  1361. if !(a > 2 || (a == 2 && (b > 9 || (b == 9 && (c > 6 || (c == 6)))))) {
  1362. return 0;
  1363. }
  1364. } else {
  1365. return 0;
  1366. }
  1367. }
  1368. let mut pluginfo = if let Some(pluginfo) = PluginInfo::new(plugin_name, plugin_desc, plugin_version) {
  1369. pluginfo
  1370. } else {
  1371. return 0;
  1372. };
  1373. let r: thread::Result<Option<Box<_>>> = {
  1374. catch_unwind(move || {
  1375. let mut pluginhandle = PluginHandle::new(ph, pluginfo);
  1376. let plug = T::default();
  1377. if plug.init(&mut pluginhandle, if !arg.is_null() { Some(CStr::from_ptr(arg).to_str().expect("arg not valid utf-8 - broken hexchat")) } else { None }) {
  1378. if !(pluginfo.name.is_null() || pluginfo.desc.is_null() || pluginfo.vers.is_null()) {
  1379. Some(Box::new(PhUserdata { plug: Box::new(plug), pluginfo }))
  1380. } else {
  1381. // TODO log: forgot to call register
  1382. None
  1383. }
  1384. } else {
  1385. None
  1386. }
  1387. })
  1388. };
  1389. match r {
  1390. Result::Ok(Option::Some(plug @ _)) => {
  1391. if (*plugin_name).is_null() || (*plugin_desc).is_null() || (*plugin_version).is_null() {
  1392. // TODO deallocate any which are non-null
  1393. pluginfo.drop_info();
  1394. 0
  1395. } else {
  1396. put_userdata(ph, plug);
  1397. 1
  1398. }
  1399. },
  1400. r @ _ => {
  1401. // if the initialization fails, deinit doesn't get called, so we need to clean up
  1402. // ourselves.
  1403. // TODO might leak pluginfo on panic?
  1404. if let Err(_) = r {
  1405. // TODO try to log panic?
  1406. }
  1407. 0
  1408. },
  1409. }
  1410. }
  1411. #[doc(hidden)]
  1412. pub unsafe fn hexchat_plugin_deinit<T>(plugin_handle: *mut libc::c_void) -> libc::c_int where T: Plugin {
  1413. let mut safe_to_unload = 1;
  1414. // plugin_handle should never be null, but just in case.
  1415. if !plugin_handle.is_null() {
  1416. let ph = plugin_handle as *mut internals::Ph;
  1417. // userdata should also never be null.
  1418. if !(*ph).userdata.is_null() {
  1419. {
  1420. let mut info: Option<PluginInfo> = None;
  1421. {
  1422. let mut ausinfo = ::std::panic::AssertUnwindSafe(&mut info);
  1423. safe_to_unload = if catch_unwind(move || {
  1424. let userdata = *pop_userdata(ph);
  1425. **ausinfo = Some(userdata.pluginfo);
  1426. userdata.plug.deinit(&mut PluginHandle::new(ph, userdata.pluginfo));
  1427. }).is_ok() { 1 } else { 0 };
  1428. }
  1429. if let Some(mut info) = info {
  1430. info.drop_info();
  1431. } else {
  1432. eprintln!("I have no idea tbh, I didn't know `pop_userdata` could panic!");
  1433. }
  1434. }
  1435. } else {
  1436. eprintln!("null userdata in hexchat_plugin_deinit - broken hexchat or broken hexchat-plugin.rs");
  1437. }
  1438. } else {
  1439. eprintln!("hexchat_plugin_deinit called with a null plugin_handle - broken hexchat");
  1440. }
  1441. safe_to_unload
  1442. }
  1443. /// Exports a hexchat plugin.
  1444. #[macro_export]
  1445. macro_rules! hexchat_plugin {
  1446. ($t:ty) => {
  1447. #[no_mangle]
  1448. pub unsafe extern "C" fn hexchat_plugin_init(plugin_handle: *mut $crate::libc::c_void,
  1449. plugin_name: *mut *const $crate::libc::c_char,
  1450. plugin_desc: *mut *const $crate::libc::c_char,
  1451. plugin_version: *mut *const $crate::libc::c_char,
  1452. arg: *const $crate::libc::c_char) -> $crate::libc::c_int {
  1453. $crate::hexchat_plugin_init::<$t>(plugin_handle, plugin_name, plugin_desc, plugin_version, arg)
  1454. }
  1455. #[no_mangle]
  1456. pub unsafe extern "C" fn hexchat_plugin_deinit(plugin_handle: *mut $crate::libc::c_void) -> $crate::libc::c_int {
  1457. $crate::hexchat_plugin_deinit::<$t>(plugin_handle)
  1458. }
  1459. // unlike what the documentation states, there's no need to define hexchat_plugin_get_info.
  1460. // so we don't. it'd be impossible to make it work well with rust anyway.
  1461. };
  1462. }