-
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathapp.rs
More file actions
354 lines (317 loc) · 9.29 KB
/
Copy pathapp.rs
File metadata and controls
354 lines (317 loc) · 9.29 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
//! Main logic for the app
use std::collections::HashMap;
use crate::app::apps::{App, AppCommand, ICNS_ICON};
use crate::commands::Function;
use crate::config::{Config, MainPage, Shelly, ThemeMode};
use crate::debounce::DebouncePolicy;
use crate::platform::macos::launching::Shortcut;
use crate::utils::icns_data_to_handle;
use crate::{app::tile::ExtSender, clipboard::ClipBoardContentType};
use iced::time::Duration;
pub mod apps;
pub mod menubar;
pub mod pages;
pub mod tile;
use iced::window::{self, Id, Settings};
/// The default window width
pub const WINDOW_WIDTH: f32 = 500.;
/// The default window height
pub const DEFAULT_WINDOW_HEIGHT: f32 = 100.;
/// Maximum file search results returned by a single mdfind invocation.
pub const FILE_SEARCH_MAX_RESULTS: u32 = 400;
/// Number of results to accumulate before flushing a batch to the UI.
pub const FILE_SEARCH_BATCH_SIZE: u32 = 10;
/// The rustcast descriptor name to be put for all rustcast commands
pub const RUSTCAST_DESC_NAME: &str = "Utility";
/// The different pages that rustcast can have / has
#[derive(Debug, Clone, PartialEq)]
pub enum Page {
Main,
FileSearch,
ClipboardHistory,
EmojiSearch,
Settings,
}
/// The settings panel tabs
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SettingsTab {
General,
Appearance,
Commands,
}
/// Actions that open a native file dialog
#[derive(Debug, Clone)]
pub enum FileDialogAction {
PickModeFile(String),
EditSearchDir(String),
AddSearchDir,
}
/// Config fields that can be individually reset to default
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ResetField {
ToggleHotkey,
ClipboardHotkey,
Placeholder,
SearchUrl,
DebounceDelay,
StartAtLogin,
AutoUpdate,
HapticFeedback,
ShowMenubarIcon,
ClipboardHistory,
MainPage,
ShowScrollbar,
ClearOnHide,
ClearOnEnter,
ShowIcons,
Font,
EventDuration,
TextColor,
BackgroundColor,
ThemeMode,
Aliases,
Modes,
SearchDirs,
ShellCommands,
}
impl std::fmt::Display for Page {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self.to_owned() {
Page::Main => "App search",
Page::FileSearch => "File search",
Page::EmojiSearch => "Emoji search",
Page::ClipboardHistory => "Clipboard history",
Page::Settings => "Settings",
})
}
}
/// The types of arrow keys
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum ArrowKey {
Up,
Down,
Left,
Right,
}
/// The ways the cursor can move when a key is pressed
#[derive(Debug, Clone)]
pub enum Move {
Back,
Forwards(String),
}
#[derive(Debug, Clone)]
pub enum Editable<T> {
Create(T),
Delete(T),
Update { old: T, new: T },
}
/// The message type that iced uses for actions that can do something
#[derive(Debug, Clone)]
pub enum Message {
UriReceived(String),
WriteConfig(bool),
SaveRanking,
ToggleAutoStartup(bool),
LoadRanking,
ToggleFavouriteApp(String),
UpdateAvailable,
ResizeWindow(Id, f32),
OpenWindow,
OpenResult(u32),
OpenToSettings,
SearchQueryChanged(String, Id),
KeyPressed(Shortcut),
FocusTextInput(Move),
HideWindow(Id),
RunFunction(Function),
OpenFocused,
SetConfig(SetConfigFields),
OpenFileDialog(FileDialogAction),
FileDialogResult(Option<Box<Message>>),
ReturnFocus,
SwitchSettingsTab(SettingsTab),
ResetField(ResetField),
EscKeyPressed(Id),
UpdateEvents,
ClearSearchResults,
WindowFocusChanged(Id, bool),
ClearSearchQuery,
HideTrayIcon,
SwitchMode(String),
ReloadConfig,
UpdateApps,
SetSender(ExtSender),
SwitchToPage(Page),
EditClipboardHistory(Editable<ClipBoardContentType>),
ClearClipboardHistory,
ChangeFocus(ArrowKey, u32),
FileSearchResult(Vec<App>),
FileSearchClear,
SetFileSearchSender(tokio::sync::watch::Sender<(String, Vec<String>)>),
DebouncedSearch(Id),
CheckEventTap,
ThemeModeChanged(bool),
}
#[derive(Debug, Clone)]
#[allow(unused)]
pub enum SetConfigFields {
ToDefault,
ToggleHotkey(String),
ClipboardHotkey(String),
PlaceHolder(String),
SearchUrl(String),
ClipboardHistory(bool),
SetAutoUpdate(bool),
HapticFeedback(bool),
ShowMenubarIcon(bool),
SetPage(MainPage),
SetEventDuration(String),
Modes(Editable<(String, String)>),
Aliases(Editable<(String, String)>),
SearchDirs(Editable<String>),
ShellCommands(Editable<Shelly>),
DebounceDelay(u64),
SetThemeFields(SetConfigThemeFields),
SetBufferFields(SetConfigBufferFields),
}
#[derive(Debug, Clone)]
pub enum SetConfigThemeFields {
ShowScrollBar(bool),
TextColor(f32, f32, f32),
BackgroundColor(f32, f32, f32),
ShowIcons(bool),
Font(String),
ThemeMode(ThemeMode),
}
#[derive(Debug, Clone)]
pub enum SetConfigBufferFields {
ClearOnHide(bool),
ClearOnEnter(bool),
}
/// 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()
}
}
/// A Trait to define that a struct can be converted to an app
pub trait ToApp {
/// Convert self into an app
fn to_app(&self) -> App;
}
/// A Trait to define that a type (containing multiple elements) can be converted to multiple Apps
///
/// i.e. [`Vec<Box<dyn ToApp>>`] can implement ToApps but it doesn't make sense to do that
pub trait ToApps {
/// convert self into a Vec of apps
fn to_apps(&self) -> Vec<App>;
}
/// [`HashMap<String, String>`] is for storing the modes, and is an assumtion that the String
/// values are shell commands
impl ToApps for HashMap<String, String> {
fn to_apps(&self) -> Vec<App> {
let icons = icns_data_to_handle(ICNS_ICON.to_vec());
let mut to_apps: Vec<App> = self
.keys()
.map(|key| {
let display_name = format!(
"{}{} Mode",
key.split_at(1).0.to_uppercase(),
key.split_at(1).1
);
App {
ranking: 0,
open_command: apps::AppCommand::Message(Message::SwitchMode(
key.trim().to_owned(),
)),
search_name: key.to_owned(),
desc: "Switch Modes".to_string(),
icons: icons.clone(),
display_name,
}
})
.collect();
if self.get("default").is_none() {
to_apps.push(App {
ranking: 0,
open_command: AppCommand::Message(Message::SwitchMode("Default".to_string())),
desc: "Change mode".to_string(),
icons: icons.clone(),
display_name: "Default mode".to_string(),
search_name: "default".to_string(),
});
};
to_apps
}
}
impl DebouncePolicy for Page {
fn debounce_delay(&self, config: &Config) -> Option<Duration> {
match self {
Page::Main | Page::ClipboardHistory | Page::Settings => None,
Page::FileSearch | Page::EmojiSearch => {
Some(Duration::from_millis(config.debounce_delay))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
#[test]
fn page_display_labels_are_stable() {
assert_eq!(Page::Main.to_string(), "App search");
assert_eq!(Page::FileSearch.to_string(), "File search");
assert_eq!(Page::ClipboardHistory.to_string(), "Clipboard history");
assert_eq!(Page::EmojiSearch.to_string(), "Emoji search");
assert_eq!(Page::Settings.to_string(), "Settings");
}
#[test]
fn page_debounce_policy_matches_expected_pages() {
let config = Config {
debounce_delay: 123,
..Config::default()
};
assert_eq!(Page::Main.debounce_delay(&config), None);
assert_eq!(Page::ClipboardHistory.debounce_delay(&config), None);
assert_eq!(Page::Settings.debounce_delay(&config), None);
assert_eq!(
Page::FileSearch.debounce_delay(&config),
Some(Duration::from_millis(123))
);
assert_eq!(
Page::EmojiSearch.debounce_delay(&config),
Some(Duration::from_millis(123))
);
}
#[test]
fn mode_to_apps_adds_default_when_missing() {
let mut modes = HashMap::new();
modes.insert("work".to_string(), "echo work".to_string());
let apps = modes.to_apps();
assert!(apps.iter().any(|app| app.search_name == "work"));
assert!(apps.iter().any(|app| app.search_name == "default"));
}
#[test]
fn mode_to_apps_does_not_duplicate_default() {
let mut modes = HashMap::new();
modes.insert("default".to_string(), "echo default".to_string());
let apps = modes.to_apps();
let default_count = apps
.iter()
.filter(|app| app.search_name == "default")
.count();
assert_eq!(default_count, 1);
}
}