Auto merge of #12448 - jdm:file-reading-task-source-2, r=KiChjang

Implement file reading task source

Implement the task source API for the File Reader task source, enabling using task sources from non-main threads.

---
- [X] `./mach build -d` does not report any errors
- [X] `./mach test-tidy` does not report any errors
- [X] These changes fix (partially) #7959 (github issue number if applicable).
- [X] These changes do not require tests because they're refactoring existing code

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/12448)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2016-07-14 10:55:17 -07:00 committed by GitHub
commit 48a912f57e
14 changed files with 155 additions and 84 deletions

View file

@ -23,9 +23,10 @@ use net_traits::filemanager_thread::FileManagerThreadMsg;
use net_traits::{ResourceThreads, CoreResourceThread, RequestSource, IpcSend}; use net_traits::{ResourceThreads, CoreResourceThread, RequestSource, IpcSend};
use profile_traits::{mem, time}; use profile_traits::{mem, time};
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
use script_thread::{MainThreadScriptChan, ScriptThread}; use script_thread::{MainThreadScriptChan, ScriptThread, RunnableWrapper};
use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEventRequest}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEventRequest};
use task_source::dom_manipulation::DOMManipulationTaskSource; use task_source::dom_manipulation::DOMManipulationTaskSource;
use task_source::file_reading::FileReadingTaskSource;
use timers::{OneshotTimerCallback, OneshotTimerHandle}; use timers::{OneshotTimerCallback, OneshotTimerHandle};
use url::Url; use url::Url;
@ -219,10 +220,10 @@ impl<'a> GlobalRef<'a> {
/// `ScriptChan` used to send messages to the event loop of this global's /// `ScriptChan` used to send messages to the event loop of this global's
/// thread. /// thread.
pub fn file_reading_task_source(&self) -> Box<ScriptChan + Send> { pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
match *self { match *self {
GlobalRef::Window(ref window) => window.file_reading_task_source(), GlobalRef::Window(ref window) => window.file_reading_task_source(),
GlobalRef::Worker(ref worker) => worker.script_chan(), GlobalRef::Worker(ref worker) => worker.file_reading_task_source(),
} }
} }
@ -297,6 +298,15 @@ impl<'a> GlobalRef<'a> {
GlobalRef::Worker(ref worker) => worker.panic_chan(), GlobalRef::Worker(ref worker) => worker.panic_chan(),
} }
} }
/// Returns a wrapper for runnables to ensure they are cancelled if the global
/// is being destroyed.
pub fn get_runnable_wrapper(&self) -> RunnableWrapper {
match *self {
GlobalRef::Window(ref window) => window.get_runnable_wrapper(),
GlobalRef::Worker(ref worker) => worker.get_runnable_wrapper(),
}
}
} }
impl GlobalRoot { impl GlobalRoot {

View file

@ -23,12 +23,12 @@ use encoding::label::encoding_from_whatwg_label;
use encoding::types::{DecoderTrap, EncodingRef}; use encoding::types::{DecoderTrap, EncodingRef};
use hyper::mime::{Attr, Mime}; use hyper::mime::{Attr, Mime};
use rustc_serialize::base64::{CharacterSet, Config, Newline, ToBase64}; use rustc_serialize::base64::{CharacterSet, Config, Newline, ToBase64};
use script_runtime::ScriptThreadEventCategory::FileRead; use script_thread::RunnableWrapper;
use script_runtime::{ScriptChan, CommonScriptMsg};
use script_thread::Runnable;
use std::cell::Cell; use std::cell::Cell;
use std::sync::Arc; use std::sync::Arc;
use string_cache::Atom; use string_cache::Atom;
use task_source::TaskSource;
use task_source::file_reading::{FileReadingTaskSource, FileReadingRunnable, FileReadingTask};
use util::thread::spawn_named; use util::thread::spawn_named;
#[derive(PartialEq, Clone, Copy, JSTraceable, HeapSizeOf)] #[derive(PartialEq, Clone, Copy, JSTraceable, HeapSizeOf)]
@ -358,10 +358,11 @@ impl FileReader {
let fr = Trusted::new(self); let fr = Trusted::new(self);
let gen_id = self.generation_id.get(); let gen_id = self.generation_id.get();
let script_chan = self.global().r().file_reading_task_source(); let wrapper = self.global().r().get_runnable_wrapper();
let task_source = self.global().r().file_reading_task_source();
spawn_named("file reader async operation".to_owned(), move || { spawn_named("file reader async operation".to_owned(), move || {
perform_annotated_read_operation(gen_id, load_data, blob_contents, fr, script_chan) perform_annotated_read_operation(gen_id, load_data, blob_contents, fr, task_source, wrapper)
}); });
Ok(()) Ok(())
} }
@ -371,47 +372,20 @@ impl FileReader {
} }
} }
#[derive(Clone)]
pub enum FileReaderEvent {
ProcessRead(TrustedFileReader, GenerationId),
ProcessReadData(TrustedFileReader, GenerationId),
ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName),
ProcessReadEOF(TrustedFileReader, GenerationId, ReadMetaData, Arc<Vec<u8>>)
}
impl Runnable for FileReaderEvent {
fn name(&self) -> &'static str { "FileReaderEvent" }
fn handler(self: Box<FileReaderEvent>) {
let file_reader_event = *self;
match file_reader_event {
FileReaderEvent::ProcessRead(filereader, gen_id) => {
FileReader::process_read(filereader, gen_id);
},
FileReaderEvent::ProcessReadData(filereader, gen_id) => {
FileReader::process_read_data(filereader, gen_id);
},
FileReaderEvent::ProcessReadError(filereader, gen_id, error) => {
FileReader::process_read_error(filereader, gen_id, error);
},
FileReaderEvent::ProcessReadEOF(filereader, gen_id, data, blob_contents) => {
FileReader::process_read_eof(filereader, gen_id, data, blob_contents);
}
}
}
}
// https://w3c.github.io/FileAPI/#thread-read-operation // https://w3c.github.io/FileAPI/#thread-read-operation
fn perform_annotated_read_operation(gen_id: GenerationId, data: ReadMetaData, blob_contents: Arc<Vec<u8>>, fn perform_annotated_read_operation(gen_id: GenerationId,
filereader: TrustedFileReader, script_chan: Box<ScriptChan + Send>) { data: ReadMetaData,
let chan = &script_chan; blob_contents: Arc<Vec<u8>>,
filereader: TrustedFileReader,
task_source: FileReadingTaskSource,
wrapper: RunnableWrapper) {
// Step 4 // Step 4
let thread = box FileReaderEvent::ProcessRead(filereader.clone(), gen_id); let task = FileReadingRunnable::new(FileReadingTask::ProcessRead(filereader.clone(), gen_id));
chan.send(CommonScriptMsg::RunnableMsg(FileRead, thread)).unwrap(); task_source.queue_with_wrapper(task, &wrapper).unwrap();
let thread = box FileReaderEvent::ProcessReadData(filereader.clone(), gen_id); let task = FileReadingRunnable::new(FileReadingTask::ProcessReadData(filereader.clone(), gen_id));
chan.send(CommonScriptMsg::RunnableMsg(FileRead, thread)).unwrap(); task_source.queue_with_wrapper(task, &wrapper).unwrap();
let thread = box FileReaderEvent::ProcessReadEOF(filereader, gen_id, data, blob_contents); let task = FileReadingRunnable::new(FileReadingTask::ProcessReadEOF(filereader, gen_id, data, blob_contents));
chan.send(CommonScriptMsg::RunnableMsg(FileRead, thread)).unwrap(); task_source.queue_with_wrapper(task, &wrapper).unwrap();
} }

View file

@ -5,6 +5,7 @@
use dom::attr::Attr; use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding;
use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
@ -78,7 +79,7 @@ impl VirtualMethods for HTMLDetailsElement {
element: details, element: details,
toggle_number: counter toggle_number: counter
}; };
let _ = task_source.queue(runnable, window.r()); let _ = task_source.queue(runnable, GlobalRef::Window(&window));
} }
} }
} }

View file

@ -12,6 +12,7 @@ use dom::bindings::codegen::Bindings::HTMLFormElementBinding::HTMLFormElementMet
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
use dom::bindings::conversions::DerivedFrom; use dom::bindings::conversions::DerivedFrom;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
@ -484,7 +485,7 @@ impl HTMLFormElement {
}; };
// Step 3 // Step 3
window.dom_manipulation_task_source().queue(nav, window).unwrap(); window.dom_manipulation_task_source().queue(nav, GlobalRef::Window(window)).unwrap();
} }
/// Interactively validate the constraints of form elements /// Interactively validate the constraints of form elements

View file

@ -184,7 +184,7 @@ impl HTMLImageElement {
src: src.into(), src: src.into(),
}; };
let task = window.dom_manipulation_task_source(); let task = window.dom_manipulation_task_source();
let _ = task.queue(runnable, window); let _ = task.queue(runnable, GlobalRef::Window(window));
} }
} }
} }

View file

@ -241,7 +241,7 @@ impl HTMLMediaElement {
elem: Trusted::new(self), elem: Trusted::new(self),
}; };
let win = window_from_node(self); let win = window_from_node(self);
let _ = win.dom_manipulation_task_source().queue(task, win.r()); let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win));
} }
// https://html.spec.whatwg.org/multipage/#internal-pause-steps step 2.2 // https://html.spec.whatwg.org/multipage/#internal-pause-steps step 2.2
@ -265,13 +265,13 @@ impl HTMLMediaElement {
elem: Trusted::new(self), elem: Trusted::new(self),
}; };
let win = window_from_node(self); let win = window_from_node(self);
let _ = win.dom_manipulation_task_source().queue(task, win.r()); let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win));
} }
fn queue_fire_simple_event(&self, type_: &'static str) { fn queue_fire_simple_event(&self, type_: &'static str) {
let win = window_from_node(self); let win = window_from_node(self);
let task = box FireSimpleEventTask::new(self, type_); let task = box FireSimpleEventTask::new(self, type_);
let _ = win.dom_manipulation_task_source().queue(task, win.r()); let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win));
} }
fn fire_simple_event(&self, type_: &str) { fn fire_simple_event(&self, type_: &str) {
@ -498,7 +498,8 @@ impl HTMLMediaElement {
fn queue_dedicated_media_source_failure_steps(&self) { fn queue_dedicated_media_source_failure_steps(&self) {
let window = window_from_node(self); let window = window_from_node(self);
let _ = window.dom_manipulation_task_source().queue(box DedicatedMediaSourceFailureTask::new(self), window.r()); let _ = window.dom_manipulation_task_source().queue(box DedicatedMediaSourceFailureTask::new(self),
GlobalRef::Window(&window));
} }
// https://html.spec.whatwg.org/multipage/#dedicated-media-source-failure-steps // https://html.spec.whatwg.org/multipage/#dedicated-media-source-failure-steps

View file

@ -161,7 +161,8 @@ impl Storage {
let window = global_ref.as_window(); let window = global_ref.as_window();
let task_source = window.dom_manipulation_task_source(); let task_source = window.dom_manipulation_task_source();
let trusted_storage = Trusted::new(self); let trusted_storage = Trusted::new(self);
task_source.queue(box StorageEventRunnable::new(trusted_storage, key, old_value, new_value), window).unwrap(); task_source.queue(box StorageEventRunnable::new(trusted_storage, key, old_value, new_value),
global_ref).unwrap();
} }
} }

View file

@ -302,7 +302,7 @@ impl Window {
self.history_traversal_task_source.clone() self.history_traversal_task_source.clone()
} }
pub fn file_reading_task_source(&self) -> Box<ScriptChan + Send> { pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
self.file_reading_task_source.clone() self.file_reading_task_source.clone()
} }

View file

@ -29,6 +29,7 @@ use net_traits::{LoadContext, ResourceThreads, load_whole_resource};
use net_traits::{RequestSource, LoadOrigin, CustomResponseSender, IpcSend}; use net_traits::{RequestSource, LoadOrigin, CustomResponseSender, IpcSend};
use profile_traits::{mem, time}; use profile_traits::{mem, time};
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result};
use script_thread::RunnableWrapper;
use script_traits::ScriptMsg as ConstellationMsg; use script_traits::ScriptMsg as ConstellationMsg;
use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerEventRequest, TimerSource}; use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerEventRequest, TimerSource};
use std::cell::Cell; use std::cell::Cell;
@ -38,6 +39,7 @@ use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::Receiver; use std::sync::mpsc::Receiver;
use task_source::file_reading::FileReadingTaskSource;
use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback}; use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback};
use url::Url; use url::Url;
@ -268,6 +270,12 @@ impl WorkerGlobalScope {
pub fn panic_chan(&self) -> &IpcSender<PanicMsg> { pub fn panic_chan(&self) -> &IpcSender<PanicMsg> {
&self.panic_chan &self.panic_chan
} }
pub fn get_runnable_wrapper(&self) -> RunnableWrapper {
RunnableWrapper {
cancelled: self.closing.clone(),
}
}
} }
impl LoadOrigin for WorkerGlobalScope { impl LoadOrigin for WorkerGlobalScope {
@ -453,6 +461,10 @@ impl WorkerGlobalScope {
} }
} }
pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
FileReadingTaskSource(self.script_chan())
}
pub fn pipeline(&self) -> PipelineId { pub fn pipeline(&self) -> PipelineId {
let dedicated = self.downcast::<DedicatedWorkerGlobalScope>(); let dedicated = self.downcast::<DedicatedWorkerGlobalScope>();
let service_worker = self.downcast::<ServiceWorkerGlobalScope>(); let service_worker = self.downcast::<ServiceWorkerGlobalScope>();

View file

@ -575,6 +575,8 @@ impl ScriptThread {
// Ask the router to proxy IPC messages from the control port to us. // Ask the router to proxy IPC messages from the control port to us.
let control_port = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(state.control_port); let control_port = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(state.control_port);
let boxed_script_sender = MainThreadScriptChan(chan.clone()).clone();
ScriptThread { ScriptThread {
browsing_context: MutNullableHeap::new(None), browsing_context: MutNullableHeap::new(None),
incomplete_loads: DOMRefCell::new(vec!()), incomplete_loads: DOMRefCell::new(vec!()),
@ -595,8 +597,8 @@ impl ScriptThread {
dom_manipulation_task_source: DOMManipulationTaskSource(chan.clone()), dom_manipulation_task_source: DOMManipulationTaskSource(chan.clone()),
user_interaction_task_source: UserInteractionTaskSource(chan.clone()), user_interaction_task_source: UserInteractionTaskSource(chan.clone()),
networking_task_source: NetworkingTaskSource(chan.clone()), networking_task_source: NetworkingTaskSource(chan.clone()),
history_traversal_task_source: HistoryTraversalTaskSource(chan.clone()), history_traversal_task_source: HistoryTraversalTaskSource(chan),
file_reading_task_source: FileReadingTaskSource(chan), file_reading_task_source: FileReadingTaskSource(boxed_script_sender),
control_chan: state.control_chan, control_chan: state.control_chan,
control_port: control_port, control_port: control_port,
@ -1227,7 +1229,7 @@ impl ScriptThread {
// https://html.spec.whatwg.org/multipage/#the-end step 7 // https://html.spec.whatwg.org/multipage/#the-end step 7
let handler = box DocumentProgressHandler::new(Trusted::new(doc)); let handler = box DocumentProgressHandler::new(Trusted::new(doc));
self.dom_manipulation_task_source.queue(handler, doc.window()).unwrap(); self.dom_manipulation_task_source.queue(handler, GlobalRef::Window(doc.window())).unwrap();
self.constellation_chan.send(ConstellationMsg::LoadComplete(pipeline)).unwrap(); self.constellation_chan.send(ConstellationMsg::LoadComplete(pipeline)).unwrap();
} }
@ -1585,7 +1587,6 @@ impl ScriptThread {
let UserInteractionTaskSource(ref user_sender) = self.user_interaction_task_source; let UserInteractionTaskSource(ref user_sender) = self.user_interaction_task_source;
let NetworkingTaskSource(ref network_sender) = self.networking_task_source; let NetworkingTaskSource(ref network_sender) = self.networking_task_source;
let HistoryTraversalTaskSource(ref history_sender) = self.history_traversal_task_source; let HistoryTraversalTaskSource(ref history_sender) = self.history_traversal_task_source;
let FileReadingTaskSource(ref file_sender) = self.file_reading_task_source;
let (ipc_timer_event_chan, ipc_timer_event_port) = ipc::channel().unwrap(); let (ipc_timer_event_chan, ipc_timer_event_port) = ipc::channel().unwrap();
ROUTER.route_ipc_receiver_to_mpsc_sender(ipc_timer_event_port, ROUTER.route_ipc_receiver_to_mpsc_sender(ipc_timer_event_port,
@ -1598,7 +1599,7 @@ impl ScriptThread {
UserInteractionTaskSource(user_sender.clone()), UserInteractionTaskSource(user_sender.clone()),
NetworkingTaskSource(network_sender.clone()), NetworkingTaskSource(network_sender.clone()),
HistoryTraversalTaskSource(history_sender.clone()), HistoryTraversalTaskSource(history_sender.clone()),
FileReadingTaskSource(file_sender.clone()), self.file_reading_task_source.clone(),
self.image_cache_channel.clone(), self.image_cache_channel.clone(),
self.custom_message_chan.clone(), self.custom_message_chan.clone(),
self.image_cache_thread.clone(), self.image_cache_thread.clone(),

View file

@ -2,11 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::global::GlobalRef;
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventRunnable, SimpleEventRunnable}; use dom::event::{EventBubbles, EventCancelable, EventRunnable, SimpleEventRunnable};
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
use dom::window::Window; use dom::window::Window;
use script_thread::{MainThreadScriptMsg, Runnable, ScriptThread}; use script_thread::{MainThreadScriptMsg, Runnable, RunnableWrapper, ScriptThread};
use std::result::Result; use std::result::Result;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use string_cache::Atom; use string_cache::Atom;
@ -16,8 +17,12 @@ use task_source::TaskSource;
pub struct DOMManipulationTaskSource(pub Sender<MainThreadScriptMsg>); pub struct DOMManipulationTaskSource(pub Sender<MainThreadScriptMsg>);
impl TaskSource for DOMManipulationTaskSource { impl TaskSource for DOMManipulationTaskSource {
fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, window: &Window) -> Result<(), ()> { fn queue_with_wrapper<T>(&self,
let msg = DOMManipulationTask(window.get_runnable_wrapper().wrap_runnable(msg)); msg: Box<T>,
wrapper: &RunnableWrapper)
-> Result<(), ()>
where T: Runnable + Send + 'static {
let msg = DOMManipulationTask(wrapper.wrap_runnable(msg));
self.0.send(MainThreadScriptMsg::DOMManipulation(msg)).map_err(|_| ()) self.0.send(MainThreadScriptMsg::DOMManipulation(msg)).map_err(|_| ())
} }
} }
@ -36,7 +41,7 @@ impl DOMManipulationTaskSource {
bubbles: bubbles, bubbles: bubbles,
cancelable: cancelable, cancelable: cancelable,
}; };
let _ = self.queue(runnable, window); let _ = self.queue(runnable, GlobalRef::Window(window));
} }
pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) { pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) {
@ -45,7 +50,7 @@ impl DOMManipulationTaskSource {
target: target, target: target,
name: name, name: name,
}; };
let _ = self.queue(runnable, window); let _ = self.queue(runnable, GlobalRef::Window(window));
} }
} }

View file

@ -2,19 +2,72 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use script_runtime::{CommonScriptMsg, ScriptChan}; use dom::domexception::DOMErrorName;
use script_thread::MainThreadScriptMsg; use dom::filereader::{FileReader, TrustedFileReader, GenerationId, ReadMetaData};
use std::sync::mpsc::Sender; use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory, ScriptChan};
use script_thread::{Runnable, RunnableWrapper};
use std::sync::Arc;
use task_source::TaskSource;
#[derive(JSTraceable)] #[derive(JSTraceable)]
pub struct FileReadingTaskSource(pub Sender<MainThreadScriptMsg>); pub struct FileReadingTaskSource(pub Box<ScriptChan + Send + 'static>);
impl ScriptChan for FileReadingTaskSource { impl Clone for FileReadingTaskSource {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { fn clone(&self) -> FileReadingTaskSource {
self.0.send(MainThreadScriptMsg::Common(msg)).map_err(|_| ()) FileReadingTaskSource(self.0.clone())
} }
}
fn clone(&self) -> Box<ScriptChan + Send> {
box FileReadingTaskSource((&self.0).clone()) impl TaskSource for FileReadingTaskSource {
fn queue_with_wrapper<T>(&self,
msg: Box<T>,
wrapper: &RunnableWrapper)
-> Result<(), ()>
where T: Runnable + Send + 'static {
self.0.send(CommonScriptMsg::RunnableMsg(ScriptThreadEventCategory::FileRead,
wrapper.wrap_runnable(msg)))
}
}
pub struct FileReadingRunnable {
task: FileReadingTask,
}
impl FileReadingRunnable {
pub fn new(task: FileReadingTask) -> Box<FileReadingRunnable> {
box FileReadingRunnable {
task: task
}
}
}
impl Runnable for FileReadingRunnable {
fn handler(self: Box<FileReadingRunnable>) {
self.task.handle_task();
}
}
#[allow(dead_code)]
pub enum FileReadingTask {
ProcessRead(TrustedFileReader, GenerationId),
ProcessReadData(TrustedFileReader, GenerationId),
ProcessReadError(TrustedFileReader, GenerationId, DOMErrorName),
ProcessReadEOF(TrustedFileReader, GenerationId, ReadMetaData, Arc<Vec<u8>>),
}
impl FileReadingTask {
pub fn handle_task(self) {
use self::FileReadingTask::*;
match self {
ProcessRead(reader, gen_id) =>
FileReader::process_read(reader, gen_id),
ProcessReadData(reader, gen_id) =>
FileReader::process_read_data(reader, gen_id),
ProcessReadError(reader, gen_id, error) =>
FileReader::process_read_error(reader, gen_id, error),
ProcessReadEOF(reader, gen_id, metadata, blob_contents) =>
FileReader::process_read_eof(reader, gen_id, metadata, blob_contents),
}
} }
} }

View file

@ -8,10 +8,17 @@ pub mod history_traversal;
pub mod networking; pub mod networking;
pub mod user_interaction; pub mod user_interaction;
use dom::window::Window; use dom::bindings::global::GlobalRef;
use script_thread::Runnable; use script_thread::{Runnable, RunnableWrapper};
use std::result::Result; use std::result::Result;
pub trait TaskSource { pub trait TaskSource {
fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, window: &Window) -> Result<(), ()>; fn queue_with_wrapper<T>(&self,
msg: Box<T>,
wrapper: &RunnableWrapper)
-> Result<(), ()>
where T: Runnable + Send + 'static;
fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: GlobalRef) -> Result<(), ()> {
self.queue_with_wrapper(msg, &global.get_runnable_wrapper())
}
} }

View file

@ -2,11 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::global::GlobalRef;
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventRunnable}; use dom::event::{EventBubbles, EventCancelable, EventRunnable};
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
use dom::window::Window; use dom::window::Window;
use script_thread::{MainThreadScriptMsg, Runnable, ScriptThread}; use script_thread::{MainThreadScriptMsg, Runnable, RunnableWrapper, ScriptThread};
use std::result::Result; use std::result::Result;
use std::sync::mpsc::Sender; use std::sync::mpsc::Sender;
use string_cache::Atom; use string_cache::Atom;
@ -16,8 +17,12 @@ use task_source::TaskSource;
pub struct UserInteractionTaskSource(pub Sender<MainThreadScriptMsg>); pub struct UserInteractionTaskSource(pub Sender<MainThreadScriptMsg>);
impl TaskSource for UserInteractionTaskSource { impl TaskSource for UserInteractionTaskSource {
fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, window: &Window) -> Result<(), ()> { fn queue_with_wrapper<T>(&self,
let msg = UserInteractionTask(window.get_runnable_wrapper().wrap_runnable(msg)); msg: Box<T>,
wrapper: &RunnableWrapper)
-> Result<(), ()>
where T: Runnable + Send + 'static {
let msg = UserInteractionTask(wrapper.wrap_runnable(msg));
self.0.send(MainThreadScriptMsg::UserInteraction(msg)).map_err(|_| ()) self.0.send(MainThreadScriptMsg::UserInteraction(msg)).map_err(|_| ())
} }
} }
@ -36,7 +41,7 @@ impl UserInteractionTaskSource {
bubbles: bubbles, bubbles: bubbles,
cancelable: cancelable, cancelable: cancelable,
}; };
let _ = self.queue(runnable, window); let _ = self.queue(runnable, GlobalRef::Window(window));
} }
} }