Skip to content

Commit

Permalink
chore: simplify windows_subsystem attribute (tauri-apps#6273)
Browse files Browse the repository at this point in the history
  • Loading branch information
amrbashir authored Feb 18, 2023
1 parent bfa6969 commit f6c3ea6
Show file tree
Hide file tree
Showing 34 changed files with 205 additions and 333 deletions.
1 change: 1 addition & 0 deletions core/tauri-codegen/src/embedded_assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ impl ToTokens for EmbeddedAssets {

// we expect phf related items to be in path when generating the path code
tokens.append_all(quote! {{
#[allow(unused)]
use ::tauri::utils::assets::{CspHash, EmbeddedAssets, phf, phf::phf_map};
EmbeddedAssets::new(phf_map! { #assets }, &[#global_hashes], phf_map! { #html_hashes })
}});
Expand Down
5 changes: 1 addition & 4 deletions core/tests/app-updater/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
let mut context = tauri::generate_context!();
Expand Down
2 changes: 1 addition & 1 deletion examples/api/dist/assets/index.css

Large diffs are not rendered by default.

62 changes: 31 additions & 31 deletions examples/api/dist/assets/index.js

Large diffs are not rendered by default.

13 changes: 0 additions & 13 deletions examples/api/src-tauri/Cargo.lock

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

4 changes: 3 additions & 1 deletion examples/api/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ edition = "2021"
rust-version = "1.59"
license = "Apache-2.0 OR MIT"

[lib]
name = "api_lib"

[build-dependencies]
tauri-build = { path = "../../../core/tauri-build", features = ["codegen", "isolation"] }

Expand All @@ -32,7 +35,6 @@ features = [
]

[target."cfg(target_os = \"windows\")".dependencies]
window-vibrancy = "0.2"
window-shadows= "0.2"

[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
Expand Down
2 changes: 1 addition & 1 deletion examples/api/src-tauri/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use serde::Deserialize;
use tauri::command;

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
#[allow(unused)]
pub struct RequestBody {
id: i32,
name: String,
Expand Down
262 changes: 134 additions & 128 deletions examples/api/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,156 +2,162 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]

mod cmd;
mod tray;

use serde::Serialize;
use tauri::{window::WindowBuilder, App, AppHandle, RunEvent, WindowUrl};
use tauri::{
api::dialog::{ask, message},
GlobalShortcutManager, Manager, RunEvent, WindowBuilder, WindowEvent, WindowUrl,
};

#[derive(Clone, Serialize)]
struct Reply {
data: String,
}

pub type SetupHook = Box<dyn FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send>;
pub type OnEvent = Box<dyn FnMut(&AppHandle, RunEvent)>;

#[derive(Default)]
pub struct AppBuilder {
setup: Option<SetupHook>,
on_event: Option<OnEvent>,
}

impl AppBuilder {
pub fn new() -> Self {
Self::default()
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.setup(move |app| {
tray::create_tray(app)?;

#[allow(unused_mut)]
let mut window_builder = WindowBuilder::new(app, "main", WindowUrl::default())
.user_agent("Tauri API")
.title("Tauri API Validation")
.inner_size(1000., 800.)
.min_inner_size(600., 400.)
.content_protected(true);

#[cfg(target_os = "windows")]
{
window_builder = window_builder.transparent(true).decorations(false);
}

#[must_use]
pub fn setup<F>(mut self, setup: F) -> Self
where
F: FnOnce(&mut App) -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
{
self.setup.replace(Box::new(setup));
self
}
let window = window_builder.build().unwrap();

#[must_use]
pub fn on_event<F>(mut self, on_event: F) -> Self
where
F: Fn(&AppHandle, RunEvent) + 'static,
{
self.on_event.replace(Box::new(on_event));
self
}

pub fn run(self) {
let setup = self.setup;
let mut on_event = self.on_event;
#[cfg(target_os = "windows")]
{
let _ = window_shadows::set_shadow(&window, true);
}

#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.setup(move |app| {
if let Some(setup) = setup {
(setup)(app)?;
}
#[cfg(debug_assertions)]
window.open_devtools();

#[allow(unused_mut)]
let mut window_builder = WindowBuilder::new(app, "main", WindowUrl::default())
.user_agent("Tauri API")
.title("Tauri API Validation")
.inner_size(1000., 800.)
.min_inner_size(600., 400.)
.content_protected(true);

#[cfg(target_os = "windows")]
{
window_builder = window_builder.transparent(true);
window_builder = window_builder.decorations(false);
std::thread::spawn(|| {
let server = match tiny_http::Server::http("localhost:3003") {
Ok(s) => s,
Err(e) => {
eprintln!("{}", e);
std::process::exit(1);
}
};
loop {
if let Ok(mut request) = server.recv() {
let mut body = Vec::new();
let _ = request.as_reader().read_to_end(&mut body);
let response = tiny_http::Response::new(
tiny_http::StatusCode(200),
request.headers().to_vec(),
std::io::Cursor::new(body),
request.body_length(),
None,
);
let _ = request.respond(response);
}
}
});

let window = window_builder.build().unwrap();

#[cfg(target_os = "windows")]
{
let _ = window_shadows::set_shadow(&window, true);
let _ = window_vibrancy::apply_blur(&window, Some((0, 0, 0, 0)));
}
Ok(())
})
.on_page_load(|window, _| {
let window_ = window.clone();
window.listen("js-event", move |event| {
println!("got js-event with message '{:?}'", event.payload());
let reply = Reply {
data: "something else".to_string(),
};

window_
.emit("rust-event", Some(reply))
.expect("failed to emit");
});
});

#[cfg(debug_assertions)]
window.open_devtools();
#[cfg(target_os = "macos")]
{
builder = builder.menu(tauri::Menu::os_default("Tauri API Validation"));
}

std::thread::spawn(|| {
let server = match tiny_http::Server::http("localhost:3003") {
Ok(s) => s,
Err(e) => {
eprintln!("{}", e);
std::process::exit(1);
}
};
loop {
if let Ok(mut request) = server.recv() {
let mut body = Vec::new();
let _ = request.as_reader().read_to_end(&mut body);
let response = tiny_http::Response::new(
tiny_http::StatusCode(200),
request.headers().to_vec(),
std::io::Cursor::new(body),
request.body_length(),
None,
#[allow(unused_mut)]
let mut app = builder
.invoke_handler(tauri::generate_handler![
cmd::log_operation,
cmd::perform_request,
])
.build(tauri::tauri_build_context!())
.expect("error while building tauri application");

#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Regular);

#[allow(unused_variables)]
app.run(move |app_handle, e| {
match e {
// Application is ready (triggered only once)
RunEvent::Ready => {
let app_handle = app_handle.clone();
app_handle
.global_shortcut_manager()
.register("CmdOrCtrl+1", move || {
let app_handle = app_handle.clone();
if let Some(window) = app_handle.get_window("main") {
message(
Some(&window),
"Tauri API",
"CmdOrCtrl+1 global shortcut triggered",
);
let _ = request.respond(response);
}
}
});

Ok(())
})
.on_page_load(|window, _| {
let window_ = window.clone();
window.listen("js-event", move |event| {
println!("got js-event with message '{:?}'", event.payload());
let reply = Reply {
data: "something else".to_string(),
};

window_
.emit("rust-event", Some(reply))
.expect("failed to emit");
});
});

#[cfg(target_os = "macos")]
{
builder = builder.menu(tauri::Menu::os_default("Tauri API Validation"));
}
})
.unwrap();
}

#[allow(unused_mut)]
let mut app = builder
.invoke_handler(tauri::generate_handler![
cmd::log_operation,
cmd::perform_request,
])
.build(tauri::tauri_build_context!())
.expect("error while building tauri application");

#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Regular);

#[allow(unused_variables)]
app.run(move |app_handle, e| {
if let RunEvent::ExitRequested { api, .. } = &e {
// Triggered when a window is trying to close
RunEvent::WindowEvent {
label,
event: WindowEvent::CloseRequested { api, .. },
..
} => {
// for other windows, we handle it in JS
if label == "main" {
let app_handle = app_handle.clone();
let window = app_handle.get_window(&label).unwrap();
// use the exposed close api, and prevent the event loop to close
api.prevent_close();
// ask the user if he wants to quit
ask(
Some(&window),
"Tauri API",
"Are you sure that you want to close this window?",
move |answer| {
if answer {
// .close() cannot be called on the main thread
std::thread::spawn(move || {
app_handle.get_window(&label).unwrap().close().unwrap();
});
}
},
);
}
}
RunEvent::ExitRequested { api, .. } => {
// Keep the event loop running even if all windows are closed
// This allow us to catch system tray events when there is no window
api.prevent_exit();
}
if let Some(on_event) = &mut on_event {
(on_event)(app_handle, e);
}
})
}
_ => (),
}
})
}
11 changes: 3 additions & 8 deletions examples/api/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]

#[cfg(desktop)]
mod desktop;
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
#[cfg(desktop)]
desktop::main();
api_lib::run();
}
Loading

0 comments on commit f6c3ea6

Please sign in to comment.