Skip to content

Commit b90b736

Browse files
authored
Merge pull request #178 from unsecretised/fix-energy-usage
Improve energy usage.. its better but still needs to be improved
2 parents 4b84ea2 + ec9522b commit b90b736

File tree

5 files changed

+180
-141
lines changed

5 files changed

+180
-141
lines changed

src/app/tile.rs

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ impl AppIndex {
6666
app.ranking += 5;
6767
}
6868

69+
fn empty() -> AppIndex {
70+
AppIndex {
71+
by_name: BTreeMap::new(),
72+
}
73+
}
74+
6975
/// Factory function for creating
7076
pub fn from_apps(options: Vec<App>) -> Self {
7177
let mut bmap = BTreeMap::new();
@@ -238,7 +244,7 @@ impl Tile {
238244
} else if self.page == Page::EmojiSearch {
239245
&self.emoji_apps
240246
} else {
241-
&AppIndex::from_apps(vec![])
247+
&AppIndex::empty()
242248
};
243249
let results: Vec<App> = options
244250
.search_prefix(&query)
@@ -270,10 +276,9 @@ impl Tile {
270276
/// This is the subscription function that handles hot reloading of the config
271277
fn handle_hot_reloading() -> impl futures::Stream<Item = Message> {
272278
stream::channel(100, async |mut output| {
273-
let mut content = fs::read_to_string(
274-
std::env::var("HOME").unwrap_or("".to_owned()) + "/.config/rustcast/config.toml",
275-
)
276-
.unwrap_or("".to_string());
279+
let config_path =
280+
&(std::env::var("HOME").unwrap_or("".to_owned()) + "/.config/rustcast/config.toml");
281+
let mut last_modified = fs::metadata(config_path).unwrap().modified().unwrap();
277282

278283
let paths = default_app_paths();
279284
let mut total_files: usize = paths
@@ -282,25 +287,24 @@ fn handle_hot_reloading() -> impl futures::Stream<Item = Message> {
282287
.sum();
283288

284289
loop {
285-
let current_content = fs::read_to_string(
286-
std::env::var("HOME").unwrap_or("".to_owned()) + "/.config/rustcast/config.toml",
287-
)
288-
.unwrap_or("".to_string());
290+
let last_modified_check = fs::metadata(config_path).unwrap().modified().unwrap();
289291

290292
let current_total_files: usize = paths
291293
.par_iter()
292294
.map(|dir| count_dirs_in_dir(Path::new(dir)))
293295
.sum();
294296

295-
if current_content != content {
296-
content = current_content;
297-
output.send(Message::ReloadConfig).await.unwrap();
297+
if last_modified_check != last_modified {
298+
last_modified = last_modified_check;
299+
info!("Config file was modified");
300+
let _ = output.send(Message::ReloadConfig).await;
298301
} else if total_files != current_total_files {
299302
total_files = current_total_files;
300-
output.send(Message::ReloadConfig).await.unwrap();
303+
info!("App count was changed");
304+
let _ = output.send(Message::ReloadConfig).await;
301305
}
302306

303-
tokio::time::sleep(Duration::from_millis(10)).await;
307+
tokio::time::sleep(Duration::from_millis(1000)).await;
304308
}
305309
})
306310
}
@@ -330,7 +334,7 @@ fn handle_hotkeys() -> impl futures::Stream<Item = Message> {
330334
{
331335
output.try_send(Message::KeyPressed(event.id)).unwrap();
332336
}
333-
tokio::time::sleep(Duration::from_millis(10)).await;
337+
tokio::time::sleep(Duration::from_millis(100)).await;
334338
}
335339
})
336340
}
@@ -385,7 +389,7 @@ fn handle_recipient() -> impl futures::Stream<Item = Message> {
385389
if let Some(abcd) = abcd {
386390
abcd.await;
387391
}
388-
tokio::time::sleep(Duration::from_nanos(10)).await;
392+
tokio::time::sleep(Duration::from_millis(100)).await;
389393
}
390394
})
391395
}

src/app/tile/update.rs

Lines changed: 119 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use crate::app::menubar::menu_icon;
2323
use crate::app::tile::AppIndex;
2424
use crate::app::{Message, Page, tile::Tile};
2525
use crate::calculator::Expr;
26+
use crate::calculator::is_valid_expr;
2627
use crate::clipboard::ClipBoardContentType;
2728
use crate::commands::Function;
2829
use crate::config::Config;
@@ -328,11 +329,15 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
328329
};
329330

330331
if tile.config.buffer_rules.clear_on_enter {
331-
window::latest()
332-
.map(|x| x.unwrap())
333-
.map(Message::HideWindow)
334-
.chain(Task::done(Message::ClearSearchQuery))
335-
.chain(return_focus_task)
332+
if tile.visible {
333+
window::latest()
334+
.map(|x| x.unwrap())
335+
.map(Message::HideWindow)
336+
.chain(Task::done(Message::ClearSearchQuery))
337+
.chain(return_focus_task)
338+
} else {
339+
Task::none()
340+
}
336341
} else {
337342
Task::none()
338343
}
@@ -373,7 +378,7 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
373378
}
374379

375380
Message::ClearSearchResults => {
376-
tile.results = vec![];
381+
tile.results = Vec::new();
377382
Task::none()
378383
}
379384
Message::WindowFocusChanged(wid, focused) => {
@@ -400,32 +405,76 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
400405

401406
tile.query_lc = input.trim().to_lowercase();
402407
tile.query = input;
408+
403409
let prev_size = tile.results.len();
404-
if tile.query_lc.is_empty() && tile.page != Page::ClipboardHistory {
405-
tile.results = vec![];
406-
return Task::done(Message::ResizeWindow(id, DEFAULT_WINDOW_HEIGHT));
407-
} else if tile.query_lc == "randomvar" {
408-
let rand_num = rand::random_range(0..100);
409-
tile.results = vec![App {
410-
ranking: 0,
411-
open_command: AppCommand::Function(Function::RandomVar(rand_num)),
412-
desc: "Easter egg".to_string(),
413-
icons: None,
414-
display_name: rand_num.to_string(),
415-
search_name: String::new(),
416-
}];
417-
return single_item_resize_task(id);
418-
} else if tile.query_lc == "67" {
419-
tile.results = vec![App {
420-
ranking: 0,
421-
open_command: AppCommand::Function(Function::RandomVar(67)),
422-
desc: "Easter egg".to_string(),
423-
icons: None,
424-
display_name: 67.to_string(),
425-
search_name: String::new(),
426-
}];
427-
return single_item_resize_task(id);
428-
} else if tile.query_lc.ends_with("?") {
410+
411+
if tile.page == Page::ClipboardHistory && tile.query_lc != "main" {
412+
return Task::none();
413+
} else if tile.page == Page::EmojiSearch && tile.query_lc.is_empty() {
414+
tile.results = if tile.query_lc.is_empty() {
415+
Vec::new()
416+
} else {
417+
tile.emoji_apps
418+
.search_prefix(&tile.query_lc)
419+
.map(|x| x.to_owned())
420+
.collect()
421+
};
422+
}
423+
424+
if tile.query_lc.is_empty() {
425+
tile.results = Vec::new();
426+
return zero_item_resize_task(id);
427+
};
428+
429+
match tile.query_lc.as_str() {
430+
"randomvar" => {
431+
let rand_num = rand::random_range(0..100);
432+
tile.results = vec![App {
433+
ranking: 0,
434+
open_command: AppCommand::Function(Function::RandomVar(rand_num)),
435+
desc: "Easter egg".to_string(),
436+
icons: None,
437+
display_name: rand_num.to_string(),
438+
search_name: String::new(),
439+
}];
440+
return single_item_resize_task(id);
441+
}
442+
"lemon" => {
443+
tile.results = vec![App {
444+
ranking: 0,
445+
open_command: AppCommand::Display,
446+
desc: "Easter Egg".to_string(),
447+
icons: lemon_icon_handle(),
448+
display_name: "Lemon".to_string(),
449+
search_name: "".to_string(),
450+
}];
451+
return single_item_resize_task(id);
452+
}
453+
"67" => {
454+
tile.results = vec![App {
455+
ranking: 0,
456+
open_command: AppCommand::Function(Function::RandomVar(67)),
457+
desc: "Easter egg".to_string(),
458+
icons: None,
459+
display_name: 67.to_string(),
460+
search_name: String::new(),
461+
}];
462+
return single_item_resize_task(id);
463+
}
464+
"cbhist" => {
465+
task = task.chain(Task::done(Message::SwitchToPage(Page::ClipboardHistory)));
466+
tile.page = Page::ClipboardHistory;
467+
}
468+
"main" => {
469+
if tile.page != Page::Main {
470+
task = task.chain(Task::done(Message::SwitchToPage(Page::Main)));
471+
return Task::batch([zero_item_resize_task(id), task]);
472+
}
473+
}
474+
_ => {}
475+
}
476+
477+
if tile.query_lc.ends_with("?") || tile.query_lc.split_whitespace().nth(2).is_some() {
429478
tile.results = vec![App {
430479
ranking: 0,
431480
open_command: AppCommand::Function(Function::GoogleSearch(tile.query.clone())),
@@ -435,44 +484,51 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
435484
search_name: String::new(),
436485
}];
437486
return single_item_resize_task(id);
438-
} else if tile.query_lc == "cbhist" {
439-
task = task.chain(Task::done(Message::SwitchToPage(Page::ClipboardHistory)));
440-
tile.page = Page::ClipboardHistory
441-
} else if tile.query_lc == "main" && tile.page != Page::Main {
442-
task = task.chain(Task::done(Message::SwitchToPage(Page::Main)));
443-
tile.page = Page::Main;
444487
} else if tile.query_lc.starts_with(">") && tile.page == Page::Main {
488+
let command = tile.query.strip_prefix(">").unwrap_or("");
445489
tile.results = vec![App {
446490
ranking: 20,
447491
open_command: AppCommand::Function(Function::RunShellCommand(
448-
tile.query.strip_prefix(">").unwrap_or("").to_string(),
492+
command.to_string(),
449493
)),
450-
display_name: format!(
451-
"Shell Command: {}",
452-
tile.query.strip_prefix(">").unwrap_or("")
453-
),
494+
display_name: format!("Shell Command: {}", command),
454495
icons: None,
455496
search_name: "".to_string(),
456497
desc: "Shell Command".to_string(),
457498
}];
458499
return single_item_resize_task(id);
459500
}
501+
460502
tile.handle_search_query_changed();
461503

462-
if tile.results.is_empty()
463-
&& let Some(res) = Expr::from_str(&tile.query).ok()
464-
{
504+
if !tile.results.is_empty() {
505+
tile.results.par_sort_by_key(|x| -x.ranking);
506+
507+
let new_length = tile.results.len();
508+
let max_elem = min(5, new_length);
509+
510+
if prev_size != new_length {
511+
return task.chain(Task::batch([
512+
Task::done(Message::ResizeWindow(
513+
id,
514+
((max_elem * 55) + 35 + DEFAULT_WINDOW_HEIGHT as usize) as f32,
515+
)),
516+
Task::done(Message::ChangeFocus(ArrowKey::Left, 1)),
517+
]));
518+
} else {
519+
return task;
520+
}
521+
}
522+
if is_valid_url(&tile.query) {
465523
tile.results.push(App {
466524
ranking: 0,
467-
open_command: AppCommand::Function(Function::Calculate(res.clone())),
468-
desc: RUSTCAST_DESC_NAME.to_string(),
525+
open_command: AppCommand::Function(Function::OpenWebsite(tile.query.clone())),
526+
desc: "Web Browsing".to_string(),
469527
icons: None,
470-
display_name: res.eval().map(|x| x.to_string()).unwrap_or("".to_string()),
471-
search_name: "".to_string(),
528+
display_name: "Open Website: ".to_string() + &tile.query,
529+
search_name: String::new(),
472530
});
473-
} else if tile.results.is_empty()
474-
&& let Some(conversions) = unit_conversion::convert_query(&tile.query)
475-
{
531+
} else if let Some(conversions) = unit_conversion::convert_query(&tile.query) {
476532
tile.results = conversions
477533
.into_iter()
478534
.map(|conversion| {
@@ -498,66 +554,18 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
498554
}
499555
})
500556
.collect();
501-
} else if tile.results.is_empty() && is_valid_url(&tile.query) {
557+
} else if is_valid_expr(&tile.query) {
558+
let res = Expr::from_str(&tile.query).unwrap();
502559
tile.results.push(App {
503560
ranking: 0,
504-
open_command: AppCommand::Function(Function::OpenWebsite(tile.query.clone())),
505-
desc: "Web Browsing".to_string(),
506-
icons: None,
507-
display_name: "Open Website: ".to_string() + &tile.query,
508-
search_name: "".to_string(),
509-
});
510-
} else if tile.query_lc.split(' ').count() > 1 {
511-
tile.results.push(App {
512-
ranking: 0,
513-
open_command: AppCommand::Function(Function::GoogleSearch(tile.query.clone())),
561+
open_command: AppCommand::Function(Function::Calculate(res.clone())),
562+
desc: RUSTCAST_DESC_NAME.to_string(),
514563
icons: None,
515-
desc: "Web Search".to_string(),
516-
display_name: format!("Search for: {}", tile.query),
517-
search_name: String::new(),
518-
});
519-
} else if tile.results.is_empty() && tile.query_lc == "lemon" {
520-
tile.results.push(App {
521-
ranking: 0,
522-
open_command: AppCommand::Display,
523-
desc: "Easter Egg".to_string(),
524-
icons: lemon_icon_handle(),
525-
display_name: "Lemon".to_string(),
564+
display_name: res.eval().map(|x| x.to_string()).unwrap_or("".to_string()),
526565
search_name: "".to_string(),
527566
});
528567
}
529-
if !tile.query_lc.is_empty() && tile.page == Page::EmojiSearch {
530-
tile.results = tile
531-
.emoji_apps
532-
.search_prefix(&tile.query_lc)
533-
.map(|x| x.to_owned())
534-
.collect()
535-
}
536-
537-
tile.results.sort_by_key(|x| -x.ranking);
538-
539-
let new_length = tile.results.len();
540-
let max_elem = min(5, new_length);
541-
542-
if prev_size != new_length && tile.page != Page::ClipboardHistory {
543-
task.chain(Task::batch([
544-
Task::done(Message::ResizeWindow(
545-
id,
546-
((max_elem * 55) + 35 + DEFAULT_WINDOW_HEIGHT as usize) as f32,
547-
)),
548-
Task::done(Message::ChangeFocus(ArrowKey::Left, 1)),
549-
]))
550-
} else if tile.page == Page::ClipboardHistory {
551-
task.chain(Task::batch([
552-
Task::done(Message::ResizeWindow(
553-
id,
554-
((7 * 55) + 35 + DEFAULT_WINDOW_HEIGHT as usize) as f32,
555-
)),
556-
Task::done(Message::ChangeFocus(ArrowKey::Left, 1)),
557-
]))
558-
} else {
559-
task
560-
}
568+
task
561569
}
562570
}
563571
}
@@ -578,6 +586,11 @@ fn single_item_resize_task(id: Id) -> Task<Message> {
578586
Task::done(Message::ResizeWindow(id, 55. + DEFAULT_WINDOW_HEIGHT))
579587
}
580588

589+
/// A helper function for resizing rustcast when zero results are found
590+
fn zero_item_resize_task(id: Id) -> Task<Message> {
591+
Task::done(Message::ResizeWindow(id, DEFAULT_WINDOW_HEIGHT))
592+
}
593+
581594
/// Handling the lemon easter egg icon
582595
fn lemon_icon_handle() -> Option<Handle> {
583596
image::ImageReader::new(Cursor::new(include_bytes!("../../../docs/lemon.png")))

src/calculator.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
//! "log(100)" => 2
1515
//! "log(2, 8)" => 3
1616
17+
pub fn is_valid_expr(s: &str) -> bool {
18+
let mut p = Parser::new(s);
19+
p.parse_expr().and_then(|_| p.expect(Token::End)).is_ok()
20+
}
21+
1722
#[derive(Debug, Clone, PartialEq)]
1823
pub enum Expr {
1924
Number(f64),

0 commit comments

Comments
 (0)