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
//! Stuff that's specific to Windows, through `winapi`.

use super::*;

use std::alloc::{alloc_zeroed, dealloc, Layout};
use std::ptr::null_mut;

use winapi::shared::guiddef::*;
use winapi::{
  shared::{minwindef::*, windef::*, winerror::*},
  um::{errhandlingapi::*, wingdi::*, winnt::*, winuser::*},
};

unsafe impl ZeroSafe for BITMAPINFO {}
unsafe impl ZeroSafe for RECT {}

pub mod message_box;
pub mod xinput;

/// Forms a wide string with a null terminator from the `&str` given.
///
/// ```
/// use thorium::win32::wide_null;
/// assert_eq!(wide_null("𝄞"), vec![0xD834, 0xDD1E, 0]);
/// ```
pub fn wide_null(s: &str) -> Vec<u16> {
  s.encode_utf16().chain(Some(0)).collect()
}

/// Packages up an offscreen bitmap buffer.
#[derive(Clone, Copy)]
pub struct OffscreenBuffer {
  info: BITMAPINFO,
  memory: *mut u8,
  memory_layout: Option<Layout>,
  width: i32,
  height: i32,
  pitch: isize,
  bytes_per_pixel: usize,
}
impl std::fmt::Debug for OffscreenBuffer {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
    write!(f, "OffscreenBuffer {{ info: {:?}, memory: {:p}, memory_layout: {:?}, width: {:?}, height: {:?}, pitch: {:?}, bytes_per_pixel: {:?} }}",
      self.info,
      self.memory,
      self.memory_layout,
      self.width,
      self.height,
      self.pitch,
      self.bytes_per_pixel
    )
  }
}
impl OffscreenBuffer {
  /// Gives a `const` empty buffer value.
  pub const fn empty() -> Self {
    Self {
      info: BITMAPINFO {
        bmiHeader: BITMAPINFOHEADER {
          biSize: core::mem::size_of::<BITMAPINFO>() as u32,
          biWidth: 0,
          biHeight: 0,
          biPlanes: 1,
          biBitCount: 32,
          biCompression: BI_RGB,
          biSizeImage: 0,
          biXPelsPerMeter: 0,
          biYPelsPerMeter: 0,
          biClrUsed: 0,
          biClrImportant: 0,
        },
        bmiColors: [RGBQUAD {
          rgbBlue: 0,
          rgbGreen: 0,
          rgbRed: 0,
          rgbReserved: 0,
        }],
      },
      memory: null_mut(),
      memory_layout: None,
      width: 0,
      height: 0,
      pitch: 0,
      bytes_per_pixel: 4,
    }
  }

  /// the buffer width
  pub fn width(&self) -> i32 {
    self.width
  }

  /// the buffer height
  pub fn height(&self) -> i32 {
    self.height
  }

  /// the raw memory pointer
  pub fn memory(&self) -> *mut u8 {
    self.memory
  }

  /// the buffer format info
  pub fn info(&self) -> BITMAPINFO {
    self.info
  }

  /// Renders the weird gradient into the buffer.
  pub fn render_weird_gradient(&mut self, x_offset: i32, y_offset: i32) {
    let bitmap_memory = self.memory;
    let width = self.width;
    let height = self.height;
    let pitch = self.pitch;
    let mut row_start = bitmap_memory;
    for y in 0..height {
      let mut pixel = row_start as *mut u32;
      for x in 0..width {
        // Note(Lokathor): Windows uses "BGRA" bitmaps, when written as a
        // little-endian `u32` the bytes end up being ordered as `0xAA_RR_GG_BB`.
        let blue = (x + x_offset) as u8 as u32;
        let green = (y + y_offset) as u8 as u32;
        unsafe {
          pixel.write(blue | (green << 8));
          pixel = pixel.offset(1);
        }
      }
      row_start = unsafe { row_start.offset(pitch) };
    }
  }

  /// Resize the buffer.
  ///
  /// The newly allocated buffer is zeroed.
  pub fn resize(&mut self, width: i32, height: i32) {
    // TODO: bulletproof the memory acquisition process. Only free the old memory
    // after getting the new memory, but if we _can't_ get new memory then free
    // the old memory and try a second time.

    if !self.memory.is_null() {
      unsafe { dealloc(self.memory, self.memory_layout.unwrap()) };
      self.memory = null_mut();
      self.memory_layout = None;
    }

    self.info.bmiHeader.biWidth = width;
    // negative height gives a top-down bitmap
    self.info.bmiHeader.biHeight = -height;
    self.width = width;
    self.height = height;
    self.pitch = (width as usize * self.bytes_per_pixel) as isize;;

    let new_memory_size = width as usize * height as usize * self.bytes_per_pixel;
    let new_layout = Layout::from_size_align(new_memory_size, 4)
      .expect("Rust code isn't allowed to handle OOM gracefully, it's the law");
    let new_memory = unsafe { alloc_zeroed(new_layout) };

    if !new_memory.is_null() {
      self.memory = new_memory;
      self.memory_layout = Some(new_layout);
    } else {
      debugln!("Failed to allocate a new buffer!");
    }
  }
}

/// The dimensions of the client rectangle of a window
#[allow(missing_docs)]
pub struct WindowDimension {
  pub width: i32,
  pub height: i32,
}
/// Obtains the dimensions of the window handle given, or an error code.
pub fn get_window_dimension(window: HWND) -> Result<WindowDimension, DWORD> {
  unsafe {
    let mut client_rect: RECT = core::mem::zeroed();
    if GetClientRect(window, &mut client_rect) > 0 {
      Ok(WindowDimension {
        width: client_rect.right - client_rect.left,
        height: client_rect.bottom - client_rect.top,
      })
    } else {
      Err(GetLastError())
    }
  }
}