[][src]Struct hexavalent::PluginHandle

pub struct PluginHandle<'ph, P> { /* fields omitted */ }

Interacts with HexChat's plugin API.

Cannot be constructed in user code, but is passed into Plugin::init, Plugin::deinit, and hook callbacks such as PluginHandle::hook_command.

Most of HexChat's functions are available as associated functions, without the hexchat_ prefix.

Examples

All functions which take &str/impl AsRef<str> arguments will allocate if the string is not null-terminated, and panic if the string contains interior nulls.

// for example, this would not allocate
ph.print("hello\0");
// ...this would allocate
ph.print("hello");
// ...and this would panic
ph.print("hel\0lo");

Implementations

impl<'ph, P> PluginHandle<'ph, P>[src]

General Functions

General functions allow printing text, running commands, creating events, and other miscellaneous operations.

pub fn print(self, text: &str)[src]

Prints text to the current context. Text may contain mIRC color codes and formatting.

Analogous to hexchat_print.

Examples

use hexavalent::PluginHandle;

fn say_hello<P>(ph: PluginHandle<'_, P>) {
    // null-termination is not required, but avoids allocation
    ph.print("hello!\0");
}

pub fn command(self, cmd: &str)[src]

Executes a command in the current context as if it were typed into HexChat's input box after a /.

Analogous to hexchat_command.

Examples

use hexavalent::PluginHandle;

fn op_user<P>(ph: PluginHandle<'_, P>, username: &str) {
    // do not include the leading slash
    ph.command(&format!("OP {}\0", username));
}

pub fn emit_print<E: PrintEvent>(
    self,
    event: E,
    args: <E as Event<'_>>::Args
) -> Result<(), ()>
[src]

Emits a print event in the current context.

See the event::print submodule for a list of print events.

Note that this triggers any print hooks registered for the event, so be careful to avoid infinite recursion when calling this function from hook callbacks such as PluginHandle::hook_print.

Analogous to hexchat_emit_print.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::print::ChannelMessage;

fn print_fake_message<P>(ph: PluginHandle<'_, P>, user: &str, text: &str) -> Result<(), ()> {
    ph.emit_print(ChannelMessage, [user, text, "@\0", "$\0"])
}

pub fn emit_print_attrs<E: PrintEvent>(
    self,
    event: E,
    attrs: EventAttrs<'_>,
    args: <E as Event<'_>>::Args
) -> Result<(), ()>
[src]

Emits a print event in the current context, specifying its attributes.

See the event::print submodule for a list of print events.

Note that this triggers any print hooks registered for the event, so be careful to avoid infinite recursion when calling this function from hook callbacks such as PluginHandle::hook_print_attrs.

Analogous to hexchat_emit_print_attrs.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::EventAttrs;
use hexavalent::event::print::ChannelMessage;
use time::OffsetDateTime;

fn print_fake_message_like_its_1979<P>(ph: PluginHandle<'_, P>, user: &str, text: &str) -> Result<(), ()> {
    let attrs = EventAttrs::new(OffsetDateTime::from_unix_timestamp(86400 * 365 * 10));
    ph.emit_print_attrs(ChannelMessage, attrs, [user, text, "@\0", "$\0"])
}

pub fn send_modes(self, targets: &[impl AsRef<str>], sign: Sign, mode_char: u8)[src]

Sends channel mode changes to targets in the current context.

Analogous to hexchat_send_modes.

Examples

use hexavalent::PluginHandle;
use hexavalent::mode::Sign;

fn op_users<P>(ph: PluginHandle<'_, P>, users: &[&str]) {
    // sends `MODE <users> +o`
    ph.send_modes(users, Sign::Add, b'o');
}

fn unban_user<P>(ph: PluginHandle<'_, P>, user: &str) {
    // sends `MODE <user> -b`
    ph.send_modes(&[user], Sign::Remove, b'b');
}

pub fn nickcmp(self, s1: &str, s2: &str) -> Ordering[src]

Performs a comparison of nicknames or channel names, compliant with RFC1459.

RFC1459 says:

Because of IRC's scandanavian origin, the characters {}| are considered to be the lower case equivalents of the characters []\, respectively. This is a critical issue when determining the equivalence of two nicknames.

Note that, like other functions taking &str, this function will allocate if the provided strings are not already null-terminated. This may be expensive; if you are calling this function in a loop, consider implementing your own RFC1459 string comparison. (This function is provided mainly for API completeness.)

Analogous to hexchat_nickcmp.

Examples

use hexavalent::PluginHandle;

fn sort_nicknames<P>(ph: PluginHandle<'_, P>, nicks: &mut [impl AsRef<str>]) {
    nicks.sort_by(|n1, n2| ph.nickcmp(n1.as_ref(), n2.as_ref()));
}

pub fn strip(
    self,
    str: &str,
    mirc: MircColors,
    attrs: TextAttrs
) -> Result<String, ()>
[src]

Strips mIRC colors and/or text attributes (bold, underline, etc.) from a string.

Analogous to hexchat_strip.

Examples

use hexavalent::PluginHandle;
use hexavalent::strip::{MircColors, TextAttrs};

fn strip_example<P>(ph: PluginHandle<'_, P>) {
    let orig = "\x0312Blue\x03 \x02Bold!\x02";

    let strip_all = ph.strip(orig, MircColors::Remove, TextAttrs::Remove);
    assert_eq!(strip_all.unwrap(), "Blue Bold!");

    let strip_colors = ph.strip(orig, MircColors::Remove, TextAttrs::Keep);
    assert_eq!(strip_colors.unwrap(), "Blue \x02Bold!\x02");
}

pub fn strip_with<R>(
    self,
    str: &str,
    mirc: MircColors,
    attrs: TextAttrs,
    f: impl FnOnce(Result<&str, ()>) -> R
) -> R
[src]

Strips mIRC colors and/or text attributes (bold, underline, etc.) from a string.

Behaves the same as PluginHandle::strip, but avoids allocating a String to hold the stripped string.

Analogous to hexchat_strip.

Examples

use hexavalent::PluginHandle;
use hexavalent::strip::{MircColors, TextAttrs};

fn strip_example<P>(ph: PluginHandle<'_, P>) {
    let orig = "\x0312Blue\x03 \x02Bold!\x02";

    ph.strip_with(orig, MircColors::Remove, TextAttrs::Remove, |strip_all| {
        assert_eq!(strip_all, Ok("Blue Bold!"));
    });

    ph.strip_with(orig, MircColors::Remove, TextAttrs::Keep, |strip_colors| {
        assert_eq!(strip_colors, Ok("Blue \x02Bold!\x02"));
    });
}

impl<'ph, P> PluginHandle<'ph, P>[src]

Getting Information

Allows you get information about the current context or HexChat's settings.

pub fn get_info<I: Info>(self, info: I) -> <I as Info>::Type[src]

Gets information based on the current context.

See the info submodule for a list of info types.

Analogous to hexchat_get_info.

Example

use hexavalent::PluginHandle;
use hexavalent::info::{AwayReason, Channel};

fn current_channel<P>(ph: PluginHandle<'_, P>) -> String {
    ph.get_info(Channel)
}

fn current_away_reason<P>(ph: PluginHandle<'_, P>) -> Option<String> {
    ph.get_info(AwayReason)
}

pub fn get_pref<Pr: Pref>(self, pref: Pr) -> Result<<Pr as Pref>::Type, ()>[src]

Gets settings information from HexChat, as available with /set.

See the pref submodule for a list of preferences.

Analogous to hexchat_get_prefs.

Example

use hexavalent::PluginHandle;
use hexavalent::pref::IrcNick1;

fn print_nick_setting<P>(ph: PluginHandle<'_, P>) {
    match ph.get_pref(IrcNick1) {
        Ok(nick) => ph.print(&format!("Current nickname setting is: {}\0", nick)),
        Err(()) => ph.print("Failed to get nickname!\0"),
    }
}

pub fn get_list<L: List>(self, list: L) -> Result<Vec<<L as List>::Elem>, ()>[src]

Gets a list of information, possibly specific to the current context.

See the list submodule for a list of lists.

Analogous to hexchat_list_get and related functions.

Examples

use hexavalent::PluginHandle;
use hexavalent::context::Context;
use hexavalent::list::{Channels, Users};

fn print_all_users_in_all_channels<P>(ph: PluginHandle<'_, P>) {
    let channels = match ph.get_list(Channels) {
        Ok(channels) => channels,
        Err(()) => return ph.print("Failed to get channels!\0"),
    };
    for channel in channels {
        let ctxt = match ph.find_context(Context::FullyQualified { servname: channel.servname(), channel: channel.name() }) {
            Some(ctxt) => ctxt,
            None => {
                ph.print(&format!("Failed to find channel {} in server {}, skipping.\0", channel.name(), channel.servname()));
                continue;
            }
        };
        ph.print(&format!("Users in {} on {}:\0", channel.name(), channel.servname()));
        let users = ph.with_context(ctxt, || ph.get_list(Users).unwrap_or_default());
        for user in users {
            ph.print(&format!("  {}{}", user.prefix().unwrap_or(' '), user.nick()));
        }
    }
}

pub fn get_list_with<L: List, R>(
    self,
    list: L,
    f: impl FnOnce(Result<&mut dyn Iterator<Item = <L as List>::Elem>, ()>) -> R
) -> R
[src]

Gets a list of information, possibly specific to the current context.

See the list submodule for a list of lists.

Behaves the same as PluginHandle::get_list, but avoids allocating a Vec to hold the list.

Analogous to hexchat_list_get and related functions.

Examples

use hexavalent::PluginHandle;
use hexavalent::context::Context;
use hexavalent::list::{Channels, Users};

fn print_all_users_in_all_channels<P>(ph: PluginHandle<'_, P>) {
    ph.get_list_with(Channels, |channels| {
        let channels = match channels {
            Ok(channels) => channels,
            Err(()) => return ph.print("Failed to get channels!\0"),
        };
        for channel in channels {
            let ctxt = match ph.find_context(Context::FullyQualified { servname: channel.servname(), channel: channel.name() }) {
                Some(ctxt) => ctxt,
                None => {
                    ph.print(&format!("Failed to find channel {} in server {}, skipping.\0", channel.name(), channel.servname()));
                    continue;
                }
            };
            ph.print(&format!("Users in {} on {}:\0", channel.name(), channel.servname()));
            let users = ph.with_context(ctxt, || ph.get_list(Users).unwrap_or_default());
            for user in users {
                ph.print(&format!("  {}{}", user.prefix().unwrap_or(' '), user.nick()));
            }
        }
    });
}

impl<'ph, P: 'static> PluginHandle<'ph, P>[src]

Hook Functions

Hook functions register hook callbacks with HexChat. You can execute code when the user runs a command, when print or server events happen, or on a timer interval.

Examples

The callback passed into each hook function is a function pointer (fn(X) -> Y) and not a type implementing a function trait (impl Fn(X) -> Y), unlike most higher-order functions in Rust. This means that no allocation is required to register a hook, so the plugin cannot leak memory on unload. However, it also means that you cannot capture local variables in hook callbacks.

For example, the following does not compile, because count is captured by the closure.

This example deliberately fails to compile
use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority};

struct MyPlugin;

fn add_counting_command(ph: PluginHandle<'_, MyPlugin>) {
    let mut count = 0;
    ph.hook_command(
        "count\0",
        "Usage: COUNT, counts the number of times this command was used\0",
        Priority::Normal,
        |plugin, ph, words| {
            count += 1;
            ph.print(&format!("Called {} time(s)!\0", count));
            Eat::All
        }
    );
}

Instead, store state on the plugin struct. Each hook callback gets a shared reference to the plugin.

Use Cell to store simple Copy types, as in the following (working) example of a count command. Also use Cell when a non-Copy type should be moved in and out of the state without mutation, as in PluginHandle::unhook's example of storing HookHandle.

use std::cell::Cell;
use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority};

struct MyPlugin {
    count: Cell<u32>,
}

fn add_counting_command(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_command(
        "count\0",
        "Usage: COUNT, counts the number of times this command was used\0",
        Priority::Normal,
        |plugin, ph, words| {
            plugin.count.set(plugin.count.get() + 1);
            ph.print(&format!("Called {} time(s)!\0", plugin.count.get()));
            Eat::All
        }
    );
}

Use RefCell to store values which are mutated while in the state, as in the following example of a map.

use std::cell::RefCell;
use std::collections::HashMap;
use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority};

struct MyPlugin {
    map: RefCell<HashMap<String, String>>,
}

fn add_map_command(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_command("map_set\0", "Usage: MAP_SET <k> <v>\0", Priority::Normal, |plugin, ph, words| {
        let key = words[1].to_string();
        let val = words[2].to_string();
        plugin.map.borrow_mut().insert(key, val);
        Eat::All
    });
    ph.hook_command("map_del\0", "Usage: MAP_DEL <k>\0", Priority::Normal, |plugin, ph, words| {
        let key = words[1];
        plugin.map.borrow_mut().remove(key);
        Eat::All
    });
    ph.hook_command("map_get\0", "Usage: MAP_GET <k>\0", Priority::Normal, |plugin, ph, words| {
        let key = words[1];
        match plugin.map.borrow().get(key) {
            Some(val) => ph.print(&format!("map['{}']: '{}'\0", key, val)),
            None => ph.print(&format!("map['{}']: <not found>\0", key)),
        }
        Eat::All
    });
}

pub fn hook_command(
    self,
    name: &str,
    help_text: &str,
    priority: Priority,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>, words: &[&str]) -> Eat
) -> HookHandle
[src]

Registers a command hook with HexChat.

The command is usable by typing /command <words...>. Command names starting with . are hidden in /help. Hooking the special command "" (empty string) captures non-commands, i.e. input without a / at the beginning.

Each element of words is an argument to the command. words[0] is the name of the command, so words[1] is the first user-provided argument. words is limited to 32 elements, and HexChat may provide excess elements, so the length of words is not meaningful.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_command.

Example

use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority};

struct MyPlugin;

fn add_greeting_command(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_command(
        "greet\0",
        "Usage: GREET <name>, prints a greeting locally\0",
        Priority::Normal,
        |plugin, ph, words| {
            ph.print(&format!("Hello {}!\0", words[1]));
            Eat::All
        }
    );
}

pub fn hook_print<E: PrintEvent>(
    self,
    event: E,
    priority: Priority,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>, args: <E as Event<'_>>::Args) -> Eat
) -> HookHandle
[src]

Registers a print event hook with HexChat.

See the event::print submodule for a list of print events.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Also note that passing a closure as callback will ICE the compiler, due to rustc bug #62529. A fn item must be used instead, as in the example below.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_print.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::Event;
use hexavalent::event::print::YouPartWithReason;
use hexavalent::hook::{Eat, Priority};

struct MyPlugin;

fn hook_you_part(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_print(YouPartWithReason, Priority::Normal, you_part_cb);
}

fn you_part_cb(
    plugin: &MyPlugin,
    ph: PluginHandle<'_, MyPlugin>,
    args: <YouPartWithReason as Event<'_>>::Args
) -> Eat {
    let [your_nick, your_host, channel, reason] = args;
    ph.print(&format!("You left channel {}: {}.", channel, reason));
    Eat::HexChat
}

pub fn hook_print_attrs<E: PrintEvent>(
    self,
    event: E,
    priority: Priority,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>, attrs: EventAttrs<'_>, args: <E as Event<'_>>::Args) -> Eat
) -> HookHandle
[src]

Registers a print event hook with HexChat, capturing the event's attributes.

See the event::print submodule for a list of print events.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Also note that passing a closure as callback will ICE the compiler, due to rustc bug #62529. A fn item must be used instead, as in the example below.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_print_attrs.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::{Event, EventAttrs};
use hexavalent::event::print::YouPartWithReason;
use hexavalent::hook::{Eat, Priority};

struct MyPlugin;

fn hook_you_part(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_print_attrs(YouPartWithReason, Priority::Normal, you_part_cb);
}

fn you_part_cb(
    plugin: &MyPlugin,
    ph: PluginHandle<'_, MyPlugin>,
    attrs: EventAttrs,
    args: <YouPartWithReason as Event<'_>>::Args
) -> Eat {
    let [your_nick, your_host, channel, reason] = args;
    ph.print(&format!("You left channel {} at {}: {}.", channel, attrs.time(), reason));
    Eat::HexChat
}

pub fn hook_server<E: ServerEvent>(
    self,
    event: E,
    priority: Priority,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>, args: <E as Event<'_>>::Args) -> Eat
) -> HookHandle
[src]

Registers a server event hook with HexChat.

See the event::server submodule for a list of server events.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Also note that passing a closure as callback will ICE the compiler, due to rustc bug #62529. A fn item must be used instead, as in the example below.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_server.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::Event;
use hexavalent::event::server::Part;
use hexavalent::hook::{Eat, Priority};

struct MyPlugin;

fn hook_part(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_server(Part, Priority::Normal, part_cb);
}

fn part_cb(
    plugin: &MyPlugin,
    ph: PluginHandle<'_, MyPlugin>,
    args: <Part as Event<'_>>::Args
) -> Eat {
    let [sender, _, channel, reason] = args;
    ph.print(&format!("{} left channel {}: {}.", sender, channel, reason));
    Eat::None
}

pub fn hook_server_attrs<E: ServerEvent>(
    self,
    event: E,
    priority: Priority,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>, attrs: EventAttrs<'_>, args: <E as Event<'_>>::Args) -> Eat
) -> HookHandle
[src]

Registers a server event hook with HexChat, capturing the event's attributes.

See the event::server submodule for a list of server events.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Also note that passing a closure as callback will ICE the compiler, due to rustc bug #62529. A fn item must be used instead, as in the example below.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_server_attrs.

Examples

use hexavalent::PluginHandle;
use hexavalent::event::{Event, EventAttrs};
use hexavalent::event::server::Part;
use hexavalent::hook::{Eat, Priority};

struct MyPlugin;

fn hook_part(ph: PluginHandle<'_, MyPlugin>) {
    ph.hook_server_attrs(Part, Priority::Normal, part_cb);
}

fn part_cb(
    plugin: &MyPlugin,
    ph: PluginHandle<'_, MyPlugin>,
    attrs: EventAttrs<'_>,
    args: <Part as Event<'_>>::Args
) -> Eat {
    let [sender, _, channel, reason] = args;
    ph.print(&format!("{} left channel {} at {}: {}.", sender, channel, attrs.time(), reason));
    Eat::None
}

pub fn hook_timer(
    self,
    timeout: Duration,
    callback: fn(plugin: &P, ph: PluginHandle<'_, P>) -> Timer
) -> HookHandle
[src]

Registers a timer hook with HexChat.

callback will be called at the interval specified by timeout, with a resolution of 1 millisecond.

Note that callback is a function pointer and not an impl Fn(). This means that it cannot capture any variables; instead, use plugin to store state. See the impl header for more details.

Returns a HookHandle which can be passed to PluginHandle::unhook to unregister the hook.

Analogous to hexchat_hook_timer.

Panics

If timeout is more than i32::MAX milliseconds.

Examples

use std::cell::Cell;
use std::time::Duration;
use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority, Timer};

struct MyPlugin {
    should_run: Cell<bool>,
}

fn add_annoying_command(plugin: &MyPlugin, ph: PluginHandle<'_, MyPlugin>) {
    plugin.should_run.set(true);

    ph.hook_timer(Duration::from_secs(5), |plugin, ph| {
        if plugin.should_run.get() {
            ph.print("Annoying message! Type /stop to stop.\0");
            Timer::Continue
        } else {
            ph.print("This is the last annoying message!\0");
            Timer::Stop
        }
    });

    ph.hook_command(
        "stop\0",
        "Usage: STOP, stops being annoying\0",
        Priority::Normal,
        |plugin, ph, words| {
            if plugin.should_run.get() {
                // Instead of using this `Cell<bool>` flag,
                // it would make more sense to store a `HookHandle`
                // and call `ph.unhook(hook)` here,
                // but this demonstrates the use of `Timer::Stop`.
                plugin.should_run.set(false);
            }
            Eat::All
        }
    );
}

pub fn unhook(self, hook: HookHandle)[src]

Unregisters a hook from HexChat.

Used with hook registrations functions such as PluginHandle::hook_command.

HexChat automatically unhooks any remaining hooks after your plugin finishes unloading, so this function is only useful if you need to unhook a hook while your plugin is running.

Example

use std::cell::Cell;
use hexavalent::{Plugin, PluginHandle};
use hexavalent::hook::{Eat, HookHandle, Priority};

#[derive(Default)]
struct MyPlugin {
    cmd_handle: Cell<Option<HookHandle>>,
}

impl Plugin for MyPlugin {
    fn init(&self, ph: PluginHandle<'_, Self>) {
        let hook = ph.hook_command(
            "thisCommandOnlyWorksOnce\0",
            "Usage: THISCOMMANDONLYWORKSONCE <args...>, this command only works once\0",
            Priority::Normal,
            |plugin, ph, words| {
                ph.print(&format!("You'll only see this once: {}\0", words.join("|")));
                if let Some(hook) = plugin.cmd_handle.take() {
                    ph.unhook(hook);
                }
                Eat::All
            }
        );
        self.cmd_handle.set(Some(hook));
    }
}

impl<'ph, P> PluginHandle<'ph, P>[src]

Context Functions

Allows you to work with server/channel contexts.

It is not always necessary to change context, as hook callbacks usually execute in a context related to the event. For example:

pub fn find_context(self, find: Context<'_>) -> Option<ContextHandle<'ph>>[src]

Finds a server/channel context based on various criteria.

See Context for available criteria. These include: the currently-focused tab, a specified channel, or the frontmost tab in a server.

Returns a ContextHandle which can be passed to PluginHandle::with_context to enter the context.

Analogous to hexchat_find_context.

Examples

use hexavalent::PluginHandle;
use hexavalent::context::Context;

fn find_context_example<P>(ph: PluginHandle<'_, P>) {
    if let Some(ctxt) = ph.find_context(Context::Focused) {
        ph.with_context(ctxt, || ph.print("This tab is focused!\0"));
    }
    if let Some(ctxt) = ph.find_context(Context::Nearby { channel: "#help\0" }) {
        ph.with_context(ctxt, || ph.print("This tab is #help!\0"));
    }
    if let Some(ctxt) = ph.find_context(Context::Frontmost { servname: "Snoonet\0" }) {
        ph.with_context(ctxt, || ph.print("This tab is frontmost on snoonet!\0"));
    }
}

pub fn with_context<R>(
    self,
    context: ContextHandle<'_>,
    f: impl FnOnce() -> R
) -> R
[src]

Executes a function in a different server/channel context.

Used with PluginHandle::find_context.

Analogous to hexchat_get_context and hexchat_set_context.

Examples

use hexavalent::PluginHandle;
use hexavalent::context::Context;

fn send_message_to_channel<P>(
    ph: PluginHandle<'_, P>,
    channel: &str,
    message: &str,
) -> Result<(), ()> {
    let ctxt = match ph.find_context(Context::Nearby { channel }) {
        Some(ctxt) => ctxt,
        None => return Err(()),
    };
    ph.with_context(ctxt, || {
        ph.print(message);
        Ok(())
    })
}

impl<'ph, P> PluginHandle<'ph, P>[src]

Plugin Preferences

Allows you to get and set preferences associated with your plugin.

pub fn pluginpref_set_str(self, name: &str, value: &str) -> Result<(), ()>[src]

Sets a plugin-specific string preference.

Fails if value exceeds 511 bytes in length.

Analogous to hexchat_pluginpref_set_str.

Examples

use hexavalent::PluginHandle;

fn save_str<P>(ph: PluginHandle<'_, P>) -> Result<(), ()> {
    ph.pluginpref_set_str("myvar1\0", "something important\0")
}

pub fn pluginpref_get_str(self, name: &str) -> Result<String, ()>[src]

Gets a plugin-specific string preference.

Note that int preferences can be successfully loaded as strings.

Analogous to hexchat_pluginpref_get_str.

Examples

use hexavalent::PluginHandle;

fn load_str<P>(ph: PluginHandle<'_, P>) {
    let pref = ph.pluginpref_get_str("myvar1\0");
    assert_eq!(pref.unwrap(), "something important");
}

pub fn pluginpref_get_str_with<R>(
    self,
    name: &str,
    f: impl FnOnce(Result<&str, ()>) -> R
) -> R
[src]

Gets a plugin-specific string preference, passing the result to a closure.

Note that int preferences can be successfully loaded as strings.

Behaves the same as PluginHandle::pluginpref_get_str, but avoids allocating a String to hold the preference value.

Analogous to hexchat_pluginpref_get_str.

Examples

use hexavalent::PluginHandle;

fn load_str<P>(ph: PluginHandle<'_, P>) {
    ph.pluginpref_get_str_with("myvar1\0", |pref| {
        assert_eq!(pref, Ok("something important"));
    });
}

pub fn pluginpref_set_int(self, name: &str, value: i32) -> Result<(), ()>[src]

Sets a plugin-specific int preference.

-1 is a reserved value and cannot be used.

Analogous to hexchat_pluginpref_set_int.

Examples

use hexavalent::PluginHandle;

fn save_int<P>(ph: PluginHandle<'_, P>) -> Result<(), ()> {
    ph.pluginpref_set_int("answer\0", 42)
}

pub fn pluginpref_get_int(self, name: &str) -> Result<i32, ()>[src]

Gets a plugin-specific int preference.

Analogous to hexchat_pluginpref_get_int.

Examples

use hexavalent::PluginHandle;

fn load_int<P>(ph: PluginHandle<'_, P>) {
    let pref = ph.pluginpref_get_int("answer\0");
    assert_eq!(pref, Ok(42));
}

pub fn pluginpref_delete(self, name: &str) -> Result<(), ()>[src]

Deletes a plugin-specific preference.

Returns Ok(()) both when an existing preference is deleted and when no preference with name exists.

Analogous to hexchat_pluginpref_delete.

Examples

use hexavalent::PluginHandle;

fn remove_answer<P>(ph: PluginHandle<'_, P>) -> Result<(), ()> {
    ph.pluginpref_delete("answer\0")
}

pub fn pluginpref_list(self) -> Result<Vec<String>, ()>[src]

Lists the names of all plugin-specific preferences.

Note that the total length of all preference names is limited to about 4095 bytes.

Analogous to hexchat_pluginpref_list.

Examples

use hexavalent::PluginHandle;

fn print_all_prefs<P>(ph: PluginHandle<'_, P>) {
    let prefs = match ph.pluginpref_list() {
        Ok(prefs) => prefs,
        Err(()) => return ph.print("Failed to list plugin preferences!\0"),
    };
    ph.print("All plugin preferences:\0");
    for pref in prefs {
        let val = ph.pluginpref_get_str(&pref);
        let val = match &val {
            Ok(v) => v,
            Err(()) => "<not found>",
        };
        ph.print(&format!("{} = {}\0", pref, val));
    }
}

pub fn pluginpref_list_with<R>(
    self,
    f: impl FnOnce(Result<&mut dyn Iterator<Item = &str>, ()>) -> R
) -> R
[src]

Lists the names of all plugin-specific preferences, passing the result to a closure.

Note that the total length of all preference names is limited to about 4095 bytes.

Behaves the same as PluginHandle::pluginpref_list, but avoids allocating a Vec and Strings to hold each preference name.

Analogous to hexchat_pluginpref_list.

Examples

use hexavalent::PluginHandle;

fn print_all_prefs<P>(ph: PluginHandle<'_, P>) {
    ph.pluginpref_list_with(|prefs| {
        let prefs = match prefs {
            Ok(prefs) => prefs,
            Err(()) => return ph.print("Failed to list plugin preferences!\0"),
        };
        ph.print("All plugin preferences:\0");
        for pref in prefs {
            ph.pluginpref_get_str_with(pref, |val| {
                let val = val.unwrap_or("<not found>");
                ph.print(&format!("{} = {}\0", pref, val));
            });
        }
    });
}

impl<'ph, P> PluginHandle<'ph, P>[src]

Plugin GUI

Allows you to add and remove fake plugins from the plugin GUI.

pub fn plugingui_add(
    self,
    filename: &str,
    name: &str,
    desc: &str,
    version: &str
) -> FakePluginHandle
[src]

Adds a fake plugin to the plugin GUI.

Only useful if your plugin loads other plugins. Do not call this function with the same arguments you pass to export_plugin.

Returns a FakePluginHandle which can be passed to PluginHandle::plugingui_remove to remove the fake plugin.

Analogous to hexchat_plugingui_add.

pub fn plugingui_remove(self, gui: FakePluginHandle)[src]

Removes a fake plugin from the plugin GUI.

Used with PluginHandle::plugingui_add.

Analogous to hexchat_plugingui_remove.

Trait Implementations

impl<'ph, P> Clone for PluginHandle<'ph, P>[src]

impl<'ph, P> Copy for PluginHandle<'ph, P>[src]

impl<'ph, P: Debug> Debug for PluginHandle<'ph, P>[src]

Auto Trait Implementations

impl<'ph, P> RefUnwindSafe for PluginHandle<'ph, P> where
    P: RefUnwindSafe

impl<'ph, P> !Send for PluginHandle<'ph, P>

impl<'ph, P> !Sync for PluginHandle<'ph, P>

impl<'ph, P> Unpin for PluginHandle<'ph, P> where
    P: Unpin

impl<'ph, P> UnwindSafe for PluginHandle<'ph, P> where
    P: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.