-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.rs
517 lines (458 loc) · 17.1 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static; // used in the generated emojis module
mod emojis; // generated by build.rs
use rand::prelude::*;
use std::collections::HashMap;
use gio::prelude::*;
use glib::clone;
use gtk::prelude::*;
/// Things that the user can configure, if they want.
#[derive(Clone)]
struct Options {
// window things
title: String,
width: i32,
height: i32,
/// Maximum number of emoji matches to show
n_matches: usize,
}
impl Options {
/// `clap` arguments to be added to `clap::App`.
fn args<'a, 'b>() -> Vec<clap::Arg<'a, 'b>> {
vec![
clap::Arg::with_name("title")
.long("title")
.takes_value(true)
.value_name("TITLE")
.default_value("Emoji picker")
.help("Sets the window title"),
clap::Arg::with_name("width")
.long("width")
.takes_value(true)
.value_name("WIDTH")
.validator(parse_validator::<i32>)
.default_value("300")
.help("Sets the window width"),
clap::Arg::with_name("height")
.long("height")
.takes_value(true)
.value_name("HEIGHT")
.validator(parse_validator::<i32>)
.default_value("150")
.help("Sets the window height"),
clap::Arg::with_name("n_matches")
.long("n-matches")
.takes_value(true)
.value_name("N")
.validator(parse_validator::<usize>)
.default_value("5")
.help("How many emoji matches to show"),
]
}
/// Produces an `Options` struct from `clap::ArgMatches` assuming that `Options::args` have
/// been added to the `clap::App`.
fn from_matches<'a>(matches: clap::ArgMatches<'a>) -> Options {
Options {
// NOTE: all this `unwrap`ing is safe assuming `Options::args` was passed to the
// `clap::App`.
title: matches.value_of("title").unwrap().to_string(),
width: matches.value_of("width").unwrap().parse().unwrap(),
height: matches.value_of("height").unwrap().parse().unwrap(),
n_matches: matches.value_of("n_matches").unwrap().parse().unwrap(),
}
}
}
// See `gio::Application::id_is_valid`
const APPLICATION_ID: &'static str = "com.github.jmackie.emoji_picker";
fn main() {
let version = env!("CARGO_PKG_VERSION");
// I'm the only author rn
let author = env!("CARGO_PKG_AUTHORS").split(",").next().unwrap();
// Define the CLI and parse options
let options = Options::from_matches(
clap::App::new("emoji-picker")
.version(version)
.author(author)
.about(env!("CARGO_PKG_DESCRIPTION"))
.args(&Options::args())
.get_matches(),
);
env_logger::init();
debug!("version {}", version); // should be helpful for debuggin'
gtk::init().expect("failed to initialize gtk");
let application = gtk::ApplicationBuilder::new()
.application_id(APPLICATION_ID)
.flags(gio::ApplicationFlags::empty())
.build();
info!("application initialized");
// Create a channel for the UI to send out the final emoji selection.
let (done_sender, done_receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
application.connect_activate(move |app| {
init_styles();
info!("styles initialized");
init_ui(&options, app, done_sender.clone());
info!("ui initialized");
});
// Quit when the user presses escape.
let quit = gio::SimpleAction::new("quit", None);
quit.connect_activate(clone!(@weak application => move |_action, _parameter| {
debug!("quit action activated");
application.quit();
}));
application.set_accels_for_action("app.quit", &["Escape"]);
application.add_action(&quit);
// Listen for the final selection.
done_receiver.attach(
None,
clone!(@weak application => @default-return glib::Continue(false), move |selection| {
match selection {
Some(emoji) => {
// NOTE: no trailing newline because we expect the user to
// copy stdout to the clipboard, so a newline would be unhelpful.
print!("{}", emoji);
},
None => {
warn!("no emoji selected");
},
}
// All done!
application.quit();
glib::Continue(false)
}),
);
// Expects `std::env::args()` but we're handling the CLI with `clap`, so
// just pass an empty vector.
application.run(&vec![]);
}
// Add CSS to the application.
fn init_styles() {
let styles = b"
#application_window {
background-color: #ffffff;
}
#root_vbox {
}
#search_entry {
font-family: monospace;
}
#picker_flowbox {
}
#emoji {
font-size: 30px;
}
#focused_emoji {
font-size: 50px;
}
";
let provider = gtk::CssProvider::new();
provider.load_from_data(styles).expect("failed to load css");
gtk::StyleContext::add_provider_for_screen(
&gdk::Screen::get_default().expect("failed to get default screen"),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
}
/// A more useful form of the generated `EMOJIS` map, mostly because it lets us
/// prioritise searching for emojis by name. Also means we can keep the string
/// normalizing logic together.
struct EmojiMaps {
by_name: HashMap<String, &'static str>,
by_keyword: HashMap<String, &'static str>,
}
impl EmojiMaps {
/// Initialize using the data generated from emojilib (emojis.json)
fn from_generated_emojis() -> Self {
return EmojiMaps {
by_name: emojis::EMOJIS
.iter()
.fold(HashMap::new(), |mut acc, (name, emoji)| {
// Multi-word emoji names are snake case (see emojis.json).
// Only I'm using pretty simple matching logic, and if I
// type "call me" I want it to match the "call_me_hand" emoji.
// Hence we remove underscores and smash the words together,
// and similarly remove whitespace from queries prior to matching.
let normalized_name = name.split("_").collect::<Vec<&str>>().concat();
acc.insert(normalized_name, emoji.char);
acc
}),
by_keyword: emojis::EMOJIS
.values()
.flat_map(|emoji| emoji.keywords.into_iter().zip(std::iter::repeat(emoji)))
.fold(HashMap::new(), |mut acc, (keyword, emoji)| {
acc.insert(keyword.to_string(), emoji.char);
acc
}),
};
}
/// Return `n` emojis matching the search query `q`.
fn match_query(&self, q: String, n: usize) -> Vec<&'static str> {
let normalized_q = q.split_whitespace().collect::<Vec<&str>>().concat();
let mut matches = self
.by_name // NOTE: prefer matches by name
.iter()
.chain(self.by_keyword.iter())
.filter_map(|(k, v)| {
if k.contains(&normalized_q) {
Some(*v)
} else {
None
}
})
.collect();
dedup(&mut matches); // pretty gross, but also fine...
if matches.len() == 0 {
let mut sampled = self.sample(n);
dedup(&mut sampled); // ditto
return sampled;
}
matches.iter().take(n).copied().collect()
}
/// Return a random sample of `n` emojis.
fn sample(&self, n: usize) -> Vec<&'static str> {
let all_emojis = self
.by_name
.values()
.chain(self.by_keyword.values())
.copied()
.collect();
return sample(n, all_emojis);
}
}
/// The state of the thing below the search box.
#[derive(Debug)]
struct Picker {
focus_index: Option<usize>,
emojis: Vec<&'static str>,
}
impl Picker {
fn render(&self, flowbox: &mut gtk::FlowBox) {
flowbox.foreach(|child| {
flowbox.remove(child);
});
self.render_labels().iter().for_each(|label| {
flowbox.add(label); // NOTE: `FlowBoxChild` should be inserted automatically
label.show();
});
}
fn render_labels(&self) -> Vec<gtk::Label> {
self.emojis
.iter()
.enumerate()
.map(|(i, emoji)| {
let label = gtk::LabelBuilder::new().label(emoji).build();
gtk::WidgetExt::set_widget_name(
&label,
if Some(i) == self.focus_index {
"focused_emoji"
} else {
"emoji"
},
);
label
})
.collect()
}
}
/// Messages used for widget communication.
#[derive(Debug)]
enum Message {
SearchChanged(String),
TabPressed,
ShiftPressed,
ShiftReleased,
EnterPressed,
}
fn init_ui(
options: &Options,
application: >k::Application,
done_sender: glib::Sender<Option<&'static str>>,
) {
let application_window = gtk::ApplicationWindowBuilder::new()
.application(application)
.title(&options.title)
.border_width(5)
.window_position(gtk::WindowPosition::Center)
.width_request(options.width)
.height_request(options.height)
.build();
gtk::WidgetExt::set_widget_name(&application_window, "application_window"); // css selector is #application_window
let root_vbox = gtk::BoxBuilder::new()
.orientation(gtk::Orientation::Vertical)
.spacing(0)
.build();
gtk::WidgetExt::set_widget_name(&root_vbox, "root_vbox");
let search_entry = gtk::EntryBuilder::new().build();
gtk::WidgetExt::set_widget_name(&search_entry, "search_entry");
let mut picker_flowbox = gtk::FlowBoxBuilder::new()
.expand(true)
.valign(gtk::Align::Center)
.halign(gtk::Align::Center)
.min_children_per_line(5) // else the halign Center makes a single column
.selection_mode(gtk::SelectionMode::None)
.build();
gtk::WidgetExt::set_widget_name(&picker_flowbox, "picker_flowbox");
// Put it all together.
root_vbox.add(&search_entry);
root_vbox.add(&picker_flowbox);
application_window.add(&root_vbox);
// Connect up events.
let (message_sender, message_receiver) =
glib::MainContext::channel::<Message>(glib::PRIORITY_DEFAULT);
search_entry.connect_changed(clone!(@strong message_sender => move |q| {
match q.get_text().map(|text| text.to_string()) {
None => (), // ?
Some(q_string) => {
message_sender.send(Message::SearchChanged(q_string)).expect("message_sender error");
},
};
}));
// Handle tabbing.
search_entry
.connect(
"key-press-event",
false,
clone!(@strong message_sender => move |values| {
// Give these return values names in the interest of readability.
let propagate = Some(glib::Value::from(&false));
let capture = Some(glib::Value::from(&true));
// This took a while to figure out
let events: Vec<gdk::Event> = values
.into_iter()
.filter_map(|value| value.get().ok().flatten())
.collect();
match events.as_slice() {
[event] => match event.get_keycode() {
Some(23 /* tab key */) => {
message_sender.send(Message::TabPressed).expect("message_sender error");
// Capture so as not to use Gtk's default behaviour
// of cycling through widgets.
capture
},
Some(50 /* shift key */) => {
message_sender.send(Message::ShiftPressed).expect("message_sender error");
propagate
},
_ => propagate,
},
_ => propagate,
}
}),
)
.unwrap();
// Handle shift release.
search_entry
.connect(
"key-release-event",
false,
clone!(@strong message_sender => move |values| {
let events: Vec<gdk::Event> = values
.into_iter()
.filter_map(|value| value.get().ok().flatten())
.collect();
match events.as_slice() {
[event] => match event.get_keycode() {
Some(50 /* shift key */) => {
message_sender.send(Message::ShiftReleased).expect("message_sender error");
},
_ => (),
},
_ => (),
}
Some(glib::Value::from(&false)) // propagate
}),
)
.unwrap();
search_entry.connect_activate(clone!(@strong message_sender => move |_entry| {
message_sender.send(Message::EnterPressed).expect("message_sender error");
}));
let emoji_maps = EmojiMaps::from_generated_emojis(); // is this the best place to do this?
let mut picker = Picker {
focus_index: None,
emojis: emoji_maps.match_query(String::new(), options.n_matches),
};
picker.render(&mut picker_flowbox);
let mut shift_held = false; // TODO: should this be something fancier?
// Our main event loop
message_receiver.attach(
None,
clone!(@strong options => move |msg| {
debug!("message received: {:?}", msg);
match msg {
Message::SearchChanged(q) => {
picker.emojis = emoji_maps.match_query(q, options.n_matches);
picker.focus_index =
if picker.emojis.len() == 1 {
// If there's only one matching emoji then focus it.
Some(0)
} else {
None
};
picker.render(&mut picker_flowbox);
}
Message::TabPressed => {
let end = picker.emojis.len() - 1;
picker.focus_index =
match picker.focus_index {
None if shift_held => Some(end),
None => Some(0),
Some(i) if i == end && !shift_held => Some(0),
Some(i) if i == 0 && shift_held => Some(end),
Some(i) if shift_held => Some(i - 1),
Some(i) => Some(i+1),
};
picker.render(&mut picker_flowbox);
},
Message::ShiftPressed => {
debug!("shift_held {} -> true", shift_held);
shift_held = true;
},
Message::ShiftReleased => {
debug!("shift_held {} -> false", shift_held);
shift_held = false;
},
Message::EnterPressed => {
let _ = match picker.focus_index {
None => done_sender.send(None),
Some(i) => done_sender.send(Some(picker.emojis[i])),
};
}
};
debug!("picker: {:?}", picker);
// NOTE: returning false here would close the receiver and have senders fail
glib::Continue(true)
}),
);
application_window.show_all();
}
/// Randomly sample `n` elements of a vector.
fn sample<T: Clone>(n: usize, xs: Vec<T>) -> Vec<T> {
// NOTE: while it would perhaps be more useful here to return a sample of
// unique elements, doing so risks getting stuck in an infinite loop.
let mut idxs = Vec::new();
let mut rng = rand::thread_rng();
while idxs.len() < n {
let i = rng.gen_range(0, xs.len());
if !idxs.contains(&i) {
idxs.push(i);
}
}
idxs.iter().map(|i| xs[*i].clone()).collect()
}
/// Deduplicate a vector in place.
fn dedup<T: Eq + std::hash::Hash + Copy>(v: &mut Vec<T>) {
let mut uniques = std::collections::HashSet::new();
v.retain(|e| uniques.insert(*e));
}
/// Validator function to be passed to `clap::Arg::validator`.
fn parse_validator<T>(s: String) -> Result<(), String>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
match s.parse::<T>() {
Ok(_) => Ok(()),
Err(err) => Err(format!("{}", err)),
}
}