跳转至

Miscellaneous

本节添加一些额外功能。

首先,当文件没有被修改时,可以设置禁用保存按钮。这样可以避免用户误操作。在on_press_maybe中传入None即可。同时,可以根据文件的修改情况设置按钮的样式。

fn toolbar_button<'a>(description: &str, callback: Option<Message>) -> Element<'a, Message> {
    let font = Font::with_name("editor-icon");
    let lower = description.to_lowercase();
    let icon = text(match lower.as_str() {
        "new" => '\u{E800}',
        "open" => '\u{F115}',
        "save" => '\u{E801}',
        _ => ' '
    }).font(font);
    let is_disabled = callback.is_none();
    tooltip(
        button(container(icon)
            .width(30)  // Set the width of the button
            .center_x() // Center the icon
        ).on_press_maybe(callback).style(
            if is_disabled {
                theme::Button::Secondary
            } else {
                theme::Button::Primary
            }
        ),
        description, tooltip::Position::FollowCursor
    ).style(theme::Container::Box).into()
}

同时修改toolbar_button的调用。

// ... In `view` function
let controls = row![
    toolbar_button("New", Some(Message::NewButtonPressed)),
    toolbar_button("Open", Some(Message::OpenButtonPressed)),
    toolbar_button("Save", if self.modified { Some(Message::SaveButtonPressed) } else { None }),
    horizontal_space(Length::Fill),
    pick_list(highlighter::Theme::ALL, Some(self.theme), Message::ThemeChanged)
].spacing(10);

我们可以添加不同的快捷键,以方便用户操作。

// In `impl Application for Editor`
fn subscription(&self) -> Subscription<Message> {
    keyboard::on_key_press(|keycode, modifier| {
        match (keycode, modifier) {
            (keyboard::KeyCode::S, keyboard::Modifiers::COMMAND) => {
                Some(Message::SaveButtonPressed)
            },
            (keyboard::KeyCode::O, keyboard::Modifiers::COMMAND) => {
                Some(Message::OpenButtonPressed)
            },
            (keyboard::KeyCode::N, keyboard::Modifiers::COMMAND) => {
                Some(Message::NewButtonPressed)
            },
            _ => None
        }
    })
}

这样,用户可以使用Command + S来保存文件,Command + O来打开文件,Command + N来新建文件。

文件的标题栏通常显示文件路径,可以和左下角的状态栏保持同步。

// ... In `impl Application for Editor`
fn title(&self) -> String {
    let path_text = match &self.path {
        None => String::from("New file"),
        Some(path) => path.to_string_lossy().to_string()
    };
    let suffix = if self.modified { "*" } else { "" };
    format!("{}{}", path_text, suffix)
}

// ... In `view` function
let path_indicator = if let Some(error) = &self.error {
    match error {
        Error::DialogClosed => text("Dialog closed"),
        Error::IO(kind) => text(format!("I/O error: {:?}", kind))
    }
} else {
    text(self.title())
};

以下为完整的main.rs文件内容:

Download source code

  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
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use iced::{executor, keyboard, theme, Application, Command, Element, Font, Length, Settings, Subscription, Theme};
use iced::highlighter::{self, Highlighter};
use iced::widget::{button, column, container, horizontal_space, pick_list, row, text, text_editor, tooltip};

fn main() -> iced::Result {
    Editor::run(Settings {
        fonts: vec![include_bytes!("../fonts/editor-icon.ttf").as_slice().into()],
        ..Default::default()
    })
}

struct Editor {
    path: Option<PathBuf>,
    content: text_editor::Content,
    modified: bool,
    error: Option<Error>,
    theme: highlighter::Theme
}

#[derive(Debug, Clone)]
enum Message {
    EditorEdit(text_editor::Action),
    FileOpened(Result<(PathBuf, Arc<String>), Error>),
    FileSaved(Result<PathBuf, Error>),
    ThemeChanged(highlighter::Theme),
    NewButtonPressed,
    OpenButtonPressed,
    SaveButtonPressed
}

impl Application for Editor {
    type Message = Message; // Define the type of messages
    type Theme = Theme;
    type Executor = executor::Default; // Engine for running async tasks
    type Flags = ();

    fn new(_flags: Self::Flags) -> (Self, Command<Message>) {
        (
            Self {
                content: text_editor::Content::new(),
                error: None,
                modified: false,
                path: None,
                theme: highlighter::Theme::SolarizedDark
            },
            Command::perform(
            load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))),
            Message::FileOpened
            )
        )
    }

    fn title(&self) -> String {
        let path_text = match &self.path {
            None => String::from("New file"),
            Some(path) => path.to_string_lossy().to_string()
        };
        let suffix = if self.modified { "*" } else { "" };
        format!("{}{}", path_text, suffix)
    }

    fn subscription(&self) -> Subscription<Message> {
        keyboard::on_key_press(|keycode, modifier| {
            match (keycode, modifier) {
                (keyboard::KeyCode::S, keyboard::Modifiers::COMMAND) => {
                    Some(Message::SaveButtonPressed)
                },
                (keyboard::KeyCode::O, keyboard::Modifiers::COMMAND) => {
                    Some(Message::OpenButtonPressed)
                },
                (keyboard::KeyCode::N, keyboard::Modifiers::COMMAND) => {
                    Some(Message::NewButtonPressed)
                },
                _ => None
            }
        })
    }

    fn update(&mut self, message: Message) -> Command<Message> {
        // Handle messages here
        match message {
            Message::EditorEdit(action) => {
                match &action {
                    text_editor::Action::Edit(_) => self.modified = true,
                    _ => {}
                }
                self.content.edit(action);
                Command::none()
            },
            Message::FileOpened(Ok((path, result))) => {
                self.path = Some(path);
                self.modified = false;
                self.content = text_editor::Content::with(&result);
                Command::none()
            },
            Message::FileSaved(Ok(path)) => {
                self.path = Some(path);
                self.modified = false;
                Command::none()
            },
            Message::FileOpened(Err(error)) | Message::FileSaved(Err(error)) => {
                self.error = Some(error);
                Command::none()
            },
            Message::ThemeChanged(theme) => {
                self.theme = theme;
                Command::none()
            },
            Message::NewButtonPressed => {
                self.content = text_editor::Content::new();
                self.error = None;
                self.path = None;
                self.modified = false;
                Command::none()
            },
            Message::OpenButtonPressed => {
                self.modified = false;
                Command::perform(pick_file(), Message::FileOpened)
            },
            Message::SaveButtonPressed => {
                let content = self.content.text();
                match self.modified {
                    false => Command::none(),
                    true => Command::perform(
                        save_file(self.path.clone(), content),
                        Message::FileSaved
                    )
                }
            }
        }
    }

    fn view(&self) -> Element<'_, Message> {
        // Create the user interface here
        let editor = text_editor(&self.content)
            .on_edit(Message::EditorEdit)
            .highlight::<Highlighter>(
                highlighter::Settings {
                    theme: self.theme,
                    extension: self.path
                        .as_ref()
                        .and_then(|path| path.extension()?.to_str())
                        .unwrap_or("rs")
                        .to_string()
                }, |highlighter, _theme| {
                    highlighter.to_format()
                }
            )
            .font(Font::MONOSPACE);
        let controls = row![
            toolbar_button("New", Some(Message::NewButtonPressed)),
            toolbar_button("Open", Some(Message::OpenButtonPressed)),
            toolbar_button("Save", if self.modified { Some(Message::SaveButtonPressed) } else { None }),
            horizontal_space(Length::Fill),
            pick_list(highlighter::Theme::ALL, Some(self.theme), Message::ThemeChanged)
        ].spacing(10);

        // Query cursor position
        let path_indicator = if let Some(error) = &self.error {
            match error {
                Error::DialogClosed => text("Dialog closed"),
                Error::IO(kind) => text(format!("I/O error: {:?}", kind))
            }
        } else {
            text(self.title())
        };
        let cursor_indicator = {
            let (line, column) = self.content.cursor_position();

            text(format!("Line: {}, Column: {}", line + 1, column + 1))
        };
        let status_bar = row![
            path_indicator,
            horizontal_space(Length::Fill),
            cursor_indicator
        ];

        container(column![controls, editor, status_bar].spacing(10)).padding(10).into()
    }

    fn theme(&self) -> Theme {
        if self.theme.is_dark() {
            Theme::Dark
        } else {
            Theme::Light
        }
    }
}

async fn pick_file() -> Result<(PathBuf, Arc<String>), Error> {
    let file_handle = rfd::AsyncFileDialog::new()
        .set_title("Choose a text file...")
        .pick_file()
        .await
        .ok_or(Error::DialogClosed)?;
    load_file(file_handle.path()).await
}

async fn load_file(path: impl AsRef<Path>) -> Result<(PathBuf, Arc<String>), Error> {
    let content = tokio::fs::read_to_string(path.as_ref())
        .await
        .map(Arc::new)
        .map_err(|err| err.kind())
        .map_err(Error::IO);
    content.and_then(|content| Ok((path.as_ref().to_path_buf(), content)))
}

async fn save_file(path: Option<PathBuf>, content: String) -> Result<PathBuf, Error> {
    let path = if let Some(path) = path {
        path
    } else {
        rfd::AsyncFileDialog::new()
            .set_title("Save the file to...")
            .save_file()
            .await
            .ok_or(Error::DialogClosed)?
            .path()
            .to_path_buf()
    };
    tokio::fs::write(&path, content)
        .await
        .map_err(|err| err.kind())
        .map_err(Error::IO)
        .map(|_| path)
}

fn toolbar_button<'a>(description: &str, callback: Option<Message>) -> Element<'a, Message> {
    let font = Font::with_name("editor-icon");
    let lower = description.to_lowercase();
    let icon = text(match lower.as_str() {
        "new" => '\u{E800}',
        "open" => '\u{F115}',
        "save" => '\u{E801}',
        _ => ' '
    }).font(font);
    let is_disabled = callback.is_none();
    tooltip(
        button(container(icon)
            .width(30)  // Set the width of the button
            .center_x() // Center the icon
        ).on_press_maybe(callback).style(
            if is_disabled {
                theme::Button::Secondary
            } else {
                theme::Button::Primary
            }
        ),
        description, tooltip::Position::FollowCursor
    ).style(theme::Container::Box).into()
}

#[derive(Debug, Clone)]
enum Error {
    DialogClosed,
    IO(io::ErrorKind)
}

评论