Skip to content

feat(desktop): spawn app where cursor is #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apps/desktop/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"settings_general_hotkey": "Hotkey",
"settings_general_menu_bar_icon": "Menu Bar Icon",
"settings_general_hide_on_blur": "Hide On Blur",
"settings_general_show_on_cursor_position": "Show On Cursor Position",
"settings_general_extension_auto_upgrade": "Extension Auto Upgrade",
"settings_general_dev_extension_hmr": "Dev Extension HMR",
"settings_general_join_beta_updates": "Join Beta Updates",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/messages/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"settings_general_hotkey": "Tecla de Atalho",
"settings_general_menu_bar_icon": "Ícone na Barra de Menu",
"settings_general_hide_on_blur": "Ocultar ao Perder Foco",
"settings_general_show_on_cursor_position": "Mostrar na Posição do Cursor",
"settings_general_extension_auto_upgrade": "Atualização Automática de Extensões",
"settings_general_dev_extension_hmr": "HMR de Extensão de Desenvolvedor",
"settings_general_join_beta_updates": "Participar das Atualizações Beta",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/messages/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"settings_general_hotkey": "Сочетание клавиш",
"settings_general_menu_bar_icon": "Иконка в строке меню",
"settings_general_hide_on_blur": "Скрыть окно при потере фокуса",
"settings_general_show_on_cursor_position": "Показывать окно в позиции курсора",
"settings_general_extension_auto_upgrade": "Автообновление расширений",
"settings_general_dev_extension_hmr": "Горячая замена модуля (HMR) у dev-расширений",
"settings_general_join_beta_updates": "Получать бета-обновления",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/messages/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"settings_general_hotkey": "Phím tắt",
"settings_general_menu_bar_icon": "Biểu tượng thanh menu",
"settings_general_hide_on_blur": "Ẩn khi chuyển sang ứng dụng khác",
"settings_general_show_on_cursor_position": "Hiển thị ở vị trí con trỏ",
"settings_general_extension_auto_upgrade": "Tự động nâng cấp tiện ích mở rộng",
"settings_general_dev_extension_hmr": "HMR cho tiện ích mở rộng đang phát triển",
"settings_general_join_beta_updates": "Cài đặt cập nhật thử nghiệm (beta)",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/messages/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"settings_general_hotkey": "快捷键",
"settings_general_menu_bar_icon": "菜单栏图标",
"settings_general_hide_on_blur": "隐藏在后台",
"settings_general_show_on_cursor_position": "显示在鼠标位置",
"settings_general_extension_auto_upgrade": "自动更新插件",
"settings_general_dev_extension_hmr": "开发模式",
"settings_general_join_beta_updates": "加入 Beta 更新",
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ pub fn run() {
.unwrap();
})
.setup(move |app| {
#[cfg(target_os = "macos")]
{
app.set_activation_policy(ActivationPolicy::Accessory);
}
setup::window::setup_window(app.handle());
setup::tray::create_tray(app.handle())?;
setup::stronghold::setup_stronghold(app.handle())?;
Expand Down
5 changes: 4 additions & 1 deletion apps/desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"width": 800,
"visible": false,
"height": 600,
"decorations": true
"decorations": true,
"maximizable": false,
"resizable": false,
"visibleOnAllWorkspaces": true
},
{
"url": "/splashscreen",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@
<span>{m.settings_general_hide_on_blur()}</span>
<Switch bind:checked={$appConfig.hideOnBlur} />
</li>
<li>
<span>{m.settings_general_show_on_cursor_position()}</span>
<Switch bind:checked={$appConfig.showOnCursorPosition} />
</li>
<li>
<span>{m.settings_general_extension_auto_upgrade()}</span>
<Switch bind:checked={$appConfig.extensionAutoUpgrade} />
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/lib/stores/appConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export const defaultAppConfig: AppConfig = {
extensionAutoUpgrade: true,
joinBetaProgram: false,
onBoarded: false,
developerMode: false
developerMode: false,
showOnCursorPosition: true
}

export const appConfigLoaded = writable(false)
Expand Down
6 changes: 4 additions & 2 deletions apps/desktop/src/lib/utils/hotkey.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { appConfig } from "@/stores"
import { showWindow } from "@kunkunapi/src/commands"
import { getAllWindows } from "@tauri-apps/api/window"
import { isRegistered, register, unregister } from "@tauri-apps/plugin-global-shortcut"
import { debug, info, warn } from "@tauri-apps/plugin-log"
import { info, warn } from "@tauri-apps/plugin-log"
import { sendNotificationWithPermission } from "./notification"

/**
Expand Down Expand Up @@ -39,7 +41,7 @@ export async function registerAppHotkey(hotkeyStr: string) {
mainWin.setFocus()
}
} else {
mainWin.show()
await showWindow(appConfig.get().showOnCursorPosition, "main")
mainWin.setFocus()
}
}
Expand Down
17 changes: 17 additions & 0 deletions packages/api/src/commands/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,20 @@ export async function setTransparentTitlebar(windowLabel?: string): Promise<void
windowLabel
})
}

/**
* Given a window label, show it. It is a fancier version of bult-in
* wry's `show` function which respects current mouse position.
* If no window label is provided, the current window will be used.
* @param showOnCursorPosition
* @param windowLabel
*/
export async function showWindow(
showOnCursorPosition: boolean,
windowLabel?: string
): Promise<void> {
await invoke<void>(generateJarvisPluginCommand("show_window"), {
showOnCursorPosition,
windowLabel
})
}
1 change: 1 addition & 0 deletions packages/tauri-plugins/jarvis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ grpc = { workspace = true }
futures-util = "0.3.31"
rayon = { workspace = true }
local-ip-address = "0.6.3"
mouse_position = "0.1.4"


[target.'cfg(target_os = "macos")'.dependencies]
Expand Down
1 change: 1 addition & 0 deletions packages/tauri-plugins/jarvis/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ const COMMANDS: &[&str] = &[
/* Window */
/* -------------------------------------------------------------------------- */
"set_transparent_titlebar",
"show_window"
];

fn main() {
Expand Down
1 change: 1 addition & 0 deletions packages/tauri-plugins/jarvis/permissions/all.toml
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,5 @@ commands.allow = [
"file_transfer_preview_bucket",
# Windows
"set_transparent_titlebar",
"show_window",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!

"$schema" = "../../schemas/schema.json"

[[permission]]
identifier = "allow-show-window"
description = "Enables the show_window command without any pre-configured scope."
commands.allow = ["show_window"]

[[permission]]
identifier = "deny-show-window"
description = "Denies the show_window command without any pre-configured scope."
commands.deny = ["show_window"]
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,32 @@ Denies the show_desktop command without any pre-configured scope.
<tr>
<td>

`jarvis:allow-show-window`

</td>
<td>

Enables the show_window command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`jarvis:deny-show-window`

</td>
<td>

Denies the show_window command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`jarvis:allow-shutdown`

</td>
Expand Down
10 changes: 10 additions & 0 deletions packages/tauri-plugins/jarvis/permissions/schemas/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,16 @@
"type": "string",
"const": "deny-show-desktop"
},
{
"description": "Enables the show_window command without any pre-configured scope.",
"type": "string",
"const": "allow-show-window"
},
{
"description": "Denies the show_window command without any pre-configured scope.",
"type": "string",
"const": "deny-show-window"
},
{
"description": "Enables the shutdown command without any pre-configured scope.",
"type": "string",
Expand Down
47 changes: 45 additions & 2 deletions packages/tauri-plugins/jarvis/src/commands/window.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::setup::window::WindowExt;
use tauri::{Manager, Runtime};
use crate::{setup::window::WindowExt, utils::window::get_current_monitor};
use log::warn;
use tauri::{LogicalPosition, Manager, Runtime};

#[tauri::command]
pub async fn set_transparent_titlebar<R: Runtime>(
Expand All @@ -17,3 +18,45 @@ pub async fn set_transparent_titlebar<R: Runtime>(
}
Ok(())
}

#[tauri::command]
pub async fn show_window<R: Runtime>(
app: tauri::AppHandle<R>,
window: tauri::Window<R>,
show_on_cursor_position: bool,
window_label: Option<String>,
) -> Result<(), String> {
let win_label = window_label.unwrap_or(window.label().to_string());
let window = match app.get_webview_window(win_label.as_str()) {
Some(webview_win) => webview_win,
None => {
warn!("Window not found");
return Err("Window not found".to_string());
}
};
if show_on_cursor_position {
let screen = get_current_monitor(&window);
let dpi = screen.scale_factor();
let screen_position = screen.position().to_logical::<i32>(dpi);
let screen_size = screen.size().to_logical::<i32>(dpi);

let window_dpi = window.scale_factor().unwrap();
let window_size = window.outer_size().unwrap().to_logical::<i32>(window_dpi);

let final_pos = LogicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_position.y + ((screen_size.height / 2) - (window_size.height / 2)),
};

if let Err(e) = window.set_position(final_pos) {
warn!("Failed to set window position: {}", e);
};
}
match window.show() {
Ok(_) => Ok(()),
Err(_) => {
warn!("Failed to show window");
Err("Failed to show window".to_string())
}
}
}
1 change: 1 addition & 0 deletions packages/tauri-plugins/jarvis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
/* Window */
/* -------------------------------------------------------------------------- */
commands::window::set_transparent_titlebar,
commands::window::show_window,
])
.setup(move |app, api| {
utils::setup::setup_app_path(app);
Expand Down
1 change: 1 addition & 0 deletions packages/tauri-plugins/jarvis/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ pub mod settings;
pub mod setup;
pub mod time;
pub mod transfer_stats;
pub mod window;
2 changes: 2 additions & 0 deletions packages/tauri-plugins/jarvis/src/utils/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub struct AppSettings {
pub dev_ext_load_url: bool,
pub hide_on_blur: bool,
pub trigger_hotkey: Option<Vec<String>>,
pub show_on_cursor_position: bool,
}

impl Default for AppSettings {
Expand All @@ -37,6 +38,7 @@ impl Default for AppSettings {
dev_ext_load_url: false,
hide_on_blur: true,
trigger_hotkey: None,
show_on_cursor_position: false,
}
}
}
Expand Down
35 changes: 35 additions & 0 deletions packages/tauri-plugins/jarvis/src/utils/window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use log::{info, warn};
use tauri::{Monitor, Runtime, WebviewWindow};

pub fn get_current_monitor<R: Runtime>(window: &WebviewWindow<R>) -> Monitor {
use mouse_position::mouse_position::{Mouse, Position};

let mouse_position = match Mouse::get_mouse_position() {
Mouse::Position { x, y } => Position { x, y },
Mouse::Error => {
warn!("Mouse position not found, using primary monitor");
return window.primary_monitor().unwrap().unwrap();
}
};

info!("Mouse position: {} {}", mouse_position.x, mouse_position.y);

let monitors = window.available_monitors().unwrap();

for m in monitors {
let dpi = m.scale_factor();
let size = m.size().to_logical::<f64>(dpi);
let position = m.position().to_logical(dpi);

if mouse_position.x >= position.x
&& mouse_position.x <= (position.x + size.width as i32)
&& mouse_position.y >= position.y
&& mouse_position.y <= (position.y + size.height as i32)
{
info!("Current monitor found: {:?}", m);
return m;
}
}
warn!("Current monitor not found, using primary monitor");
window.primary_monitor().unwrap().unwrap()
}
3 changes: 2 additions & 1 deletion packages/types/src/appConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export const PersistedAppConfig = v.object({
extensionAutoUpgrade: v.boolean(),
joinBetaProgram: v.boolean(),
onBoarded: v.boolean(),
developerMode: v.boolean()
developerMode: v.boolean(),
showOnCursorPosition: v.optional(v.boolean(), true)
})

export type PersistedAppConfig = v.InferOutput<typeof PersistedAppConfig>
Expand Down