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
//! Service to load files using `FileReader`.

use super::Task;
use crate::callback::Callback;
use std::cmp;
use std::fmt;
use stdweb::unstable::TryInto;
use stdweb::web::event::LoadEndEvent;
pub use stdweb::web::{Blob, File, IBlob};
use stdweb::web::{FileReader, FileReaderReadyState, FileReaderResult, IEventTarget, TypedArray};
#[allow(unused_imports)]
use stdweb::{_js_impl, js};

/// Struct that represents data of a file.
#[derive(Clone, Debug)]
pub struct FileData {
    /// Name of loaded file.
    pub name: String,
    /// Content of loaded file.
    pub content: Vec<u8>,
}

/// Struct that represents a chunk of a file.
#[derive(Clone, Debug)]
pub enum FileChunk {
    /// Reading of chunks started. Equals **0%** progress.
    Started {
        /// Name of loaded file.
        name: String,
    },
    /// The next data chunk that read. Also provides a progress value.
    DataChunk {
        /// The chunk of binary data.
        data: Vec<u8>,
        /// The progress value in interval: `0 < progress <= 1`.
        progress: f32,
    },
    /// Reading of chunks finished. Equals **100%** progress.
    Finished,
}

/// A reader service attached to a user context.
#[derive(Default, Debug)]
pub struct ReaderService {}

impl ReaderService {
    /// Creates a new service instance connected to `App` by provided `sender`.
    pub fn new() -> Self {
        Self {}
    }

    /// Reads all bytes from a file and returns them with a callback.
    pub fn read_file(&mut self, file: File, callback: Callback<FileData>) -> ReaderTask {
        let file_reader = FileReader::new();
        let reader = file_reader.clone();
        let name = file.name();
        file_reader.add_event_listener(move |_event: LoadEndEvent| match reader.result() {
            Some(FileReaderResult::String(_)) => {
                unreachable!();
            }
            Some(FileReaderResult::ArrayBuffer(buffer)) => {
                let array: TypedArray<u8> = buffer.into();
                let data = FileData {
                    name: name.clone(),
                    content: array.to_vec(),
                };
                callback.emit(data);
            }
            None => {}
        });
        file_reader.read_as_array_buffer(&file).unwrap();
        ReaderTask { file_reader }
    }

    /// Reads data chunks from a file and returns them with a callback.
    pub fn read_file_by_chunks(
        &mut self,
        file: File,
        callback: Callback<FileChunk>,
        chunk_size: usize,
    ) -> ReaderTask {
        let file_reader = FileReader::new();
        let name = file.name();
        let mut position = 0;
        let total_size = file.len() as usize;
        let reader = file_reader.clone();
        file_reader.add_event_listener(move |_event: LoadEndEvent| {
            match reader.result() {
                // This branch is used to start reading
                Some(FileReaderResult::String(_)) => {
                    let started = FileChunk::Started { name: name.clone() };
                    callback.emit(started);
                }
                // This branch is used to send a chunk value
                Some(FileReaderResult::ArrayBuffer(buffer)) => {
                    let array: TypedArray<u8> = buffer.into();
                    let chunk = FileChunk::DataChunk {
                        data: array.to_vec(),
                        progress: position as f32 / total_size as f32,
                    };
                    callback.emit(chunk);
                }
                None => {}
            }
            // Read the next chunk
            if position < total_size {
                let file = &file;
                let from = position;
                let to = cmp::min(position + chunk_size, total_size);
                position = to;
                // TODO Implement `slice` method in `stdweb`
                let blob: Blob = (js! {
                    return @{file}.slice(@{from as u32}, @{to as u32});
                })
                .try_into()
                .unwrap();
                reader.read_as_array_buffer(&blob).unwrap();
            } else {
                let finished = FileChunk::Finished;
                callback.emit(finished);
            }
        });
        let blob: Blob = (js! {
            return (new Blob());
        })
        .try_into()
        .unwrap();
        file_reader.read_as_text(&blob).unwrap();
        ReaderTask { file_reader }
    }
}

/// A handle to control reading.
#[must_use]
pub struct ReaderTask {
    file_reader: FileReader,
}

impl fmt::Debug for ReaderTask {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ReaderTask")
    }
}

impl Task for ReaderTask {
    fn is_active(&self) -> bool {
        self.file_reader.ready_state() == FileReaderReadyState::Loading
    }

    fn cancel(&mut self) {
        self.file_reader.abort();
    }
}

impl Drop for ReaderTask {
    fn drop(&mut self) {
        if self.is_active() {
            self.cancel();
        }
    }
}