diff options
-rw-r--r-- | ports/servo/browser.rs | 306 | ||||
-rw-r--r-- | ports/servo/glutin_app/keyutils.rs | 72 | ||||
-rw-r--r-- | ports/servo/glutin_app/window.rs | 240 | ||||
-rw-r--r-- | ports/servo/main.rs | 13 | ||||
-rw-r--r-- | ports/servo/non_android_main.rs | 77 | ||||
-rw-r--r-- | ports/servo/platform/macos/mod.rs | 1 |
6 files changed, 386 insertions, 323 deletions
diff --git a/ports/servo/browser.rs b/ports/servo/browser.rs index 9e58581d928..dee5055f449 100644 --- a/ports/servo/browser.rs +++ b/ports/servo/browser.rs @@ -75,7 +75,7 @@ impl Browser { }, event => { self.event_queue.push(event); - } + }, } } } @@ -85,7 +85,13 @@ impl Browser { } /// Handle key events before sending them to Servo. - fn handle_key_from_window(&mut self, ch: Option<char>, key: Key, state: KeyState, mods: KeyModifiers) { + fn handle_key_from_window( + &mut self, + ch: Option<char>, + key: Key, + state: KeyState, + mods: KeyModifiers, + ) { let pressed = state == KeyState::Pressed; // We don't match the state in the parent `match` because we don't want to do anything // on KeyState::Released when it's a combo that we handle on Pressed. For example, @@ -93,7 +99,7 @@ impl Browser { match (mods, ch, key, self.browser_id) { (CMD_OR_CONTROL, _, Key::R, Some(id)) => if pressed { self.event_queue.push(WindowEvent::Reload(id)); - } + }, (CMD_OR_CONTROL, _, Key::L, Some(id)) => if pressed { let url: String = if let Some(ref current_url) = self.current_url { current_url.to_string() @@ -107,69 +113,92 @@ impl Browser { self.event_queue.push(WindowEvent::LoadUrl(id, url)); } } - } + }, (CMD_OR_CONTROL, _, Key::Q, _) => if pressed { self.event_queue.push(WindowEvent::Quit); - } - (_, Some('3'), _, _) if mods ^ KeyModifiers::CONTROL == KeyModifiers::SHIFT => if pressed { - self.event_queue.push(WindowEvent::CaptureWebRender); - } + }, + (_, Some('3'), _, _) if mods ^ KeyModifiers::CONTROL == KeyModifiers::SHIFT => { + if pressed { + self.event_queue.push(WindowEvent::CaptureWebRender); + } + }, (KeyModifiers::CONTROL, None, Key::F10, _) => if pressed { - let event = WindowEvent::ToggleWebRenderDebug(WebRenderDebugOption::RenderTargetDebug); + let event = + WindowEvent::ToggleWebRenderDebug(WebRenderDebugOption::RenderTargetDebug); self.event_queue.push(event); - } + }, (KeyModifiers::CONTROL, None, Key::F11, _) => if pressed { - let event = WindowEvent::ToggleWebRenderDebug(WebRenderDebugOption::TextureCacheDebug); + let event = + WindowEvent::ToggleWebRenderDebug(WebRenderDebugOption::TextureCacheDebug); self.event_queue.push(event); - } + }, (KeyModifiers::CONTROL, None, Key::F12, _) => if pressed { let event = WindowEvent::ToggleWebRenderDebug(WebRenderDebugOption::Profiler); self.event_queue.push(event); - } + }, (CMD_OR_ALT, None, Key::Right, Some(id)) | (KeyModifiers::NONE, None, Key::NavigateForward, Some(id)) => if pressed { let event = WindowEvent::Navigation(id, TraversalDirection::Forward(1)); self.event_queue.push(event); - } + }, (CMD_OR_ALT, None, Key::Left, Some(id)) | (KeyModifiers::NONE, None, Key::NavigateBackward, Some(id)) => if pressed { let event = WindowEvent::Navigation(id, TraversalDirection::Back(1)); self.event_queue.push(event); - } + }, (KeyModifiers::NONE, None, Key::Escape, _) => if pressed { self.event_queue.push(WindowEvent::Quit); - } + }, _ => { self.platform_handle_key(ch, key, mods, state); - } + }, } } #[cfg(not(target_os = "win"))] - fn platform_handle_key(&mut self, ch: Option<char>, key: Key, mods: KeyModifiers, state: KeyState) { + fn platform_handle_key( + &mut self, + ch: Option<char>, + key: Key, + mods: KeyModifiers, + state: KeyState, + ) { let pressed = state == KeyState::Pressed; match (mods, key, self.browser_id) { (CMD_OR_CONTROL, Key::LeftBracket, Some(id)) => if pressed { let event = WindowEvent::Navigation(id, TraversalDirection::Back(1)); self.event_queue.push(event); - } + }, (CMD_OR_CONTROL, Key::RightBracket, Some(id)) => if pressed { let event = WindowEvent::Navigation(id, TraversalDirection::Back(1)); self.event_queue.push(event); - } + }, _ => { - self.event_queue.push(WindowEvent::KeyEvent(ch, key, state, mods)); - } + self.event_queue + .push(WindowEvent::KeyEvent(ch, key, state, mods)); + }, } } #[cfg(target_os = "win")] - fn platform_handle_key(&mut self, _ch: Option<char>, _key: Key, _mods: KeyModifiers, _state: KeyState) { + fn platform_handle_key( + &mut self, + _ch: Option<char>, + _key: Key, + _mods: KeyModifiers, + _state: KeyState, + ) { } /// Handle key events after they have been handled by Servo. - fn handle_key_from_servo(&mut self, _: Option<BrowserId>, ch: Option<char>, - key: Key, state: KeyState, mods: KeyModifiers) { + fn handle_key_from_servo( + &mut self, + _: Option<BrowserId>, + ch: Option<char>, + key: Key, + state: KeyState, + mods: KeyModifiers, + ) { if state == KeyState::Released { return; } @@ -177,55 +206,66 @@ impl Browser { match (mods, ch, key) { (CMD_OR_CONTROL, Some('='), _) | (CMD_OR_CONTROL, Some('+'), _) => { self.event_queue.push(WindowEvent::Zoom(1.1)); - } + }, (_, Some('='), _) if mods == (CMD_OR_CONTROL | KeyModifiers::SHIFT) => { self.event_queue.push(WindowEvent::Zoom(1.1)); }, (CMD_OR_CONTROL, Some('-'), _) => { self.event_queue.push(WindowEvent::Zoom(1.0 / 1.1)); - } + }, (CMD_OR_CONTROL, Some('0'), _) => { self.event_queue.push(WindowEvent::ResetZoom); - } + }, (KeyModifiers::NONE, None, Key::PageDown) => { - let scroll_location = ScrollLocation::Delta(TypedVector2D::new(0.0, - -self.window.page_height() + 2.0 * LINE_HEIGHT)); + let scroll_location = ScrollLocation::Delta(TypedVector2D::new( + 0.0, + -self.window.page_height() + 2.0 * LINE_HEIGHT, + )); self.scroll_window_from_key(scroll_location, TouchEventType::Move); - } + }, (KeyModifiers::NONE, None, Key::PageUp) => { - let scroll_location = ScrollLocation::Delta(TypedVector2D::new(0.0, - self.window.page_height() - 2.0 * LINE_HEIGHT)); + let scroll_location = ScrollLocation::Delta(TypedVector2D::new( + 0.0, + self.window.page_height() - 2.0 * LINE_HEIGHT, + )); self.scroll_window_from_key(scroll_location, TouchEventType::Move); - } + }, (KeyModifiers::NONE, None, Key::Home) => { self.scroll_window_from_key(ScrollLocation::Start, TouchEventType::Move); - } + }, (KeyModifiers::NONE, None, Key::End) => { self.scroll_window_from_key(ScrollLocation::End, TouchEventType::Move); - } + }, (KeyModifiers::NONE, None, Key::Up) => { - self.scroll_window_from_key(ScrollLocation::Delta(TypedVector2D::new(0.0, 3.0 * LINE_HEIGHT)), - TouchEventType::Move); - } + self.scroll_window_from_key( + ScrollLocation::Delta(TypedVector2D::new(0.0, 3.0 * LINE_HEIGHT)), + TouchEventType::Move, + ); + }, (KeyModifiers::NONE, None, Key::Down) => { - self.scroll_window_from_key(ScrollLocation::Delta(TypedVector2D::new(0.0, -3.0 * LINE_HEIGHT)), - TouchEventType::Move); - } + self.scroll_window_from_key( + ScrollLocation::Delta(TypedVector2D::new(0.0, -3.0 * LINE_HEIGHT)), + TouchEventType::Move, + ); + }, (KeyModifiers::NONE, None, Key::Left) => { - self.scroll_window_from_key(ScrollLocation::Delta(TypedVector2D::new(LINE_HEIGHT, 0.0)), - TouchEventType::Move); - } + self.scroll_window_from_key( + ScrollLocation::Delta(TypedVector2D::new(LINE_HEIGHT, 0.0)), + TouchEventType::Move, + ); + }, (KeyModifiers::NONE, None, Key::Right) => { - self.scroll_window_from_key(ScrollLocation::Delta(TypedVector2D::new(-LINE_HEIGHT, 0.0)), - TouchEventType::Move); - } + self.scroll_window_from_key( + ScrollLocation::Delta(TypedVector2D::new(-LINE_HEIGHT, 0.0)), + TouchEventType::Move, + ); + }, - _ => { - } + _ => {}, } } @@ -254,81 +294,93 @@ impl Browser { }; let title = format!("{} - Servo", title); self.window.set_title(&title); - } + }, EmbedderMsg::MoveTo(point) => { self.window.set_position(point); - } + }, EmbedderMsg::ResizeTo(size) => { self.window.set_inner_size(size); - } + }, EmbedderMsg::Alert(message, sender) => { if !opts::get().headless { - let _ = thread::Builder::new().name("display alert dialog".to_owned()).spawn(move || { - tinyfiledialogs::message_box_ok("Alert!", &message, MessageBoxIcon::Warning); - }).unwrap().join().expect("Thread spawning failed"); + let _ = thread::Builder::new() + .name("display alert dialog".to_owned()) + .spawn(move || { + tinyfiledialogs::message_box_ok( + "Alert!", + &message, + MessageBoxIcon::Warning, + ); + }).unwrap() + .join() + .expect("Thread spawning failed"); } if let Err(e) = sender.send(()) { let reason = format!("Failed to send Alert response: {}", e); - self.event_queue.push(WindowEvent::SendError(browser_id, reason)); + self.event_queue + .push(WindowEvent::SendError(browser_id, reason)); } - } + }, EmbedderMsg::AllowUnload(sender) => { // Always allow unload for now. if let Err(e) = sender.send(true) { let reason = format!("Failed to send AllowUnload response: {}", e); - self.event_queue.push(WindowEvent::SendError(browser_id, reason)); + self.event_queue + .push(WindowEvent::SendError(browser_id, reason)); } - } + }, EmbedderMsg::AllowNavigation(_url, sender) => { if let Err(e) = sender.send(true) { warn!("Failed to send AllowNavigation response: {}", e); } - } + }, EmbedderMsg::AllowOpeningBrowser(response_chan) => { // Note: would be a place to handle pop-ups config. // see Step 7 of #the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name if let Err(e) = response_chan.send(true) { warn!("Failed to send AllowOpeningBrowser response: {}", e); }; - } + }, EmbedderMsg::BrowserCreated(new_browser_id) => { // TODO: properly handle a new "tab" self.browsers.push(new_browser_id); if self.browser_id.is_none() { self.browser_id = Some(new_browser_id); } - self.event_queue.push(WindowEvent::SelectBrowser(new_browser_id)); - } + self.event_queue + .push(WindowEvent::SelectBrowser(new_browser_id)); + }, EmbedderMsg::KeyEvent(ch, key, state, modified) => { self.handle_key_from_servo(browser_id, ch, key, state, modified); - } + }, EmbedderMsg::SetCursor(cursor) => { self.window.set_cursor(cursor); - } + }, EmbedderMsg::NewFavicon(url) => { self.favicon = Some(url); - } + }, EmbedderMsg::HeadParsed => { self.loading_state = Some(LoadingState::Loading); - } + }, EmbedderMsg::HistoryChanged(urls, current) => { self.current_url = Some(urls[current].clone()); - } + }, EmbedderMsg::SetFullscreenState(state) => { self.window.set_fullscreen(state); - } + }, EmbedderMsg::LoadStart => { self.loading_state = Some(LoadingState::Connecting); - } + }, EmbedderMsg::LoadComplete => { self.loading_state = Some(LoadingState::Loaded); - } + }, EmbedderMsg::CloseBrowser => { // TODO: close the appropriate "tab". let _ = self.browsers.pop(); if let Some(prev_browser_id) = self.browsers.last() { self.browser_id = Some(*prev_browser_id); - self.event_queue.push(WindowEvent::SelectBrowser(*prev_browser_id)); + self.event_queue + .push(WindowEvent::SelectBrowser(*prev_browser_id)); } else { self.event_queue.push(WindowEvent::Quit); } @@ -336,92 +388,107 @@ impl Browser { EmbedderMsg::Shutdown => { self.shutdown_requested = true; }, - EmbedderMsg::Panic(_reason, _backtrace) => { - }, + EmbedderMsg::Panic(_reason, _backtrace) => {}, EmbedderMsg::GetSelectedBluetoothDevice(devices, sender) => { let selected = platform_get_selected_devices(devices); if let Err(e) = sender.send(selected) { - let reason = format!("Failed to send GetSelectedBluetoothDevice response: {}", e); + let reason = + format!("Failed to send GetSelectedBluetoothDevice response: {}", e); self.event_queue.push(WindowEvent::SendError(None, reason)); }; }, EmbedderMsg::SelectFiles(patterns, multiple_files, sender) => { - let res = match (opts::get().headless, get_selected_files(patterns, multiple_files)) { + let res = match ( + opts::get().headless, + get_selected_files(patterns, multiple_files), + ) { (true, _) | (false, None) => sender.send(None), - (false, Some(files)) => sender.send(Some(files)) + (false, Some(files)) => sender.send(Some(files)), }; if let Err(e) = res { let reason = format!("Failed to send SelectFiles response: {}", e); self.event_queue.push(WindowEvent::SendError(None, reason)); }; - } + }, EmbedderMsg::ShowIME(_kind) => { debug!("ShowIME received"); - } + }, EmbedderMsg::HideIME => { debug!("HideIME received"); - } + }, } } } - } #[cfg(target_os = "linux")] fn platform_get_selected_devices(devices: Vec<String>) -> Option<String> { let picker_name = "Choose a device"; - thread::Builder::new().name(picker_name.to_owned()).spawn(move || { - let dialog_rows: Vec<&str> = devices.iter() - .map(|s| s.as_ref()) - .collect(); - let dialog_rows: Option<&[&str]> = Some(dialog_rows.as_slice()); + thread::Builder::new() + .name(picker_name.to_owned()) + .spawn(move || { + let dialog_rows: Vec<&str> = devices.iter().map(|s| s.as_ref()).collect(); + let dialog_rows: Option<&[&str]> = Some(dialog_rows.as_slice()); - match tinyfiledialogs::list_dialog("Choose a device", &["Id", "Name"], dialog_rows) { - Some(device) => { - // The device string format will be "Address|Name". We need the first part of it. - device.split("|").next().map(|s| s.to_string()) - }, - None => { - None + match tinyfiledialogs::list_dialog("Choose a device", &["Id", "Name"], dialog_rows) { + Some(device) => { + // The device string format will be "Address|Name". We need the first part of it. + device.split("|").next().map(|s| s.to_string()) + }, + None => None, } - } - }).unwrap().join().expect("Thread spawning failed") + }).unwrap() + .join() + .expect("Thread spawning failed") } #[cfg(not(target_os = "linux"))] fn platform_get_selected_devices(devices: Vec<String>) -> Option<String> { for device in devices { if let Some(address) = device.split("|").next().map(|s| s.to_string()) { - return Some(address) + return Some(address); } } None } fn get_selected_files(patterns: Vec<FilterPattern>, multiple_files: bool) -> Option<Vec<String>> { - let picker_name = if multiple_files { "Pick files" } else { "Pick a file" }; - thread::Builder::new().name(picker_name.to_owned()).spawn(move || { - let mut filters = vec![]; - for p in patterns { - let s = "*.".to_string() + &p.0; - filters.push(s) - } - let filter_ref = &(filters.iter().map(|s| s.as_str()).collect::<Vec<&str>>()[..]); - let filter_opt = if filters.len() > 0 { Some((filter_ref, "")) } else { None }; + let picker_name = if multiple_files { + "Pick files" + } else { + "Pick a file" + }; + thread::Builder::new() + .name(picker_name.to_owned()) + .spawn(move || { + let mut filters = vec![]; + for p in patterns { + let s = "*.".to_string() + &p.0; + filters.push(s) + } + let filter_ref = &(filters.iter().map(|s| s.as_str()).collect::<Vec<&str>>()[..]); + let filter_opt = if filters.len() > 0 { + Some((filter_ref, "")) + } else { + None + }; - if multiple_files { - tinyfiledialogs::open_file_dialog_multi(picker_name, "", filter_opt) - } else { - let file = tinyfiledialogs::open_file_dialog(picker_name, "", filter_opt); - file.map(|x| vec![x]) - } - }).unwrap().join().expect("Thread spawning failed") + if multiple_files { + tinyfiledialogs::open_file_dialog_multi(picker_name, "", filter_opt) + } else { + let file = tinyfiledialogs::open_file_dialog(picker_name, "", filter_opt); + file.map(|x| vec![x]) + } + }).unwrap() + .join() + .expect("Thread spawning failed") } fn sanitize_url(request: &str) -> Option<ServoUrl> { let request = request.trim(); - ServoUrl::parse(&request).ok() + ServoUrl::parse(&request) + .ok() .or_else(|| { if request.contains('/') || is_reg_domain(request) { ServoUrl::parse(&format!("http://{}", request)).ok() @@ -429,9 +496,12 @@ fn sanitize_url(request: &str) -> Option<ServoUrl> { None } }).or_else(|| { - PREFS.get("shell.searchpage").as_string().and_then(|s: &str| { - let url = s.replace("%s", request); - ServoUrl::parse(&url).ok() - }) + PREFS + .get("shell.searchpage") + .as_string() + .and_then(|s: &str| { + let url = s.replace("%s", request); + ServoUrl::parse(&url).ok() + }) }) } diff --git a/ports/servo/glutin_app/keyutils.rs b/ports/servo/glutin_app/keyutils.rs index e816fa6cd36..2c685cf10e5 100644 --- a/ports/servo/glutin_app/keyutils.rs +++ b/ports/servo/glutin_app/keyutils.rs @@ -114,7 +114,7 @@ pub fn char_to_script_key(c: char) -> Option<constellation_msg::Key> { '\\' => Some(Key::Backslash), '}' => Some(Key::RightBracket), ']' => Some(Key::RightBracket), - _ => None + _ => None, } } @@ -233,69 +233,13 @@ pub fn winit_key_to_script_key(key: VirtualKeyCode) -> Result<constellation_msg: pub fn is_printable(key_code: VirtualKeyCode) -> bool { use winit::VirtualKeyCode::*; match key_code { - Escape | - F1 | - F2 | - F3 | - F4 | - F5 | - F6 | - F7 | - F8 | - F9 | - F10 | - F11 | - F12 | - F13 | - F14 | - F15 | - Snapshot | - Scroll | - Pause | - Insert | - Home | - Delete | - End | - PageDown | - PageUp | - Left | - Up | - Right | - Down | - Back | - LAlt | - LControl | - LShift | - LWin | - Mail | - MediaSelect | - MediaStop | - Mute | - MyComputer | - NavigateForward | - NavigateBackward | - NextTrack | - NoConvert | - PlayPause | - Power | - PrevTrack | - RAlt | - RControl | - RShift | - RWin | - Sleep | - Stop | - VolumeDown | - VolumeUp | - Wake | - WebBack | - WebFavorites | - WebForward | - WebHome | - WebRefresh | - WebSearch | - WebStop => false, + Escape | F1 | F2 | F3 | F4 | F5 | F6 | F7 | F8 | F9 | F10 | F11 | F12 | F13 | F14 | + F15 | Snapshot | Scroll | Pause | Insert | Home | Delete | End | PageDown | PageUp | + Left | Up | Right | Down | Back | LAlt | LControl | LShift | LWin | Mail | + MediaSelect | MediaStop | Mute | MyComputer | NavigateForward | NavigateBackward | + NextTrack | NoConvert | PlayPause | Power | PrevTrack | RAlt | RControl | RShift | + RWin | Sleep | Stop | VolumeDown | VolumeUp | Wake | WebBack | WebFavorites | + WebForward | WebHome | WebRefresh | WebSearch | WebStop => false, _ => true, } } - diff --git a/ports/servo/glutin_app/window.rs b/ports/servo/glutin_app/window.rs index 42df41c49c4..783f7e9a494 100644 --- a/ports/servo/glutin_app/window.rs +++ b/ports/servo/glutin_app/window.rs @@ -42,7 +42,6 @@ use winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize}; #[cfg(target_os = "macos")] use winit::os::macos::{ActivationPolicy, WindowBuilderExt}; - // This should vary by zoom level and maybe actual text size (focused or under cursor) pub const LINE_HEIGHT: f32 = 38.0; @@ -91,20 +90,21 @@ impl HeadlessContext { attribs.push(3); attribs.push(0); - let context = unsafe { - osmesa_sys::OSMesaCreateContextAttribs(attribs.as_ptr(), ptr::null_mut()) - }; + let context = + unsafe { osmesa_sys::OSMesaCreateContextAttribs(attribs.as_ptr(), ptr::null_mut()) }; assert!(!context.is_null()); let mut buffer = vec![0; (width * height) as usize]; unsafe { - let ret = osmesa_sys::OSMesaMakeCurrent(context, - buffer.as_mut_ptr() as *mut _, - gl::UNSIGNED_BYTE, - width as i32, - height as i32); + let ret = osmesa_sys::OSMesaMakeCurrent( + context, + buffer.as_mut_ptr() as *mut _, + gl::UNSIGNED_BYTE, + width as i32, + height as i32, + ); assert_ne!(ret, 0); }; @@ -127,9 +127,7 @@ impl HeadlessContext { #[cfg(any(target_os = "linux", target_os = "macos"))] fn get_proc_address(s: &str) -> *const c_void { let c_str = CString::new(s).expect("Unable to create CString"); - unsafe { - mem::transmute(osmesa_sys::OSMesaGetProcAddress(c_str.as_ptr())) - } + unsafe { mem::transmute(osmesa_sys::OSMesaGetProcAddress(c_str.as_ptr())) } } #[cfg(not(any(target_os = "linux", target_os = "macos")))] @@ -167,18 +165,18 @@ fn window_creation_scale_factor() -> TypedScale<f32, DeviceIndependentPixel, Dev #[cfg(target_os = "windows")] fn window_creation_scale_factor() -> TypedScale<f32, DeviceIndependentPixel, DevicePixel> { - let hdc = unsafe { user32::GetDC(::std::ptr::null_mut()) }; - let ppi = unsafe { gdi32::GetDeviceCaps(hdc, winapi::wingdi::LOGPIXELSY) }; - TypedScale::new(ppi as f32 / 96.0) + let hdc = unsafe { user32::GetDC(::std::ptr::null_mut()) }; + let ppi = unsafe { gdi32::GetDeviceCaps(hdc, winapi::wingdi::LOGPIXELSY) }; + TypedScale::new(ppi as f32 / 96.0) } - impl Window { pub fn new( is_foreground: bool, window_size: TypedSize2D<u32, DeviceIndependentPixel>, ) -> Rc<Window> { - let win_size: DeviceUintSize = (window_size.to_f32() * window_creation_scale_factor()).to_u32(); + let win_size: DeviceUintSize = + (window_size.to_f32() * window_creation_scale_factor()).to_u32(); let width = win_size.to_untyped().width; let height = win_size.to_untyped().height; @@ -225,7 +223,10 @@ impl Window { .expect("Failed to create window."); unsafe { - glutin_window.context().make_current().expect("Couldn't make window current"); + glutin_window + .context() + .make_current() + .expect("Couldn't make window current"); } let PhysicalSize { @@ -234,8 +235,9 @@ impl Window { } = events_loop.get_primary_monitor().get_dimensions(); screen_size = TypedSize2D::new(screen_width as u32, screen_height as u32); // TODO(ajeffrey): can this fail? - let LogicalSize { width, height } = - glutin_window.get_inner_size().expect("Failed to get window inner size."); + let LogicalSize { width, height } = glutin_window + .get_inner_size() + .expect("Failed to get window inner size."); inner_size = TypedSize2D::new(width as u32, height as u32); glutin_window.show(); @@ -244,25 +246,17 @@ impl Window { }; let gl = match window_kind { - WindowKind::Window(ref window, ..) => { - match gl::GlType::default() { - gl::GlType::Gl => { - unsafe { - gl::GlFns::load_with(|s| window.get_proc_address(s) as *const _) - } - } - gl::GlType::Gles => { - unsafe { - gl::GlesFns::load_with(|s| window.get_proc_address(s) as *const _) - } - } - } - } - WindowKind::Headless(..) => { - unsafe { - gl::GlFns::load_with(|s| HeadlessContext::get_proc_address(s)) - } - } + WindowKind::Window(ref window, ..) => match gl::GlType::default() { + gl::GlType::Gl => unsafe { + gl::GlFns::load_with(|s| window.get_proc_address(s) as *const _) + }, + gl::GlType::Gles => unsafe { + gl::GlesFns::load_with(|s| window.get_proc_address(s) as *const _) + }, + }, + WindowKind::Headless(..) => unsafe { + gl::GlFns::load_with(|s| HeadlessContext::get_proc_address(s)) + }, }; if opts::get().headless { @@ -279,7 +273,7 @@ impl Window { let window = Window { kind: window_kind, - event_queue: RefCell::new(vec!()), + event_queue: RefCell::new(vec![]), mouse_down_button: Cell::new(None), mouse_down_point: Cell::new(TypedPoint2D::new(0, 0)), @@ -308,12 +302,12 @@ impl Window { let dpr = self.servo_hidpi_factor(); match self.kind { WindowKind::Window(ref window, _) => { - let size = window.get_inner_size().expect("Failed to get window inner size."); + let size = window + .get_inner_size() + .expect("Failed to get window inner size."); size.height as f32 * dpr.get() }, - WindowKind::Headless(ref context) => { - context.height as f32 * dpr.get() - } + WindowKind::Headless(ref context) => context.height as f32 * dpr.get(), } } @@ -344,7 +338,7 @@ impl Window { window.set_fullscreen(None); } }, - WindowKind::Headless(..) => {} + WindowKind::Headless(..) => {}, } self.fullscreen.set(state); } @@ -353,7 +347,10 @@ impl Window { self.animation_state.get() == AnimationState::Animating && !self.suspended.get() } - pub fn run<T>(&self, mut servo_callback: T) where T: FnMut() -> bool { + pub fn run<T>(&self, mut servo_callback: T) + where + T: FnMut() -> bool, + { match self.kind { WindowKind::Window(_, ref events_loop) => { let mut stop = false; @@ -384,7 +381,7 @@ impl Window { break; } } - } + }, WindowKind::Headless(..) => { loop { // Sleep the main thread to avoid using 100% CPU @@ -397,7 +394,7 @@ impl Window { break; } } - } + }, } } @@ -438,7 +435,12 @@ impl Window { self.toggle_modifier(KeyModifiers::SUPER, mods.logo); } - fn handle_keyboard_input(&self, element_state: ElementState, code: VirtualKeyCode, mods: ModifiersState) { + fn handle_keyboard_input( + &self, + element_state: ElementState, + code: VirtualKeyCode, + mods: ModifiersState, + ) { self.toggle_keyboard_modifiers(mods); if let Ok(key) = keyutils::winit_key_to_script_key(code) { @@ -452,7 +454,9 @@ impl Window { } else { self.last_pressed_key.set(None); let modifiers = self.key_modifiers.get(); - self.event_queue.borrow_mut().push(WindowEvent::KeyEvent(None, key, state, modifiers)); + self.event_queue + .borrow_mut() + .push(WindowEvent::KeyEvent(None, key, state, modifiers)); } } } @@ -464,34 +468,40 @@ impl Window { .. } => self.handle_received_character(ch), Event::WindowEvent { - event: winit::WindowEvent::KeyboardInput { - input: winit::KeyboardInput { - state, virtual_keycode: Some(virtual_keycode), modifiers, .. - }, .. - }, .. + event: + winit::WindowEvent::KeyboardInput { + input: + winit::KeyboardInput { + state, + virtual_keycode: Some(virtual_keycode), + modifiers, + .. + }, + .. + }, + .. } => self.handle_keyboard_input(state, virtual_keycode, modifiers), Event::WindowEvent { - event: winit::WindowEvent::MouseInput { - state, button, .. - }, .. + event: winit::WindowEvent::MouseInput { state, button, .. }, + .. } => { if button == MouseButton::Left || button == MouseButton::Right { self.handle_mouse(button, state, self.mouse_pos.get()); } }, Event::WindowEvent { - event: winit::WindowEvent::CursorMoved { - position, - .. - }, + event: winit::WindowEvent::CursorMoved { position, .. }, .. } => { let pos = position.to_physical(self.device_hidpi_factor().get() as f64); let (x, y): (i32, i32) = pos.into(); self.mouse_pos.set(TypedPoint2D::new(x, y)); - self.event_queue.borrow_mut().push( - WindowEvent::MouseWindowMoveEventClass(TypedPoint2D::new(x as f32, y as f32))); - } + self.event_queue + .borrow_mut() + .push(WindowEvent::MouseWindowMoveEventClass(TypedPoint2D::new( + x as f32, y as f32, + ))); + }, Event::WindowEvent { event: winit::WindowEvent::MouseWheel { delta, phase, .. }, .. @@ -499,9 +509,10 @@ impl Window { let (mut dx, mut dy) = match delta { MouseScrollDelta::LineDelta(dx, dy) => (dx, dy * LINE_HEIGHT), MouseScrollDelta::PixelDelta(position) => { - let position = position.to_physical(self.device_hidpi_factor().get() as f64); + let position = + position.to_physical(self.device_hidpi_factor().get() as f64); (position.x as f32, position.y as f32) - } + }, }; // Scroll events snap to the major axis of movement, with vertical // preferred over horizontal. @@ -524,10 +535,14 @@ impl Window { let phase = winit_phase_to_touch_event_type(touch.phase); let id = TouchId(touch.id as i32); - let position = touch.location.to_physical(self.device_hidpi_factor().get() as f64); + let position = touch + .location + .to_physical(self.device_hidpi_factor().get() as f64); let point = TypedPoint2D::new(position.x as f32, position.y as f32); - self.event_queue.borrow_mut().push(WindowEvent::Touch(phase, id, point)); - } + self.event_queue + .borrow_mut() + .push(WindowEvent::Touch(phase, id, point)); + }, Event::WindowEvent { event: winit::WindowEvent::Refresh, .. @@ -537,7 +552,7 @@ impl Window { .. } => { self.event_queue.borrow_mut().push(WindowEvent::Quit); - } + }, Event::WindowEvent { event: winit::WindowEvent::Resized(size), .. @@ -555,17 +570,17 @@ impl Window { self.inner_size.set(new_size); self.event_queue.borrow_mut().push(WindowEvent::Resize); } - } + }, Event::Suspended(suspended) => { self.suspended.set(suspended); if !suspended { self.event_queue.borrow_mut().push(WindowEvent::Idle); } - } + }, Event::Awakened => { self.event_queue.borrow_mut().push(WindowEvent::Idle); - } - _ => {} + }, + _ => {}, } } @@ -580,9 +595,12 @@ impl Window { } /// Helper function to handle a click - fn handle_mouse(&self, button: winit::MouseButton, - action: winit::ElementState, - coords: TypedPoint2D<i32, DevicePixel>) { + fn handle_mouse( + &self, + button: winit::MouseButton, + action: winit::ElementState, + coords: TypedPoint2D<i32, DevicePixel>, + ) { use servo::script_traits::MouseButton; let max_pixel_dist = 10.0 * self.servo_hidpi_factor().get(); @@ -591,17 +609,20 @@ impl Window { self.mouse_down_point.set(coords); self.mouse_down_button.set(Some(button)); MouseWindowEvent::MouseDown(MouseButton::Left, coords.to_f32()) - } + }, ElementState::Released => { let mouse_up_event = MouseWindowEvent::MouseUp(MouseButton::Left, coords.to_f32()); match self.mouse_down_button.get() { None => mouse_up_event, Some(but) if button == but => { let pixel_dist = self.mouse_down_point.get() - coords; - let pixel_dist = ((pixel_dist.x * pixel_dist.x + - pixel_dist.y * pixel_dist.y) as f32).sqrt(); + let pixel_dist = + ((pixel_dist.x * pixel_dist.x + pixel_dist.y * pixel_dist.y) as f32) + .sqrt(); if pixel_dist < max_pixel_dist { - self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(mouse_up_event)); + self.event_queue + .borrow_mut() + .push(WindowEvent::MouseWindowEventClass(mouse_up_event)); MouseWindowEvent::Click(MouseButton::Left, coords.to_f32()) } else { mouse_up_event @@ -609,19 +630,17 @@ impl Window { }, Some(_) => mouse_up_event, } - } + }, }; - self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(event)); + self.event_queue + .borrow_mut() + .push(WindowEvent::MouseWindowEventClass(event)); } fn device_hidpi_factor(&self) -> TypedScale<f32, DeviceIndependentPixel, DevicePixel> { match self.kind { - WindowKind::Window(ref window, ..) => { - TypedScale::new(window.get_hidpi_factor() as f32) - } - WindowKind::Headless(..) => { - TypedScale::new(1.0) - } + WindowKind::Window(ref window, ..) => TypedScale::new(window.get_hidpi_factor() as f32), + WindowKind::Headless(..) => TypedScale::new(1.0), } } @@ -630,8 +649,8 @@ impl Window { Some(device_pixels_per_px) => TypedScale::new(device_pixels_per_px), _ => match opts::get().output_file { Some(_) => TypedScale::new(1.0), - None => self.device_hidpi_factor() - } + None => self.device_hidpi_factor(), + }, } } @@ -676,11 +695,11 @@ impl Window { CursorKind::AllScroll => MouseCursor::AllScroll, CursorKind::ZoomIn => MouseCursor::ZoomIn, CursorKind::ZoomOut => MouseCursor::ZoomOut, - _ => MouseCursor::Default + _ => MouseCursor::Default, }; window.set_cursor(winit_cursor); - } - WindowKind::Headless(..) => {} + }, + WindowKind::Headless(..) => {}, } } } @@ -695,13 +714,19 @@ impl WindowMethods for Window { WindowKind::Window(ref window, _) => { // TODO(ajeffrey): can this fail? let dpr = self.device_hidpi_factor(); - let LogicalSize { width, height } = window.get_outer_size().expect("Failed to get window outer size."); - let LogicalPosition { x, y } = window.get_position().unwrap_or(LogicalPosition::new(0., 0.)); + let LogicalSize { width, height } = window + .get_outer_size() + .expect("Failed to get window outer size."); + let LogicalPosition { x, y } = window + .get_position() + .unwrap_or(LogicalPosition::new(0., 0.)); let win_size = (TypedSize2D::new(width as f32, height as f32) * dpr).to_u32(); let win_origin = (TypedPoint2D::new(x as f32, y as f32) * dpr).to_i32(); let screen = (self.screen_size.to_f32() * dpr).to_u32(); - let LogicalSize { width, height } = window.get_inner_size().expect("Failed to get window inner size."); + let LogicalSize { width, height } = window + .get_inner_size() + .expect("Failed to get window inner size."); let inner_size = (TypedSize2D::new(width as f32, height as f32) * dpr).to_u32(); let viewport = DeviceUintRect::new(TypedPoint2D::zero(), inner_size); @@ -718,7 +743,8 @@ impl WindowMethods for Window { }, WindowKind::Headless(ref context) => { let dpr = self.servo_hidpi_factor(); - let size = (TypedSize2D::new(context.width, context.height).to_f32() * dpr).to_u32(); + let size = + (TypedSize2D::new(context.width, context.height).to_f32() * dpr).to_u32(); EmbedderCoordinates { viewport: DeviceUintRect::new(TypedPoint2D::zero(), size), framebuffer: size, @@ -727,7 +753,7 @@ impl WindowMethods for Window { screen_avail: size, hidpi_factor: dpr, } - } + }, } } @@ -737,8 +763,8 @@ impl WindowMethods for Window { if let Err(err) = window.swap_buffers() { warn!("Failed to swap window buffers ({}).", err); } - } - WindowKind::Headless(..) => {} + }, + WindowKind::Headless(..) => {}, } } @@ -752,9 +778,7 @@ impl WindowMethods for Window { WindowKind::Window(_, ref events_loop) => { Some(Arc::new(events_loop.borrow().create_proxy())) }, - WindowKind::Headless(..) => { - None - } + WindowKind::Headless(..) => None, }; GlutinEventLoopWaker { proxy } } @@ -782,7 +806,11 @@ impl WindowMethods for Window { self.animation_state.set(state); } - fn prepare_for_composite(&self, _width: Length<u32, DevicePixel>, _height: Length<u32, DevicePixel>) -> bool { + fn prepare_for_composite( + &self, + _width: Length<u32, DevicePixel>, + _height: Length<u32, DevicePixel>, + ) -> bool { true } diff --git a/ports/servo/main.rs b/ports/servo/main.rs index c4cd657d138..8345d03850d 100644 --- a/ports/servo/main.rs +++ b/ports/servo/main.rs @@ -19,12 +19,17 @@ // Have this here rather than in non_android_main.rs to work around // https://github.com/rust-lang/rust/issues/53205 -#[cfg(not(target_os = "android"))] #[macro_use] extern crate log; +#[cfg(not(target_os = "android"))] +#[macro_use] +extern crate log; -#[cfg(not(target_os = "android"))] include!("non_android_main.rs"); +#[cfg(not(target_os = "android"))] +include!("non_android_main.rs"); #[cfg(target_os = "android")] pub fn main() { - println!("Cannot start /ports/servo/ on Android. \ - Use /support/android/apk/ + /ports/libsimpleservo/ instead"); + println!( + "Cannot start /ports/servo/ on Android. \ + Use /support/android/apk/ + /ports/libsimpleservo/ instead" + ); } diff --git a/ports/servo/non_android_main.rs b/ports/servo/non_android_main.rs index 7db35a35e78..7fcc5f0df35 100644 --- a/ports/servo/non_android_main.rs +++ b/ports/servo/non_android_main.rs @@ -4,20 +4,29 @@ extern crate backtrace; extern crate euclid; -#[cfg(target_os = "windows")] extern crate gdi32; +#[cfg(target_os = "windows")] +extern crate gdi32; extern crate gleam; extern crate glutin; -#[macro_use] extern crate lazy_static; -#[cfg(any(target_os = "linux", target_os = "macos"))] extern crate osmesa_sys; +#[macro_use] +extern crate lazy_static; +#[cfg(any(target_os = "linux", target_os = "macos"))] +extern crate osmesa_sys; extern crate servo; #[cfg(feature = "unstable")] #[macro_use] extern crate sig; -#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] +#[cfg(any( + target_os = "macos", + target_os = "linux", + target_os = "windows" +))] extern crate tinyfiledialogs; +#[cfg(target_os = "windows")] +extern crate user32; +#[cfg(target_os = "windows")] +extern crate winapi; extern crate winit; -#[cfg(target_os = "windows")] extern crate winapi; -#[cfg(target_os = "windows")] extern crate user32; // The window backed by glutin mod glutin_app; @@ -100,21 +109,21 @@ pub fn main() { warn!("Panic hook called."); let msg = match info.payload().downcast_ref::<&'static str>() { Some(s) => *s, - None => { - match info.payload().downcast_ref::<String>() { - Some(s) => &**s, - None => "Box<Any>", - } + None => match info.payload().downcast_ref::<String>() { + Some(s) => &**s, + None => "Box<Any>", }, }; let current_thread = thread::current(); let name = current_thread.name().unwrap_or("<unnamed>"); if let Some(location) = info.location() { - println!("{} (thread {}, at {}:{})", - msg, - name, - location.file(), - location.line()); + println!( + "{} (thread {}, at {}:{})", + msg, + name, + location.file(), + location.line() + ); } else { println!("{} (thread {})", msg, name); } @@ -142,7 +151,9 @@ pub fn main() { // or a blank page in case the homepage is not set either. let cwd = env::current_dir().unwrap(); let cmdline_url = opts::get().url.clone(); - let pref_url = PREFS.get("shell.homepage").as_string() + let pref_url = PREFS + .get("shell.homepage") + .as_string() .and_then(|str| parse_url_or_filename(&cwd, str).ok()); let blank_url = ServoUrl::parse("about:blank").ok(); @@ -195,43 +206,49 @@ pub fn main() { #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glBindVertexArrayOES(_array: usize) -{ +pub extern "C" fn glBindVertexArrayOES(_array: usize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glDeleteVertexArraysOES(_n: isize, _arrays: *const ()) -{ +pub extern "C" fn glDeleteVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glGenVertexArraysOES(_n: isize, _arrays: *const ()) -{ +pub extern "C" fn glGenVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glRenderbufferStorageMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize) -{ +pub extern "C" fn glRenderbufferStorageMultisampleIMG( + _: isize, + _: isize, + _: isize, + _: isize, + _: isize, +) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glFramebufferTexture2DMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize, _: isize) -{ +pub extern "C" fn glFramebufferTexture2DMultisampleIMG( + _: isize, + _: isize, + _: isize, + _: isize, + _: isize, + _: isize, +) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] -pub extern "C" fn glDiscardFramebufferEXT(_: isize, _: isize, _: *const ()) -{ +pub extern "C" fn glDiscardFramebufferEXT(_: isize, _: isize, _: *const ()) { unimplemented!() } - diff --git a/ports/servo/platform/macos/mod.rs b/ports/servo/platform/macos/mod.rs index b980b83f5fb..9aaa63b8a1a 100644 --- a/ports/servo/platform/macos/mod.rs +++ b/ports/servo/platform/macos/mod.rs @@ -16,4 +16,3 @@ pub fn deinit() { #[link_section = "__TEXT,__info_plist"] #[no_mangle] pub static INFO_PLIST: [u8; 619] = *include_bytes!("Info.plist"); - |