1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
use sdl2::event::Event as SdlEvent;
use sdl2::event::WindowEvent;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::render::Canvas;
use sdl2::render::Texture;
use sdl2::render::TextureCreator;
use sdl2::surface::Surface;

use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc;
use std::time::Duration;
use std::time::Instant;

use crate::Image;
use crate::ImageData;
use crate::ImageInfo;
#[cfg(feature = "save")]
use crate::KeyCode;
use crate::KeyState;
use crate::KeyboardEvent;
#[cfg(feature = "save")]
use crate::KeyModifiers;
use crate::PixelFormat;
use crate::Rectangle;
use crate::WaitKeyError;
use crate::WindowOptions;
use crate::oneshot;
use crate::background_thread::BackgroundThread;
use crate::MouseState;
use crate::MouseMoveEvent;
use crate::MouseButtonState;
use crate::MouseButton;
use crate::MouseButtonEvent;
use crate::Event;

mod monochrome;
mod key_code;
mod key_location;
mod modifiers;
mod scan_code;

pub use super::EventHandler;
pub use super::EventHandlerContext;

const RESULT_TIMEOUT: Duration = Duration::from_millis(500);

/// A context for creating windows.
///
/// Once initialized, the context runs an event loop in a background thread.
/// You can interact with the background thead through the context object.
pub struct Context {
	/// Channel to send command to the background thread.
	command_tx: mpsc::SyncSender<ContextCommand>,

	/// Join handle for the background thread.
	thread: Mutex<Option<BackgroundThread<Result<(), String>>>>,
}

/// A window capable of displaying images.
///
/// The handle can be used to set the displayed image,
/// handle key events and to close the window.
///
/// If the handle is dropped, the window is closed.
pub struct Window {
	/// The window ID.
	id: u32,

	/// Channel to send commands to the background thread.
	command_tx: mpsc::SyncSender<ContextCommand>,

	/// Channel to receive events from the background thread.
	event_rx: mpsc::Receiver<Event>,
}

/// Commands that can be sent to the context in the background thread.
enum ContextCommand {
	/// Stop the background thread as soon as possible.
	Stop(oneshot::Sender<()>),

	/// Create a window with the given options.
	CreateWindow(WindowOptions, mpsc::SyncSender<ContextCommand>, oneshot::Sender<Result<Window, String>>),

	/// Destroy a window.
	DestroyWindow(u32, oneshot::Sender<Result<(), String>>),

	/// Set the image of the window.
	SetImage(u32, Box<[u8]>, ImageInfo, String, oneshot::Sender<Result<(), String>>),

	/// Get the currently displayed image of the window.
	GetImage(u32, oneshot::Sender<Result<Option<Image>, String>>),

	/// Register a event handler to be run in the background context.
	AddEventHandler(u32, EventHandler, oneshot::Sender<Result<(), String>>),
}

/// Inner context doing the real work in the background thread.
struct ContextInner {
	/// SDL2 video subsystem to create windows with.
	video: sdl2::VideoSubsystem,

	/// SDL2 event pump to handle events with.
	events: sdl2::EventPump,

	/// The palette to use for drawing monochrome pictures.
	mono_palette: sdl2::pixels::Palette,

	/// List of created windows.
	windows: Vec<WindowInner>,

	/// Channel to receive commands.
	command_rx: mpsc::Receiver<ContextCommand>,

	/// Event handlers to be run in the context thread.
	event_handlers: Vec<(u32, EventHandler)>,

	/// Background tasks that might be joined later.
	background_tasks: Vec<BackgroundThread<()>>,

	/// Flag to indicate the context should stop as soon as possible.
	stop: bool,
}

/// Inner window doing the real work in the background thread.
pub struct WindowInner {
	/// The window ID, used to look up the window in the vector.
	id: u32,

	/// The canvas to draw the image on.
	canvas: Canvas<sdl2::video::Window>,

	/// A texture creator for the window.
	texture_creator: TextureCreator<sdl2::video::WindowContext>,

	/// A texture representing the current image to be drawn.
	texture: Option<(Texture<'static>, Rect)>,

	/// The data of the currently displayed image.
	image: Option<Image>,

	/// Channel to send events.
	event_tx: mpsc::SyncSender<Event>,

	/// If true, preserve aspect ratio when scaling image.
	preserve_aspect_ratio: bool,
}

impl Context {
	/// Create a new context.
	///
	/// The context will spawn a background thread immediately.
	pub fn new() -> Result<Self, String> {
		let (result_tx, mut result_rx) = oneshot::channel();
		let (command_tx, command_rx) = mpsc::sync_channel(10);
		let thread = BackgroundThread::new(move || {
			match ContextInner::new(command_rx) {
				Err(e) => {
					result_tx.send(Err(e));
					Ok(())
				},
				Ok(mut context) => {
					result_tx.send(Ok(()));
					context.run()?;
					context.join_background_tasks();
					Ok(())
				}
			}
		});

		match result_rx.recv_timeout(Duration::from_millis(1500)) {
			Err(e) => Err(format!("failed to receive ready notification from context thread: {}", e)),
			Ok(Err(e)) => Err(e),
			Ok(Ok(())) => Ok(Context {
				command_tx,
				thread: Mutex::new(Some(thread)),
			})
		}
	}

	/// Create a new window with default options.
	pub fn make_window(&self, name: impl Into<String>) -> Result<Window, String> {
		let options = WindowOptions { name: name.into(), ..Default::default() };
		self.make_window_full(options)
	}

	/// Create a new window with the given options.
	pub fn make_window_full(&self, options: WindowOptions) -> Result<Window, String> {
		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::CreateWindow(options, self.command_tx.clone(), result_tx))
			.map_err(|e| format!("failed to send CreateWindow command to context thread: {}", e))?;
		result_rx.recv_timeout(RESULT_TIMEOUT).map_err(|e| format!("failed to receive CreateWindow result from context thread: {}", e))?
	}

	/// Close all windows and stop the background thread.
	///
	/// The background thread will stop as soon as possible,
	/// but it may still be running when this function returns.
	///
	/// Use [`Context::join`] to join the background thread if desired.
	#[allow(unused)]
	pub fn stop(&self) -> Result<(), String> {
		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::Stop(result_tx))
			.map_err(|e| format!("failed to send Stop command to context thread: {}", e))?;
		result_rx.recv_timeout(RESULT_TIMEOUT).map_err(|e| format!("failed to receive Stop result from context thread: {}", e))
	}

	/// Join the background thread, blocking until the thread has terminated.
	///
	/// This function also returns any possible error that occured in the background thread.
	///
	/// Note that the background thread will only terminate if an error occurs
	/// or if [`Context::stop`] is called.
	#[allow(unused)]
	pub fn join(&self) -> Result<(), String> {
		// Join main context thread.
		let mut thread = self.thread.lock().unwrap();
		if let Some(thread) = thread.take() {
			thread.join().map_err(|e| format!("failed to join context thread: {:?}", e))?
		} else {
			Ok(())
		}
	}
}

impl Window {
	/// Set the image to de displayed by the window.
	///
	/// The name is used to suggest a defaullt file name when saving images.
	/// It is also returned again by [`Window::get_image`].
	pub fn set_image(&self, image: impl ImageData, name: impl Into<String>) -> Result<(), String> {
		let info = image.info().map_err(|e| format!("failed to display image: {}", e))?;
		let data = image.data();

		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::SetImage(self.id, data, info, name.into(), result_tx)).unwrap();
		result_rx.recv_timeout(RESULT_TIMEOUT)
			.map_err(|e| format!("failed to receive SetImage result from context thread: {}", e))?
			.map_err(|e| format!("failed to display image: {}", e))
	}

	/// Get the currently displayed image of the window.
	pub fn get_image(&self) -> Result<Option<Image>, String> {
		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::GetImage(self.id, result_tx)).unwrap();
		result_rx.recv_timeout(RESULT_TIMEOUT)
			.map_err(|e| format!("failed to receive GetImage result from context thread: {}", e))?
	}

	/// Add a handler for events.
	///
	/// The added handler will be run directly in the context thread.
	/// This allows you to handle events asynchronously,
	/// but it also means your hander shouldn't block for long.
	///
	/// The handler can use the [`EventHandlerContext::spawn_task`] to perform long running operations.
	///
	/// If you want to handle events in your own thread,
	/// use [`Window::wait_key`], [`Window::wait_key_deadline`] or [`Window::events`].
	pub fn add_event_handler<Handler>(&self, handler: Handler) -> Result<(), String>
	where
		Handler: FnMut(&mut EventHandlerContext) + Send + 'static,
	{
		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::AddEventHandler(self.id, Box::new(handler), result_tx)).unwrap();
		result_rx.recv_timeout(RESULT_TIMEOUT)
			.map_err(|e| format!("failed to receive AddEventHandler result from context thread: {}", e))?
	}

	/// Close the window.
	///
	/// The window is automatically closed if the handle is dropped,
	/// but this function allows you to handle errors that may occur.
	pub fn close(self) -> Result<(), String> {
		self.close_impl()
	}

	/// Get the receiver for events.
	pub fn events(&self) -> &mpsc::Receiver<Event> {
		&self.event_rx
	}

	/// Wait for a key-down event with a timeout.
	///
	/// If an error is returned, no further key events will be received.
	/// Any loop processing keyboard input should terminate.
	///
	/// If no key press was available within the timeout, `Ok(None)` is returned.
	///
	/// This function discards all key-up events and blocks until a key is pressed or the timeout occurs.
	pub fn wait_key(&self, timeout: Duration) -> Result<Option<KeyboardEvent>, WaitKeyError> {
		self.wait_key_deadline(Instant::now() + timeout)
	}

	/// Wait for a key-down event with a deadline.
	///
	/// If an error is returned, no further key events will be received.
	/// Any loop processing keyboard input should terminate.
	///
	/// If no key press was available within the timeout, `Ok(None)` is returned.
	///
	/// This function discards all key-up events and blocks until a key is pressed or the deadline passes.
	pub fn wait_key_deadline(&self, deadline: Instant) -> Result<Option<KeyboardEvent>, WaitKeyError> {
		loop {
			let now = Instant::now();
			if now >= deadline {
				return Ok(None);
			}
			let event = match self.events().recv_timeout(deadline - now) {
				Ok(Event::KeyboardEvent(x)) => x,
				Ok(_) => continue,
				Err(mpsc::RecvTimeoutError::Timeout) => return Ok(None),
				Err(mpsc::RecvTimeoutError::Disconnected) => return Err(WaitKeyError::WindowClosed),
			};

			if event.state == KeyState::Down {
				return Ok(Some(event))
			}
		}
	}

	/// Close the window without dropping the handle.
	fn close_impl(&self) -> Result<(), String> {
		let (result_tx, mut result_rx) = oneshot::channel();
		self.command_tx.send(ContextCommand::DestroyWindow(self.id, result_tx))
			.map_err(|e| format!("failed to send DestroyWindow command to window: {}", e))?;
		result_rx.recv_timeout(RESULT_TIMEOUT).map_err(|e| format!("failed to receive DestroyWindow result from context thread: {}", e))?
	}
}

/// Close the window when the handle is dropped.
impl Drop for Window {
	fn drop(&mut self) {
		let _ = self.close_impl();
	}
}

impl ContextInner {
	/// Create a new context.
	fn new(command_rx: mpsc::Receiver<ContextCommand>) -> Result<Self, String> {
		sdl2::hint::set("SDL_NO_SIGNAL_HANDLERS", "1");
		let context = sdl2::init().map_err(|e| format!("failed to initialize SDL2: {}", e))?;
		let video = context.video().map_err(|e| format!("failed to get SDL2 video subsystem: {}", e))?;
		let events = context.event_pump().map_err(|e| format!("failed to get SDL2 event pump: {}", e))?;
		let mono_palette = monochrome::mono_palette().map_err(|e| format!("failed to create monochrome palette: {}", e))?;

		Ok(Self {
			video,
			events,
			mono_palette,
			windows: Vec::new(),
			command_rx,
			event_handlers: Vec::new(),
			background_tasks: Vec::new(),
			stop: false,
		})
	}

	/// Run the event loop.
	fn run(&mut self) -> Result<(), String> {
		let delay = Duration::from_nanos(1_000_000_000 / 60);
		let mut next_frame = Instant::now() + delay;

		while !self.stop {
			self.run_one()?;

			// Sleep till the next scheduled frame.
			let now = Instant::now();
			if now < next_frame {
				std::thread::sleep(next_frame - now);
				next_frame += delay;
			} else {
				next_frame = now.max(next_frame + delay);
			}
		}

		Ok(())
	}

	/// Run one iteration of the event loop.
	fn run_one(&mut self) -> Result<(), String> {
		// Handle all queued SDL events.
		// Skip all key events for windows that just got focused,
		// because these are probably virtual events that happened while the window was not focused.
		// Work-around for https://bugzilla.libsdl.org/show_bug.cgi?id=4989
		let mut focused_windows = Vec::new();
		while let Some(event) = self.events.poll_event() {
			if let SdlEvent::Window { window_id, win_event, .. } = event {
				match win_event {
					WindowEvent::Close => self.destroy_window(window_id)?,
					WindowEvent::FocusGained => focused_windows.push(window_id),
					_ => (),
				}

				continue;
			}

			if let Some((window_id, event)) = convert_event(event, &focused_windows) {
				self.handle_event(window_id, event);
			}
		}

		// Handle all queued commands for the context.
		self.poll_commands();

		// Loop over all windows.
		for window in &mut self.windows {
			window.draw()?;
		}

		self.clean_background_tasks();
		Ok(())
	}

	fn handle_event(&mut self, window_id: u32, event: Event) {
		if let Some(window) = self.windows.iter_mut().find(|x| x.id == window_id) {
			#[cfg(feature = "save")] {
				if let Event::KeyboardEvent(event) = &event {
					let ctrl  = event.modifiers.contains(KeyModifiers::CONTROL);
					let shift = event.modifiers.contains(KeyModifiers::SHIFT);
					let alt   = event.modifiers.contains(KeyModifiers::ALT);
					if event.state == KeyState::Down && event.key == KeyCode::Character("S".into()) && ctrl && !shift && !alt {
						if let Some(work) = window.save_image() {
							self.background_tasks.push(work);
						}
					}
				}
			}

			for (_, handler) in self.event_handlers.iter_mut().filter(|(id, _)| *id == window_id) {
				let mut context = EventHandlerContext::new(&mut self.background_tasks, &event, &window);
				handler(&mut context);
				if context.should_stop_propagation() {
					break;
				}
			}

			let _ = window.event_tx.try_send(event);
		}
	}

	/// Handle all queued commands.
	fn poll_commands(&mut self) {
		while let Ok(command) = self.command_rx.try_recv() {
			self.handle_command(command);
		}
	}

	/// Handle a single command.
	fn handle_command(&mut self, command: ContextCommand) {
		match command {
			ContextCommand::Stop(result_tx) => {
				self.stop = true;
				result_tx.send(());
			},
			ContextCommand::CreateWindow(options, command_tx, result_tx) => {
				result_tx.send(self.make_window(options, command_tx));
			},
			ContextCommand::DestroyWindow(id, result_tx) => {
				result_tx.send(self.destroy_window(id));
			},
			ContextCommand::SetImage(id, data, info, name, result_tx) => {
				match self.windows.iter_mut().find(|x| x.id == id) {
					None => result_tx.send(Err(format!("failed to find window with ID {}", id))),
					Some(window) => result_tx.send(window.set_image(&self.mono_palette, data, info, name)),
				}
			},
			ContextCommand::GetImage(id, result_tx) => {
				match self.windows.iter_mut().find(|x| x.id == id) {
					None => result_tx.send(Err(format!("failed to find window with ID {}", id))),
					Some(window) => result_tx.send(Ok(window.image.clone())),
				}
			},
			ContextCommand::AddEventHandler(id, handler, result_tx) => {
				match self.windows.iter_mut().find(|x| x.id == id) {
					None => result_tx.send(Err(format!("failed to find window with ID {}", id))),
					Some(_) => {
						self.event_handlers.push((id, handler));
						result_tx.send(Ok(()))
					}
				}
			},
		}
	}

	/// Create a new window.
	fn make_window(&mut self, options: WindowOptions, command_tx: mpsc::SyncSender<ContextCommand>) -> Result<Window, String> {
		let window = self.video.window(&options.name, options.size[0], options.size[1])
			.borderless()
			.resizable()
			.build()
			.map_err(|e| format!("failed to create window {:?}: {}", options.name, e))?;

		let id = window.id();
		let canvas = window.into_canvas().build().map_err(|e| format!("failed to create canvas for window {:?}: {}", options.name, e))?;
		let texture_creator = canvas.texture_creator();
		let (event_tx, event_rx) = mpsc::sync_channel(10);


		let inner = WindowInner {
			id,
			canvas,
			texture_creator,
			texture: None,
			image: None,
			event_tx,
			preserve_aspect_ratio: options.preserve_aspect_ratio,
		};

		self.windows.push(inner);

		Ok(Window { id, command_tx, event_rx })
	}

	/// Destroy a window by ID.
	fn destroy_window(&mut self, id: u32) -> Result<(), String> {
		self.event_handlers.retain(|(handler_window_id, _)| *handler_window_id != id);
		let index = self.windows.iter().position(|x| x.id == id)
			.ok_or_else(|| format!("failed to find window with ID {}", id))?;
		let mut window = self.windows.remove(index);
		window.close();
		Ok(())
	}

	/// Clean finished background threads.
	///
	/// Finished threads are joined to check their result.
	/// If a joined thread returns an error, the error is returned and no other threads are cleaned.
	fn clean_background_tasks(&mut self) {
		self.background_tasks.retain(|x| !x.is_done());
	}

	/// Join all background threads.
	///
	/// If a joined thread returns an error, the error is returned and no other threads are joined.
	fn join_background_tasks(&mut self) {
		while !self.background_tasks.is_empty() {
			let _ = self.background_tasks.remove(self.background_tasks.len() - 1).join();
		}
	}
}

impl<'a> From<&'a Rect> for Rectangle {
	fn from(other: &'a Rect) -> Self {
		Self::from_xywh(other.x(), other.y(), other.width(), other.height())
	}
}

impl From<Rect> for Rectangle {
	fn from(other: Rect) -> Self {
		(&other).into()
	}
}

impl<'a> From<&'a Rectangle> for Rect {
	fn from(other: &'a Rectangle) -> Self {
		Self::new(other.x(), other.y(), other.width(), other.height())
	}
}

impl From<Rectangle> for Rect {
	fn from(other: Rectangle) -> Self {
		(&other).into()
	}
}

impl WindowInner {
	pub fn image(&self) -> Option<&Image> {
		self.image.as_ref()
	}
	/// Get the size of the window.
	pub fn size(&self) -> [u32; 2] {
		let viewport = self.canvas.viewport();
		[viewport.width(), viewport.height()]
	}

	/// Get the rectangle with the visible image.
	pub fn image_area(&self) -> Option<Rectangle> {
		let (_texture, image_size) = self.texture.as_ref()?;
		if self.preserve_aspect_ratio {
			let image_size = Rectangle::from(image_size);
			let canvas_size = Rectangle::from(&self.canvas.viewport());
			Some(compute_target_rect_with_aspect_ratio(&image_size, &canvas_size))
		} else {
			Some(self.canvas.viewport().into())
		}
	}

	/// Set the displayed image.
	fn set_image(&mut self, mono_palette: &sdl2::pixels::Palette, mut data: Box<[u8]>, info: ImageInfo, name: String) -> Result<(), String> {
		let pixel_format = match info.pixel_format {
			PixelFormat::Mono8 => PixelFormatEnum::Index8,
			PixelFormat::Rgb8  => PixelFormatEnum::RGB24,
			PixelFormat::Rgba8 => PixelFormatEnum::RGBA32,
			PixelFormat::Bgr8  => PixelFormatEnum::BGR24,
			PixelFormat::Bgra8 => PixelFormatEnum::BGRA32,
		};

		let mut surface = Surface::from_data(&mut data, info.width as u32, info.height as u32, info.row_stride as u32, pixel_format)
			.map_err(|e| format!("failed to create surface for pixel data: {}", e))?;
		let image_size = surface.rect();

		if info.pixel_format == PixelFormat::Mono8 {
			surface.set_palette(mono_palette).map_err(|e| format!("failed to set monochrome palette on canvas: {}", e))?;
		}

		let texture = self.texture_creator.create_texture_from_surface(surface)
			.map_err(|e| format!("failed to create texture from surface: {}", e))?;
		let texture = unsafe { std::mem::transmute::<_, Texture<'static>>(texture) };
		self.texture = Some((texture, image_size));
		self.image = Some(Image { data: Arc::from(data), info, name });

		Ok(())
	}

	/// Draw the contents of the window.
	fn draw(&mut self) -> Result<(), String> {
		// Always clear the whole window, to avoid artefacts.
		self.canvas.clear();

		// Redraw the image, if any.
		if let Some((texture, image_size)) = &self.texture {
			let rect = if self.preserve_aspect_ratio {
				compute_target_rect_with_aspect_ratio(&image_size.into(), &self.canvas.viewport().into()).into()
			} else {
				self.canvas.viewport()
			};

			self.canvas.copy(&texture, image_size.clone(), rect)
				.map_err(|e| format!("failed to copy data to self: {}", e))?;
		}

		self.canvas.present();
		Ok(())
	}

	/// Close the window.
	fn close(&mut self) {
		self.canvas.window_mut().hide();
	}

	#[cfg(feature = "save")]
	fn save_image(&mut self) -> Option<BackgroundThread<()>> {
		let image = self.image.as_ref()?.clone();

		Some(BackgroundThread::new(move || {
			let _ = crate::prompt_save_image(&format!("{}.png", image.name), &image.data, image.info);
		}))
	}
}

/// Convert an SDL2 event to the more generic Event.
fn convert_event(event: SdlEvent, focused_windows: &Vec<u32>) -> Option<(u32, Event)> {
	match event {
		SdlEvent::KeyDown { window_id, keycode, scancode, keymod, repeat, .. } if !focused_windows.contains(&window_id) => {
			Some((window_id, Event::KeyboardEvent(convert_keyboard_event(KeyState::Down, keycode, scancode, keymod, repeat))))
		},
		SdlEvent::KeyUp { window_id, keycode, scancode, keymod, repeat, .. } if !focused_windows.contains(&window_id) => {
			Some((window_id, Event::KeyboardEvent(convert_keyboard_event(KeyState::Up, keycode, scancode, keymod, repeat))))
		},
		SdlEvent::MouseMotion { window_id, which, mousestate, x, y, xrel, yrel, .. } if !focused_windows.contains(&window_id) => {
			Some((window_id, Event::MouseMoveEvent(convert_mouse_move_event(which, mousestate, x, y, xrel, yrel))))
		},
		SdlEvent::MouseButtonDown { window_id, which, mouse_btn, clicks, x, y, .. } if !focused_windows.contains(&window_id) => {
			Some((window_id, Event::MouseButtonEvent(convert_mouse_button_event(which, MouseState::Down, mouse_btn, clicks, x, y))))
		},
		SdlEvent::MouseButtonUp { window_id, which, mouse_btn, clicks, x, y, .. } if !focused_windows.contains(&window_id) => {
			Some((window_id, Event::MouseButtonEvent(convert_mouse_button_event(which, MouseState::Up, mouse_btn, clicks, x, y))))
		},
		_ => None,
	}
}

/// Convert an SDL2 keyboard event to the more generic KeyboardEvent.
fn convert_keyboard_event(
	state: KeyState,
	key_code: Option<sdl2::keyboard::Keycode>,
	scan_code: Option<sdl2::keyboard::Scancode>,
	modifiers: sdl2::keyboard::Mod,
	repeat: bool,
) -> KeyboardEvent {
	KeyboardEvent {
		state,
		key: key_code::convert_key_code(key_code),
		code: scan_code::convert_scan_code(scan_code),
		location: key_location::get_key_location(scan_code),
		modifiers: modifiers::convert_modifiers(modifiers),
		repeat,
		is_composing: false,
	}
}

/// Convert an SDL2 mouse state to the more generic MouseButtonState.
fn convert_mouse_state(
	mouse_state: sdl2::mouse::MouseState,
) -> MouseButtonState {
	MouseButtonState {
		left: mouse_state.left(),
		middle: mouse_state.middle(),
		right: mouse_state.right(),
	}
}

/// Convert an SDL2 mouse motion event to the more generic MouseMoveEvent.
fn convert_mouse_move_event(
	mouse_id: u32,
	mouse_state: sdl2::mouse::MouseState,
	x: i32,
	y: i32,
	xrel: i32,
	yrel: i32,
) -> MouseMoveEvent {
	MouseMoveEvent {
		mouse_id,
		mouse_state: convert_mouse_state(mouse_state),
		position_x: x,
		position_y: y,
		relative_x: xrel,
		relative_y: yrel,
	}
}

/// Convert an SDL2 mouse button to the more generic MouseButton.
fn convert_mouse_button(
	mouse_button: sdl2::mouse::MouseButton,
) -> MouseButton {
	match mouse_button {
		sdl2::mouse::MouseButton::Left => MouseButton::Left,
		sdl2::mouse::MouseButton::Middle => MouseButton::Middle,
		sdl2::mouse::MouseButton::Right => MouseButton::Right,
		_ => MouseButton::Unknown,
	}
}

/// Convert an SDL2 mouse button event to the more generic MouseButtonEvent.
fn convert_mouse_button_event(
	mouse_id: u32,
	state: MouseState,
	button: sdl2::mouse::MouseButton,
	clicks: u8,
	x: i32,
	y: i32,
) -> MouseButtonEvent {
	MouseButtonEvent {
		mouse_id,
		state,
		button: convert_mouse_button(button),
		clicks,
		position_x: x,
		position_y: y,
	}
}

fn compute_target_rect_with_aspect_ratio(source: &Rectangle, canvas: &Rectangle) -> Rectangle {
	let source_w = f64::from(source.width());
	let source_h = f64::from(source.height());
	let canvas_w = f64::from(canvas.width());
	let canvas_h = f64::from(canvas.height());

	let scale_w = canvas_w / source_w;
	let scale_h = canvas_h / source_h;

	if scale_w < scale_h {
		let new_height = (source_h * scale_w).round() as u32;
		let top = (canvas.height() - new_height) / 2;
		Rectangle::from_xywh(canvas.x(), canvas.y() + top as i32, canvas.width(), new_height)
	} else {
		let new_width = (source_w * scale_h).round() as u32;
		let left = (canvas.width() - new_width) / 2;
		Rectangle::from_xywh(canvas.x() + left as i32, canvas.y(), new_width, canvas.height())
	}
}