跳转至

Syntax Highlighting

Keywords: iced::widget::pick_list

本节添加代码编辑器的语法高亮功能。

首先,修改编辑器的默认字体为等宽字体,以便更好地显示代码。

// ... In `view` function
let editor = text_editor(&self.content)
    .on_edit(Message::EditorEdit)
    .font(Font::MONOSPACE);

接下来,添加高亮处理的逻辑。高亮功能由icedhighlighter模块提供,需要在Cargo.toml中添加依赖。

[dependencies]
iced = { git = "https://github.com/iced-rs/iced.git", rev = "refs/tags/text-editor", features = [ "highlighter" ] }

在文本框的highlight方法中设置高亮。highlight方法需要指定配色方案theme和语法extensionextension可以根据文件路径的后缀名自动识别,如果没有后缀名,则默认为rs

let editor = text_editor(&self.content)
    .on_edit(Message::EditorEdit)
    .highlight::<Highlighter>( // use iced::highlighter::Highlighter
        highlighter::Settings {
            theme: highlighter::Theme::SolarizedDark, // Set the theme
            extension: self.path
                .as_ref()
                .and_then(|path| path.extension()?.to_str())
                .unwrap_or("rs") // If extension is not found, use `rs`
                .to_string()
        }, |highlighter, _theme| {
            highlighter.to_format()
        }
    )
    .font(Font::MONOSPACE);

接下来添加高亮风格的选择功能。首先在Editor中添加theme状态作为当前的主题,并且设置初始化状态。

struct Editor {
    // ...
    theme: highlighter::Theme
}
// ... In `new` function
Self {
    // ...
    theme: highlighter::Theme::SolarizedDark
},
// ... In `view` function
highlighter::Settings {
    theme: self.theme,
    // ...
}

添加一个pick_list控件用于选择高亮风格,pick_list需要设置选项、当前选中项和触发事件。每次更新时都会以选中项为参数触发事件。

let controls = row![
    toolbar_button("New", Message::NewButtonPressed),
    toolbar_button("Open", Message::OpenButtonPressed),
    toolbar_button("Save", Message::SaveButtonPressed),
    horizontal_space(Length::Fill),
    pick_list(highlighter::Theme::ALL, Some(self.theme), Message::ThemeChanged)
].spacing(10);

同时更新ThemeChanged事件的处理逻辑

// ... In `update` function
Message::ThemeChanged(theme) => {
    self.theme = theme;
    Command::none()
}

内置的部分主题并不是暗色主题,需要添加一个根据主题的亮暗切换窗口配色的功能:

// ... In `impl Application for Editor`
fn theme(&self) -> Theme {
    if self.theme.is_dark() {
        Theme::Dark
    } else {
        Theme::Light
    }
}

以下为完整的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
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use iced::{executor, theme, Application, Command, Element, Font, Length, Settings, 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 {
        String::from("A text editor")
    }

    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", Message::NewButtonPressed),
            toolbar_button("Open", Message::OpenButtonPressed),
            toolbar_button("Save", Message::SaveButtonPressed),
            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 {
            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 { "" };
            text(format!("{}{}", path_text, suffix))
        };
        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: 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);

    tooltip(
        button(container(icon)
            .width(30)  // Set the width of the button
            .center_x() // Center the icon
        ).on_press(callback),
        description, tooltip::Position::FollowCursor
    ).style(theme::Container::Box).into()
}

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

评论