Skip to content

Commit

Permalink
Merge pull request #198 from greenhat616/fix-issues
Browse files Browse the repository at this point in the history
fix: issues
  • Loading branch information
keiko233 authored Dec 29, 2023
2 parents 333560a + 46071c6 commit aebaa5c
Show file tree
Hide file tree
Showing 13 changed files with 144 additions and 64 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,13 @@ jobs:
- name: Set Env
run: |
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
echo "CURRENT_GIT_SHA=$(git rev-parse HEAD)" >> $GITHUB_ENV
shell: bash
- name: Update Tag
uses: richardsimko/update-tag@v1.0.11
uses: greenhat616/update-tag@v1
with:
tag_name: pre-release
ref: dev
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: |
Expand Down
4 changes: 2 additions & 2 deletions backend/tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json", "rustls-tls"] }
tauri = { version = "1.5.3", features = [
"updater",
"os-all",
"global-shortcut-all",
"notification-all",
"process-all",
"shell-all",
"system-tray",
"updater",
"window-all",
] }
window-vibrancy = { version = "0.4.3" }
Expand All @@ -64,9 +64,9 @@ rs-snowflake = "0.6"
rocksdb = "0.21"
thiserror = { workspace = true, version = "1.0" }
simd-json = "0.13.4"
runas = "=1.0.0" # blocked by https://github.com/mitsuhiko/rust-runas/issues/13

[target.'cfg(windows)'.dependencies]
runas = "=1.0.0" # blocked by https://github.com/mitsuhiko/rust-runas/issues/13
deelevate = "0.2.0"
winreg = { version = "0.50", features = ["transactions"] }
windows-sys = { version = "0.48", features = [
Expand Down
4 changes: 2 additions & 2 deletions backend/tauri/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
}

#[tauri::command]
pub fn view_profile(index: String) -> CmdResult {
pub fn view_profile(app_handle: tauri::AppHandle, index: String) -> CmdResult {
let file = {
wrap_err!(Config::profiles().latest().get_item(&index))?
.file
Expand All @@ -106,7 +106,7 @@ pub fn view_profile(index: String) -> CmdResult {
ret_err!("the file not found");
}

wrap_err!(help::open_file(path))
wrap_err!(help::open_file(app_handle, path))
}

#[tauri::command]
Expand Down
99 changes: 74 additions & 25 deletions backend/tauri/src/core/updater.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use std::{collections::HashMap, io::Cursor, path::Path, sync::OnceLock};

use super::CoreManager;
use crate::config::ClashCore;
use anyhow::{anyhow, Result};
use gunzip::Decompressor;
use log::debug;
use serde::{de, Deserialize, Serialize};
use log::{debug, warn};
use runas::Command as RunasCommand;
use serde::{Deserialize, Serialize};
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
use tempfile::{tempdir, TempDir};
use tokio::{join, sync::RwLock, task::spawn_blocking};
use zip::ZipArchive;

use super::CoreManager;

pub struct Updater {
manifest_version: ManifestVersion,
mirror: String,
Expand Down Expand Up @@ -123,14 +123,15 @@ impl Updater {
self.mirror.as_str(),
"MetaCubeX/mihomo/releases/download/Prerelease-Alpha/version.txt"
);
Ok(client
.get(url)
.send()
.await?
.text()
.await?
.trim()
.to_string())
let res = client.get(url).send().await?;
let status_code = res.status();
if !status_code.is_success() {
anyhow::bail!(
"failed to get mihomo alpha version: response status is {}, expected 200",
status_code
);
}
Ok(res.text().await?.trim().to_string())
}

pub async fn update_core(&self, core_type: &ClashCore) -> Result<()> {
Expand All @@ -154,7 +155,7 @@ impl Updater {
.await??;
// 3. if core is used, close it
if current_core == *core_type {
CoreManager::global().stop_core()?;
tokio::task::spawn_blocking(move || CoreManager::global().stop_core()).await??;
}
// 4. replace core
#[cfg(target_os = "windows")]
Expand All @@ -165,10 +166,47 @@ impl Updater {
let core_dir = core_dir.parent().ok_or(anyhow!("failed to get core dir"))?;
let target_core = core_dir.join(target_core);
debug!("copying core to {:?}", target_core);
std::fs::copy(
tmp_dir.path().join(core_type.clone().to_string()),
target_core,
)?;
let tmp_core_path = tmp_dir.path().join(core_type.clone().to_string());
match std::fs::copy(tmp_core_path.clone(), target_core.clone()) {
Ok(_) => {}
Err(err) => {
warn!(
"failed to copy core: {}, trying to use elevated permission to copy and override core",
err
);
let mut target_core_str = target_core.to_str().unwrap().to_string();
if target_core_str.starts_with("\\\\?\\") {
target_core_str = target_core_str[4..].to_string();
}
debug!("tmp core path: {:?}", tmp_core_path);
debug!("target core path: {:?}", target_core_str);
// 防止 UAC 弹窗堵塞主线程
let status_code = tokio::task::spawn_blocking(move || {
#[cfg(target_os = "windows")]
{
RunasCommand::new("cmd")
.args(&[
"/C",
"copy",
"/Y",
tmp_core_path.to_str().unwrap(),
&target_core_str,
])
.status()
}
#[cfg(not(target_os = "windows"))]
{
RunasCommand::new("cp")
.args(&["-f", tmp_core_path.to_str().unwrap(), &target_core_str])
.status()
}
})
.await??;
if !status_code.success() {
anyhow::bail!("failed to copy core: {}", status_code);
}
}
};

// 5. if core is used before, restart it
if current_core == *core_type {
Expand Down Expand Up @@ -235,7 +273,15 @@ impl Updater {
let mut dst = std::fs::File::create(&file_path)?;

let client = reqwest::Client::new();
let mut buff = Cursor::new(client.get(url).send().await?.bytes().await?);
let res = client.get(url).send().await?;
let status_code = res.status();
if !status_code.is_success() {
anyhow::bail!(
"failed to download core: response status is {}, expected 200",
status_code
);
}
let mut buff = Cursor::new(res.bytes().await?);
std::io::copy(&mut buff, &mut dst)?;
Ok(artifact)
}
Expand Down Expand Up @@ -284,7 +330,7 @@ fn decompress_and_set_permission(
};
let tmp_core = tmp_path.join(core_type.clone().to_string());
debug!("writing core to {:?} ({} bytes)", tmp_core, buff.len());
let mut core_file = std::fs::File::create(tmp_core.to_owned())?;
let mut core_file = std::fs::File::create(&tmp_core)?;
std::io::copy(&mut buff.as_slice(), &mut core_file)?;
#[cfg(target_family = "unix")]
{
Expand All @@ -300,12 +346,15 @@ pub async fn get_latest_version_manifest(mirror: &str) -> Result<ManifestVersion
);
log::debug!("{}", url);
let client = reqwest::Client::new();
Ok(client
.get(url)
.send()
.await?
.json::<ManifestVersion>()
.await?)
let res = client.get(url).send().await?;
let status_code = res.status();
if !status_code.is_success() {
anyhow::bail!(
"failed to get latest version manifest: response status is {}, expected 200",
status_code
);
}
Ok(res.json::<ManifestVersion>().await?)
}

enum CoreTypeMeta {
Expand Down
5 changes: 4 additions & 1 deletion backend/tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ fn main() -> std::io::Result<()> {
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.system_tray(SystemTray::new())
.setup(|app| Ok(resolve::resolve_setup(app)))
.setup(|app| {
resolve::resolve_setup(app);
Ok(())
})
.on_system_tray_event(core::tray::Tray::on_system_tray_event)
.invoke_handler(tauri::generate_handler![
// common
Expand Down
21 changes: 13 additions & 8 deletions backend/tauri/src/utils/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ use nanoid::nanoid;
use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::{Mapping, Value};
use std::{fs, path::PathBuf, str::FromStr};

use tauri::{
api::shell::{open, Program},
Manager,
};
/// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
if !path.exists() {
Expand Down Expand Up @@ -81,18 +84,20 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {

/// open file
/// use vscode by default
pub fn open_file(path: PathBuf) -> Result<()> {
pub fn open_file(app: tauri::AppHandle, path: PathBuf) -> Result<()> {
#[cfg(target_os = "macos")]
let code = "Visual Studio Code";
#[cfg(not(target_os = "macos"))]
let code = "code";

// use vscode first
if let Err(err) = open::with(&path, code) {
log::error!(target: "app", "failed to open file with VScode `{err}`");
// default open
open::that(path)?;
}
let _ = match Program::from_str(code) {
Ok(code) => open(&app.shell_scope(), &path.to_string_lossy(), Some(code)),
Err(err) => {
log::error!(target: "app", "Can't find VScode `{err}`");
// default open
open(&app.shell_scope(), &path.to_string_lossy(), None)
}
};

Ok(())
}
Expand Down
31 changes: 15 additions & 16 deletions backend/tauri/src/utils/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,6 @@ pub fn create_window(app_handle: &AppHandle) {

#[cfg(target_os = "windows")]
{
use std::time::Duration;
use tokio::time::sleep;
use window_shadows::set_shadow;

match builder
Expand All @@ -161,6 +159,7 @@ pub fn create_window(app_handle: &AppHandle) {
trace_err!(win.set_fullscreen(true), "set win fullscreen");
}
}
trace_err!(set_shadow(&win, true), "set win shadow");
log::trace!("try to calculate the monitor size");
let center = (|| -> Result<bool> {
let mut center = false;
Expand All @@ -182,22 +181,22 @@ pub fn create_window(app_handle: &AppHandle) {
trace_err!(win.center(), "set win center");
}

log::trace!("try to create window");
let app_handle = app_handle.clone();
// log::trace!("try to create window");
// let app_handle = app_handle.clone();

// 加点延迟避免界面闪一下
tauri::async_runtime::spawn(async move {
// sleep(Duration::from_millis(888)).await;

if let Some(window) = app_handle.get_window("main") {
trace_err!(set_shadow(&window, true), "set win shadow");
trace_err!(window.show(), "set win visible");
trace_err!(window.unminimize(), "set win unminimize");
trace_err!(window.set_focus(), "set win focus");
} else {
log::error!(target: "app", "failed to create window, get_window is None")
}
});
// tauri::async_runtime::spawn(async move {
// // sleep(Duration::from_millis(888)).await;

// if let Some(window) = app_handle.get_window("main") {
// trace_err!(set_shadow(&window, true), "set win shadow");
// trace_err!(window.show(), "set win visible");
// trace_err!(window.unminimize(), "set win unminimize");
// trace_err!(window.set_focus(), "set win focus");
// } else {
// log::error!(target: "app", "failed to create window, get_window is None")
// }
// });
}
Err(err) => log::error!(target: "app", "failed to create window, {err}"),
}
Expand Down
3 changes: 1 addition & 2 deletions scripts/generate-latest-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ const resolveMihomoAlpha: LatestVersionResolver = async () => {

const archMapping: ArchMapping = {
// [SupportedArch.WindowsX86]: "mihomo-windows-386-{}.zip",
[SupportedArch.WindowsX86_64]:
"mihomo-windows-amd64-compatible-alpha-{}.zip",
[SupportedArch.WindowsX86_64]: "mihomo-windows-amd64-compatible-{}.zip",
// [SupportedArch.WindowsAarch64]: "mihomo-windows-arm64-{}.zip",
[SupportedArch.LinuxAarch64]: "mihomo-linux-arm64-{}.gz",
[SupportedArch.LinuxAmd64]: "mihomo-linux-amd64-compatible-{}.gz",
Expand Down
10 changes: 8 additions & 2 deletions src/components/log/log-item.module.scss
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.item {
/* stylelint-disable-next-line selector-pseudo-class-no-unknown */
:global(.shiki) {
margin-top: 0.25em;
margin-bottom: 0;
Expand All @@ -10,8 +9,15 @@
}

span {
color: var(--shiki-dark) !important;
white-space: normal;
}
}

&.dark {
:global(.shiki) {
span {
color: var(--shiki-dark) !important;
}
}
}
}
6 changes: 5 additions & 1 deletion src/components/log/log-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ const LogItem = (props: Props) => {
}
>
<span
className={classNames(styles.item, "data")}
className={classNames(
styles.item,
theme.palette.mode === "dark" && styles.dark,
"data",
)}
dangerouslySetInnerHTML={{
__html: payload,
}}
Expand Down
Loading

0 comments on commit aebaa5c

Please sign in to comment.