45 Commits
Author SHA1 Message Date
Tim-Paik a333c2a507 fix clippy 2022-11-28 19:49:11 +08:00
Tim-Paik 69531170b9 Update wry to 0.22, fix clippy 2022-11-28 19:47:41 +08:00
Tim-Paik 915b34cb5d fix wayland support
continuous-integration/drone/push Build is passing
2022-07-30 23:19:16 +08:00
Tim-Paik 44fa046fc9 Add support for creating projects, upgrade wry. Warning: Partially unavailable, Wayland support is broken 2022-07-30 23:15:33 +08:00
Tim-Paik 8962b3d80b update deps
continuous-integration/drone/push Build encountered an error
2022-07-02 01:20:37 +08:00
Tim-Paik ed45c5dcd5 Merge branch 'main' of github.com:Tim-Paik/neutauri
continuous-integration/drone/push Build is passing
2022-05-14 18:40:45 +08:00
Tim-Paik c60c0974e0 Use binary size optimization 2022-05-14 18:37:04 +08:00
Tim-Paik a782e23da4 fix drone issue 2022-05-08 14:28:32 +08:00
Tim-Paik 7d0dfe5d6f It looks like wry/tao/winit automatically scales the content? 2022-05-08 14:10:52 +08:00
Tim-Paik 5727f6b96f update drone ci 2022-05-08 14:09:07 +08:00
Tim-Paik 1054231a72 fix dev mode zoom 2022-05-08 00:21:26 +08:00
Tim-Paik 9f5111ced6 The popup of the default right-click menu is now blocked by default in release mode 2022-05-07 23:04:01 +08:00
Tim-Paik d561b97018 Update wry, now webview scales with screen zoom 2022-05-07 20:23:43 +08:00
Tim-Paik c1577c5450 Create neutauri_data crate to reduce dependencies 2022-05-07 20:16:30 +08:00
Tim-Paik fdd8e6f961 test drone 2022-05-02 20:55:49 +08:00
Tim-Paik d174ec76b8 test drone 2022-05-02 20:52:40 +08:00
Tim-Paik de232601a8 test drone 2022-05-02 19:25:42 +08:00
Tim-Paik 6bddb73719 test drone 2022-05-02 19:10:57 +08:00
Tim-Paik 42e514ff2f test drone 2022-05-02 16:23:39 +08:00
Tim-Paik 111b0a9e15 Fixed the problem of unsuccessful compilation under Linux 2022-05-02 15:56:39 +08:00
Tim-Paik 46f65e0c7e Now the icon property can modify the icon of the windows exe file 2022-05-01 19:59:22 +08:00
Tim-Paik 1f927cc6ab try using anyhow 2022-05-01 18:15:59 +08:00
Tim-Paik bb15d55214 Added manifest option 2022-05-01 17:53:29 +08:00
Tim-Paik ff70033f0f update bundler exe resources 2022-05-01 17:19:55 +08:00
Tim-Paik 1315bbab3d Rename window_icon to icon 2022-05-01 16:55:49 +08:00
Tim-Paik eb5eb5283a fix: initialization_script now reads the same way as html 2022-05-01 16:43:11 +08:00
Tim-Paik d31ddba08a Ready to integrate rcedit on windows 2022-05-01 16:41:32 +08:00
Tim-Paik 9117dc841f fix: Parent folders are now automatically created when exporting artifacts 2022-05-01 13:58:32 +08:00
Tim-Paik a5fe6d8ea9 fix: initialization_script now read the corresponding file instead of directly executing 2022-05-01 00:39:49 +08:00
Tim-Paik 92206f6ddd fix clippy 2022-05-01 00:19:09 +08:00
Tim-Paik 64ff54ea97 update deps ,dev mode now available 2022-04-30 23:05:43 +08:00
Tim-Paik 857aae8493 fix windows window resize bug 2022-04-06 23:15:58 +08:00
Tim-Paik 2a0fafc5bf update dev mode 2022-04-05 18:11:29 +08:00
Tim-Paik 45a5b6a1a6 update cli 2022-04-04 23:53:17 +08:00
Tim-Paik 376919d1a5 just no panic 2022-02-05 18:06:35 +08:00
Tim-Paik f965abf581 fix config dir 2022-02-05 18:05:04 +08:00
Tim-Paik a242b1b12d add windows icon 2022-02-04 01:08:15 +08:00
Tim-Paik 4fc4504057 fixed user data dir 2022-02-04 00:03:50 +08:00
Tim-Paik 6df36af153 added readme 2022-02-03 00:38:11 +08:00
Tim-Paik cab70b156b fixed windows error 2022-02-01 19:48:42 +08:00
Tim-Paik 4df957fdf3 bundler ready 2022-01-31 17:35:36 +08:00
Tim-Paik ceae4590e7 runner with window size 2022-01-30 13:04:26 +08:00
Tim-Paik acfb6b6c6b update runner 2022-01-29 22:06:03 +08:00
Tim-Paik 775ad8024d added config 2022-01-28 00:59:12 +08:00
Tim-Paik bb071e6c23 first commit 2022-01-27 01:02:17 +08:00
13 changed files with 1376 additions and 872 deletions
+22 -2
View File
@@ -1,6 +1,6 @@
kind: pipeline
type: docker
name: default
name: build
steps:
- name: build
@@ -27,4 +27,24 @@ steps:
- sha256
when:
event:
- tag
- tag
---
kind: pipeline
type: docker
name: clippy
steps:
- name: clippy
image: ubuntu:latest
commands:
- echo '========Install the necessary environment========'
- apt update && apt install -y curl gcc git libwebkit2gtk-4.0-dev libappindicator3-dev
- echo '========Install the Rust toolchain========'
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain stable -c clippy -y
- echo '========Compile the Neutauri binary========'
- $HOME/.cargo/bin/cargo build --release --bin neutauri_runtime
- $HOME/.cargo/bin/cargo build --release --bin neutauri_bundler
- echo '========Run Cargo Clippy========'
- $HOME/.cargo/bin/cargo clippy
Generated
+1090 -533
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -2,4 +2,10 @@
members = [
"neutauri_runtime",
"neutauri_bundler",
"neutauri_data",
]
[profile.release]
lto = true
strip = true
opt-level = "z"
+3 -4
View File
@@ -5,14 +5,13 @@ version = "0.1.0"
[dependencies]
anyhow = "1.0"
bincode = "1.3"
brotli = "3.3"
gumdrop = "0.8"
image = "0.24"
inquire = "0.5"
neutauri_data = {path = "../neutauri_data", features = ["bundler"]}
new_mime_guess = "4.0"
serde = {version = "1.0", features = ["derive"]}
toml = "0.5"
wry = {version = "0.15", default-features = false, features = ["protocol", "tray", "gtk-tray", "transparent", "fullscreen", "devtools"]}
wry = {version = "0.22", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen", "devtools"]}
[target.'cfg(windows)'.dependencies]
rcedit = {git = "https://github.com/Tim-Paik/rcedit-rs.git", rev = "2805fca"}
+13 -11
View File
@@ -1,16 +1,11 @@
use crate::data;
use std::{
fs,
io::{self, Write},
};
#[cfg(windows)]
use anyhow::Context;
use neutauri_data as data;
#[cfg(windows)]
use std::{
env,
hash::{Hash, Hasher},
};
use std::{fs, io::Write};
fn options() -> fs::OpenOptions {
#[cfg(not(windows))]
@@ -62,10 +57,17 @@ fn get_runtime_data(
Ok(runtime_data)
}
pub fn bundle(config_path: String) -> anyhow::Result<()> {
let config_path = std::path::Path::new(&config_path).canonicalize()?;
pub(crate) fn bundle(config_path: String) -> anyhow::Result<()> {
let config_path = std::path::Path::new(&config_path)
.canonicalize()
.with_context(|| {
format!(
"Error reading config file from {}\n\n{}",
&config_path, "You may want to create a neutauri.toml via the init subcommand?"
)
})?;
let config: data::Config = toml::from_str(fs::read_to_string(&config_path)?.as_str())
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
.with_context(|| "toml parsing error")?;
let source = match config_path.parent() {
Some(path) => path.join(&config.source).canonicalize()?,
None => config.source.canonicalize()?,
@@ -75,7 +77,7 @@ pub fn bundle(config_path: String) -> anyhow::Result<()> {
None => data::normalize_path(&config.target),
};
fs::create_dir_all(target.parent().unwrap_or_else(|| std::path::Path::new("/")))?;
let target = if target.extension() == None && cfg!(windows) {
let target = if target.extension().is_none() && cfg!(windows) {
target.with_extension("exe")
} else {
target
+29 -31
View File
@@ -1,40 +1,34 @@
use anyhow::{Context, Result};
use neutauri_data as data;
use std::{fs, io::Read, path::PathBuf};
use wry::{
application::{
dpi::{PhysicalSize, Size},
event::{Event, StartCause, WindowEvent},
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{Fullscreen, Icon, Window, WindowBuilder},
},
webview::{WebContext, WebViewBuilder},
};
use crate::data;
const PROTOCOL_PREFIX: &str = "{PROTOCOL}://";
const PROTOCOL_PREFIX: &str = "dev://localhost";
const PROTOCOL: &str = "dev";
fn custom_protocol_uri<T: Into<String>>(protocol: T, path: T) -> String {
PROTOCOL_PREFIX.replacen("{PROTOCOL}", &protocol.into(), 1) + &path.into()
}
fn custom_protocol_uri_to_path<T: Into<String>>(protocol: T, uri: T) -> wry::Result<String> {
let prefix = PROTOCOL_PREFIX.replacen("{PROTOCOL}", &protocol.into(), 1);
let uri = uri.into();
let path = uri.strip_prefix(&prefix);
match path {
Some(str) => Ok(str.to_string()),
None => Err(wry::Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
prefix + " is not found in " + &uri,
))),
}
fn custom_protocol_uri<T: Into<String>>(path: T) -> String {
PROTOCOL_PREFIX.to_owned() + &path.into()
}
pub fn dev(config_path: String) -> wry::Result<()> {
let config_path = std::path::Path::new(&config_path).canonicalize()?;
pub(crate) fn dev(config_path: String) -> Result<()> {
let config_path = std::path::Path::new(&config_path)
.canonicalize()
.with_context(|| {
format!(
"Error reading config file from {}\n\n{}",
&config_path, "You may want to create a neutauri.toml via the init subcommand?"
)
})?;
let config: data::Config = toml::from_str(fs::read_to_string(&config_path)?.as_str())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
.with_context(|| "toml parsing error")?;
let source = config.source.canonicalize()?;
let event_loop = EventLoop::new();
@@ -87,12 +81,12 @@ pub fn dev(config_path: String) -> wry::Result<()> {
let webview_builder = match url {
Some(url) => {
if url.starts_with('/') {
webview_builder.with_url(&custom_protocol_uri(PROTOCOL, &url))?
webview_builder.with_url(&custom_protocol_uri(&url))?
} else {
webview_builder.with_url(&url)?
}
}
None => webview_builder.with_url(&custom_protocol_uri(PROTOCOL, "/index.html"))?,
None => webview_builder.with_url(&custom_protocol_uri("/index.html"))?,
};
let html = config.webview_attr()?.html;
let webview_builder = match html {
@@ -142,13 +136,14 @@ pub fn dev(config_path: String) -> wry::Result<()> {
WebContext::new(None)
};
let webview = webview_builder
.with_clipboard(true)
.with_visible(config.window_attr()?.visible)
.with_transparent(config.window_attr()?.transparent)
.with_web_context(&mut web_context)
.with_custom_protocol(PROTOCOL.to_string(), move |request| {
let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?;
let path = request.uri().path();
let mut local_path = source.clone();
local_path.push(path.strip_prefix('/').unwrap_or(&path));
local_path.push(path.strip_prefix('/').unwrap_or(path));
let mut data = Vec::new();
let mut mime: String = "application/octet-stream".to_string();
match fs::File::open(&local_path) {
@@ -170,7 +165,10 @@ pub fn dev(config_path: String) -> wry::Result<()> {
}
}
}
wry::http::ResponseBuilder::new().mimetype(&mime).body(data)
wry::http::Response::builder()
.header("Content-Type", mime)
.body(data)
.map_err(|e| e.into())
})
.with_ipc_handler(|window: &Window, req: String| {
match req.as_str() {
@@ -186,14 +184,14 @@ pub fn dev(config_path: String) -> wry::Result<()> {
*control_flow = ControlFlow::Wait;
match event {
Event::NewEvents(StartCause::Init) => webview.focus(),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => {
let _ = webview.resize();
}
Event::GlobalShortcutEvent(id) => webview
.evaluate_script(&format!("GlobalShortcutEvent({:})", id.0))
.unwrap_or_default(),
_ => (),
}
});
}
+45
View File
@@ -0,0 +1,45 @@
use anyhow::Ok;
use neutauri_data as data;
const TEMPLATE: &str = include_str!("../../neutauri.toml.example");
pub(crate) fn init() -> anyhow::Result<()> {
let config = TEMPLATE;
let config = config.replace(
"Neutauri Demo",
&inquire::Text::new("The name of your program? (for window title)")
.with_placeholder("Neutauri App")
.with_default("Neutauri App")
.prompt()?,
);
let config = config.replace(
"web_src",
&inquire::Text::new("Where is your web source code? (relative to the current directory)")
.with_placeholder("web_src")
.with_default("web_src")
.prompt()?,
);
let config = config.replace(
"neutauri_demo",
&inquire::Text::new("The name of your output target?")
.with_placeholder("app")
.with_default("app")
.prompt()?,
);
let config = config.replacen(
"Small",
inquire::Select::new(
"The default size of the window?",
vec!["Small", "Medium", "Large"],
)
.prompt()?,
1,
);
let config_path = data::normalize_path(std::path::Path::new("./neutauri.toml"));
std::fs::write(&config_path, config)?;
eprintln!(
"The configuration file has been written to \"{}\"",
config_path.display()
);
Ok(())
}
+22 -3
View File
@@ -1,8 +1,7 @@
use gumdrop::Options;
mod bundle;
mod dev;
mod data;
mod init;
#[derive(Debug, Options)]
struct Args {
@@ -21,6 +20,8 @@ enum Command {
Bundle(BundleOpts),
#[options(help = "run the project in the current directory in development mode")]
Dev(DevOpts),
#[options(help = "initialize a neutauri project")]
Init(InitOpts),
}
#[derive(Debug, Clone, Options)]
@@ -39,6 +40,12 @@ struct DevOpts {
config: Option<String>,
}
#[derive(Debug, Clone, Options)]
struct InitOpts {
#[options(help = "print help information")]
help: bool,
}
fn print_help_and_exit(args: Args) {
if args.command.is_some() {
Args::parse_args_default_or_exit();
@@ -69,6 +76,8 @@ fn main() -> anyhow::Result<()> {
Some(command) => match command {
Command::Bundle(opts) => {
if opts.help_requested() {
eprintln!("Package according to the configuration in neutauri.toml");
eprintln!();
print_help_and_exit(args);
}
let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string());
@@ -76,11 +85,21 @@ fn main() -> anyhow::Result<()> {
}
Command::Dev(opts) => {
if opts.help_requested() {
eprintln!("Check the configuration in neutauri.toml and start directly");
eprintln!();
print_help_and_exit(args);
}
let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string());
dev::dev(config_path)?;
},
}
Command::Init(opts) => {
if opts.help_requested() {
eprintln!("Interactively create a neutauri.toml configuration file");
eprintln!();
print_help_and_exit(args);
}
init::init()?;
}
},
None => print_help_and_exit(args),
}
+17
View File
@@ -0,0 +1,17 @@
[package]
edition = "2021"
name = "neutauri_data"
version = "0.1.0"
[dependencies]
bincode = "1.3"
brotli = "3.3"
image = {version = "0.24", optional = true}
new_mime_guess = {version = "4.0", optional = true}
serde = {version = "1.0", features = ["derive"]}
toml = {version = "0.5", optional = true}
wry = {version = "0.22", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen"]}
[features]
bundler = ["new_mime_guess", "toml", "image"]
runtime = []
@@ -2,7 +2,7 @@ use bincode::Options;
use serde::{Deserialize, Serialize};
use std::{
fs,
io::{self, Read, Result},
io::{self, Read, Result, SeekFrom, Seek},
path::{self, Component, Path, PathBuf},
};
use wry::application::dpi::Position;
@@ -104,6 +104,102 @@ pub struct WebViewAttr {
pub initialization_script: Option<String>,
}
#[cfg(feature = "runtime")]
impl File {
pub fn decompressed_data(&mut self) -> Result<Vec<u8>> {
let mut data = Vec::with_capacity(self.data.len());
let mut r = brotli::Decompressor::new(self.data.as_slice(), 4096);
r.read_to_end(&mut data)?;
Ok(data)
}
pub fn mimetype(&self) -> String {
self.mime.clone()
}
}
#[cfg(feature = "runtime")]
impl Data {
pub fn new<P: AsRef<path::Path> + Copy>(path: P) -> Result<Self> {
let mut base = fs::File::open(path)?;
let base_length = base.metadata()?.len();
let mut magic_number_start_data = [0; MAGIC_NUMBER_START.len()];
let mut data_length_data = [0; USIZE_LEN];
let mut data = Vec::new();
let mut magic_number_end_data = [0; MAGIC_NUMBER_END.len()];
base.seek(SeekFrom::Start(base_length - MAGIC_NUMBER_END.len() as u64))?;
// 此时指针指向 MAGIC_NUMBER_END 之前
base.read_exact(&mut magic_number_end_data)?;
if &magic_number_end_data != MAGIC_NUMBER_END {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"MAGIC_NUMBER_END not found",
));
}
base.seek(SeekFrom::Start(
base_length - MAGIC_NUMBER_END.len() as u64 - USIZE_LEN as u64,
))?;
// 此时指针指向 data_length 之前
base.read_exact(&mut data_length_data)?;
base.seek(SeekFrom::Start(
base_length - u64::from_be_bytes(data_length_data),
))?;
// 此时指针指向 MAGIC_NUMBER_START
base.read_exact(&mut magic_number_start_data)?;
if &magic_number_start_data != MAGIC_NUMBER_START {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"MAGIC_NUMBER_START not found",
));
}
base.read_exact(&mut data_length_data)?;
// 此时指针指向 Data 前
base.take(u64::from_be_bytes(data_length_data))
.read_to_end(&mut data)?;
let serialize_options = bincode::DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_limit(104857600 /* 100MiB */);
let fs: Self = match serialize_options.deserialize(&data) {
Ok(fs) => fs,
Err(e) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, e));
}
};
Ok(fs)
}
fn open_file(current_dir: &Dir, mut path: path::Iter) -> Result<File> {
let next_path = match path.next() {
Some(str) => str.to_string_lossy().to_string(),
None => return Err(io::Error::new(io::ErrorKind::NotFound, "file not found")),
};
for (name, file) in &current_dir.files {
if next_path == *name {
return Ok(file.clone());
}
}
for (name, dir) in &current_dir.dirs {
if next_path == *name {
return Self::open_file(dir, path);
}
}
Err(io::Error::new(io::ErrorKind::NotFound, "file not found"))
}
pub fn open<P: AsRef<path::Path>>(&self, path: P) -> Result<File> {
let path = normalize_path(path.as_ref());
let path = if path.starts_with("/") {
path.strip_prefix("/")
.unwrap_or_else(|_| Path::new(""))
.to_path_buf()
} else {
path
};
Self::open_file(&self.fs, path.iter())
}
}
#[cfg(feature = "bundler")]
impl Dir {
// 使用本地文件系统填充 Dir 结构体
fn fill_with<P: AsRef<path::Path>>(
@@ -155,6 +251,7 @@ impl Dir {
}
}
#[cfg(feature = "bundler")]
impl Data {
pub fn build_from_dir<P: AsRef<path::Path>>(
source: P,
@@ -199,7 +296,7 @@ impl Data {
let mut target: Vec<u8> = Vec::new();
target.extend(MAGIC_NUMBER_START);
target.extend(&data.len().to_be_bytes());
target.extend(data.len().to_be_bytes());
target.extend(&data);
let target_length = target.len();
let target_length = target_length + USIZE_LEN;
@@ -229,6 +326,7 @@ impl Data {
}
}
#[cfg(feature = "bundler")]
impl Default for Config {
fn default() -> Self {
Self {
@@ -255,6 +353,7 @@ impl Default for Config {
}
}
#[cfg(feature = "bundler")]
impl Config {
pub fn window_attr(&self) -> Result<WindowAttr> {
Ok(WindowAttr {
@@ -294,10 +393,17 @@ impl Config {
}
}
#[cfg(feature = "runtime")]
pub fn load<P: AsRef<path::Path> + Copy>(path: P) -> Result<Data> {
Data::new(path)
}
#[cfg(feature = "bundler")]
pub fn pack<P: AsRef<path::Path>>(config: P) -> Result<()> {
Data::pack(config)
}
#[cfg(feature = "bundler")]
fn load_icon(path: &Path) -> Result<Icon> {
let image = image::open(path)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
+2 -4
View File
@@ -4,10 +4,8 @@ name = "neutauri_runtime"
version = "0.1.0"
[dependencies]
bincode = "1.3"
brotli = "3.3"
serde = {version = "1.0", features = ["derive"]}
wry = {version = "0.15", default-features = false, features = ["protocol", "tray", "gtk-tray", "transparent", "fullscreen"]}
neutauri_data = {path = "../neutauri_data", features = ["runtime"]}
wry = {version = "0.22", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen"]}
[target.'cfg(windows)'.build-dependencies]
winres = "0.1"
-255
View File
@@ -1,255 +0,0 @@
use bincode::Options;
use serde::{Deserialize, Serialize};
use std::{
fs,
io::{self, Read, Result, Seek, SeekFrom},
path::{self, Component, Path, PathBuf},
};
use wry::application::dpi::Position;
const MAGIC_NUMBER_START: &[u8; 9] = b"NEUTFSv01";
const MAGIC_NUMBER_END: &[u8; 9] = b"NEUTFSEnd";
const USIZE_LEN: usize = usize::MAX.to_be_bytes().len();
#[non_exhaustive]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum Compress {
Brotli,
None,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct File {
mime: String,
data: Vec<u8>,
compress: Compress,
}
#[derive(Serialize, Deserialize, Debug)]
struct Dir {
files: Vec<(String, File)>,
dirs: Vec<(String, Dir)>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Data {
pub window_attr: WindowAttr,
pub webview_attr: WebViewAttr,
fs: Dir,
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum WindowSize {
Large,
Medium,
Small,
Fixed { width: f64, height: f64 },
Scale { factor: f64 },
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Config {
pub source: PathBuf,
pub target: PathBuf,
pub inner_size: Option<WindowSize>,
pub min_inner_size: Option<WindowSize>,
pub max_inner_size: Option<WindowSize>,
pub resizable: bool,
pub fullscreen: bool,
pub title: String,
pub maximized: bool,
pub visible: bool,
pub transparent: bool,
pub decorations: bool,
pub always_on_top: bool,
pub icon: Option<PathBuf>,
pub spa: bool,
pub url: Option<String>,
pub html: Option<PathBuf>,
pub initialization_script: Option<String>,
pub manifest: Option<PathBuf>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Icon {
pub rgba: Vec<u8>,
pub width: u32,
pub height: u32,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct WindowAttr {
pub inner_size: Option<WindowSize>,
pub min_inner_size: Option<WindowSize>,
pub max_inner_size: Option<WindowSize>,
pub position: Option<Position>,
pub resizable: bool,
pub fullscreen: bool,
pub title: String,
pub maximized: bool,
pub visible: bool,
pub transparent: bool,
pub decorations: bool,
pub always_on_top: bool,
pub icon: Option<Icon>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct WebViewAttr {
pub visible: bool,
pub transparent: bool,
pub spa: bool,
pub url: Option<String>,
pub html: Option<String>,
pub initialization_script: Option<String>,
}
impl File {
pub fn decompressed_data(&mut self) -> Result<Vec<u8>> {
let mut data = Vec::with_capacity(self.data.len());
let mut r = brotli::Decompressor::new(self.data.as_slice(), 4096);
r.read_to_end(&mut data)?;
Ok(data)
}
pub fn mimetype(&self) -> String {
self.mime.clone()
}
}
impl Data {
pub fn new<P: AsRef<path::Path> + Copy>(path: P) -> Result<Self> {
let mut base = fs::File::open(path)?;
let base_length = base.metadata()?.len();
let mut magic_number_start_data = [0; MAGIC_NUMBER_START.len()];
let mut data_length_data = [0; USIZE_LEN];
let mut data = Vec::new();
let mut magic_number_end_data = [0; MAGIC_NUMBER_END.len()];
base.seek(SeekFrom::Start(base_length - MAGIC_NUMBER_END.len() as u64))?;
// 此时指针指向 MAGIC_NUMBER_END 之前
base.read_exact(&mut magic_number_end_data)?;
if &magic_number_end_data != MAGIC_NUMBER_END {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"MAGIC_NUMBER_END not found",
));
}
base.seek(SeekFrom::Start(
base_length - MAGIC_NUMBER_END.len() as u64 - USIZE_LEN as u64,
))?;
// 此时指针指向 data_length 之前
base.read_exact(&mut data_length_data)?;
base.seek(SeekFrom::Start(
base_length - u64::from_be_bytes(data_length_data),
))?;
// 此时指针指向 MAGIC_NUMBER_START
base.read_exact(&mut magic_number_start_data)?;
if &magic_number_start_data != MAGIC_NUMBER_START {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"MAGIC_NUMBER_START not found",
));
}
base.read_exact(&mut data_length_data)?;
// 此时指针指向 Data 前
base.take(u64::from_be_bytes(data_length_data))
.read_to_end(&mut data)?;
let serialize_options = bincode::DefaultOptions::new()
.with_fixint_encoding()
.allow_trailing_bytes()
.with_limit(104857600 /* 100MiB */);
let fs: Self = match serialize_options.deserialize(&data) {
Ok(fs) => fs,
Err(e) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, e));
}
};
Ok(fs)
}
fn open_file(&self, current_dir: &Dir, mut path: path::Iter) -> Result<File> {
let next_path = match path.next() {
Some(str) => str.to_string_lossy().to_string(),
None => return Err(io::Error::new(io::ErrorKind::NotFound, "file not found")),
};
for (name, file) in &current_dir.files {
if next_path == *name {
return Ok(file.clone());
}
}
for (name, dir) in &current_dir.dirs {
if next_path == *name {
return self.open_file(dir, path);
}
}
Err(io::Error::new(io::ErrorKind::NotFound, "file not found"))
}
pub fn open<P: AsRef<path::Path>>(&self, path: P) -> Result<File> {
let path = normalize_path(path.as_ref());
let path = if path.starts_with("/") {
path.strip_prefix("/")
.unwrap_or_else(|_| Path::new(""))
.to_path_buf()
} else {
path
};
self.open_file(&self.fs, path.iter())
}
}
impl Default for Config {
fn default() -> Self {
Self {
source: PathBuf::from("."),
target: PathBuf::from("app.neu"),
inner_size: Some(WindowSize::Medium),
min_inner_size: None,
max_inner_size: None,
resizable: true,
fullscreen: false,
title: "".into(),
maximized: false,
visible: true,
transparent: false,
decorations: true,
always_on_top: false,
icon: None,
spa: false,
url: Some("/index.html".into()),
html: None,
initialization_script: None,
manifest: None,
}
}
}
pub fn load<P: AsRef<path::Path> + Copy>(path: P) -> Result<Data> {
Data::new(path)
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => {}
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
+19 -27
View File
@@ -1,35 +1,22 @@
#![windows_subsystem = "windows"]
use neutauri_data as data;
use std::path::PathBuf;
use wry::{
application::{
dpi::{PhysicalSize, Size},
event::{Event, StartCause, WindowEvent},
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::{Fullscreen, Icon, Window, WindowBuilder},
},
webview::{WebContext, WebViewBuilder},
};
mod data;
const PROTOCOL_PREFIX: &str = "{PROTOCOL}://";
const PROTOCOL_PREFIX: &str = "neu://localhost";
const PROTOCOL: &str = "neu";
fn custom_protocol_uri<T: Into<String>>(protocol: T, path: T) -> String {
PROTOCOL_PREFIX.replacen("{PROTOCOL}", &protocol.into(), 1) + &path.into()
}
fn custom_protocol_uri_to_path<T: Into<String>>(protocol: T, uri: T) -> wry::Result<String> {
let prefix = PROTOCOL_PREFIX.replacen("{PROTOCOL}", &protocol.into(), 1);
let uri = uri.into();
let path = uri.strip_prefix(&prefix);
match path {
Some(str) => Ok(str.to_string()),
None => Err(wry::Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
prefix + " is not found in " + &uri,
))),
}
fn custom_protocol_uri<T: Into<String>>(path: T) -> String {
PROTOCOL_PREFIX.to_owned() + &path.into()
}
fn main() -> wry::Result<()> {
@@ -87,12 +74,12 @@ fn main() -> wry::Result<()> {
let webview_builder = match url {
Some(url) => {
if url.starts_with('/') {
webview_builder.with_url(&custom_protocol_uri(PROTOCOL, &url))?
webview_builder.with_url(&custom_protocol_uri(&url))?
} else {
webview_builder.with_url(&url)?
}
}
None => webview_builder.with_url(&custom_protocol_uri(PROTOCOL, "/index.html"))?,
None => webview_builder.with_url(&custom_protocol_uri("/index.html"))?,
};
let html = res.webview_attr.html.clone();
let webview_builder = match html {
@@ -142,11 +129,15 @@ fn main() -> wry::Result<()> {
WebContext::new(None)
};
let webview = webview_builder
.with_clipboard(true)
.with_visible(res.window_attr.visible)
.with_transparent(res.window_attr.transparent)
.with_web_context(&mut web_context)
.with_initialization_script(
r#"window.oncontextmenu = (event) => { event.preventDefault(); }"#,
)
.with_custom_protocol(PROTOCOL.to_string(), move |request| {
let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?;
let path = request.uri().path();
let mut file = match res.open(path) {
Ok(file) => file,
Err(e) => {
@@ -157,9 +148,10 @@ fn main() -> wry::Result<()> {
}
}
};
wry::http::ResponseBuilder::new()
.mimetype(&file.mimetype())
wry::http::Response::builder()
.header("Content-Type", file.mimetype())
.body(file.decompressed_data()?)
.map_err(|e| e.into())
})
.with_ipc_handler(|window: &Window, req: String| {
match req.as_str() {
@@ -175,14 +167,14 @@ fn main() -> wry::Result<()> {
*control_flow = ControlFlow::Wait;
match event {
Event::NewEvents(StartCause::Init) => webview.focus(),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => {
let _ = webview.resize();
}
Event::GlobalShortcutEvent(id) => webview
.evaluate_script(&format!("GlobalShortcutEvent({:})", id.0))
.unwrap_or_default(),
_ => (),
}
});
}