diff --git a/examples/animation.rs b/examples/animation.rs index 442db1948e8..1a5f1ed68e9 100644 --- a/examples/animation.rs +++ b/examples/animation.rs @@ -1,4 +1,5 @@ extern crate sdl2; + use std::path::Path; use sdl2::event::Event; @@ -7,15 +8,15 @@ use sdl2::rect::Rect; use sdl2::rect::Point; use std::time::Duration; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("SDL2", 640, 480) - .position_centered().build().map_err(|e| e.to_string())?; + .position_centered().build()?; let mut canvas = window.into_canvas() - .accelerated().build().map_err(|e| e.to_string())?; + .accelerated().build()?; let texture_creator = canvas.texture_creator(); canvas.set_draw_color(sdl2::pixels::Color::RGBA(0,0,0,255)); @@ -27,8 +28,7 @@ fn main() -> Result<(), String> { // animation sheet and extras are available from // https://opengameart.org/content/a-platformer-in-the-forest let temp_surface = sdl2::surface::Surface::load_bmp(Path::new("assets/characters.bmp"))?; - let texture = texture_creator.create_texture_from_surface(&temp_surface) - .map_err(|e| e.to_string())?; + let texture = texture_creator.create_texture_from_surface(&temp_surface)?; let frames_per_anim = 4; let sprite_tile_size = (32,32); diff --git a/examples/audio-capture-and-replay.rs b/examples/audio-capture-and-replay.rs index 81f563876ee..a154872c965 100644 --- a/examples/audio-capture-and-replay.rs +++ b/examples/audio-capture-and-replay.rs @@ -39,7 +39,7 @@ impl AudioCallback for Recording { } } -fn record(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired) -> Result, String> { +fn record(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired) -> Result, Box> { println!("Capturing {:} seconds... Please rock!", RECORDING_LENGTH_SECONDS); let (done_sender, done_receiver) = mpsc::channel(); @@ -100,7 +100,7 @@ impl AudioCallback for SoundPlayback { } } -fn replay_recorded_vec(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired, recorded_vec: Vec) -> Result<(), String> { +fn replay_recorded_vec(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpecDesired, recorded_vec: Vec) -> Result<(), Box> { println!("Playing..."); let playback_device = audio_subsystem.open_playback(None, desired_spec, |spec| { @@ -121,7 +121,7 @@ fn replay_recorded_vec(audio_subsystem: &AudioSubsystem, desired_spec: &AudioSpe } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let audio_subsystem = sdl_context.audio()?; diff --git a/examples/audio-queue-squarewave.rs b/examples/audio-queue-squarewave.rs index 7f4f7fd57e4..7a0f8fb9915 100644 --- a/examples/audio-queue-squarewave.rs +++ b/examples/audio-queue-squarewave.rs @@ -24,7 +24,7 @@ fn gen_wave(bytes_to_write: i32) -> Vec { result } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let audio_subsystem = sdl_context.audio()?; diff --git a/examples/audio-squarewave.rs b/examples/audio-squarewave.rs index 1a9b6accbae..d3344795ad1 100644 --- a/examples/audio-squarewave.rs +++ b/examples/audio-squarewave.rs @@ -21,7 +21,7 @@ impl AudioCallback for SquareWave { } } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let audio_subsystem = sdl_context.audio()?; diff --git a/examples/audio-wav.rs b/examples/audio-wav.rs index d49d8908b4a..9a0d07f9f4b 100644 --- a/examples/audio-wav.rs +++ b/examples/audio-wav.rs @@ -38,7 +38,7 @@ impl AudioCallback for Sound { } } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let wav_file : Cow<'static, Path> = match std::env::args().nth(1) { None => Cow::from(Path::new("./assets/sine.wav")), Some(s) => Cow::from(PathBuf::from(s)) diff --git a/examples/audio-whitenoise.rs b/examples/audio-whitenoise.rs index d070932046c..319c424c941 100644 --- a/examples/audio-whitenoise.rs +++ b/examples/audio-whitenoise.rs @@ -21,7 +21,7 @@ impl AudioCallback for MyCallback { } } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let audio_subsystem = sdl_context.audio()?; diff --git a/examples/cursor.rs b/examples/cursor.rs index 16304e59a60..14372abae9d 100644 --- a/examples/cursor.rs +++ b/examples/cursor.rs @@ -10,16 +10,15 @@ use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::surface::Surface; -pub fn run(png: &Path) -> Result<(), String> { +pub fn run(png: &Path) -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG)?; let window = video_subsystem.window("rust-sdl2 demo: Cursor", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().software().build()?; let surface = Surface::from_file(png) .map_err(|err| format!("failed to load cursor image: {}", err))?; @@ -53,7 +52,7 @@ pub fn run(png: &Path) -> Result<(), String> { } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); if args.len() < 2 { diff --git a/examples/demo.rs b/examples/demo.rs index 0301a4b81e9..a5953177f07 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -5,17 +5,16 @@ use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::time::Duration; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.clear(); diff --git a/examples/events.rs b/examples/events.rs index 194d724b1f5..60d0dc8095a 100644 --- a/examples/events.rs +++ b/examples/events.rs @@ -5,17 +5,16 @@ use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::time::Duration; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("rust-sdl2 demo: Events", 800, 600) .position_centered() .resizable() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.clear(); diff --git a/examples/game-controller.rs b/examples/game-controller.rs index 8e6b70f124f..e61494f75d1 100644 --- a/examples/game-controller.rs +++ b/examples/game-controller.rs @@ -1,6 +1,6 @@ extern crate sdl2; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let game_controller_subsystem = sdl_context.game_controller()?; diff --git a/examples/game-of-life-unsafe-textures.rs b/examples/game-of-life-unsafe-textures.rs index e878c40cec4..67e7581e46b 100644 --- a/examples/game-of-life-unsafe-textures.rs +++ b/examples/game-of-life-unsafe-textures.rs @@ -126,13 +126,13 @@ mod game_of_life { } #[cfg(feature = "unsafe_textures")] -fn dummy_texture<'a>(canvas: &mut Canvas) -> Result<(Texture, Texture), String> { +fn dummy_texture<'a>(canvas: &mut Canvas) -> Result<(Texture, Texture), Box> { enum TextureColor { Yellow, White, }; - let mut square_texture1 = canvas.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE).map_err(|e| e.to_string())?; - let mut square_texture2 = canvas.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE).map_err(|e| e.to_string())?; + let mut square_texture1 = canvas.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE)?; + let mut square_texture2 = canvas.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE)?; // let's change the textures we just created { let textures = vec![ @@ -198,13 +198,13 @@ fn dummy_texture<'a>(canvas: &mut Canvas) -> Result<(Texture, Texture), } } } - }).map_err(|e| e.to_string())?; + })?; } Ok((square_texture1, square_texture2)) } #[cfg(feature = "unsafe_textures")] -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; @@ -217,15 +217,14 @@ pub fn main() -> Result<(), String> { SQUARE_SIZE*PLAYGROUND_WIDTH, SQUARE_SIZE*PLAYGROUND_HEIGHT) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; // the canvas allows us to both manipulate the property of the window and to change its content // via hardware or software rendering. See CanvasBuilder for more info. let mut canvas = window.into_canvas() .target_texture() .present_vsync() - .build().map_err(|e| e.to_string())?; + .build()?; println!("Using SDL_Renderer \"{}\"", canvas.info().name); canvas.set_draw_color(Color::RGB(0, 0, 0)); diff --git a/examples/game-of-life.rs b/examples/game-of-life.rs index aac8313b89b..d792f901330 100644 --- a/examples/game-of-life.rs +++ b/examples/game-of-life.rs @@ -115,13 +115,13 @@ mod game_of_life { } } -fn dummy_texture<'a>(canvas: &mut Canvas, texture_creator: &'a TextureCreator) -> Result<(Texture<'a>, Texture<'a>), String> { +fn dummy_texture<'a>(canvas: &mut Canvas, texture_creator: &'a TextureCreator) -> Result<(Texture<'a>, Texture<'a>), Box> { enum TextureColor { Yellow, White, }; - let mut square_texture1 = texture_creator.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE).map_err(|e| e.to_string())?; - let mut square_texture2 = texture_creator.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE).map_err(|e| e.to_string())?; + let mut square_texture1 = texture_creator.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE)?; + let mut square_texture2 = texture_creator.create_texture_target(None, SQUARE_SIZE, SQUARE_SIZE)?; // let's change the textures we just created { let textures = vec![ @@ -187,12 +187,12 @@ fn dummy_texture<'a>(canvas: &mut Canvas, texture_creator: &'a TextureCr } } } - }).map_err(|e| e.to_string())?; + })?; } Ok((square_texture1, square_texture2)) } -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; @@ -205,16 +205,14 @@ pub fn main() -> Result<(), String> { SQUARE_SIZE*PLAYGROUND_WIDTH, SQUARE_SIZE*PLAYGROUND_HEIGHT) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; // the canvas allows us to both manipulate the property of the window and to change its content // via hardware or software rendering. See CanvasBuilder for more info. let mut canvas = window.into_canvas() .target_texture() .present_vsync() - .build() - .map_err(|e| e.to_string())?; + .build()?; println!("Using SDL_Renderer \"{}\"", canvas.info().name); canvas.set_draw_color(Color::RGB(0, 0, 0)); diff --git a/examples/gfx-demo.rs b/examples/gfx-demo.rs index 9c67e1e591e..8ac4397c517 100644 --- a/examples/gfx-demo.rs +++ b/examples/gfx-demo.rs @@ -9,16 +9,15 @@ use sdl2::gfx::primitives::DrawRenderer; const SCREEN_WIDTH: u32 = 800; const SCREEN_HEIGHT: u32 = 600; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsys = sdl_context.video()?; let window = video_subsys.window("rust-sdl2_gfx: draw line & FPSManager", SCREEN_WIDTH, SCREEN_HEIGHT) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; canvas.set_draw_color(pixels::Color::RGB(0, 0, 0)); canvas.clear(); diff --git a/examples/haptic.rs b/examples/haptic.rs index de3d717a75a..ae015c2460b 100644 --- a/examples/haptic.rs +++ b/examples/haptic.rs @@ -1,6 +1,6 @@ extern crate sdl2; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let joystick_subsystem = sdl_context.joystick()?; let haptic_subsystem = sdl_context.haptic()?; @@ -22,8 +22,7 @@ fn main() -> Result<(), String> { }, }).expect("Couldn't open any joystick"); - let mut haptic = haptic_subsystem.open_from_joystick_id(joystick_index) - .map_err(|e| e.to_string())?; + let mut haptic = haptic_subsystem.open_from_joystick_id(joystick_index)?; for event in sdl_context.event_pump()?.wait_iter() { use sdl2::event::Event; diff --git a/examples/image-demo.rs b/examples/image-demo.rs index b1069eef491..977c9a32932 100644 --- a/examples/image-demo.rs +++ b/examples/image-demo.rs @@ -6,16 +6,15 @@ use sdl2::image::{LoadTexture, InitFlag}; use sdl2::event::Event; use sdl2::keyboard::Keycode; -pub fn run(png: &Path) -> Result<(), String> { +pub fn run(png: &Path) -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG)?; let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().software().build()?; let texture_creator = canvas.texture_creator(); let texture = texture_creator.load_texture(png)?; @@ -36,7 +35,7 @@ pub fn run(png: &Path) -> Result<(), String> { Ok(()) } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); if args.len() < 2 { diff --git a/examples/joystick.rs b/examples/joystick.rs index 54be2e7255a..ea0fb65f278 100644 --- a/examples/joystick.rs +++ b/examples/joystick.rs @@ -1,6 +1,6 @@ extern crate sdl2; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let joystick_subsystem = sdl_context.joystick()?; @@ -22,8 +22,7 @@ fn main() -> Result<(), String> { }).expect("Couldn't open any joystick"); // Print the joystick's power level - println!("\"{}\" power level: {:?}", joystick.name(), joystick.power_level() - .map_err(|e| e.to_string())?); + println!("\"{}\" power level: {:?}", joystick.name(), joystick.power_level()?); let (mut lo_freq, mut hi_freq) = (0, 0); diff --git a/examples/keyboard-state.rs b/examples/keyboard-state.rs index 729095d49dd..016ab0c80ec 100644 --- a/examples/keyboard-state.rs +++ b/examples/keyboard-state.rs @@ -5,14 +5,13 @@ use sdl2::keyboard::Keycode; use std::collections::HashSet; use std::time::Duration; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _window = video_subsystem.window("Keyboard", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; let mut events = sdl_context.event_pump()?; diff --git a/examples/message-box.rs b/examples/message-box.rs index f8610182422..0b5eb9193de 100644 --- a/examples/message-box.rs +++ b/examples/message-box.rs @@ -5,17 +5,16 @@ use sdl2::event::Event; use sdl2::keyboard::Keycode; use ::sdl2::messagebox::*; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; canvas.set_draw_color(Color::RGB(255, 0, 0)); canvas.clear(); @@ -30,7 +29,7 @@ pub fn main() -> Result<(), String> { "Some title", "Some information inside the window", canvas.window() - ).map_err(|e| e.to_string())?; + )?; break 'running }, _ => {} diff --git a/examples/mixer-demo.rs b/examples/mixer-demo.rs index b06672744d6..7b9e12248cd 100644 --- a/examples/mixer-demo.rs +++ b/examples/mixer-demo.rs @@ -6,7 +6,7 @@ use std::env; use std::path::Path; use sdl2::mixer::{InitFlag, DEFAULT_CHANNELS, AUDIO_S16LSB}; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); if args.len() < 2 { @@ -19,7 +19,7 @@ fn main() -> Result<(), String> { Ok(()) } -fn demo(music_file: &Path, sound_file: Option<&Path>) -> Result<(), String> { +fn demo(music_file: &Path, sound_file: Option<&Path>) -> Result<(), Box> { println!("linked version: {}", sdl2::mixer::get_linked_version()); let sdl = sdl2::init()?; diff --git a/examples/mouse-state.rs b/examples/mouse-state.rs index 785345ac051..d60205ee6d2 100644 --- a/examples/mouse-state.rs +++ b/examples/mouse-state.rs @@ -5,14 +5,13 @@ use sdl2::keyboard::Keycode; use std::collections::HashSet; use std::time::Duration; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _window = video_subsystem.window("Mouse", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; let mut events = sdl_context.event_pump()?; diff --git a/examples/no-renderer.rs b/examples/no-renderer.rs index 78c866bc6ad..3b2b77e146b 100644 --- a/examples/no-renderer.rs +++ b/examples/no-renderer.rs @@ -19,7 +19,7 @@ enum Gradient { White } -fn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradient: Gradient) -> Result<(), String> { +fn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradient: Gradient) -> Result<(), Box> { let mut surface = window.surface(event_pump)?; for i in 0 .. (WINDOW_WIDTH / 4) { let c : u8 = 255 - (i as u8); @@ -33,7 +33,8 @@ fn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradie }; surface.fill_rect(Rect::new(i*4, 0, 4, WINDOW_HEIGHT), color)?; } - surface.finish() + surface.finish()?; + Ok(()) } fn next_gradient(gradient: Gradient) -> Gradient { @@ -47,14 +48,13 @@ fn next_gradient(gradient: Gradient) -> Gradient { } } -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let mut window = video_subsystem.window("rust-sdl2 demo: No Renderer", WINDOW_WIDTH, WINDOW_HEIGHT) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; let mut event_pump = sdl_context.event_pump()?; let mut current_gradient = Gradient::Red; set_window_gradient(&mut window, &event_pump, current_gradient)?; diff --git a/examples/relative-mouse-state.rs b/examples/relative-mouse-state.rs index b02525bf32a..958f6b778ef 100644 --- a/examples/relative-mouse-state.rs +++ b/examples/relative-mouse-state.rs @@ -5,14 +5,13 @@ use sdl2::mouse::MouseButton; use sdl2::keyboard::Keycode; use std::time::Duration; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let _window = video_subsystem.window("Mouse", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; + .build()?; let mut events = sdl_context.event_pump()?; let mut state; diff --git a/examples/renderer-target.rs b/examples/renderer-target.rs index 01fe59ab892..88e6232be8a 100644 --- a/examples/renderer-target.rs +++ b/examples/renderer-target.rs @@ -5,18 +5,16 @@ use sdl2::keyboard::Keycode; use sdl2::pixels::{Color, PixelFormatEnum}; use sdl2::rect::{Point, Rect}; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem .window("rust-sdl2 resource-manager demo", 800, 600) .position_centered() - .build() - .map_err(|e| e.to_string())?; - let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; + .build()?; + let mut canvas = window.into_canvas().software().build()?; let creator = canvas.texture_creator(); - let mut texture = creator.create_texture_target(PixelFormatEnum::RGBA8888, 400, 300) - .map_err(|e| e.to_string())?; + let mut texture = creator.create_texture_target(PixelFormatEnum::RGBA8888, 400, 300)?; let mut angle = 0.0; @@ -33,7 +31,7 @@ fn main() -> Result<(), String> { texture_canvas.clear(); texture_canvas.set_draw_color(Color::RGBA(255, 0, 0, 255)); texture_canvas.fill_rect(Rect::new(0, 0, 400, 300)).expect("could not fill rect"); - }).map_err(|e| e.to_string())?; + })?; canvas.set_draw_color(Color::RGBA(0, 0, 0, 255)); let dst = Some(Rect::new(0, 0, 400, 300)); canvas.clear(); diff --git a/examples/renderer-texture.rs b/examples/renderer-texture.rs index c6d6981405b..9aa23412eb8 100644 --- a/examples/renderer-texture.rs +++ b/examples/renderer-texture.rs @@ -5,21 +5,19 @@ use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; let texture_creator = canvas.texture_creator(); - let mut texture = texture_creator.create_texture_streaming(PixelFormatEnum::RGB24, 256, 256) - .map_err(|e| e.to_string())?; + let mut texture = texture_creator.create_texture_streaming(PixelFormatEnum::RGB24, 256, 256)?; // Create a red-green gradient texture.with_lock(None, |buffer: &mut [u8], pitch: usize| { for y in 0..256 { diff --git a/examples/renderer-yuv.rs b/examples/renderer-yuv.rs index c7b7c34a132..ce7b746cdb9 100644 --- a/examples/renderer-yuv.rs +++ b/examples/renderer-yuv.rs @@ -5,21 +5,19 @@ use sdl2::rect::Rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; let texture_creator = canvas.texture_creator(); - let mut texture = texture_creator.create_texture_streaming(PixelFormatEnum::IYUV, 256, 256) - .map_err(|e| e.to_string())?; + let mut texture = texture_creator.create_texture_streaming(PixelFormatEnum::IYUV, 256, 256)?; // Create a U-V gradient texture.with_lock(None, |buffer: &mut [u8], pitch: usize| { // `pitch` is the width of the Y component diff --git a/examples/resource-manager.rs b/examples/resource-manager.rs index d4b627b424d..05ed45babc9 100644 --- a/examples/resource-manager.rs +++ b/examples/resource-manager.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; use std::hash::Hash; use std::rc::Rc; -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); if args.len() < 3 { @@ -95,7 +95,7 @@ impl<'l, K, R, L> ResourceManager<'l, K, R, L> // Generics magic to allow a HashMap to use String as a key // while allowing it to use &str for gets - pub fn load(&mut self, details: &D) -> Result, String> + pub fn load(&mut self, details: &D) -> Result, Box> where L: ResourceLoader<'l, R, Args = D>, D: Eq + Hash + ?Sized, K: Borrow + for<'a> From<&'a D> @@ -115,25 +115,25 @@ impl<'l, K, R, L> ResourceManager<'l, K, R, L> // TextureCreator knows how to load Textures impl<'l, T> ResourceLoader<'l, Texture<'l>> for TextureCreator { type Args = str; - fn load(&'l self, path: &str) -> Result { + fn load(&'l self, path: &str) -> Result> { println!("LOADED A TEXTURE"); - self.load_texture(path) + Ok(self.load_texture(path)?) } } // Font Context knows how to load Fonts impl<'l> ResourceLoader<'l, Font<'l, 'static>> for Sdl2TtfContext { type Args = FontDetails; - fn load(&'l self, details: &FontDetails) -> Result, String> { + fn load(&'l self, details: &FontDetails) -> Result, Box> { println!("LOADED A FONT"); - self.load_font(&details.path, details.size) + Ok(self.load_font(&details.path, details.size)?) } } // Generic trait to Load any Resource Kind pub trait ResourceLoader<'l, R> { type Args: ?Sized; - fn load(&'l self, data: &Self::Args) -> Result; + fn load(&'l self, data: &Self::Args) -> Result>; } // Information needed to load a Font diff --git a/examples/ttf-demo.rs b/examples/ttf-demo.rs index 5b429eb0a60..fc54a1fdd04 100644 --- a/examples/ttf-demo.rs +++ b/examples/ttf-demo.rs @@ -43,18 +43,17 @@ fn get_centered_rect(rect_width: u32, rect_height: u32, cons_width: u32, cons_he rect!(cx, cy, w, h) } -fn run(font_path: &Path) -> Result<(), String> { +fn run(font_path: &Path) -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsys = sdl_context.video()?; - let ttf_context = sdl2::ttf::init().map_err(|e| e.to_string())?; + let ttf_context = sdl2::ttf::init()?; let window = video_subsys.window("SDL2_TTF Example", SCREEN_WIDTH, SCREEN_HEIGHT) .position_centered() .opengl() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().build()?; let texture_creator = canvas.texture_creator(); // Load a font @@ -63,9 +62,8 @@ fn run(font_path: &Path) -> Result<(), String> { // render a surface, and convert it to a texture bound to the canvas let surface = font.render("Hello Rust!") - .blended(Color::RGBA(255, 0, 0, 255)).map_err(|e| e.to_string())?; - let texture = texture_creator.create_texture_from_surface(&surface) - .map_err(|e| e.to_string())?; + .blended(Color::RGBA(255, 0, 0, 255))?; + let texture = texture_creator.create_texture_from_surface(&surface)?; canvas.set_draw_color(Color::RGBA(195, 217, 255, 255)); canvas.clear(); @@ -92,7 +90,7 @@ fn run(font_path: &Path) -> Result<(), String> { Ok(()) } -fn main() -> Result<(), String> { +fn main() -> Result<(), Box> { let args: Vec<_> = env::args().collect(); println!("linked sdl2_ttf: {}", sdl2::ttf::get_linked_version()); diff --git a/examples/window-properties.rs b/examples/window-properties.rs index b69cccc7dce..728c2bdde72 100644 --- a/examples/window-properties.rs +++ b/examples/window-properties.rs @@ -4,21 +4,20 @@ use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::keyboard::Keycode; -pub fn main() -> Result<(), String> { +pub fn main() -> Result<(), Box> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let window = video_subsystem .window("rust-sdl2 demo: Window", 800, 600) .resizable() - .build() - .map_err(|e| e.to_string())?; + .build()?; - let mut canvas = window.into_canvas().present_vsync().build().map_err(|e| e.to_string())?; + let mut canvas = window.into_canvas().present_vsync().build()?; let mut tick = 0; - let mut event_pump = sdl_context.event_pump().map_err(|e| e.to_string())?; + let mut event_pump = sdl_context.event_pump()?; 'running: loop { for event in event_pump.poll_iter() { @@ -41,7 +40,7 @@ pub fn main() -> Result<(), String> { size.0, size.1, tick); - window.set_title(&title).map_err(|e| e.to_string())?; + window.set_title(&title)?; tick += 1; } diff --git a/src/sdl2/audio.rs b/src/sdl2/audio.rs index 15d015f6e1e..027196962a1 100644 --- a/src/sdl2/audio.rs +++ b/src/sdl2/audio.rs @@ -62,7 +62,7 @@ use std::mem; use std::ptr; use crate::AudioSubsystem; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use crate::rwops::RWops; use crate::sys; @@ -75,7 +75,7 @@ impl AudioSubsystem { /// its data buffer) you're likely to be interested in the /// [AudioDevice.lock method](audio/struct.AudioDevice.html#method.lock). #[inline] - pub fn open_playback<'a, CB, F, D>(&self, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, String> + pub fn open_playback<'a, CB, F, D>(&self, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, Error> where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB, D: Into>, { AudioDevice::open_playback(self, device, spec, get_callback) @@ -87,7 +87,7 @@ impl AudioSubsystem { /// If you want to modify the callback-owned data at a later point (for example to update /// its data buffer) you're likely to be interested in the /// [AudioDevice.lock method](audio/struct.AudioDevice.html#method.lock). - pub fn open_capture<'a, CB, F, D>(&self, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, String> + pub fn open_capture<'a, CB, F, D>(&self, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, Error> where CB: AudioCallback, F: FnOnce(AudioSpec) -> CB, D: Into>, { AudioDevice::open_capture(self, device, spec, get_callback) @@ -95,7 +95,7 @@ impl AudioSubsystem { /// Opens a new audio device which uses queueing rather than older callback method. #[inline] - pub fn open_queue<'a, Channel, D>(&self, device: D, spec: &AudioSpecDesired) -> Result, String> + pub fn open_queue<'a, Channel, D>(&self, device: D, spec: &AudioSpecDesired) -> Result, Error> where Channel: AudioFormatNum, D: Into>, { AudioQueue::open_queue(self, device, spec) @@ -120,11 +120,11 @@ impl AudioSubsystem { } } - pub fn audio_playback_device_name(&self, index: u32) -> Result { + pub fn audio_playback_device_name(&self, index: u32) -> Result { unsafe { let dev_name = sys::SDL_GetAudioDeviceName(index as c_int, 0); if dev_name.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let cstr = CStr::from_ptr(dev_name as *const _); Ok(cstr.to_str().unwrap().to_owned()) @@ -288,13 +288,13 @@ pub struct AudioSpecWAV { impl AudioSpecWAV { /// Loads a WAVE from the file path. - pub fn load_wav>(path: P) -> Result { + pub fn load_wav>(path: P) -> Result { let mut file = RWops::from_file(path, "rb")?; AudioSpecWAV::load_wav_rw(&mut file) } /// Loads a WAVE from the data source. - pub fn load_wav_rw(src: &mut RWops) -> Result { + pub fn load_wav_rw(src: &mut RWops) -> Result { use std::mem::MaybeUninit; use std::ptr::null_mut; @@ -304,7 +304,7 @@ impl AudioSpecWAV { unsafe { let ret = sys::SDL_LoadWAV_RW(src.raw(), 0, desired.as_mut_ptr(), &mut audio_buf, &mut audio_len); if ret.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let desired = desired.assume_init(); Ok(AudioSpecWAV { @@ -552,7 +552,7 @@ pub struct AudioQueue { impl<'a, Channel: AudioFormatNum> AudioQueue { /// Opens a new audio device given the desired parameters and callback. - pub fn open_queue>>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired) -> Result, String> { + pub fn open_queue>>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired) -> Result, Error> { use std::mem::MaybeUninit; let desired = AudioSpecDesired::convert_queue_to_ll::, Option, Option>(spec.freq, spec.channels, spec.samples); @@ -572,7 +572,7 @@ impl<'a, Channel: AudioFormatNum> AudioQueue { ); match device_id { 0 => { - Err(get_error()) + Err(get_error_as_error()) }, id => { let obtained = obtained.assume_init(); @@ -640,7 +640,7 @@ pub struct AudioDevice { impl AudioDevice { /// Opens a new audio device for playback or capture (given the desired parameters and callback). - fn open<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F, capture: bool) -> Result, String> + fn open<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F, capture: bool) -> Result, Error> where F: FnOnce(AudioSpec) -> CB, D: Into>, @@ -665,7 +665,7 @@ impl AudioDevice { ); match device_id { 0 => { - Err(get_error()) + Err(get_error_as_error()) }, id => { let obtained = obtained.assume_init(); @@ -689,7 +689,7 @@ impl AudioDevice { /// /// If you want to modify the callback-owned data at a later point (for example to update /// its data buffer) you're likely to be interested in the [lock method](#method.lock). - pub fn open_playback<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, String> + pub fn open_playback<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, Error> where F: FnOnce(AudioSpec) -> CB, D: Into>, @@ -702,7 +702,7 @@ impl AudioDevice { /// /// If you want to modify the callback-owned data at a later point (for example to update /// its data buffer) you're likely to be interested in the [lock method](#method.lock). - pub fn open_capture<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, String> + pub fn open_capture<'a, F, D>(a: &AudioSubsystem, device: D, spec: &AudioSpecDesired, get_callback: F) -> Result, Error> where F: FnOnce(AudioSpec) -> CB, D: Into>, @@ -784,7 +784,7 @@ pub struct AudioCVT { impl AudioCVT { pub fn new(src_format: AudioFormat, src_channels: u8, src_rate: i32, - dst_format: AudioFormat, dst_channels: u8, dst_rate: i32) -> Result + dst_format: AudioFormat, dst_channels: u8, dst_rate: i32) -> Result { use std::mem::MaybeUninit; @@ -798,7 +798,7 @@ impl AudioCVT { let raw = raw.assume_init(); Ok(AudioCVT { raw }) } else { - Err(get_error()) + Err(get_error_as_error()) } } } diff --git a/src/sdl2/clipboard.rs b/src/sdl2/clipboard.rs index c9c56b69d3d..a5d70cf8d9c 100644 --- a/src/sdl2/clipboard.rs +++ b/src/sdl2/clipboard.rs @@ -1,7 +1,7 @@ use std::ffi::{CString, CStr}; use libc::c_void; use libc::c_char; -use crate::get_error; +use crate::{Error, get_error_as_error}; use crate::sys; @@ -29,25 +29,25 @@ impl crate::VideoSubsystem { } impl ClipboardUtil { - pub fn set_clipboard_text(&self, text: &str) -> Result<(), String> { + pub fn set_clipboard_text(&self, text: &str) -> Result<(), Error> { unsafe { let text = CString::new(text).unwrap(); let result = sys::SDL_SetClipboardText(text.as_ptr() as *const c_char); if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } } - pub fn clipboard_text(&self) -> Result { + pub fn clipboard_text(&self) -> Result { unsafe { let buf = sys::SDL_GetClipboardText(); if buf.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let s = CStr::from_ptr(buf as *const _).to_str().unwrap().to_owned(); sys::SDL_free(buf as *mut c_void); diff --git a/src/sdl2/controller.rs b/src/sdl2/controller.rs index d890e2c10c3..f2d5478d788 100644 --- a/src/sdl2/controller.rs +++ b/src/sdl2/controller.rs @@ -7,7 +7,7 @@ use std::path::Path; use crate::rwops::RWops; use crate::GameControllerSubsystem; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use crate::joystick; use crate::common::{validate_int, IntegerOrSdlError}; use std::mem::transmute; @@ -50,13 +50,13 @@ impl error::Error for AddMappingError { impl GameControllerSubsystem { /// Retrieve the total number of attached joysticks *and* controllers identified by SDL. - pub fn num_joysticks(&self) -> Result { + pub fn num_joysticks(&self) -> Result { let result = unsafe { sys::SDL_NumJoysticks() }; if result >= 0 { Ok(result as u32) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -136,7 +136,8 @@ impl GameControllerSubsystem { pub fn load_mappings>(&self, path: P) -> Result { use self::AddMappingError::*; - let rw = RWops::from_file(path, "r").map_err(InvalidFilePath)?; + let rw = RWops::from_file(path, "r") + .map_err(|e| InvalidFilePath(format!("{}", e)))?; self.load_mappings_from_rw(rw) } @@ -148,7 +149,8 @@ impl GameControllerSubsystem { use self::AddMappingError::*; let mut buffer = Vec::with_capacity(1024); - let rw = RWops::from_read(read, &mut buffer).map_err(ReadError)?; + let rw = RWops::from_read(read, &mut buffer) + .map_err(|e| ReadError(format!("{}", e)))?; self.load_mappings_from_rw(rw) } @@ -163,7 +165,7 @@ impl GameControllerSubsystem { } } - pub fn mapping_for_guid(&self, guid: joystick::Guid) -> Result { + pub fn mapping_for_guid(&self, guid: joystick::Guid) -> Result { let c_str = unsafe { sys::SDL_GameControllerMappingForGUID(guid.raw()) }; c_str_to_string_or_err(c_str) @@ -455,9 +457,9 @@ fn c_str_to_string(c_str: *const c_char) -> String { /// Convert C string `c_str` to a String. Return an SDL error if /// `c_str` is NULL. -fn c_str_to_string_or_err(c_str: *const c_char) -> Result { +fn c_str_to_string_or_err(c_str: *const c_char) -> Result { if c_str.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(unsafe { CStr::from_ptr(c_str as *const _).to_str().unwrap().to_owned() diff --git a/src/sdl2/event.rs b/src/sdl2/event.rs index 304f5dcaba1..6936fe30ccb 100644 --- a/src/sdl2/event.rs +++ b/src/sdl2/event.rs @@ -25,7 +25,7 @@ use crate::keyboard::Keycode; use crate::mouse; use crate::mouse::{MouseButton, MouseState, MouseWheelDirection}; use crate::keyboard::Scancode; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use crate::sys; use crate::sys::SDL_EventType; @@ -111,7 +111,7 @@ impl crate::EventSubsystem { } /// Pushes an event to the event queue. - pub fn push_event(&self, event: Event) -> Result<(), String> { + pub fn push_event(&self, event: Event) -> Result<(), Error> { self.event_sender().push_event(event) } @@ -144,21 +144,22 @@ impl crate::EventSubsystem { /// /// ``` #[inline(always)] - pub unsafe fn register_event(&self) -> Result { + pub unsafe fn register_event(&self) -> Result { Ok(*self.register_events(1)?.first().unwrap()) } /// Registers custom SDL events. /// /// Returns an error, if no more user events can be created. - pub unsafe fn register_events(&self, nr: u32) -> Result, String> { + pub unsafe fn register_events(&self, nr: u32) -> Result, Error> { let result = sys::SDL_RegisterEvents(nr as ::libc::c_int); const ERR_NR:u32 = ::std::u32::MAX - 1; match result { ERR_NR => { - Err("No more user events can be created; SDL_LASTEVENT reached" - .to_owned()) + Err(Error::SdlError( + "No more user events can be created; SDL_LASTEVENT reached" + .to_owned())) }, _ => { let event_ids = (result..(result+nr)).collect(); @@ -175,16 +176,16 @@ impl crate::EventSubsystem { /// See [push_custom_event](#method.push_custom_event) #[inline(always)] pub fn register_custom_event(&self) - -> Result<(), String> { + -> Result<(), Error> { use ::std::any::TypeId; let event_id = *(unsafe { self.register_events(1) })?.first().unwrap(); let mut cet = CUSTOM_EVENT_TYPES.lock().unwrap(); let type_id = TypeId::of::>(); if cet.type_id_to_sdl_id.contains_key(&type_id) { - return Err( + return Err(Error::SdlError( "The same event type can not be registered twice!".to_owned() - ); + )); } cet.sdl_id_to_type_id.insert(event_id, type_id); @@ -222,7 +223,7 @@ impl crate::EventSubsystem { /// } /// ``` pub fn push_custom_event(&self, event:T) - -> Result<(), String> { + -> Result<(), Error> { self.event_sender().push_custom_event(event) } @@ -2181,15 +2182,16 @@ pub struct EventSender { impl EventSender { /// Pushes an event to the event queue. - pub fn push_event(&self, event: Event) -> Result<(), String> { + pub fn push_event(&self, event: Event) -> Result<(), Error> { match event.to_ll() { Some(mut raw_event) => { let ok = unsafe { sys::SDL_PushEvent(&mut raw_event) == 1 }; if ok { Ok(()) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } }, None => { - Err("Cannot push unsupported event type to the queue".to_owned()) + Err(Error::SdlError( + "Cannot push unsupported event type to the queue".to_owned())) } } } @@ -2224,7 +2226,7 @@ impl EventSender { /// } /// ``` pub fn push_custom_event(&self, event:T) - -> Result<(), String> { + -> Result<(), Error> { use ::std::any::TypeId; let cet = CUSTOM_EVENT_TYPES.lock().unwrap(); @@ -2234,7 +2236,9 @@ impl EventSender { Some(id) => id, None => { return Err( - "Type is not registered as a custom event type!".to_owned() + Error::SdlError( + "Type is not registered as a custom event type!".to_owned() + ) ); } }; diff --git a/src/sdl2/filesystem.rs b/src/sdl2/filesystem.rs index 687cfd3eb46..837dbb5a298 100644 --- a/src/sdl2/filesystem.rs +++ b/src/sdl2/filesystem.rs @@ -2,12 +2,12 @@ use std::error; use std::ffi::{CStr, CString, NulError}; use std::fmt; use libc::c_void; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use libc::c_char; use crate::sys; -pub fn base_path() -> Result { +pub fn base_path() -> Result { let result = unsafe { let buf = sys::SDL_GetBasePath(); let s = CStr::from_ptr(buf as *const _).to_str().unwrap().to_owned(); @@ -16,7 +16,7 @@ pub fn base_path() -> Result { }; if result.is_empty() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(result) } diff --git a/src/sdl2/gfx/framerate.rs b/src/sdl2/gfx/framerate.rs index 81d05a52d5a..572f3944af4 100644 --- a/src/sdl2/gfx/framerate.rs +++ b/src/sdl2/gfx/framerate.rs @@ -1,9 +1,9 @@ //! Framerate control use libc; -use libc::{c_void, uint32_t, size_t}; +use libc::{c_void, size_t}; use std::mem; -use ::get_error; +use crate::{Error, get_error_as_error}; use sys::gfx; /// Structure holding the state and timing information of the framerate controller. @@ -23,11 +23,11 @@ impl FPSManager { } /// Set the framerate in Hz. - pub fn set_framerate(&mut self, rate: u32) -> Result<(), String> { - let ret = unsafe { gfx::framerate::SDL_setFramerate(self.raw, rate as uint32_t) }; + pub fn set_framerate(&mut self, rate: u32) -> Result<(), Error> { + let ret = unsafe { gfx::framerate::SDL_setFramerate(self.raw, rate as u32) }; match ret { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } diff --git a/src/sdl2/gfx/imagefilter.rs b/src/sdl2/gfx/imagefilter.rs index a8c7588f761..c2cc306c3b1 100644 --- a/src/sdl2/gfx/imagefilter.rs +++ b/src/sdl2/gfx/imagefilter.rs @@ -2,7 +2,7 @@ use std::mem; use libc::{self,size_t, c_void, c_uint, c_int}; -use ::get_error; +use crate::{Error, get_error_as_error}; use c_vec::CVec; use sys::gfx::imagefilter; @@ -32,7 +32,7 @@ fn cvec_with_size(sz: usize) -> CVec { } /// Filter using Add: D = saturation255(S1 + S2). -pub fn add(src1: CVec, src2: CVec) -> Result, String> { +pub fn add(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -41,11 +41,11 @@ pub fn add(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using Mean: D = S1/2 + S2/2. -pub fn mean(src1: CVec, src2: CVec) -> Result, String> { +pub fn mean(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -54,11 +54,11 @@ pub fn mean(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using Sub: D = saturation0(S1 - S2). -pub fn sub(src1: CVec, src2: CVec) -> Result, String> { +pub fn sub(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -67,11 +67,11 @@ pub fn sub(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `AbsDiff`: D = | S1 - S2 |. -pub fn abs_diff(src1: CVec, src2: CVec) -> Result, String> { +pub fn abs_diff(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -80,11 +80,11 @@ pub fn abs_diff(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using Mult: D = saturation255(S1 * S2). -pub fn mult(src1: CVec, src2: CVec) -> Result, String> { +pub fn mult(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -93,11 +93,11 @@ pub fn mult(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `MultNor`: D = S1 * S2. -pub fn mult_nor(src1: CVec, src2: CVec) -> Result, String> { +pub fn mult_nor(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -106,11 +106,11 @@ pub fn mult_nor(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `MultDivby2`: D = saturation255(S1/2 * S2). -pub fn mult_div_by2(src1: CVec, src2: CVec) -> Result, String> { +pub fn mult_div_by2(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -119,11 +119,11 @@ pub fn mult_div_by2(src1: CVec, src2: CVec) -> Result, String> mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `MultDivby4`: D = saturation255(S1/2 * S2/2). -pub fn mult_div_by4(src1: CVec, src2: CVec) -> Result, String> { +pub fn mult_div_by4(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -132,11 +132,11 @@ pub fn mult_div_by4(src1: CVec, src2: CVec) -> Result, String> mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `BitAnd`: D = S1 & S2. -pub fn bit_and(src1: CVec, src2: CVec) -> Result, String> { +pub fn bit_and(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -145,11 +145,11 @@ pub fn bit_and(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `BitOr`: D = S1 | S2. -pub fn bit_or(src1: CVec, src2: CVec) -> Result, String> { +pub fn bit_or(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -158,11 +158,11 @@ pub fn bit_or(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using Div: D = S1 / S2. -pub fn div(src1: CVec, src2: CVec) -> Result, String> { +pub fn div(src1: CVec, src2: CVec) -> Result, Error> { assert_eq!(src1.len(), src2.len()); let size = src1.len(); let dest = cvec_with_size(size); @@ -171,176 +171,176 @@ pub fn div(src1: CVec, src2: CVec) -> Result, String> { mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `BitNegation`: D = !S. -pub fn bit_negation(src1: CVec) -> Result, String> { +pub fn bit_negation(src1: CVec) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterBitNegation(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `AddByte`: D = saturation255(S + C). -pub fn add_byte(src1: CVec, c: u8) -> Result, String> { +pub fn add_byte(src1: CVec, c: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterAddByte(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `AddUint`: D = saturation255((S[i] + Cs[i % 4]), Cs=Swap32((uint)C). -pub fn add_uint(src1: CVec, c: u32) -> Result, String> { +pub fn add_uint(src1: CVec, c: u32) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterAddUint(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `AddByteToHalf`: D = saturation255(S/2 + C). -pub fn add_byte_to_half(src1: CVec, c: u8) -> Result, String> { +pub fn add_byte_to_half(src1: CVec, c: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterAddByteToHalf(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `SubByte`: D = saturation0(S - C). -pub fn sub_byte(src1: CVec, c: u8) -> Result, String> { +pub fn sub_byte(src1: CVec, c: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterSubByte(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `SubUint`: D = saturation0(S[i] - Cs[i % 4]), Cs=Swap32((uint)C). -pub fn sub_uint(src1: CVec, c: u32) -> Result, String> { +pub fn sub_uint(src1: CVec, c: u32) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterSubUint(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ShiftRight`: D = saturation0(S >> N). -pub fn shift_right(src1: CVec, n: u8) -> Result, String> { +pub fn shift_right(src1: CVec, n: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftRight(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ShiftRightUint`: D = saturation0((uint)S[i] >> N). -pub fn shift_right_uint(src1: CVec, n: u8) -> Result, String> { +pub fn shift_right_uint(src1: CVec, n: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftRightUint(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `MultByByte`: D = saturation255(S * C). -pub fn mult_by_byte(src1: CVec, c: u8) -> Result, String> { +pub fn mult_by_byte(src1: CVec, c: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterMultByByte(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ShiftRightAndMultByByte`: D = saturation255((S >> N) * C). -pub fn shift_right_and_mult_by_byte(src1: CVec, n: u8, c: u8) -> Result, String> { +pub fn shift_right_and_mult_by_byte(src1: CVec, n: u8, c: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftRightAndMultByByte(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n, c) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ShiftLeftByte`: D = (S << N). -pub fn shift_left_byte(src1: CVec, n: u8) -> Result, String> { +pub fn shift_left_byte(src1: CVec, n: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftLeftByte(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ShiftLeftUint`: D = ((uint)S << N). -pub fn shift_left_uint(src1: CVec, n: u8) -> Result, String> { +pub fn shift_left_uint(src1: CVec, n: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftLeftUint(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter `ShiftLeft`: D = saturation255(S << N). -pub fn shift_left(src1: CVec, n: u8) -> Result, String> { +pub fn shift_left(src1: CVec, n: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterShiftLeft(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, n) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `BinarizeUsingThreshold`: D = (S >= T) ? 255:0. -pub fn binarize_using_threshold(src1: CVec, t: u8) -> Result, String> { +pub fn binarize_using_threshold(src1: CVec, t: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterBinarizeUsingThreshold(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, t) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `ClipToRange`: D = (S >= Tmin) & (S <= Tmax) S:Tmin | Tmax. -pub fn clip_to_range(src1: CVec, tmin: u8, tmax: u8) -> Result, String> { +pub fn clip_to_range(src1: CVec, tmin: u8, tmax: u8) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterClipToRange(mem::transmute(src1.get(0)), mem::transmute(dest.get(0)), size as c_uint, tmin, tmax) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } /// Filter using `NormalizeLinear`: D = saturation255((Nmax - Nmin)/(Cmax - Cmin)*(S - Cmin) + Nmin). -pub fn normalize_linear(src1: CVec, cmin: i32, cmax: i32, nmin: i32, nmax: i32) -> Result, String> { +pub fn normalize_linear(src1: CVec, cmin: i32, cmax: i32, nmin: i32, nmax: i32) -> Result, Error> { let size = src1.len(); let dest = cvec_with_size(size); let ret = unsafe { imagefilter::SDL_imageFilterNormalizeLinear(mem::transmute(src1.get(0)), @@ -349,5 +349,5 @@ pub fn normalize_linear(src1: CVec, cmin: i32, cmax: i32, nmin: i32, nmax: i cmin as c_int, cmax as c_int, nmin as c_int, nmax as c_int) }; if ret == 0 { Ok(dest) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } diff --git a/src/sdl2/gfx/primitives.rs b/src/sdl2/gfx/primitives.rs index bc9b2119857..1aa6a5f3a18 100644 --- a/src/sdl2/gfx/primitives.rs +++ b/src/sdl2/gfx/primitives.rs @@ -9,7 +9,7 @@ use libc::c_void; use render::Canvas; use surface::Surface; use pixels; -use get_error; +use crate::{Error, get_error_as_error}; use sys::gfx::primitives; /// generic Color type @@ -68,16 +68,16 @@ impl ToColor for isize { /// For drawing with rust-sdl2 Renderer pub trait DrawRenderer { - fn pixel(&self, x: i16, y: i16, color: C) -> Result<(), String>; - fn hline(&self, x1: i16, x2: i16, y: i16, color: C) -> Result<(), String>; - fn vline(&self, x: i16, y1: i16, y2: i16, color: C) -> Result<(), String>; + fn pixel(&self, x: i16, y: i16, color: C) -> Result<(), Error>; + fn hline(&self, x1: i16, x2: i16, y: i16, color: C) -> Result<(), Error>; + fn vline(&self, x: i16, y1: i16, y2: i16, color: C) -> Result<(), Error>; fn rectangle(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn rounded_rectangle(&self, x1: i16, y1: i16, @@ -85,8 +85,8 @@ pub trait DrawRenderer { y2: i16, rad: i16, color: C) - -> Result<(), String>; - fn box_(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), String>; + -> Result<(), Error>; + fn box_(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), Error>; fn rounded_box(&self, x1: i16, y1: i16, @@ -94,15 +94,15 @@ pub trait DrawRenderer { y2: i16, rad: i16, color: C) - -> Result<(), String>; - fn line(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), String>; + -> Result<(), Error>; + fn line(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), Error>; fn aa_line(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn thick_line(&self, x1: i16, y1: i16, @@ -110,10 +110,10 @@ pub trait DrawRenderer { y2: i16, width: u8, color: C) - -> Result<(), String>; - fn circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String>; - fn aa_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String>; - fn filled_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String>; + -> Result<(), Error>; + fn circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error>; + fn aa_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error>; + fn filled_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error>; fn arc(&self, x: i16, y: i16, @@ -121,28 +121,28 @@ pub trait DrawRenderer { start: i16, end: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn ellipse(&self, x: i16, y: i16, rx: i16, ry: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn aa_ellipse(&self, x: i16, y: i16, rx: i16, ry: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn filled_ellipse(&self, x: i16, y: i16, rx: i16, ry: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn pie(&self, x: i16, y: i16, @@ -150,7 +150,7 @@ pub trait DrawRenderer { start: i16, end: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn filled_pie(&self, x: i16, y: i16, @@ -158,7 +158,7 @@ pub trait DrawRenderer { start: i16, end: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn trigon(&self, x1: i16, y1: i16, @@ -167,7 +167,7 @@ pub trait DrawRenderer { x3: i16, y3: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn aa_trigon(&self, x1: i16, y1: i16, @@ -176,7 +176,7 @@ pub trait DrawRenderer { x3: i16, y3: i16, color: C) - -> Result<(), String>; + -> Result<(), Error>; fn filled_trigon(&self, x1: i16, y1: i16, @@ -185,10 +185,10 @@ pub trait DrawRenderer { x3: i16, y3: i16, color: C) - -> Result<(), String>; - fn polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String>; - fn aa_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String>; - fn filled_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String>; + -> Result<(), Error>; + fn polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error>; + fn aa_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error>; + fn filled_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error>; fn textured_polygon(&self, vx: &[i16], vy: &[i16], @@ -196,24 +196,24 @@ pub trait DrawRenderer { texture_dx: i16, texture_dy: i16, color: C) - -> Result<(), String>; - fn bezier(&self, vx: &[i16], vy: &[i16], s: i32, color: C) -> Result<(), String>; - fn character(&self, x: i16, y: i16, c: char, color: C) -> Result<(), String>; - fn string(&self, x: i16, y: i16, s: &str, color: C) -> Result<(), String>; + -> Result<(), Error>; + fn bezier(&self, vx: &[i16], vy: &[i16], s: i32, color: C) -> Result<(), Error>; + fn character(&self, x: i16, y: i16, c: char, color: C) -> Result<(), Error>; + fn string(&self, x: i16, y: i16, s: &str, color: C) -> Result<(), Error>; } impl DrawRenderer for Canvas where T: ::render::RenderTarget { - fn pixel(&self, x: i16, y: i16, color: C) -> Result<(), String> { + fn pixel(&self, x: i16, y: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::pixelColor(self.raw(), x, y, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn hline(&self, x1: i16, x2: i16, y: i16, color: C) -> Result<(), String> { + fn hline(&self, x1: i16, x2: i16, y: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::hlineColor(self.raw(), x1, x2, y, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn vline(&self, x: i16, y1: i16, y2: i16, color: C) -> Result<(), String> { + fn vline(&self, x: i16, y1: i16, y2: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::vlineColor(self.raw(), x, y1, y2, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn rectangle(&self, x1: i16, @@ -221,9 +221,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { x2: i16, y2: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::rectangleColor(self.raw(), x1, y1, x2, y2, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn rounded_rectangle(&self, x1: i16, @@ -232,14 +232,14 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { y2: i16, rad: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::roundedRectangleColor(self.raw(), x1, y1, x2, y2, rad, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn box_(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), String> { + fn box_(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::boxColor(self.raw(), x1, y1, x2, y2, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn rounded_box(&self, x1: i16, @@ -248,13 +248,13 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { y2: i16, rad: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::roundedBoxColor(self.raw(), x1, y1, x2, y2, rad, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn line(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), String> { + fn line(&self, x1: i16, y1: i16, x2: i16, y2: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::lineColor(self.raw(), x1, y1, x2, y2, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn aa_line(&self, x1: i16, @@ -262,9 +262,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { x2: i16, y2: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::aalineColor(self.raw(), x1, y1, x2, y2, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn thick_line(&self, x1: i16, @@ -273,21 +273,21 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { y2: i16, width: u8, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::thickLineColor(self.raw(), x1, y1, x2, y2, width, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String> { + fn circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::circleColor(self.raw(), x, y, rad, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn aa_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String> { + fn aa_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::aacircleColor(self.raw(), x, y, rad, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn filled_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), String> { + fn filled_circle(&self, x: i16, y: i16, rad: i16, color: C) -> Result<(), Error> { let ret = unsafe { primitives::filledCircleColor(self.raw(), x, y, rad, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn arc(&self, x: i16, @@ -296,9 +296,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { start: i16, end: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::arcColor(self.raw(), x, y, rad, start, end, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn ellipse(&self, x: i16, @@ -306,9 +306,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { rx: i16, ry: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::ellipseColor(self.raw(), x, y, rx, ry, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn aa_ellipse(&self, x: i16, @@ -316,9 +316,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { rx: i16, ry: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::aaellipseColor(self.raw(), x, y, rx, ry, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn filled_ellipse(&self, x: i16, @@ -326,9 +326,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { rx: i16, ry: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::filledEllipseColor(self.raw(), x, y, rx, ry, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn pie(&self, x: i16, @@ -337,9 +337,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { start: i16, end: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::pieColor(self.raw(), x, y, rad, start, end, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn filled_pie(&self, x: i16, @@ -348,9 +348,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { start: i16, end: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::filledPieColor(self.raw(), x, y, rad, start, end, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn trigon(&self, x1: i16, @@ -360,9 +360,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { x3: i16, y3: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::trigonColor(self.raw(), x1, y1, x2, y2, x3, y3, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn aa_trigon(&self, x1: i16, @@ -372,9 +372,9 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { x3: i16, y3: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::aatrigonColor(self.raw(), x1, y1, x2, y2, x3, y3, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } fn filled_trigon(&self, x1: i16, @@ -384,35 +384,35 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { x3: i16, y3: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { primitives::filledTrigonColor(self.raw(), x1, y1, x2, y2, x3, y3, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } // FIXME: may we use pointer tuple? - fn polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String> { + fn polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error> { assert_eq!(vx.len(), vy.len()); let n = vx.len() as c_int; let ret = unsafe { primitives::polygonColor(self.raw(), vx.as_ptr(), vy.as_ptr(), n, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn aa_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String> { + fn aa_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error> { assert_eq!(vx.len(), vy.len()); let n = vx.len() as c_int; let ret = unsafe { primitives::aapolygonColor(self.raw(), vx.as_ptr(), vy.as_ptr(), n, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn filled_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), String> { + fn filled_polygon(&self, vx: &[i16], vy: &[i16], color: C) -> Result<(), Error> { assert_eq!(vx.len(), vy.len()); let n = vx.len() as c_int; let ret = unsafe { primitives::filledPolygonColor(self.raw(), vx.as_ptr(), vy.as_ptr(), n, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } #[allow(unused_variables)] fn textured_polygon(&self, @@ -422,11 +422,11 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { texture_dx: i16, texture_dy: i16, color: C) - -> Result<(), String> { + -> Result<(), Error> { unimplemented!() } - fn bezier(&self, vx: &[i16], vy: &[i16], s: i32, color: C) -> Result<(), String> { + fn bezier(&self, vx: &[i16], vy: &[i16], s: i32, color: C) -> Result<(), Error> { assert_eq!(vx.len(), vy.len()); let n = vx.len() as c_int; let ret = unsafe { @@ -437,21 +437,21 @@ impl DrawRenderer for Canvas where T: ::render::RenderTarget { s as c_int, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn character(&self, x: i16, y: i16, c: char, color: C) -> Result<(), String> { + fn character(&self, x: i16, y: i16, c: char, color: C) -> Result<(), Error> { let ret = unsafe { primitives::characterColor(self.raw(), x, y, c as c_char, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } - fn string(&self, x: i16, y: i16, s: &str, color: C) -> Result<(), String> { + fn string(&self, x: i16, y: i16, s: &str, color: C) -> Result<(), Error> { let ret = unsafe { let cstring = CString::new(s).unwrap(); let buf = cstring.as_bytes().as_ptr(); primitives::stringColor(self.raw(), x, y, buf as *mut c_char, color.as_u32()) }; - if ret == 0 { Ok(()) } else { Err(get_error()) } + if ret == 0 { Ok(()) } else { Err(get_error_as_error()) } } } diff --git a/src/sdl2/gfx/rotozoom.rs b/src/sdl2/gfx/rotozoom.rs index 347ce324fa4..1353e0d467e 100644 --- a/src/sdl2/gfx/rotozoom.rs +++ b/src/sdl2/gfx/rotozoom.rs @@ -1,8 +1,8 @@ //! Surface Rotozoomer use libc::c_int; -use ::surface::Surface; -use ::get_error; +use crate::surface::Surface; +use crate::{Error, get_error_as_error}; pub use std::f64::consts::PI; use sys::gfx::rotozoom; @@ -10,64 +10,64 @@ use sys::gfx::rotozoom; /// `RotozoomSurface` for work with rust-sdl2 Surface type pub trait RotozoomSurface { /// Rotates and zooms a surface and optional anti-aliasing. - fn rotozoom(&self, angle: f64, zoom: f64, smooth: bool) -> Result; + fn rotozoom(&self, angle: f64, zoom: f64, smooth: bool) -> Result; /// Rotates and zooms a surface with different horizontal and vertical scaling factors and optional anti-aliasing. - fn rotozoom_xy(&self, angle: f64, zoomx: f64, zoomy: f64, smooth: bool) -> Result; + fn rotozoom_xy(&self, angle: f64, zoomx: f64, zoomy: f64, smooth: bool) -> Result; /// Zoom a surface by independent horizontal and vertical factors with optional smoothing. - fn zoom(&self, zoomx: f64, zoomy: f64, smooth: bool) -> Result; + fn zoom(&self, zoomx: f64, zoomy: f64, smooth: bool) -> Result; /// Shrink a surface by an integer ratio using averaging. - fn shrink(&self, factorx: i32, factory: i32) -> Result; + fn shrink(&self, factorx: i32, factory: i32) -> Result; /// Rotates a 8/16/24/32 bit surface in increments of 90 degrees. - fn rotate_90deg(&self, turns: i32) -> Result; + fn rotate_90deg(&self, turns: i32) -> Result; } impl<'a> RotozoomSurface for Surface<'a> { - fn rotozoom(&self, angle: f64, zoom: f64, smooth: bool) -> Result { + fn rotozoom(&self, angle: f64, zoom: f64, smooth: bool) -> Result { let raw = unsafe { rotozoom::rotozoomSurface(self.raw(), angle, zoom, smooth as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } } - fn rotozoom_xy(&self, angle: f64, zoomx: f64, zoomy: f64, smooth: bool) -> Result { + fn rotozoom_xy(&self, angle: f64, zoomx: f64, zoomy: f64, smooth: bool) -> Result { let raw = unsafe { rotozoom::rotozoomSurfaceXY(self.raw(), angle, zoomx, zoomy, smooth as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } } - fn zoom(&self, zoomx: f64, zoomy: f64, smooth: bool) -> Result { + fn zoom(&self, zoomx: f64, zoomy: f64, smooth: bool) -> Result { let raw = unsafe { rotozoom::zoomSurface(self.raw(), zoomx, zoomy, smooth as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } } - fn shrink(&self, factorx: i32, factory: i32) -> Result { + fn shrink(&self, factorx: i32, factory: i32) -> Result { let raw = unsafe { rotozoom::shrinkSurface(self.raw(), factorx as c_int, factory as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } } - fn rotate_90deg(&self, turns: i32) -> Result { + fn rotate_90deg(&self, turns: i32) -> Result { let raw = unsafe { rotozoom::rotateSurface90Degrees(self.raw(), turns as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } diff --git a/src/sdl2/image/mod.rs b/src/sdl2/image/mod.rs index cac8c1aebb2..de4df323cb5 100644 --- a/src/sdl2/image/mod.rs +++ b/src/sdl2/image/mod.rs @@ -27,13 +27,13 @@ use surface::Surface; use render::{TextureCreator, Texture}; use rwops::RWops; use version::Version; -use get_error; +use crate::{Error, get_error, get_error_as_error}; use sys; use sys::image; -/// InitFlags are passed to init() to control which subsystem -/// functionality to load. bitflags! { + /// InitFlags are passed to init() to control which subsystem + /// functionality to load. pub struct InitFlag : u32 { const JPG = image::IMG_InitFlags_IMG_INIT_JPG as u32; const PNG = image::IMG_InitFlags_IMG_INIT_PNG as u32; @@ -46,16 +46,16 @@ bitflags! { impl ::std::fmt::Display for InitFlag { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { if self.contains(InitFlag::JPG) { - try!(f.write_str("INIT_JPG ")); + f.write_str("INIT_JPG ")?; } if self.contains(InitFlag::PNG) { - try!(f.write_str("INIT_PNG ")); + f.write_str("INIT_PNG ")?; } if self.contains(InitFlag::TIF) { - try!(f.write_str("INIT_TIF ")); + f.write_str("INIT_TIF ")?; } if self.contains(InitFlag::WEBP) { - try!(f.write_str("INIT_WEBP ")); + f.write_str("INIT_WEBP ")?; } Ok(()) } @@ -66,37 +66,37 @@ impl ::std::fmt::Display for InitFlag { pub trait LoadSurface: Sized { // Self is only returned here to type hint to the compiler. // The syntax for type hinting in this case is not yet defined. - // The intended return value is Result<~Surface, String>. - fn from_file>(filename: P) -> Result; - fn from_xpm_array(xpm: *const *const i8) -> Result; + // The intended return value is Result<~Surface, Error>. + fn from_file>(filename: P) -> Result; + fn from_xpm_array(xpm: *const *const i8) -> Result; } /// Method extensions to Surface for saving to disk pub trait SaveSurface { - fn save>(&self, filename: P) -> Result<(), String>; - fn save_rw(&self, dst: &mut RWops) -> Result<(), String>; + fn save>(&self, filename: P) -> Result<(), Error>; + fn save_rw(&self, dst: &mut RWops) -> Result<(), Error>; } impl<'a> LoadSurface for Surface<'a> { - fn from_file>(filename: P) -> Result, String> { + fn from_file>(filename: P) -> Result, Error> { //! Loads an SDL Surface from a file unsafe { let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap(); let raw = image::IMG_Load(c_filename.as_ptr() as *const _); if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Surface::from_ll(raw)) } } } - fn from_xpm_array(xpm: *const *const i8) -> Result, String> { + fn from_xpm_array(xpm: *const *const i8) -> Result, Error> { //! Loads an SDL Surface from XPM data unsafe { let raw = image::IMG_ReadXPMFromArray(xpm as *mut *mut c_char); if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Surface::from_ll(raw)) } @@ -105,26 +105,26 @@ impl<'a> LoadSurface for Surface<'a> { } impl<'a> SaveSurface for Surface<'a> { - fn save>(&self, filename: P) -> Result<(), String> { + fn save>(&self, filename: P) -> Result<(), Error> { //! Saves an SDL Surface to a file unsafe { let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap(); let status = image::IMG_SavePNG(self.raw(), c_filename.as_ptr() as *const _); if status != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } } - fn save_rw(&self, dst: &mut RWops) -> Result<(), String> { + fn save_rw(&self, dst: &mut RWops) -> Result<(), Error> { //! Saves an SDL Surface to an RWops unsafe { let status = image::IMG_SavePNG_RW(self.raw(), dst.raw(), 0); if status != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -134,17 +134,17 @@ impl<'a> SaveSurface for Surface<'a> { /// Method extensions for creating Textures from a `TextureCreator` pub trait LoadTexture { - fn load_texture>(&self, filename: P) -> Result; + fn load_texture>(&self, filename: P) -> Result; } impl LoadTexture for TextureCreator { - fn load_texture>(&self, filename: P) -> Result { + fn load_texture>(&self, filename: P) -> Result { //! Loads an SDL Texture from a file unsafe { let c_filename = CString::new(filename.as_ref().to_str().unwrap()).unwrap(); let raw = image::IMG_LoadTexture(self.raw(), c_filename.as_ptr() as *const _); if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(self.raw_create_texture(raw)) } @@ -166,7 +166,7 @@ impl Drop for Sdl2ImageContext { /// Initializes `SDL2_image` with `InitFlags`. /// If not every flag is set it returns an error -pub fn init(flags: InitFlag) -> Result { +pub fn init(flags: InitFlag) -> Result { let return_flags = unsafe { let used = image::IMG_Init(flags.bits() as c_int); InitFlag::from_bits_truncate(used as u32) @@ -179,7 +179,7 @@ pub fn init(flags: InitFlag) -> Result { error = format!("Could not init: {}", un_init_flags); let _ = ::set_error(&error); } - Err(error) + Err(Error::SdlError(error)) } else { Ok(Sdl2ImageContext) } @@ -191,9 +191,9 @@ pub fn get_linked_version() -> Version { } #[inline] -fn to_surface_result<'a>(raw: *mut sys::SDL_Surface) -> Result, String> { +fn to_surface_result<'a>(raw: *mut sys::SDL_Surface) -> Result, Error> { if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(raw)) } } @@ -201,25 +201,25 @@ fn to_surface_result<'a>(raw: *mut sys::SDL_Surface) -> Result, Stri pub trait ImageRWops { /// load as a surface. except TGA - fn load(&self) -> Result; + fn load(&self) -> Result; /// load as a surface. This can load all supported image formats. - fn load_typed(&self, _type: &str) -> Result; + fn load_typed(&self, _type: &str) -> Result; - fn load_cur(&self) -> Result; - fn load_ico(&self) -> Result; - fn load_bmp(&self) -> Result; - fn load_pnm(&self) -> Result; - fn load_xpm(&self) -> Result; - fn load_xcf(&self) -> Result; - fn load_pcx(&self) -> Result; - fn load_gif(&self) -> Result; - fn load_jpg(&self) -> Result; - fn load_tif(&self) -> Result; - fn load_png(&self) -> Result; - fn load_tga(&self) -> Result; - fn load_lbm(&self) -> Result; - fn load_xv(&self) -> Result; - fn load_webp(&self) -> Result; + fn load_cur(&self) -> Result; + fn load_ico(&self) -> Result; + fn load_bmp(&self) -> Result; + fn load_pnm(&self) -> Result; + fn load_xpm(&self) -> Result; + fn load_xcf(&self) -> Result; + fn load_pcx(&self) -> Result; + fn load_gif(&self) -> Result; + fn load_jpg(&self) -> Result; + fn load_tif(&self) -> Result; + fn load_png(&self) -> Result; + fn load_tga(&self) -> Result; + fn load_lbm(&self) -> Result; + fn load_xv(&self) -> Result; + fn load_webp(&self) -> Result; fn is_cur(&self) -> bool; fn is_ico(&self) -> bool; @@ -238,11 +238,11 @@ pub trait ImageRWops { } impl<'a> ImageRWops for RWops<'a> { - fn load(&self) -> Result { + fn load(&self) -> Result { let raw = unsafe { image::IMG_Load_RW(self.raw(), 0) }; to_surface_result(raw) } - fn load_typed(&self, _type: &str) -> Result { + fn load_typed(&self, _type: &str) -> Result { let raw = unsafe { let c_type = CString::new(_type.as_bytes()).unwrap(); image::IMG_LoadTyped_RW(self.raw(), 0, c_type.as_ptr() as *const _) @@ -250,63 +250,63 @@ impl<'a> ImageRWops for RWops<'a> { to_surface_result(raw) } - fn load_cur(&self) -> Result { + fn load_cur(&self) -> Result { let raw = unsafe { image::IMG_LoadCUR_RW(self.raw()) }; to_surface_result(raw) } - fn load_ico(&self) -> Result { + fn load_ico(&self) -> Result { let raw = unsafe { image::IMG_LoadICO_RW(self.raw()) }; to_surface_result(raw) } - fn load_bmp(&self) -> Result { + fn load_bmp(&self) -> Result { let raw = unsafe { image::IMG_LoadBMP_RW(self.raw()) }; to_surface_result(raw) } - fn load_pnm(&self) -> Result { + fn load_pnm(&self) -> Result { let raw = unsafe { image::IMG_LoadPNM_RW(self.raw()) }; to_surface_result(raw) } - fn load_xpm(&self) -> Result { + fn load_xpm(&self) -> Result { let raw = unsafe { image::IMG_LoadXPM_RW(self.raw()) }; to_surface_result(raw) } - fn load_xcf(&self) -> Result { + fn load_xcf(&self) -> Result { let raw = unsafe { image::IMG_LoadXCF_RW(self.raw()) }; to_surface_result(raw) } - fn load_pcx(&self) -> Result { + fn load_pcx(&self) -> Result { let raw = unsafe { image::IMG_LoadPCX_RW(self.raw()) }; to_surface_result(raw) } - fn load_gif(&self) -> Result { + fn load_gif(&self) -> Result { let raw = unsafe { image::IMG_LoadGIF_RW(self.raw()) }; to_surface_result(raw) } - fn load_jpg(&self) -> Result { + fn load_jpg(&self) -> Result { let raw = unsafe { image::IMG_LoadJPG_RW(self.raw()) }; to_surface_result(raw) } - fn load_tif(&self) -> Result { + fn load_tif(&self) -> Result { let raw = unsafe { image::IMG_LoadTIF_RW(self.raw()) }; to_surface_result(raw) } - fn load_png(&self) -> Result { + fn load_png(&self) -> Result { let raw = unsafe { image::IMG_LoadPNG_RW(self.raw()) }; to_surface_result(raw) } - fn load_tga(&self) -> Result { + fn load_tga(&self) -> Result { let raw = unsafe { image::IMG_LoadTGA_RW(self.raw()) }; to_surface_result(raw) } - fn load_lbm(&self) -> Result { + fn load_lbm(&self) -> Result { let raw = unsafe { image::IMG_LoadLBM_RW(self.raw()) }; to_surface_result(raw) } - fn load_xv(&self) -> Result { + fn load_xv(&self) -> Result { let raw = unsafe { image::IMG_LoadXV_RW(self.raw()) }; to_surface_result(raw) } - fn load_webp(&self) -> Result { + fn load_webp(&self) -> Result { let raw = unsafe { image::IMG_LoadWEBP_RW(self.raw()) }; to_surface_result(raw) } diff --git a/src/sdl2/joystick.rs b/src/sdl2/joystick.rs index 592e8e49758..e7c9a7c7e4a 100644 --- a/src/sdl2/joystick.rs +++ b/src/sdl2/joystick.rs @@ -2,22 +2,22 @@ use crate::sys; use crate::sys::SDL_JoystickPowerLevel; use crate::JoystickSubsystem; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use crate::clear_error; use std::ffi::{CString, CStr, NulError}; -use std::fmt::{Display, Formatter, Error}; +use std::fmt::{self, Display, Formatter}; use libc::c_char; use crate::common::{validate_int, IntegerOrSdlError}; impl JoystickSubsystem { /// Retrieve the total number of attached joysticks *and* controllers identified by SDL. - pub fn num_joysticks(&self) -> Result { + pub fn num_joysticks(&self) -> Result { let result = unsafe { sys::SDL_NumJoysticks() }; if result >= 0 { Ok(result as u32) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -455,7 +455,7 @@ impl Guid { } impl Display for Guid { - fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.string()) } } diff --git a/src/sdl2/mixer/mod.rs b/src/sdl2/mixer/mod.rs index c704f41e8ee..4ce06a36710 100644 --- a/src/sdl2/mixer/mod.rs +++ b/src/sdl2/mixer/mod.rs @@ -28,39 +28,37 @@ use std::str::from_utf8; use std::borrow::ToOwned; use std::path::Path; use libc::c_void; -use libc::{c_int, uint16_t, c_double, c_uint}; -use ::get_error; -use ::rwops::RWops; -use ::version::Version; +use libc::{c_int, c_double, c_uint}; +use crate::{Error, get_error, get_error_as_error}; +use crate::rwops::RWops; +use crate::version::Version; use sys; use sys::mixer; // This comes from SDL_audio.h #[allow(non_camel_case_types)] mod ll { - use libc::uint16_t; - - pub const AUDIO_U8: uint16_t = 0x0008; - pub const AUDIO_S8: uint16_t = 0x8008; - pub const AUDIO_U16LSB: uint16_t = 0x0010; - pub const AUDIO_S16LSB: uint16_t = 0x8010; - pub const AUDIO_U16MSB: uint16_t = 0x1010; - pub const AUDIO_S16MSB: uint16_t = 0x9010; - pub const AUDIO_U16: uint16_t = AUDIO_U16LSB; - pub const AUDIO_S16: uint16_t = AUDIO_S16LSB; - pub const AUDIO_S32LSB: uint16_t = 0x8020; - pub const AUDIO_S32MSB: uint16_t = 0x9020; - pub const AUDIO_S32: uint16_t = AUDIO_S32LSB; - pub const AUDIO_F32LSB: uint16_t = 0x8120; - pub const AUDIO_F32MSB: uint16_t = 0x9120; - pub const AUDIO_F32: uint16_t = AUDIO_F32LSB; - pub const AUDIO_U16SYS: uint16_t = AUDIO_U16LSB; - pub const AUDIO_S16SYS: uint16_t = AUDIO_S16LSB; - pub const AUDIO_S32SYS: uint16_t = AUDIO_S32LSB; - pub const AUDIO_F32SYS: uint16_t = AUDIO_F32LSB; -} - -pub type AudioFormat = uint16_t; + pub const AUDIO_U8: u16 = 0x0008; + pub const AUDIO_S8: u16 = 0x8008; + pub const AUDIO_U16LSB: u16 = 0x0010; + pub const AUDIO_S16LSB: u16 = 0x8010; + pub const AUDIO_U16MSB: u16 = 0x1010; + pub const AUDIO_S16MSB: u16 = 0x9010; + pub const AUDIO_U16: u16 = AUDIO_U16LSB; + pub const AUDIO_S16: u16 = AUDIO_S16LSB; + pub const AUDIO_S32LSB: u16 = 0x8020; + pub const AUDIO_S32MSB: u16 = 0x9020; + pub const AUDIO_S32: u16 = AUDIO_S32LSB; + pub const AUDIO_F32LSB: u16 = 0x8120; + pub const AUDIO_F32MSB: u16 = 0x9120; + pub const AUDIO_F32: u16 = AUDIO_F32LSB; + pub const AUDIO_U16SYS: u16 = AUDIO_U16LSB; + pub const AUDIO_S16SYS: u16 = AUDIO_S16LSB; + pub const AUDIO_S32SYS: u16 = AUDIO_S32LSB; + pub const AUDIO_F32SYS: u16 = AUDIO_F32LSB; +} + +pub type AudioFormat = u16; pub const AUDIO_U8: AudioFormat = ll::AUDIO_U8; pub const AUDIO_S8: AudioFormat = ll::AUDIO_S8; @@ -142,7 +140,7 @@ impl Drop for Sdl2MixerContext { /// Loads dynamic libraries and prepares them for use. Flags should be /// one or more flags from `InitFlag`. -pub fn init(flags: InitFlag) -> Result { +pub fn init(flags: InitFlag) -> Result { let return_flags = unsafe { let ret = mixer::Mix_Init(flags.bits() as c_int); InitFlag::from_bits_truncate(ret as u32) @@ -158,7 +156,7 @@ pub fn init(flags: InitFlag) -> Result { let error_str = &("Could not init: ".to_string() + &un_init_flags.to_string()); let _ = ::set_error(error_str); } - Err(get_error()) + Err(get_error_as_error()) } } @@ -174,7 +172,7 @@ pub fn open_audio(frequency: i32, format: AudioFormat, channels: i32, chunksize: i32) - -> Result<(), String> { + -> Result<(), Error> { let ret = unsafe { mixer::Mix_OpenAudio(frequency as c_int, format, @@ -184,7 +182,7 @@ pub fn open_audio(frequency: i32, if ret == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -194,13 +192,13 @@ pub fn close_audio() { } /// Get the actual audio format in use by the opened audio device. -pub fn query_spec() -> Result<(i32, AudioFormat, i32), String> { +pub fn query_spec() -> Result<(i32, AudioFormat, i32), Error> { let mut frequency: c_int = 0; - let mut format: uint16_t = 0; + let mut format: u16 = 0; let mut channels: c_int = 0; let ret = unsafe { mixer::Mix_QuerySpec(&mut frequency, &mut format, &mut channels) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok((frequency as i32, format as AudioFormat, channels as i32)) } @@ -238,10 +236,11 @@ impl Drop for Chunk { impl Chunk { /// Load file for use as a sample. - pub fn from_file>(path: P) -> Result { - let raw = unsafe { mixer::Mix_LoadWAV_RW(try!(RWops::from_file(path, "rb")).raw(), 0) }; + pub fn from_file>(path: P) -> Result { + let file = RWops::from_file(path, "rb")?; + let raw = unsafe { mixer::Mix_LoadWAV_RW(file.raw(), 0) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Chunk { raw: raw, @@ -264,17 +263,17 @@ impl Chunk { /// Loader trait for `RWops` pub trait LoaderRWops<'a> { /// Load src for use as a sample. - fn load_wav(&self) -> Result; + fn load_wav(&self) -> Result; - fn load_music(&'a self) -> Result, String>; + fn load_music(&'a self) -> Result, Error>; } impl<'a> LoaderRWops<'a> for RWops<'a> { /// Load src for use as a sample. - fn load_wav(&self) -> Result { + fn load_wav(&self) -> Result { let raw = unsafe { mixer::Mix_LoadWAV_RW(self.raw(), 0) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Chunk { raw: raw, @@ -284,10 +283,10 @@ impl<'a> LoaderRWops<'a> for RWops<'a> { } /// Load src for use as music. - fn load_music(&self) -> Result, String> { + fn load_music(&self) -> Result, Error> { let raw = unsafe { mixer::Mix_LoadMUS_RW(self.raw(), 0) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Music { raw: raw, @@ -377,25 +376,25 @@ impl Channel { unsafe { mixer::Mix_Volume(ch as c_int, -1) as i32 } } - /// Play chunk on channel, or if channel is -1, pick the first free unreserved channel. - pub fn play(self, chunk: &Chunk, loops: i32) -> Result { + /// Play chunk on channel, or if channel is -1, piczoomxk the first free unreserved channel. + pub fn play(self, chunk: &Chunk, loops: i32) -> Result { self.play_timed(chunk, loops, -1) } - pub fn play_timed(self, chunk: &Chunk, loops: i32, ticks: i32) -> Result { + pub fn play_timed(self, chunk: &Chunk, loops: i32, ticks: i32) -> Result { let Channel(ch) = self; let ret = unsafe { mixer::Mix_PlayChannelTimed(ch as c_int, chunk.raw, loops as c_int, ticks as c_int) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Channel(ret as i32)) } } /// Play chunk on channel, or if channel is -1, pick the first free unreserved channel. - pub fn fade_in(self, chunk: &Chunk, loops: i32, ms: i32) -> Result { + pub fn fade_in(self, chunk: &Chunk, loops: i32, ms: i32) -> Result { self.fade_in_timed(chunk, loops, ms, -1) } @@ -404,7 +403,7 @@ impl Channel { loops: i32, ms: i32, ticks: i32) - -> Result { + -> Result { let Channel(ch) = self; let ret = unsafe { mixer::Mix_FadeInChannelTimed(ch as c_int, @@ -414,7 +413,7 @@ impl Channel { ticks as c_int) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Channel(ret as i32)) } @@ -494,11 +493,11 @@ impl Channel { } /// This removes all effects registered to channel. - pub fn unregister_all_effects(self) -> Result<(), String> { + pub fn unregister_all_effects(self) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_UnregisterAllEffects(ch as c_int) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -506,22 +505,22 @@ impl Channel { /// Sets a panning effect, where left and right is the volume of the left and right channels. /// They range from 0 (silence) to 255 (loud). - pub fn set_panning(self, left: u8, right: u8) -> Result<(), String> { + pub fn set_panning(self, left: u8, right: u8) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetPanning(ch as c_int, left, right) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } /// Unregisters panning effect. - pub fn unset_panning(self) -> Result<(), String> { + pub fn unset_panning(self) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetPanning(ch as c_int, 255, 255) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -529,22 +528,22 @@ impl Channel { /// This effect simulates a simple attenuation of volume due to distance. /// distance ranges from 0 (close/loud) to 255 (far/quiet). - pub fn set_distance(self, distance: u8) -> Result<(), String> { + pub fn set_distance(self, distance: u8) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetDistance(ch as c_int, distance) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } /// Unregisters distance effect. - pub fn unset_distance(self) -> Result<(), String> { + pub fn unset_distance(self) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetDistance(ch as c_int, 0) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -553,22 +552,22 @@ impl Channel { /// This effect emulates a simple 3D audio effect. /// angle ranges from 0 to 360 degrees going clockwise, where 0 is directly in front. /// distance ranges from 0 (close/loud) to 255 (far/quiet). - pub fn set_position(self, angle: i16, distance: u8) -> Result<(), String> { + pub fn set_position(self, angle: i16, distance: u8) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetPosition(ch as c_int, angle, distance) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } /// Unregisters position effect. - pub fn unset_position(self) -> Result<(), String> { + pub fn unset_position(self) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetPosition(ch as c_int, 0, 0) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -576,11 +575,11 @@ impl Channel { /// Simple reverse stereo, swaps left and right channel sound. /// true for reverse, false to unregister effect. - pub fn set_reverse_stereo(self, flip: bool) -> Result<(), String> { + pub fn set_reverse_stereo(self, flip: bool) -> Result<(), Error> { let Channel(ch) = self; let ret = unsafe { mixer::Mix_SetReverseStereo(ch as c_int, flip as c_int) }; if ret == 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -752,13 +751,13 @@ impl<'a> fmt::Debug for Music<'a> { impl<'a> Music<'a> { /// Load music file to use. - pub fn from_file>(path: P) -> Result, String> { + pub fn from_file>(path: P) -> Result, Error> { let raw = unsafe { let c_path = CString::new(path.as_ref().to_str().unwrap()).unwrap(); mixer::Mix_LoadMUS(c_path.as_ptr()) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Music { raw: raw, @@ -769,18 +768,18 @@ impl<'a> Music<'a> { } /// Load music from a static byte buffer. - pub fn from_static_bytes(buf: &'static [u8]) -> Result, String> { + pub fn from_static_bytes(buf: &'static [u8]) -> Result, Error> { let rw = unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) }; if rw.is_null() { - return Err(get_error()); + return Err(get_error_as_error()); } let raw = unsafe { mixer::Mix_LoadMUS_RW(rw, 0) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Music { raw: raw, @@ -808,10 +807,10 @@ impl<'a> Music<'a> { } /// Play the loaded music loop times through from start to finish. Pass -1 to loop forever. - pub fn play(&self, loops: i32) -> Result<(), String> { + pub fn play(&self, loops: i32) -> Result<(), Error> { let ret = unsafe { mixer::Mix_PlayMusic(self.raw, loops as c_int) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -819,22 +818,22 @@ impl<'a> Music<'a> { /// Fade in over ms milliseconds of time, the loaded music, /// playing it loop times through from start to finish. - pub fn fade_in(&self, loops: i32, ms: i32) -> Result<(), String> { + pub fn fade_in(&self, loops: i32, ms: i32) -> Result<(), Error> { let ret = unsafe { mixer::Mix_FadeInMusic(self.raw, loops as c_int, ms as c_int) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } /// Fade in over ms milliseconds of time, from position. - pub fn fade_in_from_pos(&self, loops: i32, ms: i32, position: f64) -> Result<(), String> { + pub fn fade_in_from_pos(&self, loops: i32, ms: i32, position: f64) -> Result<(), Error> { let ret = unsafe { mixer::Mix_FadeInMusicPos(self.raw, loops as c_int, ms as c_int, position as c_double) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -875,23 +874,23 @@ impl<'a> Music<'a> { } /// Set the position of the currently playing music. - pub fn set_pos(position: f64) -> Result<(), String> { + pub fn set_pos(position: f64) -> Result<(), Error> { let ret = unsafe { mixer::Mix_SetMusicPosition(position as c_double) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } /// Setup a command line music player to use to play music. - pub fn set_command(command: &str) -> Result<(), String> { + pub fn set_command(command: &str) -> Result<(), Error> { let ret = unsafe { let c_command = CString::new(command).unwrap(); mixer::Mix_SetMusicCMD(c_command.as_ptr()) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -905,10 +904,10 @@ impl<'a> Music<'a> { } /// Gradually fade out the music over ms milliseconds starting from now. - pub fn fade_out(ms: i32) -> Result<(), String> { + pub fn fade_out(ms: i32) -> Result<(), Error> { let ret = unsafe { mixer::Mix_FadeOutMusic(ms as c_int) }; if ret == -1 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } diff --git a/src/sdl2/mouse/mod.rs b/src/sdl2/mouse/mod.rs index ee0c4b014f2..b0e8e4543a6 100644 --- a/src/sdl2/mouse/mod.rs +++ b/src/sdl2/mouse/mod.rs @@ -1,4 +1,4 @@ -use crate::get_error; +use crate::{Error, get_error_as_error}; use crate::surface::SurfaceRef; use crate::video; use crate::EventPump; @@ -39,7 +39,7 @@ impl Drop for Cursor { } impl Cursor { - pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> Result { + pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> Result { unsafe { let raw = sys::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), @@ -47,7 +47,7 @@ impl Cursor { hot_x as i32, hot_y as i32); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Cursor{ raw }) } @@ -55,24 +55,24 @@ impl Cursor { } // TODO: figure out how to pass Surface in here correctly - pub fn from_surface>(surface: S, hot_x: i32, hot_y: i32) -> Result { + pub fn from_surface>(surface: S, hot_x: i32, hot_y: i32) -> Result { unsafe { let raw = sys::SDL_CreateColorCursor(surface.as_ref().raw(), hot_x, hot_y); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Cursor{ raw }) } } } - pub fn from_system(cursor: SystemCursor) -> Result { + pub fn from_system(cursor: SystemCursor) -> Result { unsafe { let raw = sys::SDL_CreateSystemCursor(transmute(cursor as u32)); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Cursor{ raw }) } diff --git a/src/sdl2/pixels.rs b/src/sdl2/pixels.rs index 1b123511793..a8b0ffb0912 100644 --- a/src/sdl2/pixels.rs +++ b/src/sdl2/pixels.rs @@ -3,7 +3,7 @@ use std::mem::transmute; use std::convert::TryFrom; use crate::sys; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; pub struct Palette { raw: *mut sys::SDL_Palette @@ -12,7 +12,7 @@ pub struct Palette { impl Palette { #[inline] /// Creates a new, uninitialized palette - pub fn new(mut capacity: usize) -> Result { + pub fn new(mut capacity: usize) -> Result { use crate::common::*; let ncolors = { @@ -24,14 +24,14 @@ impl Palette { match validate_int(capacity as u32, "capacity") { Ok(len) => len, - Err(e) => return Err(format!("{}", e)), + Err(e) => return Err(Error::SdlError(format!("{}", e))), } }; let raw = unsafe { sys::SDL_AllocPalette(ncolors) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Palette { raw, @@ -40,7 +40,7 @@ impl Palette { } /// Creates a palette from the provided colors - pub fn with_colors(colors: &[Color]) -> Result { + pub fn with_colors(colors: &[Color]) -> Result { let pal = Self::new(colors.len())?; // Already validated, so don't check again @@ -57,7 +57,7 @@ impl Palette { }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(pal) } @@ -253,7 +253,7 @@ impl PixelFormatEnum { } } - pub fn into_masks(self) -> Result { + pub fn into_masks(self) -> Result { let format: u32 = self as u32; let mut bpp = 0; let mut rmask = 0; @@ -265,7 +265,7 @@ impl PixelFormatEnum { }; if result == sys::SDL_bool::SDL_FALSE { // SDL_FALSE - Err(get_error()) + Err(get_error_as_error()) } else { Ok(PixelMasks { bpp: bpp as u8, diff --git a/src/sdl2/render.rs b/src/sdl2/render.rs index 24958e06c92..bb91a983db1 100644 --- a/src/sdl2/render.rs +++ b/src/sdl2/render.rs @@ -33,9 +33,9 @@ use crate::surface; use crate::surface::{Surface, SurfaceRef, SurfaceContext}; use crate::pixels; use crate::pixels::PixelFormatEnum; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use std::fmt; -use std::error::Error; +use std::error::Error as StdError; #[cfg(not(feature = "unsafe_textures"))] use std::marker::PhantomData; use std::mem; @@ -74,7 +74,7 @@ impl fmt::Display for SdlError { } } -impl Error for SdlError { +impl StdError for SdlError { fn description(&self) -> &str { let &SdlError(ref e) = self; e @@ -91,7 +91,7 @@ impl fmt::Display for TargetRenderError { } } -impl Error for TargetRenderError { +impl StdError for TargetRenderError { fn description(&self) -> &str { use self::TargetRenderError::*; match *self { @@ -339,7 +339,7 @@ impl<'s> Canvas> { /// /// This method should only fail if SDL2 is not built with rendering /// support, or there's an out-of-memory error. - pub fn from_surface(surface: surface::Surface<'s>) -> Result { + pub fn from_surface(surface: surface::Surface<'s>) -> Result { let raw_renderer = unsafe { sys::SDL_CreateSoftwareRenderer(surface.raw()) }; if !raw_renderer.is_null() { let context = @@ -351,7 +351,7 @@ impl<'s> Canvas> { default_pixel_format, }) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -741,7 +741,7 @@ impl fmt::Display for TextureValueError { } } -impl Error for TextureValueError { +impl StdError for TextureValueError { fn description(&self) -> &str { use self::TextureValueError::*; @@ -974,7 +974,7 @@ impl Canvas { } /// Gets the output size of a rendering context. - pub fn output_size(&self) -> Result<(u32, u32), String> { + pub fn output_size(&self) -> Result<(u32, u32), Error> { let mut width = 0; let mut height = 0; @@ -984,7 +984,7 @@ impl Canvas { if result == 0 { Ok((width as u32, height as u32)) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -1061,10 +1061,10 @@ impl Canvas { } /// Sets the drawing scale for rendering on the current target. - pub fn set_scale(&mut self, scale_x: f32, scale_y: f32) -> Result<(), String> { + pub fn set_scale(&mut self, scale_x: f32, scale_y: f32) -> Result<(), Error> { let ret = unsafe { sys::SDL_RenderSetScale(self.context.raw, scale_x, scale_y) }; // Should only fail on an invalid renderer - if ret != 0 { Err(get_error()) } else { Ok(()) } + if ret != 0 { Err(get_error_as_error()) } else { Ok(()) } } /// Gets the drawing scale for the current target. @@ -1077,11 +1077,11 @@ impl Canvas { /// Draws a point on the current rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn draw_point>(&mut self, point: P) -> Result<(), String> { + pub fn draw_point>(&mut self, point: P) -> Result<(), Error> { let point = point.into(); let result = unsafe { sys::SDL_RenderDrawPoint(self.context.raw, point.x(), point.y()) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1089,7 +1089,7 @@ impl Canvas { /// Draws multiple points on the current rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn draw_points<'a, P: Into<&'a [Point]>>(&mut self, points: P) -> Result<(), String> { + pub fn draw_points<'a, P: Into<&'a [Point]>>(&mut self, points: P) -> Result<(), Error> { let points = points.into(); let result = unsafe { sys::SDL_RenderDrawPoints(self.context.raw, @@ -1097,7 +1097,7 @@ impl Canvas { points.len() as c_int) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1108,14 +1108,14 @@ impl Canvas { pub fn draw_line, P2: Into>(&mut self, start: P1, end: P2) - -> Result<(), String> { + -> Result<(), Error> { let start = start.into(); let end = end.into(); let result = unsafe { sys::SDL_RenderDrawLine(self.context.raw, start.x(), start.y(), end.x(), end.y()) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1123,7 +1123,7 @@ impl Canvas { /// Draws a series of connected lines on the current rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn draw_lines<'a, P: Into<&'a [Point]>>(&mut self, points: P) -> Result<(), String> { + pub fn draw_lines<'a, P: Into<&'a [Point]>>(&mut self, points: P) -> Result<(), Error> { let points = points.into(); let result = unsafe { sys::SDL_RenderDrawLines(self.context.raw, @@ -1131,7 +1131,7 @@ impl Canvas { points.len() as c_int) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1139,10 +1139,10 @@ impl Canvas { /// Draws a rectangle on the current rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn draw_rect(&mut self, rect: Rect) -> Result<(), String> { + pub fn draw_rect(&mut self, rect: Rect) -> Result<(), Error> { let result = unsafe { sys::SDL_RenderDrawRect(self.context.raw, rect.raw()) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1150,14 +1150,14 @@ impl Canvas { /// Draws some number of rectangles on the current rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn draw_rects(&mut self, rects: &[Rect]) -> Result<(), String> { + pub fn draw_rects(&mut self, rects: &[Rect]) -> Result<(), Error> { let result = unsafe { sys::SDL_RenderDrawRects(self.context.raw, Rect::raw_slice(rects), rects.len() as c_int) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1167,7 +1167,7 @@ impl Canvas { /// color. /// Passing None will fill the entire rendering target. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn fill_rect>>(&mut self, rect: R) -> Result<(), String> { + pub fn fill_rect>>(&mut self, rect: R) -> Result<(), Error> { let result = unsafe { sys::SDL_RenderFillRect(self.context.raw, rect.into() @@ -1176,7 +1176,7 @@ impl Canvas { .unwrap_or(ptr::null())) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1185,14 +1185,14 @@ impl Canvas { /// Fills some number of rectangles on the current rendering target with /// the drawing color. /// Errors if drawing fails for any reason (e.g. driver failure) - pub fn fill_rects(&mut self, rects: &[Rect]) -> Result<(), String> { + pub fn fill_rects(&mut self, rects: &[Rect]) -> Result<(), Error> { let result = unsafe { sys::SDL_RenderFillRects(self.context.raw, Rect::raw_slice(rects), rects.len() as c_int) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1206,7 +1206,7 @@ impl Canvas { /// /// Errors if drawing fails for any reason (e.g. driver failure), /// or if the provided texture does not belong to the renderer. - pub fn copy(&mut self, texture: &Texture, src: R1, dst: R2) -> Result<(), String> + pub fn copy(&mut self, texture: &Texture, src: R1, dst: R2) -> Result<(), Error> where R1: Into>, R2: Into> { @@ -1223,7 +1223,7 @@ impl Canvas { }) }; - if ret != 0 { Err(get_error()) } else { Ok(()) } + if ret != 0 { Err(get_error_as_error()) } else { Ok(()) } } /// Copies a portion of the texture to the current rendering target, @@ -1247,7 +1247,7 @@ impl Canvas { center: P, flip_horizontal: bool, flip_vertical: bool) - -> Result<(), String> + -> Result<(), Error> where R1: Into>, R2: Into>, P: Into> @@ -1282,7 +1282,7 @@ impl Canvas { flip) }; - if ret != 0 { Err(get_error()) } else { Ok(()) } + if ret != 0 { Err(get_error_as_error()) } else { Ok(()) } } /// Reads pixels from the current rendering target. @@ -1291,7 +1291,7 @@ impl Canvas { pub fn read_pixels>>(&self, rect: R, format: pixels::PixelFormatEnum) - -> Result, String> { + -> Result, Error> { unsafe { let rect = rect.into(); let (actual_rect, w, h) = match rect { @@ -1319,7 +1319,7 @@ impl Canvas { if ret == 0 { Ok(pixels) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -1582,7 +1582,7 @@ impl fmt::Display for UpdateTextureError { } } -impl Error for UpdateTextureError { +impl StdError for UpdateTextureError { fn description(&self) -> &str { use self::UpdateTextureError::*; @@ -1654,7 +1654,7 @@ impl fmt::Display for UpdateTextureYUVError { } } -impl Error for UpdateTextureYUVError { +impl StdError for UpdateTextureYUVError { fn description(&self) -> &str { use self::UpdateTextureYUVError::*; @@ -1940,7 +1940,7 @@ impl InternalTexture { } } - pub fn with_lock(&mut self, rect: R2, func: F) -> Result + pub fn with_lock(&mut self, rect: R2, func: F) -> Result where F: FnOnce(&mut [u8], usize) -> R, R2: Into> { @@ -1961,7 +1961,7 @@ impl InternalTexture { .byte_size_from_pitch_and_height(pitch as usize, height); Ok((::std::slice::from_raw_parts_mut(pixels as *mut u8, size), pitch)) } else { - Err(get_error()) + Err(get_error_as_error()) } }; @@ -2102,7 +2102,7 @@ impl<'r> Texture<'r> { /// This is a write-only operation, and if you need to keep a copy of the /// texture data you should do that at the application level. #[inline] - pub fn with_lock(&mut self, rect: R2, func: F) -> Result + pub fn with_lock(&mut self, rect: R2, func: F) -> Result where F: FnOnce(&mut [u8], usize) -> R, R2: Into> { @@ -2220,7 +2220,7 @@ impl<> Texture<> { /// This is a write-only operation, and if you need to keep a copy of the /// texture data you should do that at the application level. #[inline] - pub fn with_lock(&mut self, rect: R2, func: F) -> Result + pub fn with_lock(&mut self, rect: R2, func: F) -> Result where F: FnOnce(&mut [u8], usize) -> R, R2: Into> { diff --git a/src/sdl2/rwops.rs b/src/sdl2/rwops.rs index 8d595d1205a..2331e893139 100644 --- a/src/sdl2/rwops.rs +++ b/src/sdl2/rwops.rs @@ -4,7 +4,7 @@ use std::path::Path; use std::marker::PhantomData; use libc::{c_int, size_t, c_char}; use libc::c_void; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use std::mem::transmute; use crate::sys; @@ -26,7 +26,7 @@ impl<'a> RWops<'a> { } /// Creates an SDL file stream. - pub fn from_file>(path: P, mode: &str) -> Result, String> { + pub fn from_file>(path: P, mode: &str) -> Result, Error> { let raw = unsafe { let path_c = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let mode_c = CString::new(mode).unwrap(); @@ -34,7 +34,7 @@ impl<'a> RWops<'a> { }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(RWops { raw, @@ -46,13 +46,13 @@ impl<'a> RWops<'a> { /// Prepares a read-only memory buffer for use with `RWops`. /// /// This method can only fail if the buffer size is zero. - pub fn from_bytes(buf: &'a [u8]) -> Result, String> { + pub fn from_bytes(buf: &'a [u8]) -> Result, Error> { let raw = unsafe { sys::SDL_RWFromConstMem(buf.as_ptr() as *const c_void, buf.len() as c_int) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(RWops { raw, @@ -65,13 +65,13 @@ impl<'a> RWops<'a> { /// /// The buffer must be provided to this function and must live as long as the /// `RWops`, but the `RWops` does not take ownership of it. - pub fn from_read(r: &mut T, buffer: &'a mut Vec) -> Result, String> + pub fn from_read(r: &mut T, buffer: &'a mut Vec) -> Result, Error> where T: io::Read + Sized { match r.read_to_end(buffer) { Ok(_size) => RWops::from_bytes(buffer), Err(ioerror) => { let msg = format!("IO error: {}", ioerror); - Err(msg) + Err(Error::SdlError(msg)) } } } @@ -79,13 +79,13 @@ impl<'a> RWops<'a> { /// Prepares a read-write memory buffer for use with `RWops`. /// /// This method can only fail if the buffer size is zero. - pub fn from_bytes_mut(buf: &'a mut [u8]) -> Result, String> { + pub fn from_bytes_mut(buf: &'a mut [u8]) -> Result, Error> { let raw = unsafe { sys::SDL_RWFromMem(buf.as_ptr() as *mut c_void, buf.len() as c_int) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(RWops { raw, diff --git a/src/sdl2/sdl.rs b/src/sdl2/sdl.rs index 28df06272d9..760802699be 100644 --- a/src/sdl2/sdl.rs +++ b/src/sdl2/sdl.rs @@ -9,7 +9,7 @@ use crate::sys; #[repr(i32)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] -pub enum Error { +pub enum ErrorCode { NoMemError = sys::SDL_errorcode::SDL_ENOMEM as i32, ReadError = sys::SDL_errorcode::SDL_EFREAD as i32, WriteError = sys::SDL_errorcode::SDL_EFWRITE as i32, @@ -17,9 +17,9 @@ pub enum Error { UnsupportedError = sys::SDL_errorcode::SDL_UNSUPPORTED as i32 } -impl fmt::Display for Error { +impl fmt::Display for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use self::Error::*; + use self::ErrorCode::*; match *self { NoMemError => write!(f, "Out of memory"), @@ -31,9 +31,9 @@ impl fmt::Display for Error { } } -impl error::Error for Error { +impl error::Error for ErrorCode { fn description(&self) -> &str { - use self::Error::*; + use self::ErrorCode::*; match *self { NoMemError => "out of memory", @@ -45,6 +45,27 @@ impl error::Error for Error { } } +#[derive(Clone, Debug)] +pub enum Error { + SdlError(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Error::SdlError(s) => write!(f, "SDL error: {}", s), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match self { + Error::SdlError(_s) => "SDL error", + } + } +} + use std::sync::atomic::{AtomicBool}; /// Only one Sdl context can be alive at a time. /// Set to false by default (not alive). @@ -69,7 +90,7 @@ pub struct Sdl { impl Sdl { #[inline] - fn new() -> Result { + fn new() -> Result { unsafe { use std::sync::atomic::Ordering; @@ -77,7 +98,8 @@ impl Sdl { let was_alive = IS_SDL_CONTEXT_ALIVE.swap(true, Ordering::Relaxed); if was_alive { - Err("Cannot initialize `Sdl` more than once at a time.".to_owned()) + Err(Error::SdlError( + "Cannot initialize `Sdl` more than once at a time.".to_owned())) } else if sys::SDL_Init(0) == 0 { // Initialize SDL without any explicit subsystems (flags = 0). Ok(Sdl { @@ -85,38 +107,38 @@ impl Sdl { }) } else { IS_SDL_CONTEXT_ALIVE.swap(false, Ordering::Relaxed); - Err(get_error()) + Err(get_error_as_error()) } } } /// Initializes the audio subsystem. #[inline] - pub fn audio(&self) -> Result { AudioSubsystem::new(self) } + pub fn audio(&self) -> Result { AudioSubsystem::new(self) } /// Initializes the event subsystem. #[inline] - pub fn event(&self) -> Result { EventSubsystem::new(self) } + pub fn event(&self) -> Result { EventSubsystem::new(self) } /// Initializes the joystick subsystem. #[inline] - pub fn joystick(&self) -> Result { JoystickSubsystem::new(self) } + pub fn joystick(&self) -> Result { JoystickSubsystem::new(self) } /// Initializes the haptic subsystem. #[inline] - pub fn haptic(&self) -> Result { HapticSubsystem::new(self) } + pub fn haptic(&self) -> Result { HapticSubsystem::new(self) } /// Initializes the game controller subsystem. #[inline] - pub fn game_controller(&self) -> Result { GameControllerSubsystem::new(self) } + pub fn game_controller(&self) -> Result { GameControllerSubsystem::new(self) } /// Initializes the timer subsystem. #[inline] - pub fn timer(&self) -> Result { TimerSubsystem::new(self) } + pub fn timer(&self) -> Result { TimerSubsystem::new(self) } /// Initializes the video subsystem. #[inline] - pub fn video(&self) -> Result { VideoSubsystem::new(self) } + pub fn video(&self) -> Result { VideoSubsystem::new(self) } /// Obtains the SDL event pump. /// @@ -124,7 +146,7 @@ impl Sdl { /// If this function is called while an `EventPump` instance is alive, the function will return /// an error. #[inline] - pub fn event_pump(&self) -> Result { + pub fn event_pump(&self) -> Result { EventPump::new(self) } @@ -161,7 +183,7 @@ macro_rules! subsystem { ($name:ident, $flag:expr) => ( impl $name { #[inline] - fn new(sdl: &Sdl) -> Result<$name, String> { + fn new(sdl: &Sdl) -> Result<$name, Error> { let result = unsafe { sys::SDL_InitSubSystem($flag) }; if result == 0 { @@ -172,7 +194,7 @@ macro_rules! subsystem { }) }) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -259,12 +281,13 @@ pub struct EventPump { impl EventPump { /// Obtains the SDL event pump. #[inline] - fn new(sdl: &Sdl) -> Result { + fn new(sdl: &Sdl) -> Result { // Called on the main SDL thread. unsafe { if IS_EVENT_PUMP_ALIVE { - Err("an `EventPump` instance is already alive - there can only be one `EventPump` in use at a time.".to_owned()) + Err(Error::SdlError( + "an `EventPump` instance is already alive - there can only be one `EventPump` in use at a time.".to_owned())) } else { // Initialize the events subsystem, just in case none of the other subsystems have done it yet. let result = sys::SDL_InitSubSystem(sys::SDL_INIT_EVENTS); @@ -276,7 +299,7 @@ impl EventPump { _sdldrop: sdl.sdldrop.clone() }) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -319,7 +342,7 @@ pub fn get_platform() -> &'static str { /// // SDL_Quit() is called here as `sdl_context` is dropped. /// ``` #[inline] -pub fn init() -> Result { Sdl::new() } +pub fn init() -> Result { Sdl::new() } pub fn get_error() -> String { unsafe { @@ -328,6 +351,10 @@ pub fn get_error() -> String { } } +pub fn get_error_as_error() -> Error { + Error::SdlError(get_error()) +} + pub fn set_error(err: &str) -> Result<(), NulError> { let c_string = CString::new(err)?; unsafe { @@ -336,7 +363,7 @@ pub fn set_error(err: &str) -> Result<(), NulError> { Ok(()) } -pub fn set_error_from_code(err: Error) { +pub fn set_error_from_code(err: ErrorCode) { unsafe { sys::SDL_Error(transmute(err)); } } diff --git a/src/sdl2/surface.rs b/src/sdl2/surface.rs index 93e98edabf8..a1c2e8084b2 100644 --- a/src/sdl2/surface.rs +++ b/src/sdl2/surface.rs @@ -5,7 +5,7 @@ use std::path::Path; use std::rc::Rc; use crate::rect::Rect; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use std::ptr; use libc::c_int; use num::FromPrimitive; @@ -114,7 +114,7 @@ impl<'a> Surface<'a> { /// /// let surface = Surface::new(512, 512, PixelFormatEnum::RGB24).unwrap(); /// ``` - pub fn new(width: u32, height: u32, format: pixels::PixelFormatEnum) -> Result, String> { + pub fn new(width: u32, height: u32, format: pixels::PixelFormatEnum) -> Result, Error> { let masks = format.into_masks()?; Surface::from_pixelmasks(width, height, masks) } @@ -129,16 +129,16 @@ impl<'a> Surface<'a> { /// let masks = PixelFormatEnum::RGB24.into_masks().unwrap(); /// let surface = Surface::from_pixelmasks(512, 512, masks).unwrap(); /// ``` - pub fn from_pixelmasks(width: u32, height: u32, masks: pixels::PixelMasks) -> Result, String> { + pub fn from_pixelmasks(width: u32, height: u32, masks: pixels::PixelMasks) -> Result, Error> { unsafe { if width >= (1<<31) || height >= (1<<31) { - Err("Image is too large.".to_owned()) + Err(Error::SdlError("Image is too large.".to_owned())) } else { let raw = sys::SDL_CreateRGBSurface(0, width as c_int, height as c_int, masks.bpp as c_int, masks.rmask, masks.gmask, masks.bmask, masks.amask); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Surface::from_ll(raw)) } @@ -147,25 +147,25 @@ impl<'a> Surface<'a> { } /// Creates a new surface from an existing buffer, using a pixel format. - pub fn from_data(data: &'a mut [u8], width: u32, height: u32, pitch: u32, format: pixels::PixelFormatEnum) -> Result, String> { + pub fn from_data(data: &'a mut [u8], width: u32, height: u32, pitch: u32, format: pixels::PixelFormatEnum) -> Result, Error> { let masks = format.into_masks()?; Surface::from_data_pixelmasks(data, width, height, pitch, masks) } /// Creates a new surface from an existing buffer, using pixel masks. - pub fn from_data_pixelmasks(data: &'a mut [u8], width: u32, height: u32, pitch: u32, masks: pixels::PixelMasks) -> Result, String> { + pub fn from_data_pixelmasks(data: &'a mut [u8], width: u32, height: u32, pitch: u32, masks: pixels::PixelMasks) -> Result, Error> { unsafe { if width >= (1<<31) || height >= (1<<31) { - Err("Image is too large.".to_owned()) + Err(Error::SdlError("Image is too large.".to_owned())) } else if pitch >= (1<<31) { - Err("Pitch is too large.".to_owned()) + Err(Error::SdlError("Pitch is too large.".to_owned())) } else { let raw = sys::SDL_CreateRGBSurfaceFrom( data.as_mut_ptr() as *mut _, width as c_int, height as c_int, masks.bpp as c_int, pitch as c_int, masks.rmask, masks.gmask, masks.bmask, masks.amask); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Surface::from_ll(raw)) } @@ -173,19 +173,19 @@ impl<'a> Surface<'a> { } } - pub fn load_bmp_rw(rwops: &mut RWops) -> Result, String> { + pub fn load_bmp_rw(rwops: &mut RWops) -> Result, Error> { let raw = unsafe { sys::SDL_LoadBMP_RW(rwops.raw(), 0) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok( unsafe{ Surface::from_ll(raw) } ) } } - pub fn load_bmp>(path: P) -> Result, String> { + pub fn load_bmp>(path: P) -> Result, Error> { let mut file = RWops::from_file(path, "rb")?; Surface::load_bmp_rw(&mut file) } @@ -197,7 +197,7 @@ impl<'a> Surface<'a> { /// The only change is this case is that `Canvas` has a /// better API to draw stuff in the `Surface` in that case, but don't expect any performance /// changes, there will be none. - pub fn into_canvas(self) -> Result>, String> { + pub fn into_canvas(self) -> Result>, Error> { Canvas::from_surface(self) } @@ -323,25 +323,25 @@ impl SurfaceRef { (self.raw_ref().flags & sys::SDL_RLEACCEL) != 0 } - pub fn save_bmp_rw(&self, rwops: &mut RWops) -> Result<(), String> { + pub fn save_bmp_rw(&self, rwops: &mut RWops) -> Result<(), Error> { let ret = unsafe { sys::SDL_SaveBMP_RW(self.raw(), rwops.raw(), 0) }; if ret == 0 { Ok(()) } - else { Err(get_error()) } + else { Err(get_error_as_error()) } } - pub fn save_bmp>(&self, path: P) -> Result<(), String> { + pub fn save_bmp>(&self, path: P) -> Result<(), Error> { let mut file = RWops::from_file(path, "wb")?; self.save_bmp_rw(&mut file) } - pub fn set_palette(&mut self, palette: &pixels::Palette) -> Result<(), String> { + pub fn set_palette(&mut self, palette: &pixels::Palette) -> Result<(), Error> { let result = unsafe { sys::SDL_SetSurfacePalette(self.raw(), palette.raw()) }; match result { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } @@ -365,7 +365,7 @@ impl SurfaceRef { } } - pub fn set_color_key(&mut self, enable: bool, color: pixels::Color) -> Result<(), String> { + pub fn set_color_key(&mut self, enable: bool, color: pixels::Color) -> Result<(), Error> { let key = color.to_u32(&self.pixel_format()); let result = unsafe { sys::SDL_SetColorKey(self.raw(), if enable { 1 } else { 0 }, key) @@ -373,12 +373,12 @@ impl SurfaceRef { if result == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } /// The function will fail if the surface doesn't have color key enabled. - pub fn color_key(&self) -> Result { + pub fn color_key(&self) -> Result { let mut key = 0; // SDL_GetColorKey does not mutate, but requires a non-const pointer anyway. @@ -390,7 +390,7 @@ impl SurfaceRef { if result == 0 { Ok(pixels::Color::from_u32(&self.pixel_format(), key)) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -423,7 +423,7 @@ impl SurfaceRef { } } - pub fn fill_rect(&mut self, rect: R, color: pixels::Color) -> Result<(), String> + pub fn fill_rect(&mut self, rect: R, color: pixels::Color) -> Result<(), Error> where R: Into> { unsafe { @@ -434,13 +434,13 @@ impl SurfaceRef { let result = sys::SDL_FillRect(self.raw(), rect_ptr, color.to_u32(&format) ); match result { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } } #[allow(clippy::clone_on_copy)] - pub fn fill_rects(&mut self, rects: &[Rect], color: pixels::Color) -> Result<(), String> + pub fn fill_rects(&mut self, rects: &[Rect], color: pixels::Color) -> Result<(), Error> { for rect in rects.iter() { if let Err(e) = self.fill_rect(rect.clone(), color) @@ -477,14 +477,14 @@ impl SurfaceRef { } /// The function will fail if the blend mode is not supported by SDL. - pub fn set_blend_mode(&mut self, mode: BlendMode) -> Result<(), String> { + pub fn set_blend_mode(&mut self, mode: BlendMode) -> Result<(), Error> { let result = unsafe { sys::SDL_SetSurfaceBlendMode(self.raw(), transmute(mode)) }; match result { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } @@ -534,24 +534,24 @@ impl SurfaceRef { } /// Copies the surface into a new one that is optimized for blitting to a surface of a specified pixel format. - pub fn convert(&self, format: &pixels::PixelFormat) -> Result, String> { + pub fn convert(&self, format: &pixels::PixelFormat) -> Result, Error> { // SDL_ConvertSurface takes a flag as the last parameter, which should be 0 by the docs. let surface_ptr = unsafe { sys::SDL_ConvertSurface(self.raw(), format.raw(), 0u32) }; if surface_ptr.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(surface_ptr)) } } } /// Copies the surface into a new one of a specified pixel format. - pub fn convert_format(&self, format: pixels::PixelFormatEnum) -> Result, String> { + pub fn convert_format(&self, format: pixels::PixelFormatEnum) -> Result, Error> { // SDL_ConvertSurfaceFormat takes a flag as the last parameter, which should be 0 by the docs. let surface_ptr = unsafe { sys::SDL_ConvertSurfaceFormat(self.raw(), format as u32, 0u32) }; if surface_ptr.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { unsafe { Ok(Surface::from_ll(surface_ptr)) } } @@ -562,7 +562,7 @@ impl SurfaceRef { /// Returns the final blit rectangle, if a `dst_rect` was provided. pub fn blit(&self, src_rect: R1, dst: &mut SurfaceRef, dst_rect: R2) - -> Result, String> + -> Result, Error> where R1: Into>, R2: Into>, { @@ -584,7 +584,7 @@ impl SurfaceRef { if result == 0 { Ok(dst_rect) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -594,7 +594,7 @@ impl SurfaceRef { /// Unless you know what you're doing, use `blit()` instead, which will clip the input rectangles. /// This function could crash if the rectangles aren't pre-clipped to the surface, and is therefore unsafe. pub unsafe fn lower_blit(&self, src_rect: R1, - dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), String> + dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), Error> where R1: Into>, R2: Into>, { @@ -610,7 +610,7 @@ impl SurfaceRef { sys::SDL_LowerBlit(self.raw(), src_rect_ptr, dst.raw(), dst_rect_ptr) } { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } @@ -618,7 +618,7 @@ impl SurfaceRef { /// /// Returns the final blit rectangle, if a `dst_rect` was provided. pub fn blit_scaled(&self, src_rect: R1, - dst: &mut SurfaceRef, dst_rect: R2) -> Result, String> + dst: &mut SurfaceRef, dst_rect: R2) -> Result, Error> where R1: Into>, R2: Into>, { @@ -636,7 +636,7 @@ impl SurfaceRef { sys::SDL_UpperBlitScaled(self.raw(), src_rect_ptr, dst.raw(), dst_rect_ptr) } { 0 => Ok(dst_rect), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } @@ -645,7 +645,7 @@ impl SurfaceRef { /// Unless you know what you're doing, use `blit_scaled()` instead, which will clip the input rectangles. /// This function could crash if the rectangles aren't pre-clipped to the surface, and is therefore unsafe. pub unsafe fn lower_blit_scaled(&self, src_rect: R1, - dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), String> + dst: &mut SurfaceRef, dst_rect: R2) -> Result<(), Error> where R1: Into>, R2: Into> { @@ -659,7 +659,7 @@ impl SurfaceRef { sys::SDL_LowerBlitScaled(self.raw(), src_rect_ptr, dst.raw(), dst_rect_ptr) } { 0 => Ok(()), - _ => Err(get_error()) + _ => Err(get_error_as_error()) } } diff --git a/src/sdl2/ttf/context.rs b/src/sdl2/ttf/context.rs index ad3d57214b1..68dbd95eea9 100644 --- a/src/sdl2/ttf/context.rs +++ b/src/sdl2/ttf/context.rs @@ -3,9 +3,9 @@ use std::error; use std::fmt; use std::os::raw::{c_int, c_long}; use std::path::Path; -use ::get_error; -use ::rwops::RWops; -use ::version::Version; +use crate::{Error, get_error_as_error}; +use crate::rwops::RWops; +use crate::version::Version; use sys::ttf; use super::font::{ @@ -28,26 +28,26 @@ impl Drop for Sdl2TtfContext { impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. - pub fn load_font<'ttf, P: AsRef>(&'ttf self, path: P, point_size: u16) -> Result, String> { + pub fn load_font<'ttf, P: AsRef>(&'ttf self, path: P, point_size: u16) -> Result, Error> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef>(&'ttf self, path: P, index: u32, point_size: u16) - -> Result, String> { + -> Result, Error> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, point_size: u16) - -> Result, String> { + -> Result, Error> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } @@ -56,13 +56,13 @@ impl Sdl2TtfContext { /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf,'r>(&'ttf self, rwops: RWops<'r>, index: u32, - point_size: u16) -> Result, String> { + point_size: u16) -> Result, Error> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } @@ -96,7 +96,7 @@ impl error::Error for InitError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => { None diff --git a/src/sdl2/ttf/font.rs b/src/sdl2/ttf/font.rs index 3b341308201..01f8536d842 100644 --- a/src/sdl2/ttf/font.rs +++ b/src/sdl2/ttf/font.rs @@ -1,17 +1,16 @@ use std::ffi::{CString, CStr}; use std::os::raw::{c_uint, c_int, c_long}; use std::path::Path; -use std::error; -use std::error::Error; +use std::error::{self, Error as StdError}; use std::ffi::NulError; use std::fmt; use std::marker::PhantomData; -use ::surface::Surface; +use crate::surface::Surface; use sys::ttf; use sys::SDL_Surface; -use ::get_error; -use ::pixels::Color; -use ::rwops::RWops; +use crate::{Error, get_error, get_error_as_error}; +use crate::pixels::Color; +use crate::rwops::RWops; bitflags! { /// The styling of a font. @@ -69,7 +68,7 @@ impl error::Error for FontError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { FontError::InvalidLatin1Text(ref error) => { Some(error) @@ -149,7 +148,7 @@ impl<'f,'text> PartialRendering<'f,'text> { /// for an explanation. pub fn solid<'b, T>(self, color: T ) -> FontResult> where T: Into { - let source = try!(self.text.convert()); + let source = self.text.convert()?; let color = color.into().into(); let raw = unsafe { match self.text { @@ -171,7 +170,7 @@ impl<'f,'text> PartialRendering<'f,'text> { /// for an explanation. pub fn shaded<'b, T>(self, color: T, background: T) -> FontResult> where T: Into { - let source = try!(self.text.convert()); + let source = self.text.convert()?; let foreground = color.into().into(); let background = background.into().into(); let raw = unsafe { @@ -194,7 +193,7 @@ impl<'f,'text> PartialRendering<'f,'text> { /// for an explanation. pub fn blended<'b, T>(self, color: T) -> FontResult> where T: Into { - let source = try!(self.text.convert()); + let source = self.text.convert()?; let color = color.into().into(); let raw = unsafe { match self.text { @@ -217,7 +216,7 @@ impl<'f,'text> PartialRendering<'f,'text> { /// for an explanation of the mode. pub fn blended_wrapped<'b, T>(self, color: T, wrap_max_width: u32) -> FontResult> where T: Into { - let source = try!(self.text.convert()); + let source = self.text.convert()?; let color = color.into().into(); let raw = unsafe { match self.text { @@ -264,12 +263,12 @@ impl<'ttf,'r> Drop for Font<'ttf,'r> { } /// Internally used to load a font (for internal visibility). -pub fn internal_load_font<'ttf,P:AsRef>(path: P, ptsize: u16) -> Result, String> { +pub fn internal_load_font<'ttf,P:AsRef>(path: P, ptsize: u16) -> Result, Error> { unsafe { let cstring = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let raw = ttf::TTF_OpenFont(cstring.as_ptr(), ptsize as c_int); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Font { raw: raw, rwops: None, _marker: PhantomData }) } @@ -285,14 +284,14 @@ where R: Into>> { /// Internally used to load a font (for internal visibility). pub fn internal_load_font_at_index<'ttf,P: AsRef>(path: P, index: u32, ptsize: u16) - -> Result, String> { + -> Result, Error> { unsafe { let cstring = CString::new(path.as_ref().to_str().unwrap().as_bytes()) .unwrap(); let raw = ttf::TTF_OpenFontIndex(cstring.as_ptr(), ptsize as c_int, index as c_long); if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(Font { raw: raw, rwops: None, _marker: PhantomData}) } @@ -334,7 +333,7 @@ impl<'ttf,'r> Font<'ttf,'r> { /// Returns the width and height of the given text when rendered using this /// font. pub fn size_of(&self, text: &str) -> FontResult<(u32, u32)> { - let c_string = try!(RenderableText::Utf8(text).convert()); + let c_string = RenderableText::Utf8(text).convert()?; let (res, size) = unsafe { let mut w = 0; // mutated by C code let mut h = 0; // mutated by C code @@ -353,7 +352,7 @@ impl<'ttf,'r> Font<'ttf,'r> { #[allow(unused_mut)] pub fn size_of_latin1(&self, text: &[u8]) -> FontResult<(u32, u32)> { - let c_string = try!(RenderableText::Latin1(text).convert()); + let c_string = RenderableText::Latin1(text).convert()?; let (res, size) = unsafe { let mut w : i32 = 0; // mutated by C code let mut h : i32 = 0; // mutated by C code diff --git a/src/sdl2/video.rs b/src/sdl2/video.rs index d1712c4416c..d336a57248a 100644 --- a/src/sdl2/video.rs +++ b/src/sdl2/video.rs @@ -2,7 +2,7 @@ use libc::{c_int, c_uint, c_float, c_char}; use std::ffi::{CStr, CString, NulError}; use std::{mem, ptr, fmt}; use std::rc::Rc; -use std::error::Error; +use std::error::Error as StdError; use std::ops::{Deref, DerefMut}; use crate::rect::Rect; @@ -14,7 +14,7 @@ use crate::EventPump; use num::FromPrimitive; use crate::common::{validate_int, IntegerOrSdlError}; -use crate::get_error; +use crate::{Error, get_error, get_error_as_error}; use crate::sys; @@ -43,24 +43,24 @@ impl<'a> WindowSurfaceRef<'a> { /// Updates the change made to the inner Surface to the Window it was created from. /// /// This would effectively be the theoretical equivalent of `present` from a Canvas. - pub fn update_window(&self) -> Result<(), String> { + pub fn update_window(&self) -> Result<(), Error> { unsafe { if sys::SDL_UpdateWindowSurface(self.1.context.raw) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } /// Same as `update_window`, but only update the parts included in `rects` to the Window it was /// created from. - pub fn update_window_rects(&self, rects: &[Rect]) -> Result<(), String> { + pub fn update_window_rects(&self, rects: &[Rect]) -> Result<(), Error> { unsafe { if sys::SDL_UpdateWindowSurfaceRects(self.1.context.raw, Rect::raw_slice(rects), rects.len() as c_int) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -71,7 +71,7 @@ impl<'a> WindowSurfaceRef<'a> { /// If you don't want to `update_window` one last time, simply Drop this struct. However /// beware, since the Surface will still be in the state you left it the next time you will /// call `window.surface()` again. - pub fn finish(self) -> Result<(), String> { + pub fn finish(self) -> Result<(), Error> { self.update_window() } } @@ -595,10 +595,10 @@ impl VideoSubsystem { } } - pub fn num_video_displays(&self) -> Result { + pub fn num_video_displays(&self) -> Result { let result = unsafe { sys::SDL_GetNumVideoDisplays() }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(result as i32) } @@ -608,18 +608,18 @@ impl VideoSubsystem { /// /// Will return an error if the index is out of bounds or if SDL experienced a failure; inspect /// the returned string for further info. - pub fn display_name(&self, display_index: i32) -> Result { + pub fn display_name(&self, display_index: i32) -> Result { unsafe { let display = sys::SDL_GetDisplayName(display_index as c_int); if display.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(CStr::from_ptr(display as *const _).to_str().unwrap().to_owned()) } } } - pub fn display_bounds(&self, display_index: i32) -> Result { + pub fn display_bounds(&self, display_index: i32) -> Result { let mut out = mem::MaybeUninit::uninit(); let result = unsafe { sys::SDL_GetDisplayBounds(display_index as c_int, out.as_mut_ptr()) == 0 }; @@ -627,20 +627,20 @@ impl VideoSubsystem { let out = unsafe { out.assume_init() }; Ok(Rect::from_ll(out)) } else { - Err(get_error()) + Err(get_error_as_error()) } } - pub fn num_display_modes(&self, display_index: i32) -> Result { + pub fn num_display_modes(&self, display_index: i32) -> Result { let result = unsafe { sys::SDL_GetNumDisplayModes(display_index as c_int) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(result as i32) } } - pub fn display_mode(&self, display_index: i32, mode_index: i32) -> Result { + pub fn display_mode(&self, display_index: i32, mode_index: i32) -> Result { let mut dm = mem::MaybeUninit::uninit(); let result = unsafe { sys::SDL_GetDisplayMode(display_index as c_int, mode_index as c_int, dm.as_mut_ptr()) == 0}; @@ -648,11 +648,11 @@ impl VideoSubsystem { let dm = unsafe { dm.assume_init() }; Ok(DisplayMode::from_ll(&dm)) } else { - Err(get_error()) + Err(get_error_as_error()) } } - pub fn desktop_display_mode(&self, display_index: i32) -> Result { + pub fn desktop_display_mode(&self, display_index: i32) -> Result { let mut dm = mem::MaybeUninit::uninit(); let result = unsafe { sys::SDL_GetDesktopDisplayMode(display_index as c_int, dm.as_mut_ptr()) == 0}; @@ -660,11 +660,11 @@ impl VideoSubsystem { let dm = unsafe { dm.assume_init() }; Ok(DisplayMode::from_ll(&dm)) } else { - Err(get_error()) + Err(get_error_as_error()) } } - pub fn current_display_mode(&self, display_index: i32) -> Result { + pub fn current_display_mode(&self, display_index: i32) -> Result { let mut dm = mem::MaybeUninit::uninit(); let result = unsafe { sys::SDL_GetCurrentDisplayMode(display_index as c_int, dm.as_mut_ptr()) == 0}; @@ -672,18 +672,18 @@ impl VideoSubsystem { let dm = unsafe { dm.assume_init() }; Ok(DisplayMode::from_ll(&dm)) } else { - Err(get_error()) + Err(get_error_as_error()) } } - pub fn closest_display_mode(&self, display_index: i32, mode: &DisplayMode) -> Result { + pub fn closest_display_mode(&self, display_index: i32, mode: &DisplayMode) -> Result { let input = mode.to_ll(); let mut dm = mem::MaybeUninit::uninit(); let result = unsafe { sys::SDL_GetClosestDisplayMode(display_index as c_int, &input, dm.as_mut_ptr()) }; if result.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let dm = unsafe { dm.assume_init() }; Ok(DisplayMode::from_ll(&dm)) @@ -692,13 +692,13 @@ impl VideoSubsystem { /// Return a triplet `(ddpi, hdpi, vdpi)` containing the diagonal, horizontal and vertical /// dots/pixels-per-inch of a display - pub fn display_dpi(&self, display_index: i32) -> Result<(f32, f32, f32), String> { + pub fn display_dpi(&self, display_index: i32) -> Result<(f32, f32, f32), Error> { let mut ddpi = 0.0; let mut hdpi = 0.0; let mut vdpi = 0.0; let result = unsafe { sys::SDL_GetDisplayDPI(display_index as c_int, &mut ddpi, &mut hdpi, &mut vdpi) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok((ddpi, hdpi, vdpi)) } @@ -722,12 +722,12 @@ impl VideoSubsystem { /// If no OpenGL library is loaded, the default library will be loaded upon creation of the first OpenGL window. /// /// If a different library is already loaded, this function will return an error. - pub fn gl_load_library_default(&self) -> Result<(), String> { + pub fn gl_load_library_default(&self) -> Result<(), Error> { unsafe { if sys::SDL_GL_LoadLibrary(ptr::null()) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -738,14 +738,14 @@ impl VideoSubsystem { /// If no OpenGL library is loaded, the default library will be loaded upon creation of the first OpenGL window. /// /// If a different library is already loaded, this function will return an error. - pub fn gl_load_library>(&self, path: P) -> Result<(), String> { + pub fn gl_load_library>(&self, path: P) -> Result<(), Error> { unsafe { // TODO: use OsStr::to_cstring() once it's stable let path = CString::new(path.as_ref().to_str().unwrap()).unwrap(); if sys::SDL_GL_LoadLibrary(path.as_ptr() as *const c_char) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -777,10 +777,10 @@ impl VideoSubsystem { } } - pub fn gl_get_current_window_id(&self) -> Result { + pub fn gl_get_current_window_id(&self) -> Result { let raw = unsafe { sys::SDL_GL_GetCurrentWindow() }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let id = unsafe { sys::SDL_GetWindowID(raw) }; Ok(id) @@ -788,22 +788,22 @@ impl VideoSubsystem { } /// Releases the thread's current OpenGL context, i.e. sets the current OpenGL context to nothing. - pub fn gl_release_current_context(&self) -> Result<(), String> { + pub fn gl_release_current_context(&self) -> Result<(), Error> { let result = unsafe { sys::SDL_GL_MakeCurrent(ptr::null_mut(), ptr::null_mut()) }; if result == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } - pub fn gl_set_swap_interval>(&self, interval: S) -> Result<(), String> { + pub fn gl_set_swap_interval>(&self, interval: S) -> Result<(), Error> { let result = unsafe { sys::SDL_GL_SetSwapInterval(interval.into() as c_int) }; if result == 0{ Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -821,12 +821,12 @@ impl VideoSubsystem { /// If no Vulkan library is loaded, the default library will be loaded upon creation of the first Vulkan window. /// /// If a different library is already loaded, this function will return an error. - pub fn vulkan_load_library_default(&self) -> Result<(), String> { + pub fn vulkan_load_library_default(&self) -> Result<(), Error> { unsafe { if sys::SDL_Vulkan_LoadLibrary(ptr::null()) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -837,14 +837,14 @@ impl VideoSubsystem { /// If no Vulkan library is loaded, the default library will be loaded upon creation of the first Vulkan window. /// /// If a different library is already loaded, this function will return an error. - pub fn vulkan_load_library>(&self, path: P) -> Result<(), String> { + pub fn vulkan_load_library>(&self, path: P) -> Result<(), Error> { unsafe { // TODO: use OsStr::to_cstring() once it's stable let path = CString::new(path.as_ref().to_str().unwrap()).unwrap(); if sys::SDL_Vulkan_LoadLibrary(path.as_ptr() as *const c_char) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -861,10 +861,10 @@ impl VideoSubsystem { /// [`vkGetInstanceProcAddr`](https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/vkGetInstanceProcAddr.html) /// Vulkan function. This function can be called to retrieve the address of other Vulkan /// functions. - pub fn vulkan_get_proc_address_function(&self) -> Result<*const (), String> { + pub fn vulkan_get_proc_address_function(&self) -> Result<*const (), Error> { let result = unsafe { sys::SDL_Vulkan_GetVkGetInstanceProcAddr() as *const () }; if result.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(result) } @@ -892,7 +892,7 @@ impl fmt::Display for WindowBuildError { } } -impl Error for WindowBuildError { +impl StdError for WindowBuildError { fn description(&self) -> &str { use self::WindowBuildError::*; @@ -1096,34 +1096,34 @@ impl Window { unsafe { sys::SDL_GetWindowID(self.context.raw) } } - pub fn gl_create_context(&self) -> Result { + pub fn gl_create_context(&self) -> Result { let result = unsafe { sys::SDL_GL_CreateContext(self.context.raw) }; if result.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(GLContext{ raw: result }) } } /// Set the window's OpenGL context to the current context on the thread. - pub fn gl_set_context_to_current(&self) -> Result<(), String> { + pub fn gl_set_context_to_current(&self) -> Result<(), Error> { unsafe { let context_raw = sys::SDL_GL_GetCurrentContext(); if !context_raw.is_null() && sys::SDL_GL_MakeCurrent(self.context.raw, context_raw) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } - pub fn gl_make_current(&self, context: &GLContext) -> Result<(), String> { + pub fn gl_make_current(&self, context: &GLContext) -> Result<(), Error> { unsafe { if sys::SDL_GL_MakeCurrent(self.context.raw, context.raw) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -1133,14 +1133,14 @@ impl Window { } /// Get the names of the Vulkan instance extensions needed to create a surface with `vulkan_create_surface`. - pub fn vulkan_instance_extensions(&self) -> Result, String> { + pub fn vulkan_instance_extensions(&self) -> Result, Error> { let mut count: c_uint = 0; if unsafe { sys::SDL_Vulkan_GetInstanceExtensions(self.context.raw, &mut count, ptr::null_mut()) } == sys::SDL_bool::SDL_FALSE { - return Err(get_error()); + return Err(get_error_as_error()); } let mut names: Vec<*const c_char> = vec![ptr::null(); count as usize]; if unsafe { sys::SDL_Vulkan_GetInstanceExtensions(self.context.raw, &mut count, names.as_mut_ptr()) } == sys::SDL_bool::SDL_FALSE { - return Err(get_error()); + return Err(get_error_as_error()); } Ok(names.iter().map(|&val| unsafe { CStr::from_ptr(val) }.to_str().unwrap()).collect()) } @@ -1150,25 +1150,25 @@ impl Window { /// The `VkInstance` must be created using a prior call to the /// [`vkCreateInstance`](https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/vkCreateInstance.html) /// function in the Vulkan library. - pub fn vulkan_create_surface(&self, instance: VkInstance) -> Result { + pub fn vulkan_create_surface(&self, instance: VkInstance) -> Result { let mut surface: VkSurfaceKHR = 0; if unsafe { sys::SDL_Vulkan_CreateSurface(self.context.raw, instance, &mut surface) } == sys::SDL_bool::SDL_FALSE { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(surface) } } - pub fn display_index(&self) -> Result { + pub fn display_index(&self) -> Result { let result = unsafe { sys::SDL_GetWindowDisplayIndex(self.context.raw) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(result as i32) } } - pub fn set_display_mode(&mut self, display_mode: D) -> Result<(), String> + pub fn set_display_mode(&mut self, display_mode: D) -> Result<(), Error> where D: Into> { unsafe { @@ -1180,14 +1180,14 @@ impl Window { } ); if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } } - pub fn display_mode(&self) -> Result { + pub fn display_mode(&self) -> Result { let mut dm = mem::MaybeUninit::uninit(); let result = unsafe { @@ -1201,7 +1201,7 @@ impl Window { let dm = unsafe { dm.assume_init() }; Ok(DisplayMode::from_ll(&dm)) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -1270,14 +1270,14 @@ impl Window { /// /// # Remarks /// This function is only supported on X11, otherwise an error is returned. - pub fn border_size(&self) -> Result<(u16, u16, u16, u16), String> { + pub fn border_size(&self) -> Result<(u16, u16, u16, u16), Error> { let mut top: c_int = 0; let mut left: c_int = 0; let mut bottom: c_int = 0; let mut right: c_int = 0; let result = unsafe { sys::SDL_GetWindowBordersSize(self.context.raw, &mut top, &mut left, &mut bottom, &mut right) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok((top as u16, left as u16, bottom as u16, right as u16)) } @@ -1388,7 +1388,7 @@ impl Window { } pub fn set_fullscreen(&mut self, fullscreen_type: FullscreenType) - -> Result<(), String> { + -> Result<(), Error> { unsafe { let result = sys::SDL_SetWindowFullscreen( self.context.raw, fullscreen_type as u32 @@ -1396,7 +1396,7 @@ impl Window { if result == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -1413,11 +1413,11 @@ impl Window { /// to support Software Rendering (which is what using Surface is), you can still create a /// Renderer which renders in a Software-based manner, so try to rely on a Renderer as much as /// possible ! - pub fn surface<'a>(&'a self, _e: &'a EventPump) -> Result, String> { + pub fn surface<'a>(&'a self, _e: &'a EventPump) -> Result, Error> { let raw = unsafe { sys::SDL_GetWindowSurface(self.context.raw) }; if raw.is_null() { - Err(get_error()) + Err(get_error_as_error()) } else { let surface_ref = unsafe { SurfaceRef::from_ll_mut(raw) }; Ok(WindowSurfaceRef(surface_ref, self)) @@ -1432,12 +1432,12 @@ impl Window { unsafe { sys::SDL_GetWindowGrab(self.context.raw) == sys::SDL_bool::SDL_TRUE } } - pub fn set_brightness(&mut self, brightness: f64) -> Result<(), String> { + pub fn set_brightness(&mut self, brightness: f64) -> Result<(), Error> { unsafe { if sys::SDL_SetWindowBrightness(self.context.raw, brightness as c_float) == 0 { Ok(()) } else { - Err(get_error()) + Err(get_error_as_error()) } } } @@ -1446,7 +1446,7 @@ impl Window { unsafe { sys::SDL_GetWindowBrightness(self.context.raw) as f64 } } - pub fn set_gamma_ramp<'a, 'b, 'c, R, G, B>(&mut self, red: R, green: G, blue: B) -> Result<(), String> + pub fn set_gamma_ramp<'a, 'b, 'c, R, G, B>(&mut self, red: R, green: G, blue: B) -> Result<(), Error> where R: Into>, G: Into>, B: Into>, @@ -1469,14 +1469,14 @@ impl Window { ) }; if result != 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } } #[allow(clippy::type_complexity)] - pub fn gamma_ramp(&self) -> Result<(Vec, Vec, Vec), String> { + pub fn gamma_ramp(&self) -> Result<(Vec, Vec, Vec), Error> { let mut red: Vec = vec![0; 256]; let mut green: Vec = vec![0; 256]; let mut blue: Vec = vec![0; 256]; @@ -1489,7 +1489,7 @@ impl Window { if result == 0 { Ok((red, green, blue)) } else { - Err(get_error()) + Err(get_error_as_error()) } } @@ -1497,10 +1497,10 @@ impl Window { /// `0.0` (fully transparent), and `1.0` (fully opaque). /// /// This method returns an error if opacity isn't supported by the current platform. - pub fn set_opacity(&mut self, opacity: f32) -> Result<(), String> { + pub fn set_opacity(&mut self, opacity: f32) -> Result<(), Error> { let result = unsafe { sys::SDL_SetWindowOpacity(self.context.raw, opacity) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(()) } @@ -1511,11 +1511,11 @@ impl Window { /// /// If opacity isn't supported by the current platform, this method returns `Ok(1.0)` instead /// of an error. - pub fn opacity(&self) -> Result { + pub fn opacity(&self) -> Result { let mut opacity = 0.0; let result = unsafe { sys::SDL_GetWindowOpacity(self.context.raw, &mut opacity) }; if result < 0 { - Err(get_error()) + Err(get_error_as_error()) } else { Ok(opacity) }