Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web-sys reader service conversion #868

Merged
merged 11 commits into from
Jan 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ pub mod dialog;
pub mod fetch;
pub mod interval;
pub mod keyboard;
#[cfg(feature = "std_web")]
pub mod reader;
pub mod render;
pub mod resize;
Expand All @@ -20,7 +19,6 @@ pub use self::console::ConsoleService;
pub use self::dialog::DialogService;
pub use self::fetch::FetchService;
pub use self::interval::IntervalService;
#[cfg(feature = "std_web")]
pub use self::reader::ReaderService;
pub use self::render::RenderService;
pub use self::resize::ResizeService;
Expand Down
126 changes: 11 additions & 115 deletions src/services/reader.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
//! Service to load files using `FileReader`.

use super::Task;
use crate::callback::Callback;
use std::cmp;
use crate::services::Task;
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};
cfg_if::cfg_if! {
if #[cfg(feature = "std_web")] {
mod std_web;
pub use std_web::*;
} else if #[cfg(feature = "web_sys")] {
mod web_sys;
pub use self::web_sys::*;
}
}

/// Struct that represents data of a file.
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -43,119 +44,14 @@ pub enum FileChunk {
#[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();
}
self.cancel();
}
}
137 changes: 137 additions & 0 deletions src/services/reader/std_web.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
//! `stdweb` implementation for the reader service.

use super::*;
use crate::callback::Callback;
use crate::services::Task;
use std::cmp;
use stdweb::unstable::{TryFrom, 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};

fn new_file_reader() -> Result<FileReader, &'static str> {
let file_reader = js! {
try {
return new FileReader;
} catch(error) {
return error;
}
};
FileReader::try_from(js!( return @{file_reader.as_ref()}; ))
.map_err(|_| "couldn't aquire file reader")
}

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>,
) -> Result<ReaderTask, &str> {
let file_reader = new_file_reader()?;
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();
Ok(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<Option<FileChunk>>,
chunk_size: usize,
) -> Result<ReaderTask, &str> {
let file_reader = new_file_reader()?;
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| {
if let Some(result) = reader.result() {
match result {
// This branch is used to start reading
FileReaderResult::String(_) => {
let started = FileChunk::Started { name: name.clone() };
callback.emit(Some(started));
}
// This branch is used to send a chunk value
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(Some(chunk));
}
}

// 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(Some(finished));
}
} else {
callback.emit(None);
}
});
let blob: Blob = (js! {
return (new Blob());
})
.try_into()
.unwrap();
file_reader.read_as_text(&blob).unwrap();
Ok(ReaderTask { file_reader })
}
}

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

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

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