eweb-tauri 0.1.2

Transform any website into a native desktop/mobile app with Tauri - Ultra lightweight
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use anyhow::{Context, Result};
use clap::Parser;
use serde_json::json;
use std::fs;
use std::path::PathBuf;
use std::process::Command;

#[derive(Parser, Debug)]
#[command(name = "eweb-tauri")]
#[command(author = "neosun100")]
#[command(version = "0.1.2")]
#[command(about = "Transform any website into a native app with Tauri", long_about = None)]
struct Args {
    /// Target URL
    url: String,

    /// App name
    #[arg(short, long)]
    name: Option<String>,

    /// App version (default: 1.0.0)
    #[arg(long, default_value = "1.0.0")]
    app_version: String,

    /// Icon path or URL
    #[arg(short, long)]
    icon: Option<String>,

    /// Output directory
    #[arg(short, long)]
    output: Option<String>,

    /// Target platform (mac, windows, linux, ios, android)
    #[arg(short, long)]
    platform: Option<String>,
}

fn main() -> Result<()> {
    let args = Args::parse();
    
    println!("\n🚀 eweb-tauri - Ultra lightweight cross-platform app builder\n");
    
    let url = if args.url.starts_with("http") {
        args.url.clone()
    } else {
        format!("https://{}", args.url)
    };
    
    let name = args.name.unwrap_or_else(|| infer_name(&url));
    let safe_name = name.chars()
        .filter(|c| c.is_alphanumeric() || *c == '-')
        .collect::<String>()
        .to_lowercase();
    
    let output_dir = args.output.unwrap_or_else(|| ".".to_string());
    let project_dir = PathBuf::from(&output_dir).join(format!("{}-tauri", name));
    
    println!("📦 Building: {}", name);
    println!("🌐 URL: {}", url);
    println!("📁 Output: {}\n", project_dir.display());

    // 创建目录结构
    fs::create_dir_all(project_dir.join("src"))?;
    fs::create_dir_all(project_dir.join("src-tauri/src"))?;
    fs::create_dir_all(project_dir.join("src-tauri/icons"))?;
    fs::create_dir_all(project_dir.join("src-tauri/capabilities"))?;

    // 处理图标
    let icons_dir = project_dir.join("src-tauri/icons");
    if let Some(icon_path) = &args.icon {
        process_icon(icon_path, &icons_dir)?;
    } else {
        println!("⚠️  No icon specified, using default");
        create_default_icons(&icons_dir)?;
    }

    // 创建前端 HTML
    let index_html = format!(r#"<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{}</title>
</head>
<body>
  <script>window.location.href = "{}";</script>
</body>
</html>"#, name, url);
    fs::write(project_dir.join("src/index.html"), index_html)?;

    // 创建 Tauri 配置
    let tauri_config = json!({
        "$schema": "https://schema.tauri.app/config/2",
        "productName": name,
        "version": args.app_version,
        "identifier": format!("com.eweb.{}", safe_name),
        "build": {
            "frontendDist": "../src"
        },
        "app": {
            "windows": [{
                "title": name,
                "width": 1280,
                "height": 800,
                "resizable": true,
                "fullscreen": false,
                "url": url
            }],
            "security": {
                "csp": serde_json::Value::Null
            }
        },
        "bundle": {
            "active": true,
            "targets": "all",
            "icon": [
                "icons/32x32.png",
                "icons/128x128.png",
                "icons/128x128@2x.png",
                "icons/icon.icns",
                "icons/icon.ico"
            ]
        }
    });
    fs::write(
        project_dir.join("src-tauri/tauri.conf.json"),
        serde_json::to_string_pretty(&tauri_config)?
    )?;

    // 创建 Cargo.toml
    let cargo_toml = format!(r#"[package]
name = "{}"
version = "1.0.0"
edition = "2021"

[lib]
crate-type = ["staticlib", "cdylib", "rlib"]

[build-dependencies]
tauri-build = {{ version = "2", features = [] }}

[dependencies]
tauri = {{ version = "2", features = [] }}
tauri-plugin-opener = "2"
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"

[profile.release]
strip = true
lto = true
codegen-units = 1
"#, safe_name);
    fs::write(project_dir.join("src-tauri/Cargo.toml"), cargo_toml)?;

    // 创建 Rust 主文件 + lib.rs
    let main_rs = r#"#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
"#;
    fs::write(project_dir.join("src-tauri/src/main.rs"), main_rs)?;

    // 创建 lib.rs (Android 需要)
    let lib_rs = r#"#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
"#;
    fs::write(project_dir.join("src-tauri/src/lib.rs"), lib_rs)?;

    // 创建 build.rs
    fs::write(project_dir.join("src-tauri/build.rs"), "fn main() { tauri_build::build() }")?;

    // 创建 capabilities
    let capability = json!({
        "$schema": "https://schema.tauri.app/config/2",
        "identifier": "default",
        "description": "Default capability",
        "windows": ["main"],
        "permissions": ["core:default", "opener:default"]
    });
    fs::write(
        project_dir.join("src-tauri/capabilities/default.json"),
        serde_json::to_string_pretty(&capability)?
    )?;

    println!("✅ Project created successfully!");
    println!("\n📁 Project: {}", project_dir.display());

    // 如果指定了平台,尝试构建
    if let Some(platform) = args.platform {
        println!("\n🔨 Building for {}...", platform);
        let src_tauri = project_dir.join("src-tauri");
        
        let result = match platform.as_str() {
            "android" => {
                Command::new("cargo")
                    .args(["tauri", "android", "init"])
                    .current_dir(&src_tauri)
                    .status()
                    .and_then(|_| {
                        Command::new("cargo")
                            .args(["tauri", "android", "build"])
                            .current_dir(&src_tauri)
                            .status()
                    })
            }
            "ios" => {
                Command::new("cargo")
                    .args(["tauri", "ios", "init"])
                    .current_dir(&src_tauri)
                    .status()
                    .and_then(|_| {
                        Command::new("cargo")
                            .args(["tauri", "ios", "build"])
                            .current_dir(&src_tauri)
                            .status()
                    })
            }
            _ => {
                Command::new("cargo")
                    .args(["tauri", "build"])
                    .current_dir(&src_tauri)
                    .status()
            }
        };

        match result {
            Ok(status) if status.success() => {
                println!("\n✅ Build completed!");
                // 重命名构建产物
                rename_build_artifacts(&project_dir, &name, &args.app_version, &platform);
            }
            _ => println!("\n❌ Build failed"),
        }
    } else {
        println!("\n🔨 To build the app:");
        println!("   cd \"{}/src-tauri\"", project_dir.display());
        println!("   cargo tauri build\n");
        println!("📱 Mobile builds:");
        println!("   cargo tauri android init && cargo tauri android build");
        println!("   cargo tauri ios init && cargo tauri ios build\n");
        println!("💡 App size: ~3-10 MB (vs Electron 150+ MB)");
    }

    Ok(())
}

fn infer_name(url: &str) -> String {
    if let Ok(parsed) = url::Url::parse(url) {
        parsed.host_str()
            .unwrap_or("app")
            .replace("www.", "")
            .split('.')
            .next()
            .unwrap_or("app")
            .to_string()
    } else {
        "app".to_string()
    }
}

fn process_icon(icon_path: &str, icons_dir: &PathBuf) -> Result<()> {
    let source_path = if icon_path.starts_with("http") {
        println!("📥 Downloading icon from {}...", icon_path);
        let response = reqwest::blocking::get(icon_path)
            .context("Failed to download icon")?;
        let bytes = response.bytes()?;
        let temp_path = icons_dir.join("source.png");
        fs::write(&temp_path, &bytes)?;
        println!("✅ Icon downloaded");
        temp_path
    } else {
        PathBuf::from(icon_path)
    };

    println!("🎨 Generating icons...");
    
    let img = image::open(&source_path).context("Failed to open icon")?;
    
    // 生成各种尺寸
    let sizes = [(32, "32x32.png"), (128, "128x128.png"), (256, "128x128@2x.png"), (256, "256x256.png"), (512, "512x512.png")];
    
    for (size, filename) in sizes {
        let resized = img.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
        resized.save(icons_dir.join(filename))?;
    }

    // 复制为 ico 和 icns (用 png 格式,Tauri 会处理)
    let icon_256 = img.resize_exact(256, 256, image::imageops::FilterType::Lanczos3);
    icon_256.save(icons_dir.join("icon.png"))?;
    fs::copy(icons_dir.join("icon.png"), icons_dir.join("icon.ico"))?;
    fs::copy(icons_dir.join("icon.png"), icons_dir.join("icon.icns"))?;

    // 清理临时文件
    if source_path.file_name().map(|n| n == "source.png").unwrap_or(false) {
        let _ = fs::remove_file(source_path);
    }

    println!("✅ Icons generated");
    Ok(())
}

fn create_default_icons(icons_dir: &PathBuf) -> Result<()> {
    // 创建简单的占位图标
    let img = image::RgbaImage::new(256, 256);
    let sizes = [(32, "32x32.png"), (128, "128x128.png"), (256, "128x128@2x.png")];
    
    for (size, filename) in sizes {
        let resized = image::imageops::resize(&img, size, size, image::imageops::FilterType::Nearest);
        resized.save(icons_dir.join(filename))?;
    }
    // ico/icns 用 png 代替(Tauri 会处理)
    let icon_256 = image::imageops::resize(&img, 256, 256, image::imageops::FilterType::Nearest);
    icon_256.save(icons_dir.join("icon.png"))?;
    fs::copy(icons_dir.join("icon.png"), icons_dir.join("icon.ico"))?;
    fs::copy(icons_dir.join("icon.png"), icons_dir.join("icon.icns"))?;
    Ok(())
}

fn rename_build_artifacts(project_dir: &PathBuf, name: &str, version: &str, platform: &str) {
    let output_dir = project_dir.join("dist");
    let _ = fs::create_dir_all(&output_dir);
    
    match platform {
        "android" => {
            let android_dir = project_dir.join("src-tauri/gen/android/app/build/outputs");
            
            // APK 文件
            let apk_src = android_dir.join("apk/universal/release/app-universal-release-unsigned.apk");
            if apk_src.exists() {
                let apk_dst = output_dir.join(format!("{}-{}-universal.apk", name, version));
                if fs::copy(&apk_src, &apk_dst).is_ok() {
                    println!("📦 APK: {}", apk_dst.display());
                }
            }
            
            // AAB 文件
            let aab_src = android_dir.join("bundle/universalRelease/app-universal-release.aab");
            if aab_src.exists() {
                let aab_dst = output_dir.join(format!("{}-{}-universal.aab", name, version));
                if fs::copy(&aab_src, &aab_dst).is_ok() {
                    println!("📦 AAB: {}", aab_dst.display());
                }
            }
            
            // 按架构复制 APK
            let archs = [("arm64-v8a", "arm64"), ("armeabi-v7a", "arm32"), ("x86_64", "x86_64"), ("x86", "x86")];
            for (arch_dir, arch_name) in archs {
                let arch_apk = android_dir.join(format!("apk/{}/release/app-{}-release-unsigned.apk", arch_dir, arch_dir));
                if arch_apk.exists() {
                    let dst = output_dir.join(format!("{}-{}-{}.apk", name, version, arch_name));
                    if fs::copy(&arch_apk, &dst).is_ok() {
                        println!("📦 APK ({}): {}", arch_name, dst.display());
                    }
                }
            }
            
            println!("\n📁 All artifacts copied to: {}", output_dir.display());
        }
        "linux" => {
            let bundle_dir = project_dir.join("src-tauri/target/release/bundle");
            
            // DEB
            if let Ok(entries) = fs::read_dir(bundle_dir.join("deb")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "deb").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-amd64.deb", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 DEB: {}", dst.display());
                        }
                    }
                }
            }
            
            // RPM
            if let Ok(entries) = fs::read_dir(bundle_dir.join("rpm")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "rpm").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-x86_64.rpm", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 RPM: {}", dst.display());
                        }
                    }
                }
            }
            
            // AppImage
            if let Ok(entries) = fs::read_dir(bundle_dir.join("appimage")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "AppImage").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-x86_64.AppImage", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 AppImage: {}", dst.display());
                        }
                    }
                }
            }
            
            println!("\n📁 All artifacts copied to: {}", output_dir.display());
        }
        "mac" => {
            let bundle_dir = project_dir.join("src-tauri/target/release/bundle");
            
            if let Ok(entries) = fs::read_dir(bundle_dir.join("dmg")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "dmg").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-macos.dmg", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 DMG: {}", dst.display());
                        }
                    }
                }
            }
            
            println!("\n📁 All artifacts copied to: {}", output_dir.display());
        }
        "windows" => {
            let bundle_dir = project_dir.join("src-tauri/target/release/bundle");
            
            // MSI
            if let Ok(entries) = fs::read_dir(bundle_dir.join("msi")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "msi").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-x64.msi", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 MSI: {}", dst.display());
                        }
                    }
                }
            }
            
            // NSIS EXE
            if let Ok(entries) = fs::read_dir(bundle_dir.join("nsis")) {
                for entry in entries.flatten() {
                    if entry.path().extension().map(|e| e == "exe").unwrap_or(false) {
                        let dst = output_dir.join(format!("{}-{}-x64-setup.exe", name, version));
                        if fs::copy(entry.path(), &dst).is_ok() {
                            println!("📦 EXE: {}", dst.display());
                        }
                    }
                }
            }
            
            println!("\n📁 All artifacts copied to: {}", output_dir.display());
        }
        _ => {}
    }
}