14 Commits
Author SHA1 Message Date
Tim-Paik 2f9e3b80ba fix windows window resize bug 2022-04-06 23:15:58 +08:00
Tim-Paik 76e13856bd update dev mode 2022-04-05 18:11:29 +08:00
Tim-Paik 101a589bd2 update cli 2022-04-04 23:53:17 +08:00
Tim-Paik 5fc1a26dc2 just no panic 2022-02-05 18:06:35 +08:00
Tim-Paik ed51c5e264 fix config dir 2022-02-05 18:05:04 +08:00
Tim-Paik b4cb7da6ad add windows icon 2022-02-04 01:08:15 +08:00
Tim-Paik 9be31e0968 fixed user data dir 2022-02-04 00:03:50 +08:00
Tim-Paik 4cdfccef05 added readme 2022-02-03 00:38:11 +08:00
Tim-Paik 37d1a057fc fixed windows error 2022-02-01 19:48:42 +08:00
Tim-Paik 449fb69d75 bundler ready 2022-01-31 17:35:36 +08:00
Tim-Paik 6a9dbb4a19 runner with window size 2022-01-30 13:04:26 +08:00
Tim-Paik 1a94a55cf1 update runner 2022-01-29 22:06:03 +08:00
Tim-Paik 2b0084adf6 added config 2022-01-28 00:59:12 +08:00
Tim-Paik 561e19e732 first commit 2022-01-27 01:02:17 +08:00
14 changed files with 909 additions and 1455 deletions
-50
View File
@@ -1,50 +0,0 @@
kind: pipeline
type: docker
name: build
steps:
- name: build
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 -y
- echo '========Compile the Neutauri binary========'
- $HOME/.cargo/bin/cargo build --release --bin neutauri_runtime
- $HOME/.cargo/bin/cargo build --release --bin neutauri_bundler
- name: gitea_release
image: plugins/gitea-release
settings:
api_key:
from_secret: gitea_token
base_url: https://git.186526.xyz
files:
- ./target/release/neutauri_bundler
checksum:
- md5
- sha256
when:
event:
- 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
+590 -1062
View File
File diff suppressed because it is too large Load Diff
+3 -5
View File
@@ -2,10 +2,8 @@
members = [ members = [
"neutauri_runtime", "neutauri_runtime",
"neutauri_bundler", "neutauri_bundler",
"neutauri_data",
] ]
[profile.release] [neutauri_bundler.profile.release.package.wry]
lto = true debug = true
strip = true debug-assertions = true
opt-level = "z"
+4 -16
View File
@@ -4,23 +4,11 @@ name = "neutauri_bundler"
version = "0.1.0" version = "0.1.0"
[dependencies] [dependencies]
anyhow = "1.0" bincode = "1.3"
brotli = "3.3"
gumdrop = "0.8" gumdrop = "0.8"
inquire = "0.2" image = "0.23"
neutauri_data = {path = "../neutauri_data", features = ["bundler"]}
new_mime_guess = "4.0" new_mime_guess = "4.0"
serde = {version = "1.0", features = ["derive"]} serde = {version = "1.0", features = ["derive"]}
toml = "0.5" toml = "0.5"
wry = {version = "0.20", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen", "devtools"]} wry = "0.12"
[target.'cfg(windows)'.dependencies]
rcedit = {git = "https://github.com/Tim-Paik/rcedit-rs.git", rev = "2805fca"}
[target.'cfg(windows)'.build-dependencies]
winres = "0.1"
[package.metadata.winres]
FileDescription = "Neutauri Bundler"
LegalCopyright = "@2022 Neutauri Developers"
OriginalFilename = ""
ProductName = "Neutauri"
-12
View File
@@ -1,12 +0,0 @@
#[cfg(windows)]
extern crate winres;
#[cfg(windows)]
fn main() {
let mut res = winres::WindowsResource::new();
res.set_icon("../neutauri_runtime/wry.ico");
res.compile().unwrap();
}
#[cfg(unix)]
fn main() {}
+10 -57
View File
@@ -1,12 +1,11 @@
use anyhow::Context; use crate::data;
use neutauri_data as data;
#[cfg(windows)]
use std::{
env,
hash::{Hash, Hasher},
};
use std::{fs, io::Write}; use std::{fs, io::Write};
#[cfg(windows)]
const RUNTIME_DATA: &[u8] = include_bytes!("../../target/release/neutauri_runtime.exe");
#[cfg(not(windows))]
const RUNTIME_DATA: &[u8] = include_bytes!("../../target/release/neutauri_runtime");
fn options() -> fs::OpenOptions { fn options() -> fs::OpenOptions {
#[cfg(not(windows))] #[cfg(not(windows))]
use std::os::unix::prelude::OpenOptionsExt; use std::os::unix::prelude::OpenOptionsExt;
@@ -19,55 +18,10 @@ fn options() -> fs::OpenOptions {
options options
} }
#[cfg(not(windows))] pub fn bundle(config_path: String) -> std::io::Result<()> {
fn get_runtime_data( let config_path = std::path::Path::new(&config_path).canonicalize()?;
_icon_path: Option<std::path::PathBuf>,
_manifest_path: Option<std::path::PathBuf>,
) -> anyhow::Result<Vec<u8>> {
Ok(include_bytes!("../../target/release/neutauri_runtime").to_vec())
}
#[cfg(windows)]
fn get_runtime_data(
icon_path: Option<std::path::PathBuf>,
manifest_path: Option<std::path::PathBuf>,
) -> anyhow::Result<Vec<u8>> {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(b"neutauri_runtime");
std::time::SystemTime::now().hash(&mut hasher);
let temp_path = env::temp_dir().join(format!("{:x}.exe", hasher.finish()));
fs::write(
&temp_path,
include_bytes!("../../target/release/neutauri_runtime.exe"),
)?;
let mut updater = rcedit::ResourceUpdater::new();
updater.load(&temp_path)?;
if let Some(icon_path) = icon_path {
println!("{:?}", fs::canonicalize(&icon_path)?);
updater.set_icon(&fs::canonicalize(icon_path)?)?;
}
if let Some(manifest_path) = manifest_path {
updater.set_application_manifest(&fs::canonicalize(manifest_path)?)?;
}
updater.commit()?;
drop(updater);
let runtime_data =
fs::read(&temp_path).with_context(|| format!("Failed to read {}", temp_path.display()))?;
fs::remove_file(&temp_path)?;
Ok(runtime_data)
}
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()) let config: data::Config = toml::from_str(fs::read_to_string(&config_path)?.as_str())
.with_context(|| "toml parsing error")?; .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
let source = match config_path.parent() { let source = match config_path.parent() {
Some(path) => path.join(&config.source).canonicalize()?, Some(path) => path.join(&config.source).canonicalize()?,
None => config.source.canonicalize()?, None => config.source.canonicalize()?,
@@ -76,7 +30,6 @@ pub(crate) fn bundle(config_path: String) -> anyhow::Result<()> {
Some(path) => data::normalize_path(&path.join(&config.target)), Some(path) => data::normalize_path(&path.join(&config.target)),
None => data::normalize_path(&config.target), 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() == None && cfg!(windows) {
target.with_extension("exe") target.with_extension("exe")
} else { } else {
@@ -88,7 +41,7 @@ pub(crate) fn bundle(config_path: String) -> anyhow::Result<()> {
} }
let data = data::Data::build_from_dir(source, config.window_attr()?, config.webview_attr()?)?; let data = data::Data::build_from_dir(source, config.window_attr()?, config.webview_attr()?)?;
let mut f = options().open(&target)?; let mut f = options().open(&target)?;
f.write_all(&get_runtime_data(config.icon, config.manifest)?)?; f.write_all(RUNTIME_DATA)?;
f.write_all(&data)?; f.write_all(&data)?;
f.sync_all()?; f.sync_all()?;
f.flush()?; f.flush()?;
@@ -2,7 +2,7 @@ use bincode::Options;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
fs, fs,
io::{self, Read, Result, SeekFrom, Seek}, io::{self, Read, Result},
path::{self, Component, Path, PathBuf}, path::{self, Component, Path, PathBuf},
}; };
use wry::application::dpi::Position; use wry::application::dpi::Position;
@@ -62,12 +62,11 @@ pub struct Config {
pub transparent: bool, pub transparent: bool,
pub decorations: bool, pub decorations: bool,
pub always_on_top: bool, pub always_on_top: bool,
pub icon: Option<PathBuf>, pub window_icon: Option<PathBuf>,
pub spa: bool, pub spa: bool,
pub url: Option<String>, pub url: Option<String>,
pub html: Option<PathBuf>, pub html: Option<PathBuf>,
pub initialization_script: Option<PathBuf>, pub initialization_script: Option<String>,
pub manifest: Option<PathBuf>,
} }
#[derive(Serialize, Deserialize, Clone, Debug, Default)] #[derive(Serialize, Deserialize, Clone, Debug, Default)]
@@ -91,7 +90,7 @@ pub struct WindowAttr {
pub transparent: bool, pub transparent: bool,
pub decorations: bool, pub decorations: bool,
pub always_on_top: bool, pub always_on_top: bool,
pub icon: Option<Icon>, pub window_icon: Option<Icon>,
} }
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
@@ -104,102 +103,6 @@ pub struct WebViewAttr {
pub initialization_script: Option<String>, 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(&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())
}
}
#[cfg(feature = "bundler")]
impl Dir { impl Dir {
// 使用本地文件系统填充 Dir 结构体 // 使用本地文件系统填充 Dir 结构体
fn fill_with<P: AsRef<path::Path>>( fn fill_with<P: AsRef<path::Path>>(
@@ -251,7 +154,6 @@ impl Dir {
} }
} }
#[cfg(feature = "bundler")]
impl Data { impl Data {
pub fn build_from_dir<P: AsRef<path::Path>>( pub fn build_from_dir<P: AsRef<path::Path>>(
source: P, source: P,
@@ -326,7 +228,6 @@ impl Data {
} }
} }
#[cfg(feature = "bundler")]
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -343,17 +244,15 @@ impl Default for Config {
transparent: false, transparent: false,
decorations: true, decorations: true,
always_on_top: false, always_on_top: false,
icon: None, window_icon: None,
spa: false, spa: false,
url: Some("/index.html".into()), url: Some("/index.html".into()),
html: None, html: None,
initialization_script: None, initialization_script: Some("".into()),
manifest: None,
} }
} }
} }
#[cfg(feature = "bundler")]
impl Config { impl Config {
pub fn window_attr(&self) -> Result<WindowAttr> { pub fn window_attr(&self) -> Result<WindowAttr> {
Ok(WindowAttr { Ok(WindowAttr {
@@ -369,7 +268,7 @@ impl Config {
transparent: self.transparent, transparent: self.transparent,
decorations: self.decorations, decorations: self.decorations,
always_on_top: self.always_on_top, always_on_top: self.always_on_top,
icon: match &self.icon { window_icon: match &self.window_icon {
Some(path) => Some(load_icon(path.as_path())?), Some(path) => Some(load_icon(path.as_path())?),
None => None, None => None,
}, },
@@ -385,25 +284,15 @@ impl Config {
Some(path) => fs::read_to_string(path.as_path()).ok(), Some(path) => fs::read_to_string(path.as_path()).ok(),
None => None, None => None,
}, },
initialization_script: match &self.initialization_script { initialization_script: self.initialization_script.clone(),
Some(path) => fs::read_to_string(path.as_path()).ok(),
None => None,
},
}) })
} }
} }
#[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<()> { pub fn pack<P: AsRef<path::Path>>(config: P) -> Result<()> {
Data::pack(config) Data::pack(config)
} }
#[cfg(feature = "bundler")]
fn load_icon(path: &Path) -> Result<Icon> { fn load_icon(path: &Path) -> Result<Icon> {
let image = image::open(path) let image = image::open(path)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))? .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
+21 -26
View File
@@ -1,6 +1,5 @@
use anyhow::{Context, Result};
use neutauri_data as data;
use std::{fs, io::Read, path::PathBuf}; use std::{fs, io::Read, path::PathBuf};
use wry::{ use wry::{
application::{ application::{
dpi::{PhysicalSize, Size}, dpi::{PhysicalSize, Size},
@@ -8,9 +7,11 @@ use wry::{
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
window::{Fullscreen, Icon, Window, WindowBuilder}, window::{Fullscreen, Icon, Window, WindowBuilder},
}, },
webview::{WebContext, WebViewBuilder}, webview::{RpcRequest, WebContext, WebViewBuilder},
}; };
use crate::data;
const PROTOCOL_PREFIX: &str = "{PROTOCOL}://"; const PROTOCOL_PREFIX: &str = "{PROTOCOL}://";
const PROTOCOL: &str = "dev"; const PROTOCOL: &str = "dev";
@@ -30,18 +31,11 @@ fn custom_protocol_uri_to_path<T: Into<String>>(protocol: T, uri: T) -> wry::Res
} }
} }
pub(crate) fn dev(config_path: String) -> Result<()> { pub fn dev(config_path: String) -> wry::Result<()> {
let config_path = std::path::Path::new(&config_path) let config_path = std::path::Path::new(&config_path).canonicalize()?;
.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()) let config: data::Config = toml::from_str(fs::read_to_string(&config_path)?.as_str())
.with_context(|| "toml parsing error")?; .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
let source = config.source.canonicalize()?; let source = config.source.clone().canonicalize()?;
let event_loop = EventLoop::new(); let event_loop = EventLoop::new();
@@ -49,7 +43,7 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
.with_always_on_top(config.window_attr()?.always_on_top) .with_always_on_top(config.window_attr()?.always_on_top)
.with_decorations(config.window_attr()?.decorations) .with_decorations(config.window_attr()?.decorations)
.with_resizable(config.window_attr()?.resizable) .with_resizable(config.window_attr()?.resizable)
.with_title(config.window_attr()?.title) .with_title(config.window_attr()?.title.clone())
.with_maximized(config.window_attr()?.maximized) .with_maximized(config.window_attr()?.maximized)
.with_transparent(config.window_attr()?.transparent) .with_transparent(config.window_attr()?.transparent)
.with_visible(config.window_attr()?.visible); .with_visible(config.window_attr()?.visible);
@@ -57,7 +51,7 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
true => window_builder.with_fullscreen(Some(Fullscreen::Borderless(None))), true => window_builder.with_fullscreen(Some(Fullscreen::Borderless(None))),
false => window_builder, false => window_builder,
}; };
let window_builder = match config.window_attr()?.icon { let window_builder = match config.window_attr()?.window_icon {
Some(ref icon) => window_builder.with_window_icon(Some(Icon::from_rgba( Some(ref icon) => window_builder.with_window_icon(Some(Icon::from_rgba(
icon.rgba.clone(), icon.rgba.clone(),
icon.width, icon.width,
@@ -89,7 +83,7 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
let window = window_builder.build(&event_loop)?; let window = window_builder.build(&event_loop)?;
let webview_builder = WebViewBuilder::new(window)?; let webview_builder = WebViewBuilder::new(window)?;
let url = config.webview_attr()?.url; let url = config.webview_attr()?.url.clone();
let webview_builder = match url { let webview_builder = match url {
Some(url) => { Some(url) => {
if url.starts_with('/') { if url.starts_with('/') {
@@ -100,12 +94,12 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
} }
None => webview_builder.with_url(&custom_protocol_uri(PROTOCOL, "/index.html"))?, None => webview_builder.with_url(&custom_protocol_uri(PROTOCOL, "/index.html"))?,
}; };
let html = config.webview_attr()?.html; let html = config.webview_attr()?.html.clone();
let webview_builder = match html { let webview_builder = match html {
Some(html) => webview_builder.with_html(&html)?, Some(html) => webview_builder.with_html(&html)?,
None => webview_builder, None => webview_builder,
}; };
let initialization_script = config.webview_attr()?.initialization_script; let initialization_script = config.webview_attr()?.initialization_script.clone();
let webview_builder = match initialization_script { let webview_builder = match initialization_script {
Some(script) => webview_builder.with_initialization_script(&script), Some(script) => webview_builder.with_initialization_script(&script),
None => webview_builder, None => webview_builder,
@@ -115,7 +109,7 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
false => webview_builder false => webview_builder
.with_visible(false) .with_visible(false)
.with_initialization_script( .with_initialization_script(
r#"window.addEventListener('load', function(event) { window.ipc.postMessage('show_window'); });"#, r#"window.addEventListener('load', function(event) { rpc.call('show_window'); });"#,
), ),
}; };
let path = std::env::current_exe()?; let path = std::env::current_exe()?;
@@ -148,14 +142,13 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
WebContext::new(None) WebContext::new(None)
}; };
let webview = webview_builder let webview = webview_builder
.with_clipboard(true)
.with_visible(config.window_attr()?.visible) .with_visible(config.window_attr()?.visible)
.with_transparent(config.window_attr()?.transparent) .with_transparent(config.window_attr()?.transparent)
.with_web_context(&mut web_context) .with_web_context(&mut web_context)
.with_custom_protocol(PROTOCOL.to_string(), move |request| { .with_custom_protocol(PROTOCOL.to_string(), move |request| {
let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?; let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?;
let mut local_path = source.clone(); let mut local_path = source.clone();
local_path.push(path.strip_prefix('/').unwrap_or(&path)); local_path.push(path.strip_prefix("/").unwrap_or_else(|| &path));
let mut data = Vec::new(); let mut data = Vec::new();
let mut mime: String = "application/octet-stream".to_string(); let mut mime: String = "application/octet-stream".to_string();
match fs::File::open(&local_path) { match fs::File::open(&local_path) {
@@ -179,14 +172,14 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
} }
wry::http::ResponseBuilder::new().mimetype(&mime).body(data) wry::http::ResponseBuilder::new().mimetype(&mime).body(data)
}) })
.with_ipc_handler(|window: &Window, req: String| { .with_rpc_handler(|window: &Window, req: RpcRequest| {
match req.as_str() { match req.method.as_str() {
"show_window" => window.set_visible(true), "show_window" => window.set_visible(true),
"ping" => println!("recived a ping"), "ping" => println!("recived a ping"),
_ => (), _ => (),
}; };
None
}) })
.with_devtools(true)
.build()?; .build()?;
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
@@ -198,7 +191,9 @@ pub(crate) fn dev(config_path: String) -> Result<()> {
event: WindowEvent::CloseRequested, event: WindowEvent::CloseRequested,
.. ..
} => *control_flow = ControlFlow::Exit, } => *control_flow = ControlFlow::Exit,
_ => (), _ => {
let _ = webview.resize();
}
} }
}); });
} }
-45
View File
@@ -1,45 +0,0 @@
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(())
}
+5 -24
View File
@@ -1,7 +1,8 @@
use gumdrop::Options; use gumdrop::Options;
mod bundle; mod bundle;
mod dev; mod dev;
mod init; mod data;
#[derive(Debug, Options)] #[derive(Debug, Options)]
struct Args { struct Args {
@@ -20,8 +21,6 @@ enum Command {
Bundle(BundleOpts), Bundle(BundleOpts),
#[options(help = "run the project in the current directory in development mode")] #[options(help = "run the project in the current directory in development mode")]
Dev(DevOpts), Dev(DevOpts),
#[options(help = "initialize a neutauri project")]
Init(InitOpts),
} }
#[derive(Debug, Clone, Options)] #[derive(Debug, Clone, Options)]
@@ -40,12 +39,6 @@ struct DevOpts {
config: Option<String>, config: Option<String>,
} }
#[derive(Debug, Clone, Options)]
struct InitOpts {
#[options(help = "print help information")]
help: bool,
}
fn print_help_and_exit(args: Args) { fn print_help_and_exit(args: Args) {
if args.command.is_some() { if args.command.is_some() {
Args::parse_args_default_or_exit(); Args::parse_args_default_or_exit();
@@ -55,7 +48,7 @@ fn print_help_and_exit(args: Args) {
"Usage: {:?} [SUBCOMMAND] [OPTIONS]", "Usage: {:?} [SUBCOMMAND] [OPTIONS]",
std::env::args() std::env::args()
.into_iter() .into_iter()
.next() .nth(0)
.unwrap_or_else(|| "neutauri_bundler".to_string()) .unwrap_or_else(|| "neutauri_bundler".to_string())
); );
eprintln!(); eprintln!();
@@ -66,7 +59,7 @@ fn print_help_and_exit(args: Args) {
std::process::exit(0); std::process::exit(0);
} }
fn main() -> anyhow::Result<()> { fn main() -> wry::Result<()> {
let args = std::env::args().collect::<Vec<_>>(); let args = std::env::args().collect::<Vec<_>>();
let args = Args::parse_args(&args[1..], gumdrop::ParsingStyle::default()).unwrap_or_else(|e| { let args = Args::parse_args(&args[1..], gumdrop::ParsingStyle::default()).unwrap_or_else(|e| {
eprintln!("{}: {}", args[0], e); eprintln!("{}: {}", args[0], e);
@@ -76,8 +69,6 @@ fn main() -> anyhow::Result<()> {
Some(command) => match command { Some(command) => match command {
Command::Bundle(opts) => { Command::Bundle(opts) => {
if opts.help_requested() { if opts.help_requested() {
eprintln!("Package according to the configuration in neutauri.toml");
eprintln!();
print_help_and_exit(args); print_help_and_exit(args);
} }
let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string()); let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string());
@@ -85,21 +76,11 @@ fn main() -> anyhow::Result<()> {
} }
Command::Dev(opts) => { Command::Dev(opts) => {
if opts.help_requested() { if opts.help_requested() {
eprintln!("Check the configuration in neutauri.toml and start directly");
eprintln!();
print_help_and_exit(args); print_help_and_exit(args);
} }
let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string()); let config_path = opts.config.unwrap_or_else(|| "neutauri.toml".to_string());
dev::dev(config_path)?; 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), None => print_help_and_exit(args),
} }
-17
View File
@@ -1,17 +0,0 @@
[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.20", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen"]}
[features]
bundler = ["new_mime_guess", "toml", "image"]
runtime = []
+4 -10
View File
@@ -4,16 +4,10 @@ name = "neutauri_runtime"
version = "0.1.0" version = "0.1.0"
[dependencies] [dependencies]
neutauri_data = {path = "../neutauri_data", features = ["runtime"]} bincode = "1.3"
wry = {version = "0.20", default-features = false, features = ["protocol", "tray", "transparent", "fullscreen"]} brotli = "3.3"
serde = {version = "1.0", features = ["derive"]}
wry = "0.12"
[target.'cfg(windows)'.build-dependencies] [target.'cfg(windows)'.build-dependencies]
winres = "0.1" winres = "0.1"
[package.metadata.winres]
FileDescription = ""
FileVersion = ""
LegalCopyright = ""
OriginalFilename = ""
ProductName = ""
ProductVersion = ""
+253
View File
@@ -0,0 +1,253 @@
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 window_icon: Option<PathBuf>,
pub spa: bool,
pub url: Option<String>,
pub html: Option<PathBuf>,
pub initialization_script: Option<String>,
}
#[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 window_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,
window_icon: None,
spa: false,
url: Some("/index.html".into()),
html: None,
initialization_script: Some("".into()),
}
}
}
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
}
+11 -12
View File
@@ -1,7 +1,7 @@
#![windows_subsystem = "windows"] #![windows_subsystem = "windows"]
use neutauri_data as data;
use std::path::PathBuf; use std::path::PathBuf;
use wry::{ use wry::{
application::{ application::{
dpi::{PhysicalSize, Size}, dpi::{PhysicalSize, Size},
@@ -9,8 +9,9 @@ use wry::{
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
window::{Fullscreen, Icon, Window, WindowBuilder}, window::{Fullscreen, Icon, Window, WindowBuilder},
}, },
webview::{WebContext, WebViewBuilder}, webview::{RpcRequest, WebContext, WebViewBuilder},
}; };
mod data;
const PROTOCOL_PREFIX: &str = "{PROTOCOL}://"; const PROTOCOL_PREFIX: &str = "{PROTOCOL}://";
const PROTOCOL: &str = "neu"; const PROTOCOL: &str = "neu";
@@ -50,7 +51,7 @@ fn main() -> wry::Result<()> {
true => window_builder.with_fullscreen(Some(Fullscreen::Borderless(None))), true => window_builder.with_fullscreen(Some(Fullscreen::Borderless(None))),
false => window_builder, false => window_builder,
}; };
let window_builder = match res.window_attr.icon { let window_builder = match res.window_attr.window_icon {
Some(ref icon) => window_builder.with_window_icon(Some(Icon::from_rgba( Some(ref icon) => window_builder.with_window_icon(Some(Icon::from_rgba(
icon.rgba.clone(), icon.rgba.clone(),
icon.width, icon.width,
@@ -108,7 +109,7 @@ fn main() -> wry::Result<()> {
false => webview_builder false => webview_builder
.with_visible(false) .with_visible(false)
.with_initialization_script( .with_initialization_script(
r#"window.addEventListener('load', function(event) { window.ipc.postMessage('show_window'); });"#, r#"window.addEventListener('load', function(event) { rpc.call('show_window'); });"#,
), ),
}; };
let path = std::env::current_exe()?; let path = std::env::current_exe()?;
@@ -141,13 +142,9 @@ fn main() -> wry::Result<()> {
WebContext::new(None) WebContext::new(None)
}; };
let webview = webview_builder let webview = webview_builder
.with_clipboard(true)
.with_visible(res.window_attr.visible) .with_visible(res.window_attr.visible)
.with_transparent(res.window_attr.transparent) .with_transparent(res.window_attr.transparent)
.with_web_context(&mut web_context) .with_web_context(&mut web_context)
.with_initialization_script(
r#"window.oncontextmenu = (event) => { event.preventDefault(); }"#,
)
.with_custom_protocol(PROTOCOL.to_string(), move |request| { .with_custom_protocol(PROTOCOL.to_string(), move |request| {
let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?; let path = custom_protocol_uri_to_path(PROTOCOL, request.uri())?;
let mut file = match res.open(path) { let mut file = match res.open(path) {
@@ -164,14 +161,14 @@ fn main() -> wry::Result<()> {
.mimetype(&file.mimetype()) .mimetype(&file.mimetype())
.body(file.decompressed_data()?) .body(file.decompressed_data()?)
}) })
.with_ipc_handler(|window: &Window, req: String| { .with_rpc_handler(|window: &Window, req: RpcRequest| {
match req.as_str() { match req.method.as_str() {
"show_window" => window.set_visible(true), "show_window" => window.set_visible(true),
"ping" => println!("recived a ping"), "ping" => println!("recived a ping"),
_ => (), _ => (),
}; };
None
}) })
.with_devtools(false)
.build()?; .build()?;
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
@@ -183,7 +180,9 @@ fn main() -> wry::Result<()> {
event: WindowEvent::CloseRequested, event: WindowEvent::CloseRequested,
.. ..
} => *control_flow = ControlFlow::Exit, } => *control_flow = ControlFlow::Exit,
_ => (), _ => {
let _ = webview.resize();
}
} }
}); });
} }