ply-engine 1.1.1

The most powerful app engine made entirely in Rust
Documentation
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
#[cfg(not(target_arch = "wasm32"))]
use std::path::{Path, PathBuf};

#[cfg(target_arch = "wasm32")]
use macroquad::prelude::next_frame;
#[cfg(target_arch = "wasm32")]
use sapp_jsutils::JsObject;

#[derive(Debug, Clone)]
pub struct Storage {
    #[cfg(not(target_arch = "wasm32"))]
    root_path: PathBuf,
    #[cfg(target_arch = "wasm32")]
    root_id: i32,
}

impl Storage {
    pub async fn new(path: &str) -> Result<Self, String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let candidate = PathBuf::from(path);
            let root_path = if candidate.is_absolute() {
                candidate
            } else {
                let normalized_root = normalize_relative_path(path, "Storage::new path")?;
                let app_data_dir = platform_app_data_dir()?;
                join_normalized_path(&app_data_dir, &normalized_root)
            };

            std::fs::create_dir_all(&root_path).map_err(|e| e.to_string())?;

            Ok(Self { root_path })
        }

        #[cfg(target_arch = "wasm32")]
        {
            let normalized_root = normalize_relative_path(path, "Storage::new path")?;
            let op_id = unsafe { ply_storage_new(JsObject::string(&normalized_root)) };
            let result = wait_for_response(op_id).await?;
            ensure_success(&result)?;

            Ok(Self {
                root_id: result.field_u32("storage_id") as i32,
            })
        }
    }

    pub async fn save_string(&self, path: &str, data: &str) -> Result<(), String> {
        self.save_bytes(path, data.as_bytes()).await
    }

    pub async fn save_bytes(&self, path: &str, data: &[u8]) -> Result<(), String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let full_path = self.resolve_path(path)?;
            if let Some(parent) = full_path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
            }
            std::fs::write(full_path, data).map_err(|e| e.to_string())?;
            Ok(())
        }

        #[cfg(target_arch = "wasm32")]
        {
            let normalized_path = normalize_relative_path(path, "storage save path")?;
            let op_id = unsafe {
                ply_storage_save_bytes(
                    self.root_id,
                    JsObject::string(&normalized_path),
                    JsObject::buffer(data),
                )
            };
            let result = wait_for_response(op_id).await?;
            ensure_success(&result)
        }
    }

    pub async fn load_string(&self, path: &str) -> Result<Option<String>, String> {
        match self.load_bytes(path).await? {
            Some(bytes) => {
                let content = String::from_utf8(bytes)
                    .map_err(|e| format!("Invalid UTF-8 data: {e}"))?;
                Ok(Some(content))
            }
            None => Ok(None),
        }
    }

    pub async fn load_bytes(&self, path: &str) -> Result<Option<Vec<u8>>, String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let full_path = self.resolve_path(path)?;
            match std::fs::read(full_path) {
                Ok(bytes) => Ok(Some(bytes)),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(error) => Err(error.to_string()),
            }
        }

        #[cfg(target_arch = "wasm32")]
        {
            let normalized_path = normalize_relative_path(path, "storage load path")?;
            let op_id = unsafe {
                ply_storage_load_bytes(self.root_id, JsObject::string(&normalized_path))
            };
            let result = wait_for_response(op_id).await?;
            ensure_success(&result)?;

            if result.field_u32("exists") == 0 {
                return Ok(None);
            }

            let mut bytes = Vec::new();
            result.field("data").to_byte_buffer(&mut bytes);
            Ok(Some(bytes))
        }
    }

    pub async fn remove(&self, path: &str) -> Result<(), String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let full_path = self.resolve_path(path)?;
            std::fs::remove_file(full_path).map_err(|e| e.to_string())?;
            Ok(())
        }

        #[cfg(target_arch = "wasm32")]
        {
            let normalized_path = normalize_relative_path(path, "storage remove path")?;
            let op_id = unsafe {
                ply_storage_remove(self.root_id, JsObject::string(&normalized_path))
            };
            let result = wait_for_response(op_id).await?;
            ensure_success(&result)
        }
    }

    pub async fn export(&self, path: &str) -> Result<(), String> {
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
        {
            let full_path = self.resolve_path(path)?;
            let bytes = std::fs::read(&full_path).map_err(|e| e.to_string())?;

            let normalized_path = normalize_relative_path(path, "storage export path")?;
            let file_name = normalized_path
                .rsplit('/')
                .next()
                .filter(|s| !s.is_empty())
                .ok_or_else(|| "Invalid export file name".to_owned())?;

            let target_path = rfd::FileDialog::new()
                .set_file_name(file_name)
                .save_file()
                .ok_or_else(|| "Export canceled".to_owned())?;

            std::fs::write(target_path, bytes).map_err(|e| e.to_string())?;
            Ok(())
        }

        #[cfg(target_os = "android")]
        {
            let full_path = self.resolve_path(path)?;
            std::fs::metadata(&full_path).map_err(|e| e.to_string())?;

            let normalized_path = normalize_relative_path(path, "storage export path")?;
            let file_name = normalized_path
                .rsplit('/')
                .next()
                .filter(|s| !s.is_empty())
                .ok_or_else(|| "Invalid export file name".to_owned())?;

            let full_path_string = full_path.to_string_lossy().into_owned();
            let source_path_c =
                std::ffi::CString::new(full_path_string).map_err(|_| {
                    "Export path contains unsupported NUL byte".to_owned()
                })?;
            let file_name_c = std::ffi::CString::new(file_name).map_err(|_| {
                "Export file name contains unsupported NUL byte".to_owned()
            })?;
            let mime_type_c = std::ffi::CString::new(guess_mime_type(&normalized_path))
                .map_err(|_| "Export MIME type contains unsupported NUL byte".to_owned())?;

            unsafe {
                let env = macroquad::miniquad::native::android::attach_jni_env();
                let activity = macroquad::miniquad::native::android::ACTIVITY;
                if activity.is_null() {
                    return Err("Android activity is not available".to_owned());
                }

                let get_object_class = (**env).GetObjectClass.unwrap();
                let get_method_id = (**env).GetMethodID.unwrap();
                let call_void_method = (**env).CallVoidMethod.unwrap();
                let new_string_utf = (**env).NewStringUTF.unwrap();
                let delete_local_ref = (**env).DeleteLocalRef.unwrap();
                let exception_check = (**env).ExceptionCheck.unwrap();
                let exception_describe = (**env).ExceptionDescribe.unwrap();
                let exception_clear = (**env).ExceptionClear.unwrap();

                let class = get_object_class(env, activity);
                if class.is_null() {
                    return Err("Failed to access Android activity class".to_owned());
                }

                let method_name = std::ffi::CString::new("exportFile")
                    .map_err(|_| "Invalid Android method name".to_owned())?;
                let method_sig = std::ffi::CString::new(
                    "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
                )
                .map_err(|_| "Invalid Android method signature".to_owned())?;
                let method_id = get_method_id(
                    env,
                    class,
                    method_name.as_ptr(),
                    method_sig.as_ptr(),
                );
                if method_id.is_null() {
                    delete_local_ref(env, class as _);
                    return Err(
                        "MainActivity.exportFile(String,String,String) was not found"
                            .to_owned(),
                    );
                }

                let j_source_path = new_string_utf(env, source_path_c.as_ptr());
                let j_file_name = new_string_utf(env, file_name_c.as_ptr());
                let j_mime_type = new_string_utf(env, mime_type_c.as_ptr());
                if j_source_path.is_null() || j_file_name.is_null() || j_mime_type.is_null() {
                    if !j_source_path.is_null() {
                        delete_local_ref(env, j_source_path as _);
                    }
                    if !j_file_name.is_null() {
                        delete_local_ref(env, j_file_name as _);
                    }
                    if !j_mime_type.is_null() {
                        delete_local_ref(env, j_mime_type as _);
                    }
                    delete_local_ref(env, class as _);
                    return Err("Failed to allocate Android export strings".to_owned());
                }

                call_void_method(
                    env,
                    activity,
                    method_id,
                    j_source_path,
                    j_file_name,
                    j_mime_type,
                );

                if exception_check(env) != 0 {
                    exception_describe(env);
                    exception_clear(env);
                    delete_local_ref(env, j_source_path as _);
                    delete_local_ref(env, j_file_name as _);
                    delete_local_ref(env, j_mime_type as _);
                    delete_local_ref(env, class as _);
                    return Err(
                        "Android export failed to open the document picker"
                            .to_owned(),
                    );
                }

                delete_local_ref(env, j_source_path as _);
                delete_local_ref(env, j_file_name as _);
                delete_local_ref(env, j_mime_type as _);
                delete_local_ref(env, class as _);
            }

            Ok(())
        }

        #[cfg(target_os = "ios")]
        {
            use macroquad::miniquad::native::apple::apple_util::str_to_nsstring;
            use macroquad::miniquad::native::apple::frameworks::{
                class, msg_send, nil, NSRect, ObjcId,
            };

            let full_path = self.resolve_path(path)?;
            std::fs::metadata(&full_path).map_err(|e| e.to_string())?;

            let view_ctrl = macroquad::miniquad::window::apple_view_ctrl();
            if view_ctrl.is_null() {
                return Err("iOS view controller is not available".to_owned());
            }

            let full_path_string = full_path.to_string_lossy().into_owned();

            unsafe {
                let ns_path = str_to_nsstring(&full_path_string);
                let file_url: ObjcId = msg_send![class!(NSURL), fileURLWithPath: ns_path];
                if file_url.is_null() {
                    return Err("Failed to create iOS file URL for export".to_owned());
                }

                let items: ObjcId = msg_send![class!(NSMutableArray), arrayWithObject: file_url];
                let activity: ObjcId = msg_send![class!(UIActivityViewController), alloc];
                let activity: ObjcId = msg_send![
                    activity,
                    initWithActivityItems: items
                    applicationActivities: nil
                ];
                if activity.is_null() {
                    return Err("Failed to create iOS share sheet".to_owned());
                }

                // iPad requires an anchor for popovers.
                let popover: ObjcId = msg_send![activity, popoverPresentationController];
                if !popover.is_null() {
                    let view: ObjcId = msg_send![view_ctrl, view];
                    let bounds: NSRect = msg_send![view, bounds];
                    let _: () = msg_send![popover, setSourceView: view];
                    let _: () = msg_send![popover, setSourceRect: bounds];
                }

                let _: () = msg_send![
                    view_ctrl,
                    presentViewController: activity
                    animated: true
                    completion: nil
                ];
            }

            Ok(())
        }

        #[cfg(all(
            not(target_arch = "wasm32"),
            not(any(
                target_os = "linux",
                target_os = "macos",
                target_os = "windows",
                target_os = "android",
                target_os = "ios"
            ))
        ))]
        {
            let _ = path;
            Err("Storage::export is not supported on this platform yet".to_owned())
        }

        #[cfg(target_arch = "wasm32")]
        {
            let normalized_path = normalize_relative_path(path, "storage export path")?;
            let op_id = unsafe {
                ply_storage_export(self.root_id, JsObject::string(&normalized_path))
            };
            let result = wait_for_response(op_id).await?;
            ensure_success(&result)
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn resolve_path(&self, relative_path: &str) -> Result<PathBuf, String> {
        let normalized = normalize_relative_path(relative_path, "storage file path")?;
        Ok(join_normalized_path(&self.root_path, &normalized))
    }
}

#[cfg(target_os = "android")]
fn guess_mime_type(path: &str) -> &'static str {
    let extension = path
        .rsplit_once('.')
        .map(|(_, ext)| ext)
        .unwrap_or_default()
        .to_ascii_lowercase();

    match extension.as_str() {
        "txt" => "text/plain",
        "md" => "text/markdown",
        "json" => "application/json",
        "csv" => "text/csv",
        "html" | "htm" => "text/html",
        "js" => "application/javascript",
        "wasm" => "application/wasm",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "pdf" => "application/pdf",
        "zip" => "application/zip",
        _ => "application/octet-stream",
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn join_normalized_path(root: &Path, normalized: &str) -> PathBuf {
    let mut path = root.to_path_buf();
    for part in normalized.split('/') {
        path.push(part);
    }
    path
}

fn normalize_relative_path(path: &str, what: &str) -> Result<String, String> {
    let trimmed = path.trim();

    if trimmed.is_empty() {
        return Err(format!("{what} cannot be empty"));
    }

    if trimmed.starts_with('/') || trimmed.starts_with('\\') {
        return Err(format!("{what} must be a relative path"));
    }

    let bytes = trimmed.as_bytes();
    if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
        return Err(format!("{what} must be a relative path"));
    }

    let mut parts: Vec<&str> = Vec::new();
    for part in trimmed.split(|c| c == '/' || c == '\\') {
        if part.is_empty() || part == "." {
            continue;
        }
        if part == ".." {
            return Err(format!("{what} cannot contain '..'"));
        }
        parts.push(part);
    }

    if parts.is_empty() {
        return Err(format!("{what} is invalid"));
    }

    Ok(parts.join("/"))
}

#[cfg(not(target_arch = "wasm32"))]
fn platform_app_data_dir() -> Result<PathBuf, String> {
    #[cfg(target_os = "windows")]
    {
        if let Some(appdata) = std::env::var_os("APPDATA") {
            return Ok(PathBuf::from(appdata));
        }
        if let Some(home) = std::env::var_os("USERPROFILE") {
            return Ok(PathBuf::from(home).join("AppData").join("Roaming"));
        }
        return Err("Could not resolve %APPDATA% on Windows".to_owned());
    }

    #[cfg(target_os = "macos")]
    {
        if let Some(home) = std::env::var_os("HOME") {
            return Ok(PathBuf::from(home)
                .join("Library")
                .join("Application Support"));
        }
        return Err("Could not resolve HOME on macOS".to_owned());
    }

    #[cfg(target_os = "linux")]
    {
        if let Some(xdg_data_home) = std::env::var_os("XDG_DATA_HOME") {
            return Ok(PathBuf::from(xdg_data_home));
        }
        if let Some(home) = std::env::var_os("HOME") {
            return Ok(PathBuf::from(home).join(".local").join("share"));
        }
        return Err("Could not resolve data directory on Linux".to_owned());
    }

    #[cfg(target_os = "android")]
    {
        unsafe {
            let env = macroquad::miniquad::native::android::attach_jni_env();
            let activity = macroquad::miniquad::native::android::ACTIVITY;

            if activity.is_null() {
                return Err("Android activity is not available".to_owned());
            }

            let get_object_class = (**env).GetObjectClass.unwrap();
            let get_method_id = (**env).GetMethodID.unwrap();
            let call_object_method = (**env).CallObjectMethod.unwrap();
            let get_string_utf_chars = (**env).GetStringUTFChars.unwrap();
            let release_string_utf_chars = (**env).ReleaseStringUTFChars.unwrap();
            let delete_local_ref = (**env).DeleteLocalRef.unwrap();
            let exception_check = (**env).ExceptionCheck.unwrap();
            let exception_describe = (**env).ExceptionDescribe.unwrap();
            let exception_clear = (**env).ExceptionClear.unwrap();

            let class = get_object_class(env, activity);
            if class.is_null() {
                return Err("Failed to access Android activity class".to_owned());
            }

            let get_files_dir_name = std::ffi::CString::new("getFilesDir")
                .map_err(|_| "Invalid Android method name".to_owned())?;
            let get_files_dir_sig = std::ffi::CString::new("()Ljava/io/File;")
                .map_err(|_| "Invalid Android method signature".to_owned())?;
            let get_files_dir = get_method_id(
                env,
                class,
                get_files_dir_name.as_ptr(),
                get_files_dir_sig.as_ptr(),
            );

            if get_files_dir.is_null() {
                delete_local_ref(env, class as _);
                return Err("Failed to resolve Activity.getFilesDir()".to_owned());
            }

            let file_obj = call_object_method(env, activity, get_files_dir);
            if exception_check(env) != 0 || file_obj.is_null() {
                if exception_check(env) != 0 {
                    exception_describe(env);
                    exception_clear(env);
                }
                delete_local_ref(env, class as _);
                return Err("Failed to call Activity.getFilesDir()".to_owned());
            }

            let file_class = get_object_class(env, file_obj);
            if file_class.is_null() {
                delete_local_ref(env, file_obj as _);
                delete_local_ref(env, class as _);
                return Err("Failed to access java.io.File class".to_owned());
            }

            let get_abs_name = std::ffi::CString::new("getAbsolutePath")
                .map_err(|_| "Invalid Android method name".to_owned())?;
            let get_abs_sig = std::ffi::CString::new("()Ljava/lang/String;")
                .map_err(|_| "Invalid Android method signature".to_owned())?;
            let get_abs = get_method_id(
                env,
                file_class,
                get_abs_name.as_ptr(),
                get_abs_sig.as_ptr(),
            );

            if get_abs.is_null() {
                delete_local_ref(env, file_class as _);
                delete_local_ref(env, file_obj as _);
                delete_local_ref(env, class as _);
                return Err("Failed to resolve File.getAbsolutePath()".to_owned());
            }

            let path_obj = call_object_method(env, file_obj, get_abs);
            if exception_check(env) != 0 || path_obj.is_null() {
                if exception_check(env) != 0 {
                    exception_describe(env);
                    exception_clear(env);
                }
                delete_local_ref(env, file_class as _);
                delete_local_ref(env, file_obj as _);
                delete_local_ref(env, class as _);
                return Err("Failed to call File.getAbsolutePath()".to_owned());
            }

            let path_chars = get_string_utf_chars(env, path_obj as _, std::ptr::null_mut());
            if path_chars.is_null() {
                delete_local_ref(env, path_obj as _);
                delete_local_ref(env, file_class as _);
                delete_local_ref(env, file_obj as _);
                delete_local_ref(env, class as _);
                return Err("Failed to read app files directory string".to_owned());
            }

            let path = std::ffi::CStr::from_ptr(path_chars)
                .to_string_lossy()
                .into_owned();

            release_string_utf_chars(env, path_obj as _, path_chars);
            delete_local_ref(env, path_obj as _);
            delete_local_ref(env, file_class as _);
            delete_local_ref(env, file_obj as _);
            delete_local_ref(env, class as _);

            return Ok(PathBuf::from(path));
        }
    }

    #[cfg(target_os = "ios")]
    {
        if let Some(home) = std::env::var_os("HOME") {
            return Ok(PathBuf::from(home).join("Documents"));
        }
        if let Some(tmpdir) = std::env::var_os("TMPDIR") {
            return Ok(PathBuf::from(tmpdir));
        }
        return Err("Could not resolve app data directory on iOS".to_owned());
    }
}

#[cfg(target_arch = "wasm32")]
fn ensure_success(response: &JsObject) -> Result<(), String> {
    if response.field_u32("status") == 1 {
        return Ok(());
    }

    let mut error_message = String::new();
    if response.have_field("error") {
        response.field("error").to_string(&mut error_message);
    }
    if error_message.is_empty() {
        error_message = "Storage operation failed".to_owned();
    }

    Err(error_message)
}

#[cfg(target_arch = "wasm32")]
async fn wait_for_response(op_id: i32) -> Result<JsObject, String> {
    loop {
        let result = unsafe { ply_storage_try_recv(op_id) };
        if !result.is_nil() {
            return Ok(result);
        }
        next_frame().await;
    }
}

#[cfg(target_arch = "wasm32")]
extern "C" {
    fn ply_storage_new(path: JsObject) -> i32;
    fn ply_storage_save_bytes(storage_id: i32, path: JsObject, data: JsObject) -> i32;
    fn ply_storage_load_bytes(storage_id: i32, path: JsObject) -> i32;
    fn ply_storage_remove(storage_id: i32, path: JsObject) -> i32;
    fn ply_storage_export(storage_id: i32, path: JsObject) -> i32;
    fn ply_storage_try_recv(op_id: i32) -> JsObject;
}