1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
extern crate open;
extern crate percent_encoding;
use std::panic;
use std::any::Any;
use percent_encoding::{utf8_percent_encode, QUERY_ENCODE_SET};
pub fn enable() {
with_query(|msg| format!("!so [rust] {}", msg));
}
pub fn with_query<F>(query_fn: F)
where
F: Fn(&str) -> String + Send + Sync + 'static,
{
let hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
hook(info);
let payload = info.payload();
let msg = Any::downcast_ref::<String>(payload);
let msg = msg.as_ref().map(|s| s.as_str());
let msg = msg.or_else(|| Any::downcast_ref::<&'static str>(payload).map(|s| *s));
if let Some(msg) = msg {
let query = query_fn(msg);
let url = format!(
"https://duckduckgo.com/?q={}",
utf8_percent_encode(&query, QUERY_ENCODE_SET)
);
if let Err(e) = open::that(&url) {
println!("Error opening {}: {}", url, e);
}
}
}));
}