Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
//! Main logic for the app
use std::collections::HashMap;

use crate::app::apps::{App, ICNS_ICON};
use crate::commands::Function;
use crate::utils::icns_data_to_handle;
use crate::{app::tile::ExtSender, clipboard::ClipBoardContentType};

pub mod apps;
Expand Down Expand Up @@ -59,6 +63,7 @@ pub enum Message {
WindowFocusChanged(Id, bool),
ClearSearchQuery,
HideTrayIcon,
SwitchMode(String),
ReloadConfig,
SetSender(ExtSender),
SwitchToPage(Page),
Expand All @@ -82,3 +87,37 @@ pub fn default_settings() -> Settings {
..Default::default()
}
}

pub trait ToApp {
fn to_app(&self) -> App;
}

pub trait ToApps {
fn to_apps(&self) -> Vec<App>;
}

impl ToApps for HashMap<String, String> {
fn to_apps(&self) -> Vec<App> {
let icons = icns_data_to_handle(ICNS_ICON.to_vec());

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()
}
}
8 changes: 8 additions & 0 deletions src/app/apps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,14 @@ impl App {
display_name: "Open RustCast Preferences".to_string(),
search_name: "settings".to_string(),
},
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(),
},
App {
ranking: 0,
open_command: AppCommand::Message(Message::SwitchToPage(Page::EmojiSearch)),
Expand Down
46 changes: 41 additions & 5 deletions src/app/menubar.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
//! This has the menubar icon logic for the app

use std::io::Cursor;
use std::{collections::HashMap, io::Cursor};

use global_hotkey::hotkey::{Code, HotKey, Modifiers};
use image::{DynamicImage, ImageReader};
use log::info;
use tray_icon::{
Icon, TrayIcon, TrayIconBuilder,
menu::{
AboutMetadataBuilder, Icon as Ico, Menu, MenuEvent, MenuItem, PredefinedMenuItem,
accelerator::Accelerator,
AboutMetadataBuilder, Icon as Ico, IsMenuItem, Menu, MenuEvent, MenuItem,
PredefinedMenuItem, Submenu, accelerator::Accelerator,
},
};

use crate::{
app::{Message, tile::ExtSender},
config::Config,
utils::{open_settings, open_url},
};

Expand All @@ -23,9 +24,13 @@ const DISCORD_LINK: &str = "https://discord.gg/bDfNYPbnC5";
use tokio::runtime::Runtime;

/// This create a new menubar icon for the app
pub fn menu_icon(hotkey: HotKey, sender: ExtSender) -> TrayIcon {
pub fn menu_icon(config: Config, sender: ExtSender) -> TrayIcon {
let hotkey = config.toggle_hotkey.parse::<HotKey>().unwrap();
let builder = TrayIconBuilder::new();

let mut modes = config.modes;
modes.insert("Default".to_string(), "default".to_string());

let image = get_image();
let icon = Icon::from_rgba(image.as_bytes().to_vec(), image.width(), image.height()).unwrap();

Expand All @@ -38,6 +43,7 @@ pub fn menu_icon(hotkey: HotKey, sender: ExtSender) -> TrayIcon {
&PredefinedMenuItem::separator(),
&refresh_item(),
&open_item(hotkey),
&mode_item(modes),
&PredefinedMenuItem::separator(),
&open_issue_item(),
&get_help_item(),
Expand Down Expand Up @@ -104,7 +110,19 @@ fn init_event_handler(sender: ExtSender, hotkey_id: u32) {
"open_github_page" => {
open_url("https://github.com/unsecretised/rustcast");
}
_ => {}
id => {
if id.starts_with("mode_switch_") {
let id = id.to_string();
runtime.spawn(async move {
sender
.clone()
.try_send(Message::SwitchMode(
id.strip_prefix("mode_switch_").unwrap_or("").to_string(),
))
.unwrap();
});
}
}
}
}));
}
Expand All @@ -122,6 +140,24 @@ fn hide_tray_icon() -> MenuItem {
MenuItem::with_id("hide_tray_icon", "Hide Tray Icon", true, None)
}

fn mode_item(modes: HashMap<String, String>) -> Submenu {
let owned_items: Vec<MenuItem> = modes
.keys()
.map(|key| {
MenuItem::with_id(
format!("mode_switch_{}", key), // id uses the key
format!("{}{}", key.split_at(1).0.to_uppercase(), key.split_at(1).1),
true,
None,
)
})
.collect();

let items: Vec<&dyn IsMenuItem> = owned_items.iter().map(|x| x as &dyn IsMenuItem).collect();

Submenu::with_items("Modes", true, &items).unwrap()
}

fn open_item(hotkey: HotKey) -> MenuItem {
MenuItem::with_id(
"show_rustcast",
Expand Down
3 changes: 2 additions & 1 deletion src/app/tile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ pub struct Tile {
pub theme: iced::Theme,
pub focus_id: u32,
pub query: String,
pub current_mode: String,
query_lc: String,
results: Vec<App>,
options: AppIndex,
Expand Down Expand Up @@ -354,7 +355,7 @@ fn handle_clipboard_history() -> impl futures::Stream<Item = Message> {
.ok();
prev_byte_rep = byte_rep;
}
tokio::time::sleep(Duration::from_millis(10)).await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
})
}
Expand Down
30 changes: 26 additions & 4 deletions src/app/tile/elm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ use iced::{Length::Fill, widget::text_input};
use log::info;
use rayon::slice::ParallelSliceMut;

use crate::app::DEFAULT_WINDOW_HEIGHT;
use crate::app::pages::emoji::emoji_page;
use crate::app::tile::{AppIndex, Hotkeys};
use crate::app::{DEFAULT_WINDOW_HEIGHT, ToApp, ToApps};
use crate::config::Theme;
use crate::styles::{contents_style, glass_border, glass_surface, rustcast_text_input_style};
use crate::{app::WINDOW_WIDTH, platform};
Expand Down Expand Up @@ -44,6 +44,9 @@ pub fn new(hotkey: HotKey, config: &Config) -> (Tile, Task<Message>) {
options.extend(config.shells.iter().map(|x| x.to_app()));
info!("Loaded shell commands");

options.extend(config.modes.to_apps());
info!("Loaded modes");

options.extend(App::basic_apps());
info!("Loaded basic apps / default apps");
options.par_sort_by_key(|x| x.display_name.len());
Expand All @@ -59,6 +62,7 @@ pub fn new(hotkey: HotKey, config: &Config) -> (Tile, Task<Message>) {

(
Tile {
current_mode: "Default".to_string(),
query: String::new(),
query_lc: String::new(),
focus_id: 0,
Expand All @@ -70,7 +74,7 @@ pub fn new(hotkey: HotKey, config: &Config) -> (Tile, Task<Message>) {
frontmost: None,
focused: false,
config: config.clone(),
theme: config.theme.to_owned().into(),
theme: config.theme.to_owned().clone().into(),
clipboard_content: vec![],
tray_icon: None,
sender: None,
Expand Down Expand Up @@ -157,7 +161,11 @@ pub fn view(tile: &Tile, wid: window::Id) -> Element<'_, Message> {
Column::new()
.push(title_input)
.push(scrollable)
.push(footer(tile.config.theme.clone(), results_count))
.push(footer(
tile.config.theme.clone(),
results_count,
tile.current_mode.clone(),
))
.spacing(0),
)
.style(|_| container::Style {
Expand All @@ -179,7 +187,7 @@ pub fn view(tile: &Tile, wid: window::Id) -> Element<'_, Message> {
}
}

fn footer(theme: Theme, results_count: usize) -> Element<'static, Message> {
fn footer(theme: Theme, results_count: usize, current_mode: String) -> Element<'static, Message> {
if results_count == 0 {
return space().into();
}
Expand All @@ -194,6 +202,11 @@ fn footer(theme: Theme, results_count: usize) -> Element<'static, Message> {
let focused = false;
let radius = 15.0;

let current_mode = format!(
"{}{} Mode",
current_mode.split_at(1).0.to_uppercase(),
current_mode.split_at(1).1
);
container(
Row::new()
.push(
Expand All @@ -204,6 +217,15 @@ fn footer(theme: Theme, results_count: usize) -> Element<'static, Message> {
.font(theme.font())
.align_x(Alignment::Center),
)
.push(
Text::new(current_mode)
.size(12)
.height(30)
.color(theme.text_color(0.7))
.font(theme.font())
.width(Fill)
.align_x(Alignment::End),
)
.padding(4)
.width(Fill)
.height(30),
Expand Down
22 changes: 20 additions & 2 deletions src/app/tile/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use iced::window::Id;
use log::info;
use rayon::slice::ParallelSliceMut;

use crate::app::ToApp;
use crate::app::ToApps;
use crate::app::WINDOW_WIDTH;
use crate::app::apps::App;
use crate::app::apps::AppCommand;
Expand Down Expand Up @@ -40,6 +42,21 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
tile.visible = true;
Task::none()
}

Message::SwitchMode(mode) => {
if let Some(command) = tile.config.modes.get(mode.trim()) {
tile.current_mode = mode.clone();
info!("Switched mode");
Task::done(Message::RunFunction(Function::RunShellCommand(
command.to_owned(),
)))
} else {
info!("Switching to default mode");
tile.current_mode = "default".to_string();
window::latest().map(|x| Message::HideWindow(x.unwrap()))
}
}

Message::HideTrayIcon => {
tile.tray_icon = None;
tile.config.show_trayicon = false;
Expand All @@ -52,7 +69,7 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
Message::SetSender(sender) => {
tile.sender = Some(sender.clone());
if tile.config.show_trayicon {
tile.tray_icon = Some(menu_icon(tile.hotkeys.toggle, sender));
tile.tray_icon = Some(menu_icon(tile.config.clone(), sender));
}
Task::none()
}
Expand Down Expand Up @@ -216,6 +233,7 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {

let mut new_options = get_installed_apps(new_config.theme.show_icons);
new_options.extend(new_config.shells.iter().map(|x| x.to_app()));
new_options.extend(new_config.modes.to_apps());
new_options.extend(App::basic_apps());
new_options.par_sort_by_key(|x| x.display_name.len());

Expand Down Expand Up @@ -275,7 +293,7 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
}

Message::RunFunction(command) => {
command.execute(&tile.config, &tile.query);
command.execute(&tile.config);

let return_focus_task = match &command {
Function::OpenApp(_) | Function::OpenPrefPane | Function::GoogleSearch(_) => {
Expand Down
11 changes: 4 additions & 7 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{calculator::Expr, clipboard::ClipBoardContentType, config::Config};
#[derive(Debug, Clone, PartialEq)]
pub enum Function {
OpenApp(String),
RunShellCommand(String, String),
RunShellCommand(String),
OpenWebsite(String),
RandomVar(i32), // Easter egg function
CopyToClipboard(ClipBoardContentType),
Expand All @@ -24,7 +24,7 @@ pub enum Function {

impl Function {
/// Run the command
pub fn execute(&self, config: &Config, query: &str) {
pub fn execute(&self, config: &Config) {
match self {
Function::OpenApp(path) => {
let path = path.to_owned();
Expand All @@ -34,13 +34,10 @@ impl Function {
));
});
}
Function::RunShellCommand(command, alias) => {
let query = query.to_string();
let final_command =
format!(r#"{} {}"#, command, query.strip_prefix(alias).unwrap_or(""));
Function::RunShellCommand(command) => {
Command::new("sh")
.arg("-c")
.arg(final_command.trim())
.arg(format!("\"{}\"", command))
.spawn()
.ok();
}
Expand Down
Loading