interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / proto / console / text / output.rs

309 lines · 10033 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use crate::proto::unsafe_protocol;
4use crate::{CStr16, Result, ResultExt, Status, StatusExt};
5use core::fmt;
6use uefi_raw::protocol::console::{SimpleTextOutputMode, SimpleTextOutputProtocol};
7
8/// Simple Text Output [`Protocol`]. Interface for text-based output devices.
9///
10/// It implements the fmt::Write trait, so you can use it to print text with
11/// standard Rust constructs like the `write!()` and `writeln!()` macros.
12///
13/// # Accessing `Output` protocol
14///
15/// The standard output and standard error output protocols can be accessed
16/// using [`system::stdout`] and [`system::stderr`], respectively.
17///
18/// An `Output` protocol can also be accessed like any other UEFI protocol.
19/// See the [`boot`] documentation for more details of how to open a
20/// protocol.
21///
22/// [`system::stdout`]: crate::system::with_stdout
23/// [`system::stderr`]: crate::system::with_stderr
24/// [`boot`]: crate::boot#accessing-protocols
25/// [`Protocol`]: uefi::proto::Protocol
26#[derive(Debug)]
27#[repr(transparent)]
28#[unsafe_protocol(SimpleTextOutputProtocol::GUID)]
29pub struct Output(SimpleTextOutputProtocol);
30
31impl Output {
32 /// Resets and clears the text output device hardware.
33 pub fn reset(&mut self, extended: bool) -> Result {
34 // SAFETY: The memory is valid.
35 unsafe { (self.0.reset)(&mut self.0, extended.into()) }.to_result()
36 }
37
38 /// Clears the output screen.
39 ///
40 /// The background is set to the current background color.
41 /// The cursor is moved to (0, 0).
42 pub fn clear(&mut self) -> Result {
43 // SAFETY: The memory is valid.
44 unsafe { (self.0.clear_screen)(&mut self.0) }.to_result()
45 }
46
47 /// Writes a string to the output device.
48 pub fn output_string(&mut self, string: &CStr16) -> Result {
49 // SAFETY: The memory is valid.
50 unsafe { (self.0.output_string)(&mut self.0, string.as_ptr().cast()) }.to_result()
51 }
52
53 /// Writes a string to the output device. If the string contains
54 /// unknown characters that cannot be rendered they will be silently
55 /// skipped.
56 pub fn output_string_lossy(&mut self, string: &CStr16) -> Result {
57 self.output_string(string).handle_warning(|err| {
58 if err.status() == Status::WARN_UNKNOWN_GLYPH {
59 Ok(())
60 } else {
61 Err(err)
62 }
63 })
64 }
65
66 /// Checks if a string contains only supported characters.
67 ///
68 /// UEFI applications are encouraged to try to print a string even if it contains
69 /// some unsupported characters.
70 pub fn test_string(&mut self, string: &CStr16) -> Result<bool> {
71 // SAFETY: The memory is valid.
72 match unsafe { (self.0.test_string)(&mut self.0, string.as_ptr().cast()) } {
73 Status::UNSUPPORTED => Ok(false),
74 other => other.to_result_with_val(|| true),
75 }
76 }
77
78 /// Returns an iterator of all supported text modes.
79 pub const fn modes(&mut self) -> OutputModeIter<'_> {
80 let max = self.data().max_mode as usize;
81 OutputModeIter {
82 output: self,
83 current: 0,
84 max,
85 }
86 }
87
88 /// Returns the width (column count) and height (row count) of a text mode.
89 ///
90 /// Devices are required to support at least an 80x25 text mode and to
91 /// assign index 0 to it. If 80x50 is supported, then it will be mode 1,
92 /// otherwise querying for mode 1 will return the `Unsupported` error.
93 /// Modes 2+ will describe other text modes supported by the device.
94 ///
95 /// If you want to iterate over all text modes supported by the device,
96 /// consider using the iterator produced by `modes()` as a more ergonomic
97 /// alternative to this method.
98 fn query_mode(&self, index: usize) -> Result<(usize, usize)> {
99 let (mut columns, mut rows) = (0, 0);
100 // SAFETY: The memory is valid.
101 unsafe { (self.0.query_mode)(&self.0, index, &mut columns, &mut rows) }
102 .to_result_with_val(|| (columns, rows))
103 }
104
105 /// Returns the current text mode.
106 pub fn current_mode(&self) -> Result<Option<OutputMode>> {
107 match self.data().mode {
108 -1 => Ok(None),
109 n if n >= 0 => {
110 let index = n as usize;
111 self.query_mode(index)
112 .map(|dims| Some(OutputMode { index, dims }))
113 }
114 _ => unreachable!(),
115 }
116 }
117
118 /// Sets a mode as current.
119 pub fn set_mode(&mut self, mode: OutputMode) -> Result {
120 // SAFETY: The memory is valid.
121 unsafe { (self.0.set_mode)(&mut self.0, mode.index) }.to_result()
122 }
123
124 /// Returns whether the cursor is currently shown or not.
125 #[must_use]
126 pub fn cursor_visible(&self) -> bool {
127 self.data().cursor_visible.into()
128 }
129
130 /// Make the cursor visible or invisible.
131 ///
132 /// The output device may not support this operation, in which case an
133 /// `Unsupported` error will be returned.
134 pub fn enable_cursor(&mut self, visible: bool) -> Result {
135 // SAFETY: The memory is valid.
136 unsafe { (self.0.enable_cursor)(&mut self.0, visible.into()) }.to_result()
137 }
138
139 /// Returns the column and row of the cursor.
140 #[must_use]
141 pub const fn cursor_position(&self) -> (usize, usize) {
142 let column = self.data().cursor_column;
143 let row = self.data().cursor_row;
144 (column as usize, row as usize)
145 }
146
147 /// Sets the cursor's position, relative to the top-left corner, which is (0, 0).
148 ///
149 /// This function will fail if the cursor's new position would exceed the screen's bounds.
150 pub fn set_cursor_position(&mut self, column: usize, row: usize) -> Result {
151 // SAFETY: The memory is valid.
152 unsafe { (self.0.set_cursor_position)(&mut self.0, column, row) }.to_result()
153 }
154
155 /// Sets the text and background colors for the console.
156 ///
157 /// Note that for the foreground color you can choose any color.
158 /// The background must be one of the first 8 colors.
159 pub fn set_color(&mut self, foreground: Color, background: Color) -> Result {
160 let fgc = foreground as usize;
161 let bgc = background as usize;
162
163 assert!(bgc < 8, "An invalid background color was requested");
164
165 let attr = ((bgc & 0x7) << 4) | (fgc & 0xF);
166 // SAFETY: The memory is valid.
167 unsafe { (self.0.set_attribute)(&mut self.0, attr) }.to_result()
168 }
169
170 /// Get a reference to `OutputData`. The lifetime of the reference is tied
171 /// to `self`.
172 const fn data(&self) -> &SimpleTextOutputMode {
173 // SAFETY: The memory is valid.
174 unsafe { &*self.0.mode }
175 }
176}
177
178impl fmt::Write for Output {
179 fn write_str(&mut self, s: &str) -> fmt::Result {
180 // Allocate a small buffer on the stack.
181 const BUF_SIZE: usize = 128;
182 // Add 1 extra character for the null terminator.
183 let mut buf = [0u16; BUF_SIZE + 1];
184
185 let mut i = 0;
186
187 // This closure writes the local buffer to the output and resets the buffer.
188 let mut flush_buffer = |buf: &mut [u16], i: &mut usize| {
189 buf[*i] = 0;
190 let codes = &buf[..=*i];
191 *i = 0;
192
193 let text = CStr16::from_u16_with_nul(codes).map_err(|_| fmt::Error)?;
194
195 self.output_string(text).map_err(|_| fmt::Error)
196 };
197
198 // This closure converts a character to UCS-2 and adds it to the buffer,
199 // flushing it as necessary.
200 let mut add_char = |ch| {
201 // UEFI only supports UCS-2 characters, not UTF-16,
202 // so there are no multibyte characters.
203 buf[i] = ch;
204 i += 1;
205
206 if i == BUF_SIZE {
207 flush_buffer(&mut buf, &mut i).map_err(|_| ucs2::Error::BufferOverflow)
208 } else {
209 Ok(())
210 }
211 };
212
213 // This one converts Rust line feeds to UEFI line feeds beforehand
214 let add_ch = |ch| {
215 if ch == '\n' as u16 {
216 add_char('\r' as u16)?;
217 }
218 add_char(ch)
219 };
220
221 // Translate and write the input string, flushing the buffer when needed
222 ucs2::encode_with(s, add_ch).map_err(|_| fmt::Error)?;
223
224 // Flush the remainder of the buffer
225 flush_buffer(&mut buf, &mut i)
226 }
227}
228
229/// The text mode (resolution) of the output device.
230#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
231pub struct OutputMode {
232 index: usize,
233 dims: (usize, usize),
234}
235
236impl OutputMode {
237 /// Returns the index of this mode.
238 #[inline]
239 #[must_use]
240 pub const fn index(&self) -> usize {
241 self.index
242 }
243
244 /// Returns the width in columns.
245 #[inline]
246 #[must_use]
247 pub const fn columns(&self) -> usize {
248 self.dims.0
249 }
250
251 /// Returns the height in rows.
252 #[inline]
253 #[must_use]
254 pub const fn rows(&self) -> usize {
255 self.dims.1
256 }
257}
258
259/// An iterator of the text modes (possibly) supported by a device.
260#[derive(Debug)]
261pub struct OutputModeIter<'out> {
262 output: &'out mut Output,
263 current: usize,
264 max: usize,
265}
266
267impl Iterator for OutputModeIter<'_> {
268 type Item = OutputMode;
269
270 fn next(&mut self) -> Option<Self::Item> {
271 let index = self.current;
272 if index < self.max {
273 self.current += 1;
274
275 if let Ok(dims) = self.output.query_mode(index) {
276 Some(OutputMode { index, dims })
277 } else {
278 self.next()
279 }
280 } else {
281 None
282 }
283 }
284}
285
286/// Colors for the UEFI console.
287///
288/// All colors can be used as foreground colors.
289/// The first 8 colors can also be used as background colors.
290#[expect(missing_docs)]
291#[derive(Debug, Copy, Clone)]
292pub enum Color {
293 Black = 0,
294 Blue,
295 Green,
296 Cyan,
297 Red,
298 Magenta,
299 Brown,
300 LightGray,
301 DarkGray,
302 LightBlue,
303 LightGreen,
304 LightCyan,
305 LightRed,
306 LightMagenta,
307 Yellow,
308 White,
309}