tfd 0.1.0

Pure-Rust fork of the tinyfiledialogs C library
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
use super::*;
use std::ffi::{CStr, CString};
use std::path::Path;
use std::sync::{Arc, Mutex};
use jni::JNIEnv;
use jni::objects::{JClass, JObject, JString, JValue};
use jni::sys::{jint, jobject, jobjectArray, jsize, jstring};

pub const ANDROID_HELPER_CLASS: &str = include_str!("com.tfd.DialogHelper.java");

thread_local! {
    // Store JNI environment for this thread
    static JNI_ENV: Mutex<Option<Arc<JNIEnv<'static>>>> = Mutex::new(None);
    
    // Activity reference
    static CURRENT_ACTIVITY: Mutex<Option<JObject<'static>>> = Mutex::new(None);
}

// Initialize JNI for the current thread
fn init_jni() -> bool {
    JNI_ENV.with(|env| {
        let mut env_guard = env.lock().unwrap();
        if env_guard.is_none() {
            // In a real implementation, you'd get this from context
            // For now, assume it's initialized externally and cached in thread local
            false
        } else {
            true
        }
    })
}

// Get JNI environment
fn get_env() -> Option<Arc<JNIEnv<'static>>> {
    JNI_ENV.with(|env| {
        env.lock().unwrap().clone()
    })
}

// Get current activity
fn get_activity() -> Option<JObject<'static>> {
    CURRENT_ACTIVITY.with(|activity| {
        activity.lock().unwrap().clone()
    })
}

// Convert Rust string to Java string
fn to_jstring(env: &JNIEnv, s: &str) -> jstring {
    let cstr = CString::new(s).unwrap();
    let jstr = env.new_string(cstr.to_str().unwrap()).unwrap();
    jstr.into_raw()
}

// Convert Java string to Rust string
fn from_jstring(env: &JNIEnv, jstr: jstring) -> String {
    let java_str = unsafe { JString::from_raw(jstr) };
    env.get_string(&java_str).unwrap().into()
}

pub fn message_box_ok(msg_box: &MessageBox) {
    let title = msg_box.dialog.title();
    let message = msg_box.dialog.message();
    let icon = msg_box.icon();
    
    if !init_jni() {
        return;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return,
    };
    
    // Get icon resource ID based on icon type
    let icon_res_id = match icon {
        MessageBoxIcon::Info => 3,     // android.R.drawable.ic_dialog_info
        MessageBoxIcon::Warning => 1,  // android.R.drawable.ic_dialog_alert
        MessageBoxIcon::Error => 1,    // android.R.drawable.ic_dialog_alert
        MessageBoxIcon::Question => 3, // android.R.drawable.ic_dialog_info
    };
    
    // Call Android AlertDialog.Builder
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showMessageBox",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;I)V",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Int(icon_res_id),
        ],
    );
    
    if result.is_err() {
        // Handle error
        eprintln!("Failed to show message box: {:?}", result.err());
    }
}

pub fn message_box_ok_cancel(msg_box: &MessageBox, default: OkCancel) -> OkCancel {
    let title = msg_box.dialog.title();
    let message = msg_box.dialog.message();
    let icon = msg_box.icon();
    
    if !init_jni() {
        return OkCancel::Cancel;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return OkCancel::Cancel,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return OkCancel::Cancel,
    };
    
    // Get icon resource ID
    let icon_res_id = match icon {
        MessageBoxIcon::Info => 3,
        MessageBoxIcon::Warning => 1,
        MessageBoxIcon::Error => 1,
        MessageBoxIcon::Question => 3,
    };
    
    // Convert default to int (0 = Cancel, 1 = OK)
    let default_int = match default {
        OkCancel::Ok => 1,
        OkCancel::Cancel => 0,
    };
    
    // Call Android AlertDialog.Builder with result
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showOkCancelDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;II)I",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Int(icon_res_id),
            JValue::Int(default_int),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let result_int = jvalue.i().unwrap_or(0);
            if result_int == 1 {
                OkCancel::Ok
            } else {
                OkCancel::Cancel
            }
        }
        Err(_) => OkCancel::Cancel,
    }
}

pub fn message_box_yes_no(msg_box: &MessageBox, default: YesNo) -> YesNo {
    let title = msg_box.dialog.title();
    let message = msg_box.dialog.message();
    let icon = msg_box.icon();
    
    if !init_jni() {
        return YesNo::No;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return YesNo::No,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return YesNo::No,
    };
    
    // Get icon resource ID
    let icon_res_id = match icon {
        MessageBoxIcon::Info => 3,
        MessageBoxIcon::Warning => 1,
        MessageBoxIcon::Error => 1,
        MessageBoxIcon::Question => 3,
    };
    
    // Convert default to int (0 = No, 1 = Yes)
    let default_int = match default {
        YesNo::Yes => 1,
        YesNo::No => 0,
    };
    
    // Call Android AlertDialog.Builder with result
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showYesNoDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;II)I",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Int(icon_res_id),
            JValue::Int(default_int),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let result_int = jvalue.i().unwrap_or(0);
            if result_int == 1 {
                YesNo::Yes
            } else {
                YesNo::No
            }
        }
        Err(_) => YesNo::No,
    }
}

pub fn message_box_yes_no_cancel(msg_box: &MessageBox, default: YesNoCancel) -> YesNoCancel {
    let title = msg_box.dialog.title();
    let message = msg_box.dialog.message();
    let icon = msg_box.icon();
    
    if !init_jni() {
        return YesNoCancel::Cancel;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return YesNoCancel::Cancel,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return YesNoCancel::Cancel,
    };
    
    // Get icon resource ID
    let icon_res_id = match icon {
        MessageBoxIcon::Info => 3,
        MessageBoxIcon::Warning => 1,
        MessageBoxIcon::Error => 1,
        MessageBoxIcon::Question => 3,
    };
    
    // Convert default to int (0 = Cancel, 1 = Yes, 2 = No)
    let default_int = match default {
        YesNoCancel::Yes => 1,
        YesNoCancel::No => 2,
        YesNoCancel::Cancel => 0,
    };
    
    // Call Android AlertDialog.Builder with result
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showYesNoCancelDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;II)I",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Int(icon_res_id),
            JValue::Int(default_int),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let result_int = jvalue.i().unwrap_or(0);
            match result_int {
                1 => YesNoCancel::Yes,
                2 => YesNoCancel::No,
                _ => YesNoCancel::Cancel,
            }
        }
        Err(_) => YesNoCancel::Cancel,
    }
}

pub fn input_box(input: &InputBox) -> Option<String> {
    let title = input.dialog.title();
    let message = input.dialog.message();
    let default_value = input.default_value().unwrap_or("");
    let is_password = input.is_password();
    
    if !init_jni() {
        return None;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return None,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return None,
    };
    
    // Call Android Dialog with EditText
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showInputDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/String;",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Object(JObject::from(to_jstring(&env, default_value))),
            JValue::Bool(is_password as jni::sys::jboolean),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let java_string = jvalue.l().ok()?;
            if java_string.is_null() {
                None
            } else {
                Some(env.get_string(unsafe { JString::from_raw(java_string.into_raw()) }).ok()?.into())
            }
        }
        Err(_) => None,
    }
}

pub fn save_file_dialog(dialog: &FileDialog) -> Option<String> {
    let title = dialog.dialog.title();
    let path = dialog.path();
    let filter_patterns = dialog.filter_patterns();
    
    if !init_jni() {
        return None;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return None,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return None,
    };
    
    // Convert filter patterns to Java string array
    let filter_array = if !filter_patterns.is_empty() {
        let jstring_array = env.new_object_array(
            filter_patterns.len() as jsize,
            "java/lang/String",
            JObject::null(),
        ).ok()?;
        
        for (i, pattern) in filter_patterns.iter().enumerate() {
            let jstring = to_jstring(&env, pattern);
            env.set_object_array_element(jstring_array, i as jsize, JObject::from(jstring)).ok()?;
        }
        
        JObject::from(jstring_array)
    } else {
        JObject::null()
    };
    
    // Call Android to show file picker in SAVE mode
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showSaveFileDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, path))),
            JValue::Object(filter_array),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let java_string = jvalue.l().ok()?;
            if java_string.is_null() {
                None
            } else {
                Some(env.get_string(unsafe { JString::from_raw(java_string.into_raw()) }).ok()?.into())
            }
        }
        Err(_) => None,
    }
}

pub fn open_file_dialog(dialog: &FileDialog) -> Option<Vec<String>> {
    let title = dialog.dialog.title();
    let path = dialog.path();
    let filter_patterns = dialog.filter_patterns();
    let allow_multi = dialog.multiple_selection();
    
    if !init_jni() {
        return None;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return None,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return None,
    };
    
    // Convert filter patterns to Java string array
    let filter_array = if !filter_patterns.is_empty() {
        let jstring_array = env.new_object_array(
            filter_patterns.len() as jsize,
            "java/lang/String",
            JObject::null(),
        ).ok()?;
        
        for (i, pattern) in filter_patterns.iter().enumerate() {
            let jstring = to_jstring(&env, pattern);
            env.set_object_array_element(jstring_array, i as jsize, JObject::from(jstring)).ok()?;
        }
        
        JObject::from(jstring_array)
    } else {
        JObject::null()
    };
    
    // Call Android to show file picker in OPEN mode
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showOpenFileDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Z)[Ljava/lang/String;",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, path))),
            JValue::Object(filter_array),
            JValue::Bool(allow_multi as jni::sys::jboolean),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let java_array = jvalue.l().ok()?;
            if java_array.is_null() {
                return None;
            }
            
            let array = unsafe { jobjectArray::from(java_array.into_raw()) };
            let length = env.get_array_length(array).ok()?;
            
            let mut files = Vec::with_capacity(length as usize);
            for i in 0..length {
                let jstr = env.get_object_array_element(array, i).ok()?;
                if !jstr.is_null() {
                    let string = env.get_string(unsafe { JString::from_raw(jstr.into_raw()) }).ok()?.into();
                    files.push(string);
                }
            }
            
            if files.is_empty() {
                None
            } else {
                Some(files)
            }
        }
        Err(_) => None,
    }
}

pub fn select_folder_dialog(dialog: &FileDialog) -> Option<String> {
    let title = dialog.dialog.title();
    let path = dialog.path();
    
    if !init_jni() {
        return None;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return None,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return None,
    };
    
    // Call Android to show folder picker
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showFolderDialog",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, path))),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let java_string = jvalue.l().ok()?;
            if java_string.is_null() {
                None
            } else {
                Some(env.get_string(unsafe { JString::from_raw(java_string.into_raw()) }).ok()?.into())
            }
        }
        Err(_) => None,
    }
}

pub fn color_chooser_dialog(chooser: &ColorChooser) -> Option<(String, [u8; 3])> {
    let title = chooser.dialog.title();
    
    let default_rgb = match chooser.default_color() {
        DefaultColorValue::Hex(hex) => super::hex_to_rgb(hex),
        DefaultColorValue::RGB(rgb) => *rgb,
    };
    
    if !init_jni() {
        return None;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return None,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return None,
    };
    
    // Call Android color picker
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showColorChooser",
        "(Landroid/app/Activity;Ljava/lang/String;III)[I",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Int(default_rgb[0] as jint),
            JValue::Int(default_rgb[1] as jint),
            JValue::Int(default_rgb[2] as jint),
        ],
    );
    
    match result {
        Ok(jvalue) => {
            let java_array = jvalue.l().ok()?;
            if java_array.is_null() {
                return None;
            }
            
            let array = env.get_int_array_elements(unsafe { 
                jni::sys::jintArray::from(java_array.into_raw())
            }, 0).ok()?;
            
            if array.len() >= 3 {
                let r = array[0] as u8;
                let g = array[1] as u8;
                let b = array[2] as u8;
                
                let rgb = [r, g, b];
                let hex = super::rgb_to_hex(&rgb);
                
                Some((hex, rgb))
            } else {
                None
            }
        }
        Err(_) => None,
    }
}

pub fn notification(notification: &Notification) -> bool {
    let title = notification.title();
    let message = notification.message();
    let subtitle = notification.subtitle().unwrap_or("");
    
    if !init_jni() {
        return false;
    }
    
    let env = match get_env() {
        Some(env) => env,
        None => return false,
    };
    
    let activity = match get_activity() {
        Some(activity) => activity,
        None => return false,
    };
    
    // Call Android notification service
    let result = env.call_static_method(
        "com/example/tinyfiledialogs/DialogHelper",
        "showNotification",
        "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
        &[
            JValue::Object(activity),
            JValue::Object(JObject::from(to_jstring(&env, title))),
            JValue::Object(JObject::from(to_jstring(&env, message))),
            JValue::Object(JObject::from(to_jstring(&env, subtitle))),
        ],
    );
    
    match result {
        Ok(jvalue) => jvalue.z().unwrap_or(false),
        Err(_) => false,
    }
}