servo: Merge #12612 - Remove use of util::opts from net crate (from nox:die-opts-die); r=Ms2ger
authorAnthony Ramine <n.oxyde@gmail.com>
Wed, 27 Jul 2016 03:31:03 -0500
changeset 339375 d717781d7084dac585b938eb3dcc9fa6297c46b9
parent 339374 258d7275c4e6615b749af905af6db34f1d5210b0
child 339376 6c5c1473dacd6ec98a81a3af77f51716cc5ab518
push id31307
push usergszorc@mozilla.com
push dateSat, 04 Feb 2017 00:59:06 +0000
treeherdermozilla-central@94079d43835f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersMs2ger
servo: Merge #12612 - Remove use of util::opts from net crate (from nox:die-opts-die); r=Ms2ger Source-Repo: https://github.com/servo/servo Source-Revision: d8991496c6ddcce3c93ba36d36619a3200626c1f
servo/components/net/resource_thread.rs
servo/components/net/storage_thread.rs
servo/components/servo/lib.rs
servo/tests/unit/net/resource_thread.rs
--- a/servo/components/net/resource_thread.rs
+++ b/servo/components/net/resource_thread.rs
@@ -37,23 +37,23 @@ use rustc_serialize::json;
 use rustc_serialize::{Decodable, Encodable};
 use std::borrow::ToOwned;
 use std::boxed::FnBox;
 use std::cell::Cell;
 use std::collections::HashMap;
 use std::error::Error;
 use std::fs::File;
 use std::io::prelude::*;
-use std::path::Path;
+use std::ops::Deref;
+use std::path::{Path, PathBuf};
 use std::rc::Rc;
 use std::sync::mpsc::{Receiver, Sender, channel};
 use std::sync::{Arc, RwLock};
 use storage_thread::StorageThreadFactory;
 use url::Url;
-use util::opts;
 use util::prefs::PREFS;
 use util::thread::spawn_named;
 use websocket_loader;
 
 const TFD_PROVIDER: &'static TFDProvider = &TFDProvider;
 
 pub enum ProgressSender {
     Channel(IpcSender<ProgressMsg>),
@@ -160,61 +160,71 @@ fn start_sending_opt(start_chan: LoadCon
             Ok(ProgressSender::Listener(target))
         }
     }
 }
 
 /// Returns a tuple of (public, private) senders to the new threads.
 pub fn new_resource_threads(user_agent: String,
                             devtools_chan: Option<Sender<DevtoolsControlMsg>>,
-                            profiler_chan: ProfilerChan) -> (ResourceThreads, ResourceThreads) {
+                            profiler_chan: ProfilerChan,
+                            config_dir: Option<PathBuf>)
+                            -> (ResourceThreads, ResourceThreads) {
     let filemanager_chan: IpcSender<FileManagerThreadMsg> = FileManagerThreadFactory::new(TFD_PROVIDER);
-    let (public_core, private_core) = new_core_resource_thread(user_agent, devtools_chan,
-                                                               profiler_chan, filemanager_chan.clone());
-    let storage: IpcSender<StorageThreadMsg> = StorageThreadFactory::new();
+    let (public_core, private_core) = new_core_resource_thread(
+        user_agent,
+        devtools_chan,
+        profiler_chan,
+        filemanager_chan.clone(),
+        config_dir.clone());
+    let storage: IpcSender<StorageThreadMsg> = StorageThreadFactory::new(config_dir);
     (ResourceThreads::new(public_core, storage.clone(), filemanager_chan.clone()),
      ResourceThreads::new(private_core, storage, filemanager_chan))
 }
 
 
 /// Create a CoreResourceThread
 pub fn new_core_resource_thread(user_agent: String,
                                 devtools_chan: Option<Sender<DevtoolsControlMsg>>,
                                 profiler_chan: ProfilerChan,
-                                filemanager_chan: IpcSender<FileManagerThreadMsg>)
+                                filemanager_chan: IpcSender<FileManagerThreadMsg>,
+                                config_dir: Option<PathBuf>)
                                 -> (CoreResourceThread, CoreResourceThread) {
     let (public_setup_chan, public_setup_port) = ipc::channel().unwrap();
     let (private_setup_chan, private_setup_port) = ipc::channel().unwrap();
     let public_setup_chan_clone = public_setup_chan.clone();
     let private_setup_chan_clone = private_setup_chan.clone();
     spawn_named("ResourceManager".to_owned(), move || {
         let resource_manager = CoreResourceManager::new(
             user_agent, devtools_chan, profiler_chan, filemanager_chan
         );
 
         let mut channel_manager = ResourceChannelManager {
             resource_manager: resource_manager,
+            config_dir: config_dir,
         };
         channel_manager.start(public_setup_chan_clone,
                               private_setup_chan_clone,
                               public_setup_port,
                               private_setup_port);
     });
     (public_setup_chan, private_setup_chan)
 }
 
 struct ResourceChannelManager {
-    resource_manager: CoreResourceManager
+    resource_manager: CoreResourceManager,
+    config_dir: Option<PathBuf>,
 }
 
-fn create_resource_groups() -> (ResourceGroup, ResourceGroup) {
+fn create_resource_groups(config_dir: Option<&Path>)
+                          -> (ResourceGroup, ResourceGroup) {
     let mut hsts_list = HstsList::from_servo_preload();
     let mut auth_cache = AuthCache::new();
     let mut cookie_jar = CookieStorage::new();
-    if let Some(ref config_dir) = opts::get().config_dir {
+    if let Some(config_dir) = config_dir {
         read_json_from_file(&mut auth_cache, config_dir, "auth_cache.json");
         read_json_from_file(&mut hsts_list, config_dir, "hsts_list.json");
         read_json_from_file(&mut cookie_jar, config_dir, "cookie_jar.json");
     }
     let resource_group = ResourceGroup {
         cookie_jar: Arc::new(RwLock::new(cookie_jar)),
         auth_cache: Arc::new(RwLock::new(auth_cache)),
         hsts_list: Arc::new(RwLock::new(hsts_list.clone())),
@@ -231,17 +241,18 @@ fn create_resource_groups() -> (Resource
 
 impl ResourceChannelManager {
     #[allow(unsafe_code)]
     fn start(&mut self,
              public_control_sender: CoreResourceThread,
              private_control_sender: CoreResourceThread,
              public_receiver: IpcReceiver<CoreResourceMsg>,
              private_receiver: IpcReceiver<CoreResourceMsg>) {
-        let (public_resource_group, private_resource_group) = create_resource_groups();
+        let (public_resource_group, private_resource_group) =
+            create_resource_groups(self.config_dir.as_ref().map(Deref::deref));
 
         let mut rx_set = IpcReceiverSet::new().unwrap();
         let private_id = rx_set.add(private_receiver).unwrap();
         let public_id = rx_set.add(public_receiver).unwrap();
 
         loop {
             for (id, data) in rx_set.select().unwrap().into_iter().map(|m| m.unwrap()) {
                 let (group, sender) = if id == private_id {
@@ -292,17 +303,17 @@ impl ResourceChannelManager {
                     let _ = cancel_sender.send(());
                 }
                 self.resource_manager.cancel_load_map.remove(&res_id);
             }
             CoreResourceMsg::Synchronize(sender) => {
                 let _ = sender.send(());
             }
             CoreResourceMsg::Exit(sender) => {
-                if let Some(ref config_dir) = opts::get().config_dir {
+                if let Some(ref config_dir) = self.config_dir {
                     match group.auth_cache.read() {
                         Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"),
                         Err(_) => warn!("Error writing auth cache to disk"),
                     }
                     match group.cookie_jar.read() {
                         Ok(jar) => write_json_to_file(&*jar, config_dir, "cookie_jar.json"),
                         Err(_) => warn!("Error writing cookie jar to disk"),
                     }
@@ -314,18 +325,20 @@ impl ResourceChannelManager {
                 let _ = sender.send(());
                 return false;
             }
         }
         true
     }
 }
 
-pub fn read_json_from_file<T: Decodable>(data: &mut T, config_dir: &str, filename: &str) {
-    let path = Path::new(config_dir).join(filename);
+pub fn read_json_from_file<T>(data: &mut T, config_dir: &Path, filename: &str)
+    where T: Decodable
+{
+    let path = config_dir.join(filename);
     let display = path.display();
 
     let mut file = match File::open(&path) {
         Err(why) => {
             warn!("couldn't open {}: {}", display, Error::description(&why));
             return;
         },
         Ok(file) => file,
@@ -341,23 +354,25 @@ pub fn read_json_from_file<T: Decodable>
     }
 
     match json::decode(&string_buffer) {
         Ok(decoded_buffer) => *data = decoded_buffer,
         Err(why) => warn!("Could not decode buffer{}", why),
     }
 }
 
-pub fn write_json_to_file<T: Encodable>(data: &T, config_dir: &str, filename: &str) {
+pub fn write_json_to_file<T>(data: &T, config_dir: &Path, filename: &str)
+    where T: Encodable
+{
     let json_encoded: String;
     match json::encode(&data) {
         Ok(d) => json_encoded = d,
         Err(_) => return,
     }
-    let path = Path::new(config_dir).join(filename);
+    let path = config_dir.join(filename);
     let display = path.display();
 
     let mut file = match File::create(&path) {
         Err(why) => panic!("couldn't create {}: {}",
                            display,
                            Error::description(&why)),
         Ok(file) => file,
     };
--- a/servo/components/net/storage_thread.rs
+++ b/servo/components/net/storage_thread.rs
@@ -3,53 +3,57 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
 use net_traits::storage_thread::{StorageThreadMsg, StorageType};
 use resource_thread;
 use std::borrow::ToOwned;
 use std::collections::BTreeMap;
 use std::collections::HashMap;
+use std::path::PathBuf;
 use url::Url;
-use util::opts;
 use util::thread::spawn_named;
 
 const QUOTA_SIZE_LIMIT: usize = 5 * 1024 * 1024;
 
 pub trait StorageThreadFactory {
-    fn new() -> Self;
+    fn new(config_dir: Option<PathBuf>) -> Self;
 }
 
 impl StorageThreadFactory for IpcSender<StorageThreadMsg> {
     /// Create a storage thread
-    fn new() -> IpcSender<StorageThreadMsg> {
+    fn new(config_dir: Option<PathBuf>) -> IpcSender<StorageThreadMsg> {
         let (chan, port) = ipc::channel().unwrap();
         spawn_named("StorageManager".to_owned(), move || {
-            StorageManager::new(port).start();
+            StorageManager::new(port, config_dir).start();
         });
         chan
     }
 }
 
 struct StorageManager {
     port: IpcReceiver<StorageThreadMsg>,
     session_data: HashMap<String, (usize, BTreeMap<String, String>)>,
     local_data: HashMap<String, (usize, BTreeMap<String, String>)>,
+    config_dir: Option<PathBuf>,
 }
 
 impl StorageManager {
-    fn new(port: IpcReceiver<StorageThreadMsg>) -> StorageManager {
+    fn new(port: IpcReceiver<StorageThreadMsg>,
+           config_dir: Option<PathBuf>)
+           -> StorageManager {
         let mut local_data = HashMap::new();
-        if let Some(ref config_dir) = opts::get().config_dir {
+        if let Some(ref config_dir) = config_dir {
             resource_thread::read_json_from_file(&mut local_data, config_dir, "local_data.json");
         }
         StorageManager {
             port: port,
             session_data: HashMap::new(),
             local_data: local_data,
+            config_dir: config_dir,
         }
     }
 }
 
 impl StorageManager {
     fn start(&mut self) {
         loop {
             match self.port.recv().unwrap() {
@@ -70,17 +74,17 @@ impl StorageManager {
                 }
                 StorageThreadMsg::RemoveItem(sender, url, storage_type, name) => {
                     self.remove_item(sender, url, storage_type, name)
                 }
                 StorageThreadMsg::Clear(sender, url, storage_type) => {
                     self.clear(sender, url, storage_type)
                 }
                 StorageThreadMsg::Exit(sender) => {
-                    if let Some(ref config_dir) = opts::get().config_dir {
+                    if let Some(ref config_dir) = self.config_dir {
                         resource_thread::write_json_to_file(&self.local_data, config_dir, "local_data.json");
                     }
                     let _ = sender.send(());
                     break
                 }
             }
         }
     }
--- a/servo/components/servo/lib.rs
+++ b/servo/components/servo/lib.rs
@@ -234,17 +234,18 @@ fn create_constellation(opts: opts::Opts
                         supports_clipboard: bool,
                         webrender_api_sender: Option<webrender_traits::RenderApiSender>)
                         -> (Sender<ConstellationMsg>, SWManagerSenders) {
     let bluetooth_thread: IpcSender<BluetoothMethodMsg> = BluetoothThreadFactory::new();
 
     let (public_resource_threads, private_resource_threads) =
         new_resource_threads(opts.user_agent.clone(),
                              devtools_chan.clone(),
-                             time_profiler_chan.clone());
+                             time_profiler_chan.clone(),
+                             opts.config_dir.map(Into::into));
     let image_cache_thread = new_image_cache_thread(public_resource_threads.sender(),
                                                     webrender_api_sender.as_ref().map(|wr| wr.create_api()));
     let font_cache_thread = FontCacheThread::new(public_resource_threads.sender(),
                                                  webrender_api_sender.as_ref().map(|wr| wr.create_api()));
 
     let resource_sender = public_resource_threads.sender();
 
     let initial_state = InitialConstellationState {
--- a/servo/tests/unit/net/resource_thread.rs
+++ b/servo/tests/unit/net/resource_thread.rs
@@ -36,27 +36,29 @@ impl LoadOrigin for ResourceTest {
     }
 }
 
 #[test]
 fn test_exit() {
     let (tx, _rx) = ipc::channel().unwrap();
     let (sender, receiver) = ipc::channel().unwrap();
     let filemanager_chan = FileManagerThreadFactory::new(TFD_PROVIDER);
-    let (resource_thread, _) = new_core_resource_thread("".to_owned(), None, ProfilerChan(tx), filemanager_chan);
+    let (resource_thread, _) = new_core_resource_thread(
+        "".to_owned(), None, ProfilerChan(tx), filemanager_chan, None);
     resource_thread.send(CoreResourceMsg::Exit(sender)).unwrap();
     receiver.recv().unwrap();
 }
 
 #[test]
 fn test_bad_scheme() {
     let (tx, _rx) = ipc::channel().unwrap();
     let (sender, receiver) = ipc::channel().unwrap();
     let filemanager_chan = FileManagerThreadFactory::new(TFD_PROVIDER);
-    let (resource_thread, _) = new_core_resource_thread("".to_owned(), None, ProfilerChan(tx), filemanager_chan);
+    let (resource_thread, _) = new_core_resource_thread(
+        "".to_owned(), None, ProfilerChan(tx), filemanager_chan, None);
     let (start_chan, start) = ipc::channel().unwrap();
     let url = Url::parse("bogus://whatever").unwrap();
     resource_thread.send(CoreResourceMsg::Load(LoadData::new(LoadContext::Browsing, url, &ResourceTest),
 
     LoadConsumer::Channel(start_chan), None)).unwrap();
     let response = start.recv().unwrap();
     match response.progress_port.recv().unwrap() {
       ProgressMsg::Done(result) => { assert!(result.is_err()) }
@@ -226,17 +228,18 @@ fn test_cancelled_listener() {
             let body_vec: Vec<&str> = body_receiver.recv().unwrap();
             let _ = stream.write(body_vec.join("\r\n").as_bytes());
         }
     });
 
     let (tx, _rx) = ipc::channel().unwrap();
     let (exit_sender, exit_receiver) = ipc::channel().unwrap();
     let filemanager_chan = FileManagerThreadFactory::new(TFD_PROVIDER);
-    let (resource_thread, _) = new_core_resource_thread("".to_owned(), None, ProfilerChan(tx), filemanager_chan);
+    let (resource_thread, _) = new_core_resource_thread(
+        "".to_owned(), None, ProfilerChan(tx), filemanager_chan, None);
     let (sender, receiver) = ipc::channel().unwrap();
     let (id_sender, id_receiver) = ipc::channel().unwrap();
     let (sync_sender, sync_receiver) = ipc::channel().unwrap();
     let url = Url::parse(&format!("http://127.0.0.1:{}", port)).unwrap();
 
     resource_thread.send(CoreResourceMsg::Load(LoadData::new(LoadContext::Browsing, url, &ResourceTest),
                                         LoadConsumer::Channel(sender),
                                         Some(id_sender))).unwrap();