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
use { InnerWindow, Window, List, Entry, Label };
use traits::{ Place, Text, Click };

use std::{fs, io};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::rc::Rc;

#[derive(Clone, Debug, Eq, PartialEq)]
struct FolderItem {
    path: PathBuf,
    name: String,
    dir: bool,
}

impl Ord for FolderItem {
    fn cmp(&self, other: &Self) -> Ordering {
        if self.dir && ! other.dir {
            Ordering::Less
        } else if ! self.dir && other.dir {
            Ordering::Greater
        } else {
            self.name.cmp(&other.name)
        }
    }
}

impl PartialOrd for FolderItem {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl FolderItem {
    fn scan<P: AsRef<Path>>(path: P) -> io::Result<Vec<Result<Self, String>>> {
        let canon = path.as_ref().canonicalize()?;

        let mut items = vec![];

        if let Some(parent) = canon.parent() {
            items.push(Ok(FolderItem {
                path: parent.to_owned(),
                name: "..".to_string(),
                dir: true,
            }));
        }

        for entry_res in fs::read_dir(&canon)? {
            let item = match entry_res {
                Ok(entry) => match entry.file_name().into_string() {
                    Ok(name) => match entry.file_type() {
                        Ok(file_type) => Ok(FolderItem {
                            path: entry.path(),
                            name: name,
                            dir: file_type.is_dir(),
                        }),
                        Err(err) => Err(format!("{}", err))
                    },
                    Err(os_str) => Err(format!("Invalid filename: {:?}", os_str))
                },
                Err(err) => Err(format!("{}", err))
            };

            items.push(item);
        }

        items.sort();

        Ok(items)
    }
}

pub struct FileDialog {
    pub title: String,
    pub path: PathBuf,
    pub hidden: bool,
}

impl FileDialog {
    pub fn new() -> Self {
        FileDialog {
            title: "File Dialog".to_string(),
            path: PathBuf::from("."),
            hidden: false,
        }
    }

    pub fn exec(&self) -> Option<PathBuf> {
        let path_opt = Rc::new(RefCell::new(
            Some(self.path.clone())
        ));

        let w = 644;
        let h = 484;

        let mut orb_window = Some(InnerWindow::new(-1, -1, w, h, &self.title).unwrap());

        loop {
            let path = match path_opt.borrow_mut().take() {
                Some(path) => if ! path.is_dir() {
                    return Some(path);
                } else {
                    path
                },
                None => return None
            };

            let mut window = Box::new(Window::from_inner(orb_window.take().unwrap()));

            let list = List::new();
            list.position(2, 2).size(w - 4, h - 4);

            match FolderItem::scan(&path) {
                Ok(items) => for item_res in items {
                    match item_res {
                        Ok(item) => if self.hidden || ! item.name.starts_with(".") || item.name == ".." {
                            let mut name = item.name.clone();
                            if item.dir {
                                name.push('/');
                            }

                            let entry = Entry::new(24);

                            let label = Label::new();
                            label.position(2, 2).size(w - 8, 20).text_offset(2, 2);
                            //label.bg.set(Color::rgb(255, 255, 255));
                            label.text(name);
                            entry.add(&label);

                            let window = window.deref() as *const Window;
                            let path_opt = path_opt.clone();
                            entry.on_click(move |_, _| {
                                *path_opt.borrow_mut() = Some(item.path.clone());
                                unsafe { (*window).close(); }
                            });

                            list.push(&entry);
                        },
                        Err(err) => {
                            let entry = Entry::new(24);

                            let label = Label::new();
                            label.position(2, 2).size(w - 8, 20).text_offset(2, 2);
                            //label.bg.set(Color::rgb(242, 222, 222));
                            label.text(err);
                            entry.add(&label);

                            list.push(&entry);
                        }
                    }
                },
                Err(err) => {
                    let entry = Entry::new(24);

                    let label = Label::new();
                    label.position(2, 2).size(w - 8, 20).text_offset(2, 2);
                    //label.bg.set(Color::rgb(242, 222, 222));
                    label.text(format!("{}", err));
                    entry.add(&label);

                    list.push(&entry);
                }
            }

            window.add(&list);

            window.exec();

            orb_window = Some(window.into_inner());
        }
    }
}