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
use std::thread;
use std::thread::JoinHandle;

use async_std::{
    channel::Sender,
    sync::{Arc, Mutex},
};
use gdk::ModifierType;
use glib::{Receiver, object::Cast};
use gtk::{self, prelude::*};
use ignore_result::Ignore;

pub use error::Error;
use frontend_interface::Images;
use settings::Settings;

use crate::backend::ControlFlow;

mod backend;
mod common_structs;
mod current_downloads;
mod download_list;
mod error;
mod frontend_interface;
mod like_list;
mod localization;
mod offline_search;
mod progress_bar;
mod settings;
mod helper;

/// Widgets needed for the app to work
pub struct WindowObjects {
    pub window: gtk::ApplicationWindow,
    pub progress: progress_bar::Gui,
    pub download_list: download_list::frontend::DownloadFrontend,
    pub like_list: like_list::frontend::LikeFrontend,
    pub current_download_list: current_downloads::frontend::CurrentDownloadFrontend,
    pub stream_list: gtk::ListBox,
    pub offline_search: offline_search::frontend::OfflineSearchFrontend,
}

/// Build the UI and start both the foreground and background listeners
pub fn build_ui(
    application: &gtk::Application,
    sender_channels: SenderChannels,
    receiver_channels: ReceiverChannels,
    settings: Arc<Mutex<Settings>>,
) {
    let mut window_objects = frontend_interface::construct_window(settings, sender_channels.clone());

    let window = window_objects.window.clone();

    window.set_application(Some(application));

    window.show_all();

    window_objects.download_list.connect_events().unwrap();
    window_objects.like_list.connect_events().unwrap();
    window_objects
        .current_download_list
        .connect_events()
        .unwrap();
    window_objects.offline_search.connect_events().unwrap();
    window_objects.progress.connect_events().unwrap();

    window_objects
        .download_list
        .attach_handler(receiver_channels.download_rx)
        .unwrap();
    window_objects
        .like_list
        .attach_handler(receiver_channels.like_rx)
        .unwrap();
    window_objects
        .current_download_list
        .attach_handler(receiver_channels.current_rx)
        .unwrap();
    window_objects
        .offline_search
        .attach_handler(receiver_channels.offline_search_rx)
        .unwrap();
    window_objects
        .progress
        .attach_handler(receiver_channels.progress_rx)
        .unwrap();

    window_objects.download_list.check().unwrap();
    window_objects.like_list.check().unwrap();
    window_objects.current_download_list.check().unwrap();
    window_objects.offline_search.check().unwrap();
    window_objects.progress.check().unwrap();

    let application_clone = application.clone();

    receiver_channels
        .error_reporting_rx
        .attach(None, move |msg| match msg {
            backend::BackendError::Error(err) => {
                let dialog = gtk::MessageDialogBuilder::new()
                    .application(&application_clone)
                    .title(&fl!("error-box-title"))
                    .buttons(gtk::ButtonsType::Ok)
                    .destroy_with_parent(true)
                    .message_type(gtk::MessageType::Error)
                    .text(&fl!("error-box-content", message = err))
                    .build();
                dialog.get_children()
                    .into_iter()
                    .map(|w| w.dynamic_cast::<gtk::Label>())
                    .for_each(|l| if let Ok(l) = l {l.set_selectable(true)});
                dialog.show_all();
                glib::Continue(true)
            }
        });

    window.connect_key_release_event(move |wnd, key| match key.get_keyval().to_unicode() {
        Some('q') | Some('Q') => {
            if key.get_state().intersects(ModifierType::CONTROL_MASK) {
                unsafe {
                    wnd.destroy();
                }
                gtk::Inhibit(true)
            } else {
                gtk::Inhibit(false)
            }
        }
        _ => gtk::Inhibit(false),
    });


    window.connect_destroy(move |_| {
        let flow = ControlFlow::Quit;
        sender_channels
            .download_tx
            .try_send(download_list::backend::DownloadListAction::ControlFlow(flow.clone()))
            .ignore();
        sender_channels
            .like_tx
            .try_send(like_list::backend::LikeListAction::ControlFlow(
                flow.clone(),
            ))
            .ignore();
        sender_channels
            .current_tx
            .try_send(current_downloads::backend::ListAction::ControlFlow(
                flow.clone(),
            ))
            .ignore();
        sender_channels
            .offline_search_tx
            .try_send(offline_search::backend::OfflineSearchAction::ControlFlow(flow))
            .ignore();
        for _ in 0..2 {
            sender_channels
                .backend_control_tx
                .try_send(helper::Control::Exit)
                .ignore();
        }
    });
}

pub struct ReceiverChannels {
    download_rx: Receiver<download_list::frontend::DownloadListChange>,
    like_rx: Receiver<like_list::frontend::LikeListChange>,
    current_rx: Receiver<current_downloads::frontend::ListChange>,
    offline_search_rx: Receiver<offline_search::frontend::ListChange>,
    error_reporting_rx: Receiver<backend::BackendError>,
    progress_rx: Receiver<progress_bar::Event>,
}

#[derive(Clone)]
pub struct SenderChannels {
    download_tx: Sender<download_list::backend::DownloadListAction>,
    like_tx: Sender<like_list::backend::LikeListAction>,
    current_tx: Sender<current_downloads::backend::ListAction>,
    offline_search_tx: Sender<offline_search::backend::OfflineSearchAction>,
    backend_control_tx: Sender<helper::Control>,
    backend_download_tx: Sender<helper::download::DownloadSignal>,
}

pub fn build_backend() -> (
    JoinHandle<()>,
    SenderChannels,
    ReceiverChannels,
    Arc<Mutex<Settings>>,
) {
    let settings = Arc::new(Mutex::new(Settings::new().unwrap_or_else(|error| {
        panic!(
            "{}",
            fl!("settings-not-loaded", error = format!("{:?}", error))
        )
    })));

    let (backend_download_tx, backend_download_rx) = async_std::channel::unbounded();
    let (progress_tx, progress_rx) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
    let (download_rx, download_tx, download_list_comm) =
        download_list::backend::Communication::new(backend_download_tx.clone());
    let (like_rx, like_tx, like_list_comm) = like_list::backend::Communication::new();
    let (current_rx, current_tx, current_list_comm) =
        current_downloads::backend::Communication::new();
    let (offline_search_rx, offline_search_tx, offline_search_comm) =
        offline_search::backend::Communication::new(download_tx.clone(), like_tx.clone());
    let (error_reporting_tx, error_reporting_rx) =
        glib::MainContext::channel(glib::Priority::default());
    let (backend_control_tx, backend_control_rx) = async_std::channel::unbounded();

    let arguments = backend::BackendArguments {
        download_list_comm,
        like_list_comm,
        current_list_comm,
        download_tx: download_tx.clone(),
        current_tx: current_tx.clone(),
        like_tx: like_tx.clone(),
        offline_search_comm,
        error_reporting_tx,
        backend_download_tx: backend_download_tx.clone(),
        backend_download_rx,
        backend_control_rx,
        progress_tx,
        settings: settings.clone(),
    };

    let thread = thread::spawn(move || backend::sync_init(arguments));

    let sender_channels = SenderChannels {
        download_tx,
        like_tx,
        current_tx,
        offline_search_tx,
        backend_control_tx,
        backend_download_tx,
    };

    let receiver_channels = ReceiverChannels {
        download_rx,
        like_rx,
        current_rx,
        offline_search_rx,
        error_reporting_rx,
        progress_rx,
    };
    (thread, sender_channels, receiver_channels, settings)
}

#[cfg(test)]
mod tests {
    //#[test]
    //fn it_works() {
    //    assert_eq!(2 + 2, 4);
    //}
}