Use Result instead of panicking when the resource dir can't be found

This commit is contained in:
Manish Goregaokar 2016-07-21 12:04:18 +05:30
parent 20b1764d71
commit ceb85795b1
No known key found for this signature in database
GPG key ID: 3BBF4D3E2EF79F98
11 changed files with 81 additions and 64 deletions

View file

@ -12,7 +12,8 @@ pub fn content_process_sandbox_profile() -> Profile {
use gaol::platform; use gaol::platform;
Profile::new(vec![ Profile::new(vec![
Operation::FileReadAll(PathPattern::Literal(PathBuf::from("/dev/urandom"))), Operation::FileReadAll(PathPattern::Literal(PathBuf::from("/dev/urandom"))),
Operation::FileReadAll(PathPattern::Subpath(resource_files::resources_dir_path())), Operation::FileReadAll(PathPattern::Subpath(resource_files::resources_dir_path()
.expect("Cannot find resource dir"))),
Operation::FileReadAll(PathPattern::Subpath(PathBuf::from("/Library/Fonts"))), Operation::FileReadAll(PathPattern::Subpath(PathBuf::from("/Library/Fonts"))),
Operation::FileReadAll(PathPattern::Subpath(PathBuf::from("/System/Library/Fonts"))), Operation::FileReadAll(PathPattern::Subpath(PathBuf::from("/System/Library/Fonts"))),
Operation::FileReadAll(PathPattern::Subpath(PathBuf::from( Operation::FileReadAll(PathPattern::Subpath(PathBuf::from(
@ -34,7 +35,8 @@ pub fn content_process_sandbox_profile() -> Profile {
pub fn content_process_sandbox_profile() -> Profile { pub fn content_process_sandbox_profile() -> Profile {
Profile::new(vec![ Profile::new(vec![
Operation::FileReadAll(PathPattern::Literal(PathBuf::from("/dev/urandom"))), Operation::FileReadAll(PathPattern::Literal(PathBuf::from("/dev/urandom"))),
Operation::FileReadAll(PathPattern::Subpath(resource_files::resources_dir_path())), Operation::FileReadAll(PathPattern::Subpath(resource_files::resources_dir_path()
.expect("Cannot find resource dir"))),
]).expect("Failed to create sandbox profile!") ]).expect("Failed to create sandbox profile!")
} }

View file

@ -11,15 +11,17 @@ use net_traits::ProgressMsg::Done;
use net_traits::response::HttpsState; use net_traits::response::HttpsState;
use net_traits::{LoadConsumer, LoadData, Metadata, NetworkError}; use net_traits::{LoadConsumer, LoadData, Metadata, NetworkError};
use resource_thread::{CancellationListener, send_error, start_sending_sniffed_opt}; use resource_thread::{CancellationListener, send_error, start_sending_sniffed_opt};
use std::io;
use std::sync::Arc; use std::sync::Arc;
use url::Url; use url::Url;
use util::resource_files::resources_dir_path; use util::resource_files::resources_dir_path;
fn url_from_non_relative_scheme(load_data: &mut LoadData, filename: &str) { fn url_from_non_relative_scheme(load_data: &mut LoadData, filename: &str) -> io::Result<()> {
let mut path = resources_dir_path(); let mut path = try!(resources_dir_path());
path.push(filename); path.push(filename);
assert!(path.exists()); assert!(path.exists());
load_data.url = Url::from_file_path(&*path).unwrap(); load_data.url = Url::from_file_path(&*path).unwrap();
Ok(())
} }
pub fn factory(mut load_data: LoadData, pub fn factory(mut load_data: LoadData,
@ -27,7 +29,7 @@ pub fn factory(mut load_data: LoadData,
classifier: Arc<MimeClassifier>, classifier: Arc<MimeClassifier>,
cancel_listener: CancellationListener) { cancel_listener: CancellationListener) {
let url = load_data.url.clone(); let url = load_data.url.clone();
match url.path() { let res = match url.path() {
"blank" => { "blank" => {
let metadata = Metadata { let metadata = Metadata {
final_url: load_data.url, final_url: load_data.url,
@ -56,5 +58,9 @@ pub fn factory(mut load_data: LoadData,
return return
} }
}; };
file_loader::factory(load_data, start_chan, classifier, cancel_listener) if res.is_ok() {
file_loader::factory(load_data, start_chan, classifier, cancel_listener)
} else {
send_error(load_data.url, NetworkError::Internal("Could not access resource folder".to_owned()), start_chan);
}
} }

View file

@ -17,7 +17,7 @@ pub fn resolve_chrome_url(url: &Url) -> Result<Url, ()> {
if url.host_str() != Some("resources") { if url.host_str() != Some("resources") {
return Err(()) return Err(())
} }
let resources = canonicalize(resources_dir_path()) let resources = canonicalize(resources_dir_path().expect("Error finding resource folder"))
.expect("Error canonicalizing path to the resources directory"); .expect("Error canonicalizing path to the resources directory");
let mut path = resources.clone(); let mut path = resources.clone();
for segment in url.path_segments().unwrap() { for segment in url.path_segments().unwrap() {

View file

@ -29,7 +29,9 @@ const DEFAULT_CIPHERS: &'static str = concat!(
pub fn create_http_connector() -> Arc<Pool<Connector>> { pub fn create_http_connector() -> Arc<Pool<Connector>> {
let mut context = SslContext::new(SslMethod::Sslv23).unwrap(); let mut context = SslContext::new(SslMethod::Sslv23).unwrap();
context.set_CA_file(&resources_dir_path().join("certs")).unwrap(); context.set_CA_file(&resources_dir_path()
.expect("Need certificate file to make network requests")
.join("certs")).unwrap();
context.set_cipher_list(DEFAULT_CIPHERS).unwrap(); context.set_cipher_list(DEFAULT_CIPHERS).unwrap();
context.set_options(SSL_OP_NO_SSLV2 | SSL_OP_NO_SSLV3 | SSL_OP_NO_COMPRESSION); context.set_options(SSL_OP_NO_SSLV2 | SSL_OP_NO_SSLV3 | SSL_OP_NO_COMPRESSION);
let connector = HttpsConnector::new(ServoSslClient { let connector = HttpsConnector::new(ServoSslClient {

View file

@ -16,7 +16,7 @@ use std::borrow::ToOwned;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::{self, Read};
use std::mem; use std::mem;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{Sender, Receiver, channel}; use std::sync::mpsc::{Sender, Receiver, channel};
@ -318,29 +318,27 @@ impl LoadOrigin for ImageCacheOrigin {
} }
} }
fn get_placeholder_image(webrender_api: &Option<webrender_traits::RenderApi>) -> io::Result<Arc<Image>> {
let mut placeholder_path = try!(resources_dir_path());
placeholder_path.push("rippy.png");
let mut file = try!(File::open(&placeholder_path));
let mut image_data = vec![];
try!(file.read_to_end(&mut image_data));
let mut image = load_from_memory(&image_data).unwrap();
if let Some(ref webrender_api) = *webrender_api {
let format = convert_format(image.format);
let mut bytes = Vec::new();
bytes.extend_from_slice(&*image.bytes);
image.id = Some(webrender_api.add_image(image.width, image.height, format, bytes));
}
Ok(Arc::new(image))
}
impl ImageCache { impl ImageCache {
fn run(core_resource_thread: CoreResourceThread, fn run(core_resource_thread: CoreResourceThread,
webrender_api: Option<webrender_traits::RenderApi>, webrender_api: Option<webrender_traits::RenderApi>,
ipc_command_receiver: IpcReceiver<ImageCacheCommand>) { ipc_command_receiver: IpcReceiver<ImageCacheCommand>) {
// Preload the placeholder image, used when images fail to load. // Preload the placeholder image, used when images fail to load.
let mut placeholder_path = resources_dir_path(); let placeholder_image = get_placeholder_image(&webrender_api).ok();
placeholder_path.push("rippy.png");
let mut image_data = vec![];
let result = File::open(&placeholder_path).and_then(|mut file| {
file.read_to_end(&mut image_data)
});
let placeholder_image = result.ok().map(|_| {
let mut image = load_from_memory(&image_data).unwrap();
if let Some(ref webrender_api) = webrender_api {
let format = convert_format(image.format);
let mut bytes = Vec::new();
bytes.extend_from_slice(&*image.bytes);
image.id = Some(webrender_api.add_image(image.width, image.height, format, bytes));
}
Arc::new(image)
});
// Ask the router to proxy messages received over IPC to us. // Ask the router to proxy messages received over IPC to us.
let cmd_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_command_receiver); let cmd_receiver = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(ipc_command_receiver);

View file

@ -24,9 +24,12 @@ pub fn load_script(head: &HTMLHeadElement) {
let doc = doc.r(); let doc = doc.r();
let path = if &**path_str == "" { let path = if &**path_str == "" {
let mut p = resources_dir_path(); if let Ok(mut p) = resources_dir_path() {
p.push("user-agent-js"); p.push("user-agent-js");
p p
} else {
return
}
} else { } else {
PathBuf::from(path_str) PathBuf::from(path_str)
}; };

View file

@ -130,28 +130,31 @@ impl<Window> Browser<Window> where Window: WindowMethods + 'static {
}); });
let (webrender, webrender_api_sender) = if opts::get().use_webrender { let (webrender, webrender_api_sender) = if opts::get().use_webrender {
let mut resource_path = resources_dir_path(); if let Ok(mut resource_path) = resources_dir_path() {
resource_path.push("shaders"); resource_path.push("shaders");
// TODO(gw): Duplicates device_pixels_per_screen_px from compositor. Tidy up! // TODO(gw): Duplicates device_pixels_per_screen_px from compositor. Tidy up!
let scale_factor = window.scale_factor().get(); let scale_factor = window.scale_factor().get();
let device_pixel_ratio = match opts.device_pixels_per_px { let device_pixel_ratio = match opts.device_pixels_per_px {
Some(device_pixels_per_px) => device_pixels_per_px, Some(device_pixels_per_px) => device_pixels_per_px,
None => match opts.output_file { None => match opts.output_file {
Some(_) => 1.0, Some(_) => 1.0,
None => scale_factor, None => scale_factor,
} }
}; };
let (webrender, webrender_sender) = let (webrender, webrender_sender) =
webrender::Renderer::new(webrender::RendererOptions { webrender::Renderer::new(webrender::RendererOptions {
device_pixel_ratio: device_pixel_ratio, device_pixel_ratio: device_pixel_ratio,
resource_path: resource_path, resource_path: resource_path,
enable_aa: opts.enable_text_antialiasing, enable_aa: opts.enable_text_antialiasing,
enable_msaa: opts.use_msaa, enable_msaa: opts.use_msaa,
enable_profiler: opts.webrender_stats, enable_profiler: opts.webrender_stats,
}); });
(Some(webrender), Some(webrender_sender)) (Some(webrender), Some(webrender_sender))
} else {
(None, None)
}
} else { } else {
(None, None) (None, None)
}; };

View file

@ -195,7 +195,7 @@ fn init_user_prefs(path: &mut PathBuf) {
} }
fn read_prefs() -> Result<HashMap<String, Pref>, ()> { fn read_prefs() -> Result<HashMap<String, Pref>, ()> {
let mut path = resources_dir_path(); let mut path = try!(resources_dir_path().map_err(|_| ()));
path.push("prefs.json"); path.push("prefs.json");
let file = try!(File::open(path).or_else(|e| { let file = try!(File::open(path).or_else(|e| {

View file

@ -21,24 +21,24 @@ pub fn set_resources_path(path: Option<String>) {
} }
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
pub fn resources_dir_path() -> PathBuf { pub fn resources_dir_path() -> io::Result<PathBuf> {
PathBuf::from("/sdcard/servo/") Ok(PathBuf::from("/sdcard/servo/"))
} }
#[cfg(not(target_os = "android"))] #[cfg(not(target_os = "android"))]
pub fn resources_dir_path() -> PathBuf { pub fn resources_dir_path() -> io::Result<PathBuf> {
let mut dir = CMD_RESOURCE_DIR.lock().unwrap(); let mut dir = CMD_RESOURCE_DIR.lock().unwrap();
if let Some(ref path) = *dir { if let Some(ref path) = *dir {
return PathBuf::from(path); return Ok(PathBuf::from(path));
} }
// FIXME: Find a way to not rely on the executable being // FIXME: Find a way to not rely on the executable being
// under `<servo source>[/$target_triple]/target/debug` // under `<servo source>[/$target_triple]/target/debug`
// or `<servo source>[/$target_triple]/target/release`. // or `<servo source>[/$target_triple]/target/release`.
let mut path = env::current_exe().expect("can't get exe path"); let mut path = try!(env::current_exe());
// Follow symlink // Follow symlink
path = path.canonicalize().expect("path does not exist"); path = try!(path.canonicalize());
while path.pop() { while path.pop() {
path.push("resources"); path.push("resources");
@ -54,11 +54,11 @@ pub fn resources_dir_path() -> PathBuf {
path.pop(); path.pop();
} }
*dir = Some(path.to_str().unwrap().to_owned()); *dir = Some(path.to_str().unwrap().to_owned());
path Ok(path)
} }
pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> { pub fn read_resource_file<P: AsRef<Path>>(relative_path: P) -> io::Result<Vec<u8>> {
let mut path = resources_dir_path(); let mut path = try!(resources_dir_path());
path.push(relative_path); path.push(relative_path);
let mut file = try!(File::open(&path)); let mut file = try!(File::open(&path));
let mut data = Vec::new(); let mut data = Vec::new();

View file

@ -136,8 +136,6 @@ impl Window {
// #9996. // #9996.
let visible = is_foreground && !opts::get().no_native_titlebar; let visible = is_foreground && !opts::get().no_native_titlebar;
let mut icon_path = resource_files::resources_dir_path();
icon_path.push("servo.png");
let mut builder = let mut builder =
glutin::WindowBuilder::new().with_title("Servo".to_string()) glutin::WindowBuilder::new().with_title("Servo".to_string())
@ -147,8 +145,13 @@ impl Window {
.with_gl(Window::gl_version()) .with_gl(Window::gl_version())
.with_visibility(visible) .with_visibility(visible)
.with_parent(parent) .with_parent(parent)
.with_multitouch() .with_multitouch();
.with_icon(icon_path);
if let Ok(mut icon_path) = resource_files::resources_dir_path() {
icon_path.push("servo.png");
builder = builder.with_icon(icon_path);
}
if opts::get().enable_vsync { if opts::get().enable_vsync {
builder = builder.with_vsync(); builder = builder.with_vsync();

View file

@ -157,7 +157,7 @@ fn test_fetch_data() {
#[test] #[test]
fn test_fetch_file() { fn test_fetch_file() {
let mut path = resources_dir_path(); let mut path = resources_dir_path().expect("Cannot find resource dir");
path.push("servo.css"); path.push("servo.css");
let url = Url::from_file_path(path.clone()).unwrap(); let url = Url::from_file_path(path.clone()).unwrap();