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
use crate::{content, message::*, style, subscribe_irc, util};
use iced::{
    button, pane_grid, text_input, Align, Application, Button, Clipboard, Column, Command,
    Container, Element, Length, PaneGrid, Row, Subscription, Text, TextInput,
};
use serde::{Deserialize, Serialize};

use irc::client::prelude::{Client, Config};
use std::{collections::HashMap, sync::Arc};

// アプリケーションの状態管理
#[derive(Debug, Clone)]
pub struct State {
    input_state: text_input::State,
    input_value: String,
    connecting_flag: bool,
    display_value: String,
    channel_texts: HashMap<String, String>,
    saving: bool,
    dirty: bool,
    current_channel: String,
    show_channels: Vec<String>,
    config: Config,
    irc_button_state: button::State,
    post_button_state: button::State,
    sender: Option<Arc<futures::lock::Mutex<irc::client::Sender>>>,
    panes: pane_grid::State<content::Content>,
    panes_created: usize,
    focus: Option<pane_grid::Pane>,
    client_stream: Option<Arc<futures::lock::Mutex<irc::client::ClientStream>>>,
}

impl Default for State {
    fn default() -> Self {
        let show_channels = vec!["Setting".to_string()];
        let (panes, _) = pane_grid::State::new(content::Content::new(0, &show_channels));
        Self {
            input_state: text_input::State::new(),
            input_value: String::from(""),
            connecting_flag: false,
            display_value: String::from(""),
            channel_texts: HashMap::new(),
            saving: true,
            dirty: true,
            current_channel: String::from("Setting"),
            show_channels: show_channels,
            config: Config::default(),
            irc_button_state: button::State::new(),
            post_button_state: button::State::new(),
            sender: None,
            panes: panes,
            panes_created: 1,
            focus: None,
            client_stream: None,
        }
    }
}

// 下記の実装を元に持ってこられたもの
// https://github.com/hecrj/iced/tree/master/examples/todos
// アプリケーション起動時に設定ファイルの読み込みをする仕組みのためにSavedStateが存在する。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SavedState {
    pub nickname: String,
    pub username: String,
    pub realname: String,
    pub server: String,
    pub port: u16,
    pub use_tls: bool,
    pub encoding: String,
    pub channels: Vec<String>,
    pub current_channel: String,
}

#[cfg(not(target_arch = "wasm32"))]
impl SavedState {
    // ファイルから状態を読み込む
    async fn load() -> Result<SavedState, LoadError> {
        use async_std::prelude::*;

        let mut contents = String::new();

        let mut file = async_std::fs::File::open("setting.json")
            .await
            .map_err(|_| LoadError::FileError)?;

        file.read_to_string(&mut contents)
            .await
            .map_err(|_| LoadError::FileError)?;

        serde_json::from_str(&contents).map_err(|_| LoadError::FormatError)
    }
    // ファイルに状態を保存
    //async fn save(self) -> Result<(), SaveError> {
    //    Ok(())
    //}
}

#[derive(Debug, Clone)]
pub enum LoadError {
    // ファイル読み込み時エラー状態名
    FileError,
    FormatError,
}

#[derive(Debug, Clone)]
pub enum SaveError {
    // 設定ファイル保存時のエラー状態名
    DirectoryError,
    FileError,
    WriteError,
    FormatError,
}

#[derive(Debug, Clone)]
pub enum IrcError {
    IrcError,
}

// 試験的実装。IrcClientを取りまとめるstructを作ってみた。
pub struct IrcClient {
    client_stream: irc::client::ClientStream,
    sender: irc::client::Sender,
}

impl IrcClient {
    async fn get_client(state: &mut State) -> Result<IrcClient, failure::Error> {
        let mut client = Client::from_config(state.config.clone()).await?;
        client.identify()?;
        Ok(IrcClient {
            client_stream: client.stream()?,
            sender: client.sender(),
        })
    }
}

// アプリケーションの状態。これが大元。ライブラリからも要求される。Stateを内包する設計になっている。
// このenumの分け方とStateの分け方の設計が良いかどうかは若干考えた方がいい。色々と不便の原因にはなっている。
pub enum App {
    Loading,
    Loaded(State),
    IrcConnecting(State),
    IrcFinished(State),
}

// Iced Applicationライブラリが要求する実装
impl Application for App {
    type Executor = iced::executor::Default;
    type Message = Message;
    type Flags = ();

    // アプリケーションの初期化 App::Loading -> (futureでSaveState::loadが完了したらMessageLoadedが発行される) -> App::Loaded
    fn new(_flags: ()) -> (App, Command<Self::Message>) {
        (
            App::Loading,
            Command::perform(SavedState::load(), Message::Loaded),
        )
    }

    // アプリケーションのタイトル
    fn title(&self) -> String {
        String::from("Gelato")
    }

    // アプリケーションの更新
    fn update(
        &mut self,
        message: Self::Message,
        _clipboard: &mut Clipboard,
    ) -> Command<Self::Message> {
        // アプリケーションの種類状態でのマッチ
        match self {
            // アプリケーション初期化中
            App::Loading => {
                match message {
                    Message::Loaded(Ok(_saved_state)) => {
                        let config = Config {
                            username: Some(_saved_state.username),
                            nickname: Some(_saved_state.nickname),
                            realname: Some(_saved_state.realname),
                            server: Some(_saved_state.server),
                            port: Some(_saved_state.port),
                            use_tls: Some(_saved_state.use_tls),
                            encoding: Some(_saved_state.encoding),
                            channels: _saved_state.channels,
                            ..Default::default()
                        };
                        let state = State {
                            config: config,
                            current_channel: _saved_state.current_channel,
                            ..Default::default()
                        };
                        *self = App::Loaded(state);
                    }
                    Message::Loaded(Err(_)) => {
                        println!("gelato couldn't find setting.json");
                        *self = App::Loaded(State::default());
                    }
                    _ => {}
                }
                Command::none()
            }
            // アプリケーション初期化完了時
            App::Loaded(state) => {
                let mut saved = false;
                let mut ircflag = false;

                // アプリケーションが受け取ったメッセージごとでフラグを書き換える。
                match message {
                    Message::Saved(_) => {
                        state.saving = false;
                        saved = true;
                    }
                    Message::IrcStart => {
                        ircflag = true;
                    }
                    _ => {}
                }

                // フラグに基づき、最終的なコマンドを設定する。
                // TODOサンプルを元に作成しているため、saved, dirtyはtodoからきている。使われていないものもある。
                if !saved {
                    state.dirty = true;
                }

                if state.dirty && !state.saving {
                    state.dirty = false;
                    state.saving = true;
                    // いったん何もしないことにする。
                    /*Command::perform(
                        SavedState {
                            input_value: state.input_value.clone(),
                            display_value: state.display_value.clone(),
                        }
                        .save(),
                        Message::Saved,
                    )*/
                    // IRCが開始されたら、selfをIRCConnectingに強制上書きする。
                } else if ircflag {
                    let mut current_state = state.clone();
                    futures::executor::block_on(async {
                        let irc_client_struct = IrcClient::get_client(&mut current_state)
                            .await
                            .expect("get_client()");
                        current_state.client_stream = Some(Arc::new(futures::lock::Mutex::new(
                            irc_client_struct.client_stream,
                        )));
                        current_state.sender = Some(Arc::new(futures::lock::Mutex::new(
                            irc_client_struct.sender,
                        )));
                    });
                    *self = App::IrcConnecting(current_state);
                }
                Command::none()
            }
            // IRC接続状態の時
            App::IrcConnecting(state) => {
                state.connecting_flag = true;
                // TODO : 本当はここは1:1ではないよね
                state.show_channels.append(&mut state.config.channels);
                let mut irc_finished = false;
                let mut posted = false;
                let mut input_word = String::from("");
                match message {
                    // Message::IrcProgressedは、subscription関数のmapで渡されている関数
                    Message::IrcProgressed(progress_state) => match progress_state {
                        // model/subscribe_irc.rsで実装されているProgressから結果のmessage_textが返却される。
                        subscribe_irc::Progress::Advanced(message_text) => {
                            // メッセージのフィルタリング
                            util::filter(&message_text, &mut state.channel_texts);
                            //state.display_value.push_str(filtered_text);
                        }
                        subscribe_irc::Progress::Finished => {
                            irc_finished = true;
                        }
                        subscribe_irc::Progress::Errored => {
                            irc_finished = true;
                        }
                        _ => {}
                    },
                    Message::IrcFinished(_) => {
                        irc_finished = true;
                        state.connecting_flag = false;
                    }
                    Message::InputChanged(value) => {
                        state.input_value = value;
                    }
                    Message::PostMessage => {
                        posted = true;
                        input_word.push_str(&state.input_value.clone());
                        state.input_value = String::from("");
                    }
                    Message::Split(axis, pane) => {
                        let result = state.panes.split(
                            axis,
                            &pane,
                            content::Content::new(state.panes_created, &state.show_channels),
                        );

                        if let Some((pane, _)) = result {
                            state.focus = Some(pane);
                            if let Some(pstate) = state.panes.get(&pane) {
                                state.current_channel = pstate.channel_name.clone();
                            }
                        }

                        state.panes_created += 1;
                    }
                    Message::SplitFocused(axis) => {
                        if let Some(pane) = state.focus {
                            let result = state.panes.split(
                                axis,
                                &pane,
                                content::Content::new(state.panes_created, &state.show_channels),
                            );

                            if let Some((pane, _)) = result {
                                state.focus = Some(pane);
                                if let Some(pstate) = state.panes.get(&pane) {
                                    state.current_channel = pstate.channel_name.clone();
                                }
                            }

                            state.panes_created += 1;
                        }
                    }
                    Message::FocusAdjacent(direction) => {
                        if let Some(pane) = state.focus {
                            if let Some(adjacent) = state.panes.adjacent(&pane, direction) {
                                state.focus = Some(adjacent);
                                if let Some(pstate) = state.panes.get(&pane) {
                                    state.current_channel = pstate.channel_name.clone();
                                }
                            }
                        }
                    }
                    Message::Clicked(pane) => {
                        state.focus = Some(pane);
                        if let Some(pstate) = state.panes.get(&pane) {
                            state.current_channel = pstate.channel_name.clone();
                        }
                    }
                    Message::Resized(pane_grid::ResizeEvent { split, ratio }) => {
                        state.panes.resize(&split, ratio);
                    }
                    Message::Dragged(pane_grid::DragEvent::Dropped { pane, target }) => {
                        state.panes.swap(&pane, &target);
                    }
                    Message::Dragged(_) => {}
                    Message::Close(pane) => {
                        if let Some((_, sibling)) = state.panes.close(&pane) {
                            state.focus = Some(sibling);
                            if let Some(pstate) = state.panes.get(&sibling) {
                                state.current_channel = pstate.channel_name.clone();
                            }
                        }
                    }
                    Message::CloseFocused => {
                        if let Some(pane) = state.focus {
                            if let Some((_, sibling)) = state.panes.close(&pane) {
                                state.focus = Some(sibling);
                                if let Some(pstate) = state.panes.get(&sibling) {
                                    state.current_channel = pstate.channel_name.clone();
                                }
                            }
                        }
                    }
                    _ => {}
                }

                if posted && !input_word.is_empty() {
                    let sender_original =
                        Arc::clone(&state.sender.as_ref().expect("sender_original error"));
                    let channel = state.current_channel.clone();
                    let dummy = String::new();
                    let channel_texts = state.channel_texts.clone();
                    let input_text = channel_texts.get(&channel).unwrap_or(&dummy);
                    let nickname = state.config.username();
                    &state.channel_texts.insert(
                        channel.clone(),
                        input_text.clone() + nickname + " " + &input_word + "\n",
                    );

                    let call = async move {
                        let sender = sender_original.lock().await;
                        (*sender)
                            .send_privmsg(channel, input_word)
                            .expect("call async move send_privmsg");
                    };
                    Command::perform(call, Message::None)
                } else if irc_finished {
                    *self = App::IrcFinished(state.clone());
                    Command::perform(Message::change(), Message::IrcFinished)
                } else {
                    Command::none()
                }
            }
            App::IrcFinished(state) => {
                *self = App::Loaded(state.clone());
                Command::none()
            }
        }
    }

    // サブスクリプションの登録。
    // selfはアプリケーションのenumのため、必要に応じてStateの中身を取り出す。
    fn subscription(&self) -> Subscription<Message> {
        match self {
            App::IrcConnecting(State { client_stream, .. }) => {
                let client_stream = client_stream.as_ref();
                subscribe_irc::input(client_stream, "").map(Message::IrcProgressed)
            }
            // input関数への受け渡しは適当にいろいろ試しているため、何も考えていない。

            // IRCと接続時以外は特に何もしない。
            _ => Subscription::none(),
        }
    }

    // 更新された時に呼び出される描画関数
    // いつか部分ごとに関数化&外部ファイル化したいと考えているが、現状はここに全部書いている。
    // CSSのような装飾はstyle.rsで設定している。
    fn view(&mut self) -> Element<Self::Message> {
        match self {
            App::Loading => util::loading_panel(),
            App::Loaded(state) => {
                let label_username = state.config.username.as_ref().expect("label_username");
                let app_loaded_col = Column::new()
                    .push(Text::new("Settings").size(50))
                    .push(Text::new(label_username))
                    .push(Text::new(state.config.server.as_ref().expect("server")))
                    .push(Text::new(
                        state.config.port.as_ref().expect("port").to_string(),
                    ))
                    .push(Text::new(state.current_channel.to_string()))
                    .push(
                        Button::new(&mut state.irc_button_state, Text::new("Connect"))
                            .on_press(Message::IrcStart)
                            .style(style::Button::Post),
                    );
                Container::new(app_loaded_col)
                    .width(Length::Fill)
                    .height(Length::Fill)
                    .into()
            }
            App::IrcConnecting(state) | App::IrcFinished(state) => {
                // I'm going to delete START IRC BUTTON
                let start_irc_button_control: Element<_> = {
                    let (label, toggle, style) = if state.connecting_flag {
                        (
                            "Stop IRC",
                            Message::IrcFinished(Ok(())),
                            style::Button::Stop,
                        )
                    } else {
                        ("Start IRC", Message::IrcStart, style::Button::Start)
                    };
                    Button::new(&mut state.irc_button_state, Text::new(label).size(25))
                        .style(style)
                        .on_press(toggle)
                        .into()
                };

                // Below Contents
                let post_button: Element<_> = {
                    let (label, toggle, style) =
                        ("Post", Message::PostMessage, style::Button::Post);
                    Button::new(&mut state.post_button_state, Text::new(label).size(25))
                        .style(style)
                        .on_press(toggle)
                        .into()
                };

                let input_box = TextInput::new(
                    &mut state.input_state,
                    "Input text...",
                    &state.input_value,
                    Message::InputChanged,
                )
                .padding(10)
                .size(15)
                .on_submit(Message::PostMessage);

                let content2 = Column::new()
                    .padding(10)
                    .spacing(10)
                    .align_items(Align::Start)
                    .push(
                        Row::new()
                            .push(input_box)
                            .push(post_button)
                            .push(start_irc_button_control),
                    );

                // Panel Grid Components
                let focus = state.focus;
                let total_panes = state.panes.len();
                let channel_texts = state.channel_texts.clone();
                let pane_grid = PaneGrid::new(&mut state.panes, |pane, content| {
                    let is_focused = focus == Some(pane);
                    let dummy = String::new();
                    let text = channel_texts.get(&content.channel_name).unwrap_or(&dummy);
                    let title = Row::with_children(vec![Text::new(content.channel_name.clone())
                        .size(18)
                        .into()])
                    .spacing(3);

                    let title_bar = pane_grid::TitleBar::new(title)
                        .padding(2)
                        .style(style::TitleBar { is_focused });
                    pane_grid::Content::new(content.view(pane, total_panes, text.to_string()))
                        .title_bar(title_bar)
                        .style(style::Pane { is_focused })
                })
                .width(Length::Fill)
                .height(Length::Fill)
                .spacing(5)
                .on_click(Message::Clicked)
                .on_drag(Message::Dragged)
                .on_resize(10, Message::Resized);

                // Container Components
                let container = Column::new().spacing(1).push(pane_grid).push(content2);

                Container::new(container)
                    .width(Length::FillPortion(2))
                    .height(Length::Fill)
                    .into()
            }
        }
    }
}