-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathapp.rs
More file actions
661 lines (601 loc) · 23.1 KB
/
Copy pathapp.rs
File metadata and controls
661 lines (601 loc) · 23.1 KB
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Main logic for the app
use crate::calculator::Expression;
use crate::clipboard::ClipBoardContentType;
use crate::commands::Function;
use crate::config::Config;
use crate::macos::{focus_this_app, transform_process_to_ui_element};
use crate::{macos, utils::get_installed_apps};
use arboard::Clipboard;
use global_hotkey::{GlobalHotKeyEvent, HotKeyState};
use iced::futures::SinkExt;
use iced::widget::text::LineHeight;
use iced::{
Alignment, Element, Fill, Subscription, Task, Theme,
alignment::Vertical,
futures,
keyboard::{self, key::Named},
stream,
widget::{
Button, Column, Row, Text, container, image::Viewer, operation, scrollable, space,
text_input,
},
window::{self, Id, Settings},
};
use objc2::rc::Retained;
use objc2_app_kit::NSRunningApplication;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use rayon::slice::ParallelSliceMut;
use std::cmp::min;
use std::time::Duration;
use std::{fs, thread};
/// The default window width
pub const WINDOW_WIDTH: f32 = 500.;
/// The default window height
pub const DEFAULT_WINDOW_HEIGHT: f32 = 65.;
/// The rustcast descriptor name to be put for all rustcast commands
pub const RUSTCAST_DESC_NAME: &str = "RustCast";
/// The main app struct, that represents an "App"
///
/// This struct represents a command that rustcast can perform, providing the rustcast
/// the data needed to search for the app, to display the app in search results, and to actually
/// "run" the app.
#[derive(Debug, Clone)]
pub struct App {
pub open_command: Function,
pub desc: String,
pub icons: Option<iced::widget::image::Handle>,
pub name: String,
pub name_lc: String,
}
impl App {
/// This returns the basic apps that rustcast has, such as quiting rustcast and opening preferences
pub fn basic_apps() -> Vec<App> {
vec![
App {
open_command: Function::Quit,
desc: RUSTCAST_DESC_NAME.to_string(),
icons: None,
name: "Quit RustCast".to_string(),
name_lc: "quit".to_string(),
},
App {
open_command: Function::OpenPrefPane,
desc: RUSTCAST_DESC_NAME.to_string(),
icons: None,
name: "Open RustCast Preferences".to_string(),
name_lc: "settings".to_string(),
},
]
}
/// This renders the app into an iced element, allowing it to be displayed in the search results
pub fn render(&self, theme: &crate::config::Theme) -> impl Into<iced::Element<'_, Message>> {
let mut tile = Row::new().width(Fill).height(55);
if theme.show_icons {
if let Some(icon) = &self.icons {
tile = tile
.push(Viewer::new(icon).height(35).width(35))
.align_y(Alignment::Center);
} else {
tile = tile
.push(space().height(Fill))
.width(55)
.height(55)
.align_y(Alignment::Center);
}
}
tile = tile.push(
Button::new(
Text::new(&self.name)
.height(Fill)
.width(Fill)
.color(theme.text_color(1.))
.align_y(Vertical::Center),
)
.on_press(Message::RunFunction(self.open_command.clone()))
.style(|_, _| iced::widget::button::Style {
background: Some(iced::Background::Color(
Theme::KanagawaDragon.palette().background,
)),
text_color: Theme::KanagawaDragon.palette().text,
..Default::default()
})
.width(Fill)
.height(55),
);
tile = tile
.push(container(Text::new(&self.desc).color(theme.text_color(0.4))).padding(15))
.width(Fill);
container(tile)
.style(|_| iced::widget::container::Style {
text_color: Some(Theme::KanagawaDragon.palette().text),
background: Some(iced::Background::Color(
Theme::KanagawaDragon.palette().background,
)),
..Default::default()
})
.width(Fill)
.height(Fill)
}
}
/// The different pages that rustcast can have / has
#[derive(Debug, Clone, PartialEq)]
pub enum Page {
Main,
ClipboardHistory,
}
/// The message type that iced uses for actions that can do something
#[derive(Debug, Clone)]
pub enum Message {
OpenWindow,
SearchQueryChanged(String, Id),
KeyPressed(u32),
HideWindow(Id),
RunFunction(Function),
ClearSearchResults,
WindowFocusChanged(Id, bool),
ClearSearchQuery,
ReloadConfig,
ClipboardHistory(ClipBoardContentType),
_Nothing,
}
/// The window settings for rustcast
pub fn default_settings() -> Settings {
Settings {
resizable: false,
decorations: false,
minimizable: false,
level: window::Level::AlwaysOnTop,
transparent: true,
blur: true,
size: iced::Size {
width: WINDOW_WIDTH,
height: DEFAULT_WINDOW_HEIGHT,
},
..Default::default()
}
}
/// This is the base window, and its a "Tile"
/// Its fields are:
/// - Theme ([`iced::Theme`])
/// - Query (String)
/// - Query Lowercase (String, but lowercase)
/// - Previous Query Lowercase (String)
/// - Results (Vec<[`App`]>) the results of the search
/// - Options (Vec<[`App`]>) the options to search through
/// - Visible (bool) whether the window is visible or not
/// - Focused (bool) whether the window is focused or not
/// - Frontmost ([`Option<Retained<NSRunningApplication>>`]) the frontmost application before the window was opened
/// - Config ([`Config`]) the app's config
/// - Open Hotkey ID (`u32`) the id of the hotkey that opens the window
/// - Clipboard Content (`Vec<`[`ClipBoardContentType`]`>`) all of the cliboard contents
/// - Page ([`Page`]) the current page of the window (main or clipboard history)
#[derive(Debug, Clone)]
pub struct Tile {
theme: iced::Theme,
query: String,
query_lc: String,
prev_query_lc: String,
results: Vec<App>,
options: Vec<App>,
visible: bool,
focused: bool,
frontmost: Option<Retained<NSRunningApplication>>,
config: Config,
open_hotkey_id: u32,
clipboard_content: Vec<ClipBoardContentType>,
page: Page,
}
impl Tile {
/// Initialise the base window
pub fn new(keybind_id: u32, config: &Config) -> (Self, Task<Message>) {
let (id, open) = window::open(default_settings());
let open = open.discard().chain(window::run(id, |handle| {
macos::macos_window_config(
&handle.window_handle().expect("Unable to get window handle"),
);
// should work now that we have a window
transform_process_to_ui_element();
}));
let store_icons = config.theme.show_icons;
let user_local_path = std::env::var("HOME").unwrap() + "/Applications/";
let paths = vec![
"/Applications/",
user_local_path.as_str(),
"/System/Applications/",
"/System/Applications/Utilities/",
];
let mut options: Vec<App> = paths
.par_iter()
.map(|path| get_installed_apps(path, store_icons))
.flatten()
.collect();
options.extend(config.shells.iter().map(|x| x.to_app()));
options.extend(App::basic_apps());
options.par_sort_by_key(|x| x.name.len());
(
Self {
query: String::new(),
query_lc: String::new(),
prev_query_lc: String::new(),
results: vec![],
options,
visible: true,
frontmost: None,
focused: false,
config: config.clone(),
theme: config.theme.to_owned().into(),
open_hotkey_id: keybind_id,
clipboard_content: vec![],
page: Page::Main,
},
Task::batch([open.map(|_| Message::OpenWindow)]),
)
}
/// This handles the iced's updates, which have all the variants of [Message]
pub fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::OpenWindow => {
self.capture_frontmost();
focus_this_app();
self.focused = true;
Task::none()
}
Message::SearchQueryChanged(input, id) => {
self.query_lc = input.trim().to_lowercase();
self.query = input;
let prev_size = self.results.len();
if self.query_lc.is_empty() && self.page == Page::Main {
self.results = vec![];
return window::resize(
id,
iced::Size {
width: WINDOW_WIDTH,
height: DEFAULT_WINDOW_HEIGHT,
},
);
} else if self.query_lc == "randomvar" {
let rand_num = rand::random_range(0..100);
self.results = vec![App {
open_command: Function::RandomVar(rand_num),
desc: "Easter egg".to_string(),
icons: None,
name: rand_num.to_string(),
name_lc: String::new(),
}];
return window::resize(
id,
iced::Size {
width: WINDOW_WIDTH,
height: 55. + DEFAULT_WINDOW_HEIGHT,
},
);
} else if self.query_lc.ends_with("?") {
self.results = vec![App {
open_command: Function::GoogleSearch(self.query.clone()),
icons: None,
desc: "Search".to_string(),
name: format!("Search for: {}", self.query),
name_lc: String::new(),
}];
return window::resize(
id,
iced::Size::new(WINDOW_WIDTH, 55. + DEFAULT_WINDOW_HEIGHT),
);
} else if self.query_lc == "cbhist" {
self.page = Page::ClipboardHistory
} else if self.query_lc == "main" {
self.page = Page::Main
}
self.handle_search_query_changed();
if self.results.is_empty()
&& let Some(res) = Expression::from_str(&self.query)
{
self.results.push(App {
open_command: Function::Calculate(res),
desc: RUSTCAST_DESC_NAME.to_string(),
icons: None,
name: res.eval().to_string(),
name_lc: "".to_string(),
});
}
let new_length = self.results.len();
let max_elem = min(5, new_length);
if prev_size != new_length && self.page == Page::Main {
thread::sleep(Duration::from_millis(30));
window::resize(
id,
iced::Size {
width: WINDOW_WIDTH,
height: ((max_elem * 55) + DEFAULT_WINDOW_HEIGHT as usize) as f32,
},
)
} else if self.page == Page::ClipboardHistory {
let element_count = min(self.clipboard_content.len(), 5);
window::resize(
id,
iced::Size {
width: WINDOW_WIDTH,
height: ((element_count * 55) + DEFAULT_WINDOW_HEIGHT as usize) as f32,
},
)
} else {
Task::none()
}
}
Message::ClearSearchQuery => {
self.query_lc = String::new();
self.query = String::new();
Task::none()
}
Message::ReloadConfig => {
self.config = toml::from_str(
&fs::read_to_string(
std::env::var("HOME").unwrap_or("".to_owned())
+ "/.config/rustcast/config.toml",
)
.unwrap_or("".to_owned()),
)
.unwrap();
Task::none()
}
Message::KeyPressed(hk_id) => {
if hk_id == self.open_hotkey_id {
self.visible = !self.visible;
if self.visible {
Task::chain(
window::open(default_settings())
.1
.map(|_| Message::OpenWindow),
operation::focus("query"),
)
} else {
let to_close = window::latest().map(|x| x.unwrap());
Task::batch([
to_close.map(Message::HideWindow),
Task::done(if self.config.buffer_rules.clone().clear_on_hide {
Message::ClearSearchQuery
} else {
Message::_Nothing
}),
])
}
} else {
Task::none()
}
}
Message::RunFunction(command) => {
command.execute(&self.config, &self.query);
if self.config.buffer_rules.clear_on_enter {
window::latest()
.map(|x| x.unwrap())
.map(Message::HideWindow)
.chain(Task::done(Message::ClearSearchQuery))
} else {
Task::none()
}
}
Message::HideWindow(a) => {
self.restore_frontmost();
self.visible = false;
self.focused = false;
self.page = Page::Main;
Task::batch([window::close(a), Task::done(Message::ClearSearchResults)])
}
Message::ClearSearchResults => {
self.results = vec![];
Task::none()
}
Message::WindowFocusChanged(wid, focused) => {
self.focused = focused;
if !focused {
Task::done(Message::HideWindow(wid))
.chain(Task::done(Message::ClearSearchQuery))
} else {
Task::none()
}
}
Message::ClipboardHistory(clip_content) => {
self.clipboard_content.insert(0, clip_content);
Task::none()
}
Message::_Nothing => Task::none(),
}
}
/// This is the view of the window. It handles the rendering of the window
///
/// The rendering of the window size (the resizing of the window) is handled by the
/// [`Tile::update`] function.
pub fn view(&self, wid: window::Id) -> Element<'_, Message> {
if self.visible {
let title_input = text_input(self.config.placeholder.as_str(), &self.query)
.on_input(move |a| Message::SearchQueryChanged(a, wid))
.on_paste(move |a| Message::SearchQueryChanged(a, wid))
.on_submit({
if self.results.is_empty() {
Message::_Nothing
} else {
Message::RunFunction(self.results.first().unwrap().to_owned().open_command)
}
})
.id("query")
.width(Fill)
.line_height(LineHeight::Relative(1.5))
.padding(20);
match self.page {
Page::Main => {
let mut search_results = Column::new();
for result in &self.results {
search_results = search_results.push(result.render(&self.config.theme));
}
Column::new()
.push(title_input)
.push(scrollable(search_results))
.into()
}
Page::ClipboardHistory => {
let mut clipboard_history = Column::new();
for result in &self.clipboard_content {
clipboard_history = clipboard_history.push(result.render_clipboard_item());
}
Column::new()
.push(title_input)
.push(scrollable(clipboard_history))
.into()
}
}
} else {
space().into()
}
}
/// This returns the theme of the window
pub fn theme(&self, _: window::Id) -> Option<Theme> {
Some(self.theme.clone())
}
/// This handles the subscriptions of the window
///
/// The subscriptions are:
/// - Hotkeys
/// - Hot reloading
/// - Clipboard history
/// - Window close events
/// - Keypresses (escape to close the window)
/// - Window focus changes
pub fn subscription(&self) -> Subscription<Message> {
Subscription::batch([
Subscription::run(handle_hotkeys),
Subscription::run(handle_hot_reloading),
Subscription::run(handle_clipboard_history),
window::close_events().map(Message::HideWindow),
keyboard::listen().filter_map(|event| {
if let keyboard::Event::KeyPressed { key, .. } = event {
match key {
keyboard::Key::Named(Named::Escape) => Some(Message::KeyPressed(65598)),
_ => None,
}
} else {
None
}
}),
window::events()
.with(self.focused)
.filter_map(|(focused, (wid, event))| match event {
window::Event::Unfocused => {
if focused {
Some(Message::WindowFocusChanged(wid, false))
} else {
None
}
}
window::Event::Focused => Some(Message::WindowFocusChanged(wid, true)),
_ => None,
}),
])
}
/// Handles the search query changed event.
///
/// This is separate from the `update` function because it has a decent amount of logic, and
/// should be separated out to make it easier to test. This function is called by the `update`
/// function to handle the search query changed event.
pub fn handle_search_query_changed(&mut self) {
let filter_vec: &Vec<App> = if self.query_lc.starts_with(&self.prev_query_lc) {
self.prev_query_lc = self.query_lc.to_owned();
&self.results
} else {
&self.options
};
let query = self.query_lc.clone();
let mut exact: Vec<App> = filter_vec
.par_iter()
.filter(|x| match &x.open_command {
Function::RunShellCommand(_, _) => x
.name_lc
.starts_with(query.split_once(" ").unwrap_or((&query, "")).0),
_ => x.name_lc == query,
})
.cloned()
.collect();
let mut prefix: Vec<App> = filter_vec
.par_iter()
.filter(|x| match x.open_command {
Function::RunShellCommand(_, _) => false,
_ => x.name_lc != query && x.name_lc.starts_with(&query),
})
.cloned()
.collect();
exact.append(&mut prefix);
self.results = exact;
}
/// Gets the frontmost application to focus later.
pub fn capture_frontmost(&mut self) {
use objc2_app_kit::NSWorkspace;
let ws = NSWorkspace::sharedWorkspace();
self.frontmost = ws.frontmostApplication();
}
/// Restores the frontmost application.
#[allow(deprecated)]
pub fn restore_frontmost(&mut self) {
use objc2_app_kit::NSApplicationActivationOptions;
if let Some(app) = self.frontmost.take() {
app.activateWithOptions(NSApplicationActivationOptions::ActivateIgnoringOtherApps);
}
}
}
/// This is the subscription function that handles hot reloading of the config
fn handle_hot_reloading() -> impl futures::Stream<Item = Message> {
stream::channel(100, async |mut output| {
let content = fs::read_to_string(
std::env::var("HOME").unwrap_or("".to_owned()) + "/.config/rustcast/config.toml",
)
.unwrap_or("".to_string());
loop {
let current_content = fs::read_to_string(
std::env::var("HOME").unwrap_or("".to_owned()) + "/.config/rustcast/config.toml",
)
.unwrap_or("".to_string());
if current_content != content {
output.send(Message::ReloadConfig).await.unwrap();
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
}
/// This is the subscription function that handles hotkeys for hiding / showing the window
fn handle_hotkeys() -> impl futures::Stream<Item = Message> {
stream::channel(100, async |mut output| {
let receiver = GlobalHotKeyEvent::receiver();
loop {
if let Ok(event) = receiver.recv()
&& event.state == HotKeyState::Pressed
{
output.try_send(Message::KeyPressed(event.id)).unwrap();
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
}
/// This is the subscription function that handles the change in clipboard history
fn handle_clipboard_history() -> impl futures::Stream<Item = Message> {
stream::channel(100, async |mut output| {
let mut clipboard = Clipboard::new().unwrap();
let mut prev_byte_rep: Option<ClipBoardContentType> = None;
loop {
let byte_rep = if let Ok(a) = clipboard.get_image() {
Some(ClipBoardContentType::Image(a))
} else if let Ok(a) = clipboard.get_text() {
Some(ClipBoardContentType::Text(a))
} else {
None
};
if byte_rep != prev_byte_rep
&& let Some(content) = &byte_rep
{
output
.send(Message::ClipboardHistory(content.to_owned()))
.await
.ok();
prev_byte_rep = byte_rep;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
}