From 56b569deb24e5621e93cf89fce4f647646ca20ff Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 11 Apr 2022 22:51:54 +0200 Subject: [PATCH 1/6] Refactoring - Applied some clippy lints - Formatting - Replaced lazy_static with Lazy from spin --- Cargo.lock | 15 +----- ableos/Cargo.toml | 30 +++-------- ableos/src/alias_table/mod.rs | 5 +- ableos/src/arch/x86_64/drivers/serial.rs | 17 +++---- ableos/src/arch/x86_64/drivers/vga.rs | 14 +++--- ableos/src/arch/x86_64/gdt.rs | 52 ++++++++++---------- ableos/src/arch/x86_64/interrupts.rs | 51 ++++++++++--------- ableos/src/arch/x86_64/mod.rs | 3 +- ableos/src/devices/dev_vterm.rs | 20 ++++---- ableos/src/devices/mod.rs | 11 ++--- ableos/src/driver_traits/serial.rs | 2 +- ableos/src/experiments/absi.rs | 6 +-- ableos/src/experiments/clip.rs | 20 ++++---- ableos/src/experiments/info.rs | 17 +++---- ableos/src/experiments/kinfo.rs | 19 +++---- ableos/src/filesystem/mod.rs | 19 ++++--- ableos/src/graphics/mod.rs | 9 ++-- ableos/src/kernel_state.rs | 8 ++- ableos/src/kmain.rs | 24 ++++----- ableos/src/logger.rs | 20 +++----- ableos/src/relib/clparse/mod.rs | 14 ++---- ableos/src/relib/encoding/rle.rs | 8 ++- ableos/src/relib/network/socket.rs | 13 ++--- ableos/src/rhai_shell/mod.rs | 33 ++++++------- ableos/src/scheduler/mod.rs | 13 ++--- ableos/src/scratchpad.rs | 8 --- ableos/src/stdio.rs | 5 +- ableos/src/vga_e.rs | 16 +++--- ableos/src/wasm/mod.rs | 2 +- ableos/src/wasm_jumploader/host_functions.rs | 15 +++--- ableos/src/wasm_jumploader/mod.rs | 10 ++-- kernel/Cargo.toml | 5 -- kernel/src/lib.rs | 6 +-- repbuild/Cargo.toml | 6 +-- repbuild/src/main.rs | 16 +++--- 35 files changed, 218 insertions(+), 314 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4df9a1..b912d59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,7 +37,6 @@ dependencies = [ "genfs", "hashbrown 0.7.2", "kernel", - "lazy_static", "libwasm", "linked_list_allocator", "lliw", @@ -53,7 +52,7 @@ dependencies = [ "rkyv", "serde", "shadeable", - "spin 0.5.2", + "spin", "toml", "uart_16550", "unicode-width", @@ -274,7 +273,7 @@ dependencies = [ "bitflags", "genfs", "rlibc", - "spin 0.9.2", + "spin", ] [[package]] @@ -384,7 +383,6 @@ dependencies = [ name = "kernel" version = "0.1.2" dependencies = [ - "lazy_static", "log", "versioning", ] @@ -394,9 +392,6 @@ name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -dependencies = [ - "spin 0.5.2", -] [[package]] name = "libc" @@ -842,12 +837,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "spin" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" - [[package]] name = "spin" version = "0.9.2" diff --git a/ableos/Cargo.toml b/ableos/Cargo.toml index 9e7c935..6f5926d 100644 --- a/ableos/Cargo.toml +++ b/ableos/Cargo.toml @@ -34,6 +34,7 @@ run-args = [ "unix:../qmp-sock,server,nowait" ] + test-args = [ "-device", "isa-debug-exit,iobase=0xf4,iosize=0x04", @@ -41,12 +42,10 @@ test-args = [ "stdio", ] - - [dependencies] linked_list_allocator = "0.9.0" lliw = "0.2.0" -spin = "0.5.2" +spin = "0.9" log = "*" pretty-hex = "0.2.1" unicode-width = "0.1.7" @@ -56,39 +55,32 @@ genfs = "0.1.0" rhai = "1.6.0" libwasm = {git="https://git.ablecorp.us:443/able/libwasm.git"} acpi = "4.1.0" - axel = { git = "https://git.ablecorp.us/able/aos_userland" } - - - [dependencies.logos] -version = "0.12.0" +version = "0.12" default-features = false features = ["export_derive"] [dependencies.rdrand] -version = "0.8.1" +version = "0.8" default-features = false [dependencies.kernel] path = "../kernel" [dependencies.serde] -version = "1.0.136" +version = "1.0" default-features = false features = ["derive", "alloc"] [dependencies.hashbrown] -version = "0.7.2" +version = "0.7" default-features = false features = ["inline-more"] - - - [dependencies.rkyv] -version = "0.7.29" +version = "0.7" default-features = false features = ["size_64", "alloc"] @@ -103,15 +95,11 @@ git = "https://git.ablecorp.us:443/able/y-compositor-protocol.git" [dependencies.ext2] git = "https://git.ablecorp.us:443/able/ext2-rs.git" - - - [dependencies.toml] git = "https://github.com/diondokter/toml-rs" # version = "0.5.8" default-features = false - [dependencies.shadeable] path = "../shadeable" @@ -128,10 +116,6 @@ default-features = false features = ["core"] version = "*" -[dependencies.lazy_static] -features = ["spin_no_std"] -version = "1.0" - [dependencies.externc-libm] git = "https://git.ablecorp.us:443/able/externc-libm.git" diff --git a/ableos/src/alias_table/mod.rs b/ableos/src/alias_table/mod.rs index 3457b66..24be091 100644 --- a/ableos/src/alias_table/mod.rs +++ b/ableos/src/alias_table/mod.rs @@ -1,8 +1,7 @@ use hashbrown::HashMap; -lazy_static::lazy_static! { - pub static ref ALIAS_TABLE: spin::Mutex = spin::Mutex::new(AliasTable::new()); -} +pub static ALIAS_TABLE: spin::Mutex = spin::Mutex::new(AliasTable::new()); + /// A table of aliases /// /// This is used to allow users to specify aliases for files and commands diff --git a/ableos/src/arch/x86_64/drivers/serial.rs b/ableos/src/arch/x86_64/drivers/serial.rs index e34f4f4..dc47c9c 100644 --- a/ableos/src/arch/x86_64/drivers/serial.rs +++ b/ableos/src/arch/x86_64/drivers/serial.rs @@ -1,13 +1,12 @@ -use lazy_static::lazy_static; -use spin::Mutex; +use spin::{Lazy, Mutex}; use uart_16550::SerialPort; -lazy_static! { - pub static ref SERIAL1: Mutex = { - let mut serial_port = unsafe { SerialPort::new(0x3F8) }; - serial_port.init(); - Mutex::new(serial_port) - }; -} + +pub static SERIAL1: Lazy> = Lazy::new(|| { + let mut serial_port = unsafe { SerialPort::new(0x3F8) }; + serial_port.init(); + Mutex::new(serial_port) +}); + #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; diff --git a/ableos/src/arch/x86_64/drivers/vga.rs b/ableos/src/arch/x86_64/drivers/vga.rs index 669b8ba..a157353 100644 --- a/ableos/src/arch/x86_64/drivers/vga.rs +++ b/ableos/src/arch/x86_64/drivers/vga.rs @@ -23,7 +23,7 @@ pub enum Color { #[repr(transparent)] struct ColorCode(u8); impl ColorCode { - fn new(foreground: Color, background: Color) -> ColorCode { + const fn new(foreground: Color, background: Color) -> ColorCode { ColorCode((background as u8) << 4 | (foreground as u8)) } } @@ -114,17 +114,17 @@ impl fmt::Write for Writer { Ok(()) } } -lazy_static! { - pub static ref WRITER: Mutex = Mutex::new(Writer { + +pub static WRITER: Lazy> = Lazy::new(|| { + Mutex::new(Writer { column_position: 0, color_code: ColorCode::new(Color::White, Color::Black), buffer: unsafe { &mut *(0xb8000 as *mut Buffer) }, - }); -} + }) +}); use core::fmt; -use lazy_static::lazy_static; -use spin::Mutex; +use spin::{Lazy, Mutex}; use volatile::Volatile; diff --git a/ableos/src/arch/x86_64/gdt.rs b/ableos/src/arch/x86_64/gdt.rs index 3a0ff77..96b7c42 100644 --- a/ableos/src/arch/x86_64/gdt.rs +++ b/ableos/src/arch/x86_64/gdt.rs @@ -1,39 +1,39 @@ -use lazy_static::lazy_static; +use spin::Lazy; use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector}; use x86_64::structures::tss::TaskStateSegment; use x86_64::VirtAddr; pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; -lazy_static! { - static ref TSS: TaskStateSegment = { - let mut tss = TaskStateSegment::new(); - tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = { - const STACK_SIZE: usize = 4096 * 5; - static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE]; - let stack_start = VirtAddr::from_ptr(unsafe { &STACK }); - stack_start + STACK_SIZE - }; - tss +static TSS: Lazy = Lazy::new(|| { + let mut tss = TaskStateSegment::new(); + tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = { + const STACK_SIZE: usize = 4096 * 5; + static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE]; + + let stack_start = VirtAddr::from_ptr(unsafe { &STACK }); + stack_start + STACK_SIZE }; -} + tss +}); + +static GDT: Lazy<(GlobalDescriptorTable, Selectors)> = Lazy::new(|| { + let mut gdt = GlobalDescriptorTable::new(); + let code_selector = gdt.add_entry(Descriptor::kernel_code_segment()); + let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS)); + ( + gdt, + Selectors { + code_selector, + tss_selector, + }, + ) +}); + struct Selectors { code_selector: SegmentSelector, tss_selector: SegmentSelector, } -lazy_static! { - static ref GDT: (GlobalDescriptorTable, Selectors) = { - let mut gdt = GlobalDescriptorTable::new(); - let code_selector = gdt.add_entry(Descriptor::kernel_code_segment()); - let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS)); - ( - gdt, - Selectors { - code_selector, - tss_selector, - }, - ) - }; -} + pub fn init() { use x86_64::instructions::segmentation::{Segment, CS}; use x86_64::instructions::tables::load_tss; diff --git a/ableos/src/arch/x86_64/interrupts.rs b/ableos/src/arch/x86_64/interrupts.rs index b7f647e..28c4822 100644 --- a/ableos/src/arch/x86_64/interrupts.rs +++ b/ableos/src/arch/x86_64/interrupts.rs @@ -6,9 +6,8 @@ use crate::{ }; use cpuio::outb; -use lazy_static::lazy_static; use pic8259::ChainedPics; -use spin; +use spin::Lazy; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame}; pub const PIC_1_OFFSET: u8 = 32; pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8; @@ -35,27 +34,26 @@ impl InterruptIndex { pub fn init_idt() { IDT.load(); } -lazy_static! { - static ref IDT: InterruptDescriptorTable = { - let mut idt = InterruptDescriptorTable::new(); - idt.breakpoint.set_handler_fn(breakpoint_handler); - unsafe { - idt.double_fault.set_handler_fn(double_fault_handler) - .set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX); - } - // This gives fast interrupts - set_pit_frequency(1000); +static IDT: Lazy = Lazy::new(|| { + let mut idt = InterruptDescriptorTable::new(); + idt.breakpoint.set_handler_fn(breakpoint_handler); + unsafe { + idt.double_fault + .set_handler_fn(double_fault_handler) + .set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX); + } - idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler); - idt[InterruptIndex::Keyboard.as_usize()] .set_handler_fn(keyboard_interrupt_handler); + // This gives fast interrupts + set_pit_frequency(1000); - idt[6].set_handler_fn(floppy_disk_interrupt_handler); + idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler); + idt[InterruptIndex::Keyboard.as_usize()].set_handler_fn(keyboard_interrupt_handler); + idt[6].set_handler_fn(floppy_disk_interrupt_handler); - idt - }; -} + idt +}); extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) { println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame); @@ -84,14 +82,15 @@ extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStac }; use spin::Mutex; use x86_64::instructions::port::Port; - lazy_static! { - static ref KEYBOARD: Mutex> = - Mutex::new(Keyboard::new( - CustomLayout::new_us104key(), - CustomScancodeSet::default(), - HandleControl::Ignore - )); - } + + static KEYBOARD: Lazy>> = Lazy::new(|| { + Mutex::new(Keyboard::new( + CustomLayout::new_us104key(), + CustomScancodeSet::default(), + HandleControl::Ignore, + )) + }); + let mut keyboard = KEYBOARD.lock(); let mut port = Port::new(0x60); let scancode: u8 = unsafe { port.read() }; diff --git a/ableos/src/arch/x86_64/mod.rs b/ableos/src/arch/x86_64/mod.rs index 56392d4..94dfd80 100644 --- a/ableos/src/arch/x86_64/mod.rs +++ b/ableos/src/arch/x86_64/mod.rs @@ -54,6 +54,5 @@ pub fn generate_process_pass() -> u128 { use rdrand::RdRand; let gen = RdRand::new().unwrap(); - let ret = (gen.try_next_u64().unwrap() as u128) << 64 | (gen.try_next_u64().unwrap() as u128); - ret + (gen.try_next_u64().unwrap() as u128) << 64 | (gen.try_next_u64().unwrap() as u128) } diff --git a/ableos/src/devices/dev_vterm.rs b/ableos/src/devices/dev_vterm.rs index 39909a1..123738f 100644 --- a/ableos/src/devices/dev_vterm.rs +++ b/ableos/src/devices/dev_vterm.rs @@ -177,30 +177,30 @@ impl CharacterDevice for VTerm { '\n' => { self.cursor_position.1 += 1; self.cursor_position.0 = 0; - return true; + true } '\r' => { self.cursor_position.0 = 0; - return true; + true } '\t' => { self.cursor_position.0 += 4; - return true; + true } '\x08' => { self.cursor_position.0 -= 1; self.characters[self.cursor_position.1 as usize][self.cursor_position.0 as usize] .character = ' '; - return true; + true } - /// This is a form feed, which is used to clear the screen + // This is a form feed, which is used to clear the screen '\x0c' => { self.characters = [[VtermCharacter { character: ' ', char_color: (0xff_ff_ff_ff, 0x00_00_00_00), style: Style::default(), }; VTERM_WIDTH as usize]; VTERM_HEIGHT as usize]; - return true; + true } _ => { @@ -213,11 +213,11 @@ impl CharacterDevice for VTerm { if self.cursor_position.0 < VTERM_WIDTH { self.cursor_position.0 += 1; - return true; + true } else { self.cursor_position.0 = 0; self.cursor_position.1 += 1; - return true; + true } } } @@ -239,8 +239,6 @@ impl CharacterDevice for VTerm { } } -lazy_static::lazy_static! { - pub static ref VIRTUAL_TERMINAL_COUNT: AtomicU32 = AtomicU32::new(0); -} +pub static VIRTUAL_TERMINAL_COUNT: AtomicU32 = AtomicU32::new(0); use core::sync::atomic::AtomicU32; use core::sync::atomic::Ordering; diff --git a/ableos/src/devices/mod.rs b/ableos/src/devices/mod.rs index 10d61a4..01aca59 100644 --- a/ableos/src/devices/mod.rs +++ b/ableos/src/devices/mod.rs @@ -3,6 +3,7 @@ pub mod id; pub mod pci_inner; use hashbrown::HashMap; +use spin::Lazy; mod dev_vterm; use crate::devices::dev_vterm::VTerm; use kernel::device_interface::character::CharacterDevice; @@ -10,7 +11,7 @@ use kernel::device_interface::character::CharacterDevice; // #[derive(Debug)] pub enum Device { Character(Box), - Vterm(VTerm), + Vterm(Box), } unsafe impl Sync for Device {} unsafe impl Send for Device {} @@ -32,12 +33,10 @@ impl DeviceTable { next_read_char: 0x00 as char, })), ); - table.insert("kvterm".to_string(), Vterm(VTerm::new())); + table.insert("kvterm".to_string(), Vterm(Box::new(VTerm::new()))); DeviceTable { devices: table } } } -lazy_static::lazy_static!( - pub static ref DEVICE_TABLE: spin::Mutex = - spin::Mutex::new(DeviceTable::new()); -); +pub static DEVICE_TABLE: Lazy> = + Lazy::new(|| spin::Mutex::new(DeviceTable::new())); diff --git a/ableos/src/driver_traits/serial.rs b/ableos/src/driver_traits/serial.rs index 075d686..56f87ac 100644 --- a/ableos/src/driver_traits/serial.rs +++ b/ableos/src/driver_traits/serial.rs @@ -16,7 +16,7 @@ impl CharacterDevice for Serial { todo!() } - fn write_char(&mut self, c: char) -> bool { + fn write_char(&mut self, _c: char) -> bool { todo!() } diff --git a/ableos/src/experiments/absi.rs b/ableos/src/experiments/absi.rs index 5c60c87..36cbfa1 100644 --- a/ableos/src/experiments/absi.rs +++ b/ableos/src/experiments/absi.rs @@ -1,7 +1,7 @@ // TODO improve tokenizer/parser pub fn colorify(eval: &str) { - let y = eval.split("$"); + let y = eval.split('$'); for z in y { match z { "BLACK" => { @@ -55,7 +55,7 @@ pub fn colorify(eval: &str) { "RESET" => { // set_vga_color(Color::White, Color::Black); } - elk => { + _elk => { // kprint!("{}", elk); } } @@ -91,7 +91,7 @@ pub fn colorify_2(eval: &str) { Reset => { // set_vga_color(Color::White, Color::Black); } - Text(text) => { + Text(_text) => { // kprint!("{}", text); } err => { diff --git a/ableos/src/experiments/clip.rs b/ableos/src/experiments/clip.rs index f5f7284..6a72587 100644 --- a/ableos/src/experiments/clip.rs +++ b/ableos/src/experiments/clip.rs @@ -1,19 +1,14 @@ use alloc::{string::String, vec, vec::Vec}; // use crate::String; // use crate::Vec; -use lazy_static::lazy_static; + #[derive(Debug)] pub enum Mime { None, Text(String), } -lazy_static! { - pub static ref CLIPBOARD: spin::Mutex = { - let clipboard = Clipboard::new(); - spin::Mutex::new(clipboard) - }; -} +pub static CLIPBOARD: spin::Mutex = spin::Mutex::new(Clipboard::new()); // ctrl+v paste but not pop and pastes // ctrl+shift+v pops from the stack and pastes @@ -26,29 +21,34 @@ pub struct Clipboard { pub pages: Vec, } impl Clipboard { - pub fn new() -> Clipboard { + pub const fn new() -> Clipboard { Clipboard { index: 0, pages: vec![], } } + pub fn clear(&mut self) { self.pages = vec![]; } + pub fn set_index(&mut self, index_new: usize) { self.index = index_new; } + pub fn clip_end(&mut self) { self.index = 0; } + pub fn clip_home(&mut self) { self.index = self.pages.len(); } + pub fn copy(&mut self, copy_mime: Mime) { self.pages.push(copy_mime); } + pub fn paste(&mut self) -> &Mime { - let paste_pos = &self.pages[self.index]; - paste_pos + &self.pages[self.index] as _ } } diff --git a/ableos/src/experiments/info.rs b/ableos/src/experiments/info.rs index 3455af3..35b9908 100644 --- a/ableos/src/experiments/info.rs +++ b/ableos/src/experiments/info.rs @@ -445,7 +445,7 @@ impl Clone for BrandString { for (d, s) in bytes.iter_mut().zip(self.bytes.iter()) { *d = *s; } - BrandString { bytes: bytes } + BrandString { bytes } } } @@ -752,12 +752,12 @@ impl Master { let tpm = when_supported( max_value, RequestType::ThermalPowerManagementInformation, - || ThermalPowerManagementInformation::new(), + ThermalPowerManagementInformation::new, ); let sei = when_supported( max_value, RequestType::StructuredExtendedInformation, - || StructuredExtendedInformation::new(), + StructuredExtendedInformation::new, ); // Extended information @@ -767,9 +767,8 @@ impl Master { let eps = when_supported(max_value, RequestType::ExtendedProcessorSignature, || { ExtendedProcessorSignature::new() }); - let brand_string = - when_supported(max_value, RequestType::BrandString3, || BrandString::new()); - let cache_line = when_supported(max_value, RequestType::CacheLine, || CacheLine::new()); + let brand_string = when_supported(max_value, RequestType::BrandString3, BrandString::new); + let cache_line = when_supported(max_value, RequestType::CacheLine, CacheLine::new); let tsc = when_supported(max_value, RequestType::TimeStampCounter, || { TimeStampCounter::new() }); @@ -782,8 +781,8 @@ impl Master { thermal_power_management_information: tpm, structured_extended_information: sei, extended_processor_signature: eps, - brand_string: brand_string, - cache_line: cache_line, + brand_string, + cache_line, time_stamp_counter: tsc, physical_address_size: pas, } @@ -807,7 +806,7 @@ impl Master { self.brand_string .as_ref() .map(|bs| bs as &str) - .or(self.version_information.and_then(|vi| vi.brand_string())) + .or_else(|| self.version_information.and_then(|vi| vi.brand_string())) } delegate_flag!(version_information, { diff --git a/ableos/src/experiments/kinfo.rs b/ableos/src/experiments/kinfo.rs index c048f78..039201d 100644 --- a/ableos/src/experiments/kinfo.rs +++ b/ableos/src/experiments/kinfo.rs @@ -11,16 +11,14 @@ impl core::fmt::Display for SemanticVersion { } } // NOTE: Move to somewhere else -lazy_static! { - pub static ref KINFO: KernelInfo = KernelInfo { - kernel_version: SemanticVersion { - major: 0, - minor: 0, - patch: 0, - }, - memory: SystemMemory { used: 0, total: 0 } - }; -} +pub static KINFO: KernelInfo = KernelInfo { + kernel_version: SemanticVersion { + major: 0, + minor: 0, + patch: 0, + }, + memory: SystemMemory { used: 0, total: 0 }, +}; /// simple info you would want to know in a neofetch like program pub struct KernelInfo { // os: String, @@ -31,4 +29,3 @@ pub struct KernelInfo { pub memory: SystemMemory, } use super::systeminfo::SystemMemory; -use lazy_static::lazy_static; diff --git a/ableos/src/filesystem/mod.rs b/ableos/src/filesystem/mod.rs index 00afa56..f564f18 100644 --- a/ableos/src/filesystem/mod.rs +++ b/ableos/src/filesystem/mod.rs @@ -6,24 +6,23 @@ use ext2::{ sector::{SectorSize, Size1024}, volume::Volume, }; +use spin::Lazy; fn load_fs() -> Synced>> { let mut volume = Vec::new(); volume.extend_from_slice(include_bytes!("../../../userland/root_fs/ext2.img")); - let fs = Synced::>::new(volume).unwrap(); - - fs + Synced::>::new(volume).unwrap() } // use serde::__private::from_utf8_lossy; -pub fn walk<'vol, S: SectorSize, V: Volume>( - fs: &'vol Synced>, +pub fn walk>( + fs: &Synced>, inode: Inode, name: String, ) { - inode.directory().map(|dir| { + if let Some(dir) = inode.directory() { for entry in dir { assert!(entry.is_ok()); let entry = entry.unwrap(); @@ -38,8 +37,8 @@ pub fn walk<'vol, S: SectorSize, V: Volume>( ); } } - }); + } } -lazy_static::lazy_static!( - pub static ref FILE_SYSTEM:spin::Mutex>>>= spin::Mutex::new(load_fs()); -); + +pub static FILE_SYSTEM: Lazy>>>> = + Lazy::new(|| spin::Mutex::new(load_fs())); diff --git a/ableos/src/graphics/mod.rs b/ableos/src/graphics/mod.rs index e4f7b52..2275124 100644 --- a/ableos/src/graphics/mod.rs +++ b/ableos/src/graphics/mod.rs @@ -2,7 +2,7 @@ use ab_glyph::{Font, FontRef, Glyph}; use shadeable::{evaluate_shader, pixel_format::Rgba64}; -use spin; +use spin::Lazy; // use vga::{colors::Color16, writers::GraphicsWriter}; #[derive(Debug)] @@ -15,10 +15,8 @@ const FONT_SCALE: f32 = 1.6; const GLYPH_HEIGHT: f32 = 18.0; const GLYPH_WIDTH: f32 = 10.0; -lazy_static::lazy_static! { - pub static ref SCREEN_BUFFER: spin::Mutex = spin::Mutex::new(ScreenBuffer::new(640, 480)); - -} +pub static SCREEN_BUFFER: Lazy> = + Lazy::new(|| spin::Mutex::new(ScreenBuffer::new(640, 480))); impl ScreenSize { pub fn new(x: usize, y: usize) -> Self { @@ -46,6 +44,7 @@ impl ScreenBuffer { buff: vec![0u64; x * y].into_boxed_slice(), } } + pub fn draw_filled_circle(&mut self, cx: i32, cy: i32, radius: usize, color: Rgba64) { let r = radius as i32 * 2; for y in 0..640 { diff --git a/ableos/src/kernel_state.rs b/ableos/src/kernel_state.rs index 78f8d14..be421b2 100644 --- a/ableos/src/kernel_state.rs +++ b/ableos/src/kernel_state.rs @@ -1,9 +1,7 @@ -use lazy_static::lazy_static; +use spin::Lazy; -lazy_static! { - pub static ref KERNEL_STATE: spin::Mutex = - spin::Mutex::new(KernelInternalState::new()); -} +pub static KERNEL_STATE: Lazy> = + Lazy::new(|| spin::Mutex::new(KernelInternalState::new())); pub struct KernelInternalState { pub hostname: String, diff --git a/ableos/src/kmain.rs b/ableos/src/kmain.rs index 785db52..567c039 100644 --- a/ableos/src/kmain.rs +++ b/ableos/src/kmain.rs @@ -5,19 +5,15 @@ // use crate::{scratchpad, SCHEDULER, SCREEN_BUFFER}; -use { - crate::{ - arch::{init, sloop}, - relib::network::socket::{SimpleSock, Socket}, - scratchpad, - }, - lazy_static::lazy_static, +use crate::{ + arch::{init, sloop}, + relib::network::socket::{SimpleSock, Socket}, + scratchpad, }; +use spin::Lazy; -lazy_static! { - // TODO: Change this structure to allow for multiple cores loaded - pub static ref KERNEL_CONF: KernelConfig = KernelConfig::new(); -} +// TODO: Change this structure to allow for multiple cores loaded +pub static KERNEL_CONF: Lazy = Lazy::new(KernelConfig::new); /// The main entry point of the kernel #[no_mangle] @@ -29,7 +25,7 @@ pub fn kernel_main() -> ! { } else { log::set_max_level(log::LevelFilter::Off); } - let mut scheduler = SCHEDULER.lock(); + let scheduler = SCHEDULER.lock(); for proc in &scheduler.execution_queue { trace!("{:?}", proc); } @@ -63,6 +59,4 @@ use crate::info::master; use kernel::KERNEL_VERSION; use crate::scheduler::SCHEDULER; -use crate::{ - boot_conf::KernelConfig, scheduler::capabilities::FileAccess, systeminfo::RELEASE_TYPE, -}; +use crate::{boot_conf::KernelConfig, systeminfo::RELEASE_TYPE}; diff --git a/ableos/src/logger.rs b/ableos/src/logger.rs index d2b855e..da830e2 100644 --- a/ableos/src/logger.rs +++ b/ableos/src/logger.rs @@ -1,10 +1,7 @@ -use crate::boot_conf; use crate::kmain::KERNEL_CONF; use crate::network::socket::{SimpleSock, Socket}; use crate::time::fetch_time; -use core::sync::atomic::Ordering; -use kernel::TICK; use lliw::{Fg, Reset}; use log::{Level, Metadata, Record}; @@ -18,17 +15,16 @@ impl log::Log for SimpleLogger { } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { - let color; - let time_float = fetch_time(); - match record.level() { - log::Level::Error => color = (Fg::Red, "$RED$"), - log::Level::Warn => color = (Fg::LightYellow, "$LIGHTYELLOW$"), - log::Level::Info => color = (Fg::LightWhite, "$LIGHTGRAY$"), - log::Level::Debug => color = (Fg::Blue, "$BLUE$"), - log::Level::Trace => color = (Fg::Yellow, "$YELLOW$"), - } + let color = match record.level() { + log::Level::Error => (Fg::Red, "$RED$"), + log::Level::Warn => (Fg::LightYellow, "$LIGHTYELLOW$"), + log::Level::Info => (Fg::LightWhite, "$LIGHTGRAY$"), + log::Level::Debug => (Fg::Blue, "$BLUE$"), + log::Level::Trace => (Fg::Yellow, "$YELLOW$"), + }; + let msg = format!( "[{}{}$RESET$][$GREEN${}$RESET$]{}\n", color.1, diff --git a/ableos/src/relib/clparse/mod.rs b/ableos/src/relib/clparse/mod.rs index 818d27b..ef4b370 100644 --- a/ableos/src/relib/clparse/mod.rs +++ b/ableos/src/relib/clparse/mod.rs @@ -19,25 +19,22 @@ pub struct Command { impl Command { pub fn parse(command: String) -> Command { - let split_command = command.split("?"); + let split_command = command.split('?'); let mut root = "".to_string(); - let mut root_count = 0; let mut args: Vec = vec![]; - for subcommand in split_command { + for (root_count, subcommand) in split_command.enumerate() { match root_count { 0 => root = subcommand.to_string(), 1 => { - for subarg in subcommand.split("&") { + for subarg in subcommand.split('&') { let mut arg1 = ""; let mut arg2 = ""; - let mut arg_count = 0; - for arg in subarg.split("=") { - if arg_count == 0 { + for (n, arg) in subarg.split('=').enumerate() { + if n == 0 { arg1 = arg; } else { arg2 = arg; } - arg_count += 1; } let arg_struct = Argument { key: arg1.to_string(), @@ -48,7 +45,6 @@ impl Command { } _ => {} } - root_count += 1; } Command { diff --git a/ableos/src/relib/encoding/rle.rs b/ableos/src/relib/encoding/rle.rs index fcd4e8c..abcd216 100644 --- a/ableos/src/relib/encoding/rle.rs +++ b/ableos/src/relib/encoding/rle.rs @@ -1,11 +1,9 @@ pub fn encode(bytes: &[u8]) -> Vec { - let mut encoding; - - if bytes.first().is_none() { + let mut encoding = if bytes.first().is_none() { return vec![]; } else { - encoding = vec![*bytes.first().unwrap()]; - } + vec![*bytes.first().unwrap()] + }; let mut occurrences = 1; diff --git a/ableos/src/relib/network/socket.rs b/ableos/src/relib/network/socket.rs index 9e35600..0a546f0 100644 --- a/ableos/src/relib/network/socket.rs +++ b/ableos/src/relib/network/socket.rs @@ -7,12 +7,7 @@ pub struct SocketID { impl SocketID { pub fn protocol(self) -> Option { - let x = SOCKETS.lock()[self.id].protocol.clone(); - - match x { - Some(protocol_name) => Some(protocol_name), - None => None, - } + SOCKETS.lock()[self.id].protocol.clone() } } @@ -38,10 +33,8 @@ impl Socket for SocketID { } pub type SocketState = Vec; +pub static SOCKETS: spin::Mutex = spin::Mutex::new(vec![]); -lazy_static::lazy_static! { - pub static ref SOCKETS: spin::Mutex = spin::Mutex::new(vec![]); -} pub trait Socket { fn peek(&mut self) -> SocketReturns; @@ -116,7 +109,7 @@ impl Socket for SimpleSock { let mut return_vec = vec![]; for x in &self.stream { - return_vec.push(x.clone()); + return_vec.push(*x); } SocketReturns::ReadOk(return_vec) } diff --git a/ableos/src/rhai_shell/mod.rs b/ableos/src/rhai_shell/mod.rs index b0352c7..74e157b 100644 --- a/ableos/src/rhai_shell/mod.rs +++ b/ableos/src/rhai_shell/mod.rs @@ -1,9 +1,11 @@ +use spin::Lazy; + #[cfg(target_arch = "riscv64")] pub fn shell() {} #[cfg(target_arch = "x86_64")] pub fn shell() { - let mut current_dir = "/".to_string(); + let _current_dir = "/".to_string(); let engine = engine_construction(); let mut scope = rhai::Scope::new(); @@ -38,10 +40,9 @@ pub fn shell() { } } } -lazy_static::lazy_static!( - pub static ref KEYBUFF: spin::Mutex> = spin::Mutex::new(Vec::new()); - pub static ref CURRENT_DIR: spin::Mutex = spin::Mutex::new("/".to_string()); -); + +pub static KEYBUFF: spin::Mutex> = spin::Mutex::new(Vec::new()); +pub static CURRENT_DIR: Lazy> = Lazy::new(|| spin::Mutex::new("/".to_string())); use rhai::Engine; use x86_64::instructions::interrupts::{disable, enable}; @@ -49,7 +50,7 @@ use x86_64::instructions::interrupts::{disable, enable}; use crate::info::master; use crate::time::fetch_time; use crate::wasm_jumploader::interp; -use crate::{allocator, ALLOCATOR}; +use crate::ALLOCATOR; use crate::{ arch::{shutdown, sloop}, systeminfo::{KERNEL_VERSION, RELEASE_TYPE}, @@ -114,18 +115,18 @@ fn engine_construction() -> Engine { /// Examine a memory pointer pub fn peek_memory(ptr: i64) -> u8 { - let ptr: usize = ptr.abs() as usize; + let ptr: usize = ptr.unsigned_abs() as _; println!(">:("); unsafe { *(ptr as *const u8) } } pub fn poke_memory(ptr: i64, val: u8) { - let ptr: usize = ptr.abs() as usize; + let ptr: usize = ptr.unsigned_abs() as _; unsafe { *(ptr as *mut u8) = val } } pub fn ls() { - let mut current_dir = CURRENT_DIR.lock(); + let current_dir = CURRENT_DIR.lock(); let fs = &*FILE_SYSTEM.lock(); @@ -166,7 +167,7 @@ pub fn log_dump() { } use crate::filesystem::FILE_SYSTEM; -use genfs::{DirEntry, Fs, OpenOptions}; +use genfs::{Fs, OpenOptions}; pub fn echo_file(path: String) { let mut current_dir = CURRENT_DIR.lock(); @@ -181,12 +182,10 @@ pub fn echo_file(path: String) { if file.is_dir() { println!("{} is a directory", path); - - return; } else { let mut file_contents = Vec::new(); - let ret = file.read_to_end(&mut file_contents).unwrap(); + let _ret = file.read_to_end(&mut file_contents).unwrap(); let file_contents_str = String::from_utf8_lossy(&file_contents); @@ -197,13 +196,13 @@ pub fn echo_file(path: String) { pub fn change_directory(path: String) { let mut current_dir = CURRENT_DIR.lock(); - let fs = &*FILE_SYSTEM.lock(); + let _fs = &*FILE_SYSTEM.lock(); if path == "." || path == ".." { - let mut split_dir = current_dir.split("/").collect::>(); + let mut split_dir = current_dir.split('/').collect::>(); let mut new_dir = String::new(); split_dir.remove(split_dir.len() - 1); println!("{:?}", split_dir); - if split_dir.len() == 0 { + if split_dir.is_empty() { new_dir = "/".to_string(); } else { for x in split_dir { @@ -214,7 +213,7 @@ pub fn change_directory(path: String) { *current_dir = new_dir; } else { if !current_dir.ends_with('/') { - current_dir.push_str("/"); + current_dir.push('/'); } current_dir.push_str(&path); } diff --git a/ableos/src/scheduler/mod.rs b/ableos/src/scheduler/mod.rs index db65e03..97d6bc4 100644 --- a/ableos/src/scheduler/mod.rs +++ b/ableos/src/scheduler/mod.rs @@ -38,7 +38,7 @@ pub struct Scheduler { } impl Scheduler { /// Create a new scheduler - pub fn new() -> Self { + pub const fn new() -> Self { Self { free_pid: 0, process_exec_time: 0, @@ -69,15 +69,14 @@ impl Scheduler { working_dir: String, stdio: StdIO, ) -> Process { - let mut process = Process { + Process { pid: 0, priority, working_dir, stdio, password: generate_process_pass(), capabilities, - }; - process + } } pub fn sleep_process(&mut self, process: &mut Process) { @@ -86,11 +85,9 @@ impl Scheduler { wake_condition: WakeCondition::TimerInterrupt(0), }; - self.sleeping_queue.push(sleeping_process.clone()); + self.sleeping_queue.push(sleeping_process); self.execution_queue.remove(0); } } -lazy_static::lazy_static! { - pub static ref SCHEDULER: spin::Mutex = spin::Mutex::new(Scheduler::new()); -} +pub static SCHEDULER: spin::Mutex = spin::Mutex::new(Scheduler::new()); diff --git a/ableos/src/scratchpad.rs b/ableos/src/scratchpad.rs index 50c2701..835db95 100644 --- a/ableos/src/scratchpad.rs +++ b/ableos/src/scratchpad.rs @@ -1,13 +1,7 @@ use acpi::AcpiTables; -use kernel::device_interface::character::CharacterDevice; -use crate::devices::DEVICE_TABLE; use crate::rhai_shell::shell; -use crate::stdio::StdIO; - -use crate::devices::Device::Vterm; - /// Experimental scratchpad for testing. pub fn scratchpad() { let axel_raw = "kernel{ @@ -25,8 +19,6 @@ pub fn scratchpad() { shell(); } -use core::fmt::Write; - pub fn pci_fun() {} pub fn acpi() { diff --git a/ableos/src/stdio.rs b/ableos/src/stdio.rs index c49776e..de81978 100644 --- a/ableos/src/stdio.rs +++ b/ableos/src/stdio.rs @@ -1,8 +1,5 @@ use { - crate::{ - devices::Device::{Character, Vterm}, - kprintln, - }, + crate::devices::Device::{Character, Vterm}, core::fmt::{Arguments, Error, Write}, kernel::device_interface::character::CharacterDevice, }; diff --git a/ableos/src/vga_e.rs b/ableos/src/vga_e.rs index 440be28..cf2b584 100644 --- a/ableos/src/vga_e.rs +++ b/ableos/src/vga_e.rs @@ -3,15 +3,13 @@ use vga::{ writers::{Graphics640x480x16, GraphicsWriter}, }; -lazy_static::lazy_static! { - pub static ref VGAE: spin::Mutex = { - let xyz = Graphics640x480x16::new(); - xyz.set_mode(); - spin::Mutex::new(xyz) - }; - pub static ref VGAE_BUFF_OFFSET_X: spin::Mutex = spin::Mutex::new(0); - pub static ref VGAE_BUFF_OFFSET_Y: spin::Mutex = spin::Mutex::new(0); -} +pub static VGAE: spin::Mutex = { + let xyz = Graphics640x480x16::new(); + xyz.set_mode(); + spin::Mutex::new(xyz) +}; +pub static VGAE_BUFF_OFFSET_X: spin::Mutex = spin::Mutex::new(0); +pub static VGAE_BUFF_OFFSET_Y: spin::Mutex = spin::Mutex::new(0); /// Converts a number to ... i forgor 💀 pub fn num_to_vga16(num: u8) -> Color16 { diff --git a/ableos/src/wasm/mod.rs b/ableos/src/wasm/mod.rs index 9d77b9f..4122f4f 100644 --- a/ableos/src/wasm/mod.rs +++ b/ableos/src/wasm/mod.rs @@ -104,6 +104,6 @@ impl WasmProgram { if self.raw_bytes[4..8] == WASM_VERSION { byte_version_valid = true; } - return (byte_magic_valid, byte_version_valid); + (byte_magic_valid, byte_version_valid) } } diff --git a/ableos/src/wasm_jumploader/host_functions.rs b/ableos/src/wasm_jumploader/host_functions.rs index 9d7d427..6e3db90 100644 --- a/ableos/src/wasm_jumploader/host_functions.rs +++ b/ableos/src/wasm_jumploader/host_functions.rs @@ -1,5 +1,3 @@ -use core::arch; - use wasmi::{ Error, Externals, FuncInstance, FuncRef, ModuleImportResolver, RuntimeArgs, RuntimeValue, Signature, Trap, ValueType, @@ -113,7 +111,7 @@ impl HostExternals { return false; } } - return true; + true } SEND_SIGNAL_INDEX => { let (params, ret_ty): (&[ValueType], Option) = @@ -129,7 +127,7 @@ impl HostExternals { return false; } } - return true; + true } GET_TIME_INDEX => { let (params, ret_ty): (&[ValueType], Option) = @@ -145,7 +143,7 @@ impl HostExternals { return false; } } - return true; + true } GET_RANDOM_INDEX => { let (params, ret_ty): (&[ValueType], Option) = @@ -161,7 +159,7 @@ impl HostExternals { return false; } } - return true; + true } GET_INPUT_INDEX => { let (params, ret_ty): (&[ValueType], Option) = @@ -177,7 +175,7 @@ impl HostExternals { return false; } } - return true; + true } PRINT_CLEVER_HACK => { @@ -193,7 +191,7 @@ impl HostExternals { return false; } } - return true; + true } _ => false, } @@ -228,4 +226,3 @@ impl ModuleImportResolver for HostExternals { Ok(FuncInstance::alloc_host(signature.clone(), index)) } } -use crate::wasm_jumploader::host_functions::ValueType::I32; diff --git a/ableos/src/wasm_jumploader/mod.rs b/ableos/src/wasm_jumploader/mod.rs index 751fffe..aca74b4 100644 --- a/ableos/src/wasm_jumploader/mod.rs +++ b/ableos/src/wasm_jumploader/mod.rs @@ -35,25 +35,25 @@ pub fn interp() { match instance { Ok(inst) => { - let mut instance = inst.assert_no_start(); + let instance = inst.assert_no_start(); let mut is_driver = false; - let mut is_program = false; + let _is_program = false; let mut has_driver_entry = false; let mut has_driver_exit = false; let mut has_start = false; - if let Some(val) = instance.export_by_name("driver_entry") { + if let Some(_val) = instance.export_by_name("driver_entry") { has_driver_entry = true; } - if let Some(val) = instance.export_by_name("driver_exit") { + if let Some(_val) = instance.export_by_name("driver_exit") { has_driver_exit = true; } match instance.export_by_name("start") { - Some(val) => { + Some(_val) => { trace!("Program start function found"); has_start = true; } diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index d659c11..b6b5df2 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -3,13 +3,8 @@ edition = "2021" name = "kernel" version = "0.1.2" - [dependencies] log = "0.4.14" -[dependencies.lazy_static] -version = "1.4.0" -default-features = false - [dependencies.versioning] git = "https://git.ablecorp.us/able/aos_userland" \ No newline at end of file diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs index 97cb8ef..35cc260 100644 --- a/kernel/src/lib.rs +++ b/kernel/src/lib.rs @@ -23,10 +23,8 @@ pub fn tick() { TICK.store(data, Relaxed) } -lazy_static::lazy_static! { - /// The number of ticks since the first CPU was started - pub static ref TICK: AtomicU64 = AtomicU64::new(0); -} +/// The number of ticks since the first CPU was started +pub static TICK: AtomicU64 = AtomicU64::new(0); /// pub const KERNEL_VERSION: Version = Version { diff --git a/repbuild/Cargo.toml b/repbuild/Cargo.toml index 8e2e10c..4097401 100644 --- a/repbuild/Cargo.toml +++ b/repbuild/Cargo.toml @@ -5,13 +5,9 @@ edition = "2021" authors = ["Able", "NotAble"] [dependencies] -<<<<<<< HEAD -======= -clap = { version = "3.1", features = ["cargo", "derive"] } ->>>>>>> e6dbfb4a0a4e14c8bf2ead04bb2078627f5780eb xshell = "0.1.9" anyhow = "*" [dependencies.clap] version = "3.1.8" -features = ["derive"] \ No newline at end of file +features = ["derive"] diff --git a/repbuild/src/main.rs b/repbuild/src/main.rs index 20cc699..0033dce 100644 --- a/repbuild/src/main.rs +++ b/repbuild/src/main.rs @@ -32,8 +32,8 @@ enum Command { #[derive(clap::ArgEnum, Debug, Clone)] enum MachineType { X86, - RISCV, - ARM, + Riscv, + Arm, } fn main() -> anyhow::Result<()> { @@ -51,7 +51,7 @@ fn main() -> anyhow::Result<()> { MachineType::X86 => { xshell::cmd!("cargo run --release").run()?; } - MachineType::ARM => { + MachineType::Arm => { xshell::cmd!("cargo build --release --target=json_targets/aarch64-ableos.json") .run()?; #[rustfmt::skip] @@ -65,7 +65,7 @@ fn main() -> anyhow::Result<()> { " ).run()?; } - MachineType::RISCV => { + MachineType::Riscv => { xshell::cmd!("cargo build --release --target=riscv64gc-unknown-none-elf") .run()?; #[rustfmt::skip] @@ -91,23 +91,23 @@ fn main() -> anyhow::Result<()> { MachineType::X86 => { xshell::cmd!("cargo doc --open").run()?; } - MachineType::ARM => { + MachineType::Arm => { xshell::cmd!("cargo doc --open --target=json_targets/aarch64-ableos.json") .run()?; } - MachineType::RISCV => { + MachineType::Riscv => { xshell::cmd!("cargo doc --open --target=riscv64gc-unknown-none-elf").run()?; } } } Command::Mount { path } => { - let path = path.unwrap_or("./userland/root_fs/mnt".to_string()); + let path = path.unwrap_or_else(|| "./userland/root_fs/mnt".to_string()); xshell::cmd!("sudo mount userland/root_fs/ext2.img {path}").run()?; } Command::Unmount { path } => { - let path = path.unwrap_or("./userland/root_fs/mnt".to_string()); + let path = path.unwrap_or_else(|| "./userland/root_fs/mnt".to_string()); xshell::cmd!("sudo umount {path}").run()?; } } From 91dc000502295c7b321bb4b9dd7209fb976b8a1e Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 11 Apr 2022 22:53:06 +0200 Subject: [PATCH 2/6] fixed type in feature --- ableos/.cargo/config.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ableos/.cargo/config.toml b/ableos/.cargo/config.toml index 917f998..cc0f2e3 100644 --- a/ableos/.cargo/config.toml +++ b/ableos/.cargo/config.toml @@ -7,7 +7,7 @@ build-std = ["core", "compiler_builtins", "alloc"] build-std-features = ["compiler-builtins-mem"] [target.'cfg(target_arch = "x86_64")'] -rustflags = ["-C", "target-feature=+rdrnd"] +rustflags = ["-C", "target-feature=+rdrand"] runner = "bootimage runner" [target.riscv64gc-unknown-none-elf] From a258676d20943b89b2845028ad2748dc0091581d Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 11 Apr 2022 23:02:36 +0200 Subject: [PATCH 3/6] supressed false positive --- .vscode/settings.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 08bdd4b..0814706 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,7 +2,5 @@ "files.associations": { "stddef.h": "c" }, - "settings": { - - } + "rust-analyzer.checkOnSave.allTargets": false, } \ No newline at end of file From b86d42e48ca58ff4e0e7ab2aafb88b0ac499badf Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 11 Apr 2022 23:07:01 +0200 Subject: [PATCH 4/6] Obeyed clippy, our paperclip overlord (mostly) --- ableos/src/boot_conf.rs | 9 +++++++-- ableos/src/devices/mod.rs | 6 ++++++ ableos/src/experiments/info.rs | 12 ++++++++++++ ableos/src/experiments/mail.rs | 6 ++++++ ableos/src/experiments/y_compositor/compositor.rs | 10 ++++++++-- ableos/src/kernel_state.rs | 6 ++++++ 6 files changed, 45 insertions(+), 4 deletions(-) diff --git a/ableos/src/boot_conf.rs b/ableos/src/boot_conf.rs index f875eef..e91cf25 100644 --- a/ableos/src/boot_conf.rs +++ b/ableos/src/boot_conf.rs @@ -26,8 +26,7 @@ pub struct KernelConfig { impl KernelConfig { pub fn new() -> Self { - let p: KernelConfig = toml::from_str(include_str!("../assets/kernel.toml")).unwrap(); - p + toml::from_str(include_str!("../assets/kernel.toml")).unwrap() } pub fn log_level(&self) -> LevelFilter { @@ -43,6 +42,12 @@ impl KernelConfig { } } +impl Default for KernelConfig { + fn default() -> Self { + Self::new() + } +} + #[derive(Serialize, Debug, Deserialize)] pub struct LoggingConfig { pub enabled: bool, diff --git a/ableos/src/devices/mod.rs b/ableos/src/devices/mod.rs index 01aca59..4270540 100644 --- a/ableos/src/devices/mod.rs +++ b/ableos/src/devices/mod.rs @@ -38,5 +38,11 @@ impl DeviceTable { } } +impl Default for DeviceTable { + fn default() -> Self { + Self::new() + } +} + pub static DEVICE_TABLE: Lazy> = Lazy::new(|| spin::Mutex::new(DeviceTable::new())); diff --git a/ableos/src/experiments/info.rs b/ableos/src/experiments/info.rs index 35b9908..be9ede0 100644 --- a/ableos/src/experiments/info.rs +++ b/ableos/src/experiments/info.rs @@ -286,6 +286,12 @@ impl VersionInformation { }); } +impl Default for VersionInformation { + fn default() -> Self { + Self::new() + } +} + impl fmt::Debug for VersionInformation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { dump!(self, f, "VersionInformation", { @@ -921,6 +927,12 @@ impl Master { delegate_flag!(time_stamp_counter, { invariant_tsc }); } + +impl Default for Master { + fn default() -> Self { + Self::new() + } +} /* cfg_if! { if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] { diff --git a/ableos/src/experiments/mail.rs b/ableos/src/experiments/mail.rs index 6470643..0613498 100644 --- a/ableos/src/experiments/mail.rs +++ b/ableos/src/experiments/mail.rs @@ -101,3 +101,9 @@ impl MailBoxes { ); } } + +impl Default for MailBoxes { + fn default() -> Self { + Self::new() + } +} diff --git a/ableos/src/experiments/y_compositor/compositor.rs b/ableos/src/experiments/y_compositor/compositor.rs index 2ea6da0..03fb0be 100644 --- a/ableos/src/experiments/y_compositor/compositor.rs +++ b/ableos/src/experiments/y_compositor/compositor.rs @@ -1,7 +1,13 @@ -pub struct Compositor {} +pub struct Compositor; impl Compositor { pub fn new() -> Self { - Self {} + Self + } +} + +impl Default for Compositor { + fn default() -> Self { + Self::new() } } diff --git a/ableos/src/kernel_state.rs b/ableos/src/kernel_state.rs index be421b2..52ec371 100644 --- a/ableos/src/kernel_state.rs +++ b/ableos/src/kernel_state.rs @@ -28,3 +28,9 @@ impl KernelInternalState { } } } + +impl Default for KernelInternalState { + fn default() -> Self { + Self::new() + } +} From 9ed7dbb34c29b9b5e34c9a06af038345c9a1e3ae Mon Sep 17 00:00:00 2001 From: Erin Date: Tue, 12 Apr 2022 00:23:11 +0200 Subject: [PATCH 5/6] chore: fmt --- ableos/src/alias_table/mod.rs | 1 + ableos/src/allocator/aalloc.rs | 5 +- ableos/src/allocator/mod.rs | 16 +- ableos/src/arch/aarch64/drivers/allocator.rs | 1 - ableos/src/arch/aarch64/drivers/graphics.rs | 6 + ableos/src/arch/aarch64/drivers/nrf52.rs | 57 +-- ableos/src/arch/aarch64/mod.rs | 9 +- ableos/src/arch/riscv/drivers/allocator.rs | 1 - ableos/src/arch/riscv/drivers/graphics.rs | 6 + ableos/src/arch/riscv/drivers/mmio.rs | 1 - ableos/src/arch/riscv/drivers/uart.rs | 5 +- ableos/src/arch/riscv/mod.rs | 14 +- ableos/src/arch/x86_64/drivers/allocator.rs | 4 +- ableos/src/arch/x86_64/drivers/graphics.rs | 7 + ableos/src/arch/x86_64/drivers/mod.rs | 3 +- ableos/src/arch/x86_64/drivers/serial.rs | 2 + ableos/src/arch/x86_64/drivers/vga.rs | 25 +- ableos/src/arch/x86_64/gdt.rs | 11 +- ableos/src/arch/x86_64/init.rs | 14 +- ableos/src/arch/x86_64/interrupts.rs | 15 +- ableos/src/arch/x86_64/memory.rs | 1 - ableos/src/arch/x86_64/mod.rs | 22 +- ableos/src/devices/character_devs/dev_null.rs | 2 - .../src/devices/character_devs/dev_unicode.rs | 1 + ableos/src/devices/character_devs/dev_zero.rs | 1 - ableos/src/devices/character_devs/mod.rs | 1 - ableos/src/devices/dev_vterm.rs | 36 +- ableos/src/devices/id.rs | 3 +- ableos/src/devices/mod.rs | 48 +- ableos/src/devices/pci_inner.rs | 6 +- ableos/src/driver_traits/graphics.rs | 22 +- ableos/src/driver_traits/mouse.rs | 2 - ableos/src/driver_traits/serial.rs | 2 + ableos/src/experiments/absi.rs | 8 +- ableos/src/experiments/clip.rs | 7 +- ableos/src/experiments/futex.rs | 9 +- ableos/src/experiments/info.rs | 114 +++-- ableos/src/experiments/kinfo.rs | 30 +- ableos/src/experiments/mail.rs | 4 + ableos/src/experiments/mod.rs | 2 +- ableos/src/experiments/notification.rs | 1 - ableos/src/experiments/pkg.rs | 3 +- ableos/src/experiments/server.rs | 3 + ableos/src/experiments/systeminfo.rs | 43 +- ableos/src/experiments/virtual_memory.rs | 2 +- .../experiments/y_compositor/compositor.rs | 1 - ableos/src/experiments/y_compositor/window.rs | 5 +- ableos/src/experiments/y_compositor/wm.rs | 1 - ableos/src/filesystem/mod.rs | 18 +- ableos/src/graphics/mod.rs | 53 +- .../keyboard/abstractions/custom_layout.rs | 464 ++++++++++++++---- .../abstractions/custom_scancode_set.rs | 7 + .../src/keyboard/abstractions/layout_entry.rs | 14 +- ableos/src/keyboard/abstractions/mod.rs | 2 - ableos/src/keyboard/mod.rs | 23 +- ableos/src/keyboard/small_types.rs | 15 + ableos/src/keyboard/traits.rs | 7 +- ableos/src/kmain.rs | 16 +- ableos/src/lib.rs | 93 ++-- ableos/src/logger.rs | 11 +- ableos/src/port_io.rs | 1 + ableos/src/prelude/rust_2021.rs | 9 +- ableos/src/print.rs | 6 +- ableos/src/relib/clparse/mod.rs | 8 +- ableos/src/relib/encoding/rle.rs | 3 +- ableos/src/relib/image/mod.rs | 2 - ableos/src/relib/image/mono_bitmap.rs | 4 +- .../relib/image/stupid_simple_image/mod.rs | 6 - ableos/src/relib/network/socket.rs | 12 +- ableos/src/relib/time/kilotime.rs | 39 +- ableos/src/relib/time/mod.rs | 7 +- ableos/src/rhai_shell/mod.rs | 87 ++-- ableos/src/scheduler/capabilities.rs | 1 + ableos/src/scheduler/mod.rs | 17 +- ableos/src/scheduler/proc.rs | 2 - ableos/src/scratchpad.rs | 37 +- ableos/src/serial_print.rs | 6 +- ableos/src/stdio.rs | 1 + ableos/src/tests.rs | 11 +- ableos/src/time.rs | 5 +- ableos/src/unicode_utils.rs | 2 +- ableos/src/usb/mod.rs | 7 +- ableos/src/utils.rs | 20 +- ableos/src/vga_e.rs | 7 +- ableos/src/wasm/mod.rs | 1 + ableos/src/wasm_jumploader/host_functions.rs | 227 ++++----- ableos/src/wasm_jumploader/mod.rs | 8 +- facepalm/src/lib.rs | 2 - kernel/src/device_interface/character/mod.rs | 5 + kernel/src/lib.rs | 25 +- kernel/src/panic.rs | 6 +- kernel/src/proccess.rs | 3 +- kernel/src/syscalls.rs | 16 +- shadeable/shaders/simple.shade | 1 - shadeable/src/engine_internals.rs | 13 +- shadeable/src/lib.rs | 5 +- shadeable/src/pixel_format.rs | 140 +----- userland/lib_syscalls/C/file_calls.c | 11 +- userland/rname/src/main.rs | 30 +- userland/wasm_pk_data/src/lib.rs | 4 +- 100 files changed, 1132 insertions(+), 971 deletions(-) delete mode 100644 ableos/src/relib/image/stupid_simple_image/mod.rs diff --git a/ableos/src/alias_table/mod.rs b/ableos/src/alias_table/mod.rs index 24be091..f009aee 100644 --- a/ableos/src/alias_table/mod.rs +++ b/ableos/src/alias_table/mod.rs @@ -15,6 +15,7 @@ impl AliasTable { table: HashMap::new(), } } + pub fn add_alias(&mut self, alias: String, path: String) { self.table.insert(alias, path); } diff --git a/ableos/src/allocator/aalloc.rs b/ableos/src/allocator/aalloc.rs index f67e60f..7c1b887 100644 --- a/ableos/src/allocator/aalloc.rs +++ b/ableos/src/allocator/aalloc.rs @@ -1,12 +1,9 @@ -/*! -The allocator to be implemented by ableOS -*/ +//! The allocator to be implemented by ableOS use alloc::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; pub struct AAloc; - unsafe impl GlobalAlloc for AAloc { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { println!("Allocating memory"); diff --git a/ableos/src/allocator/mod.rs b/ableos/src/allocator/mod.rs index d580698..00e263d 100644 --- a/ableos/src/allocator/mod.rs +++ b/ableos/src/allocator/mod.rs @@ -1,22 +1,16 @@ mod aalloc; -pub const HEAP_START: usize = 0x_4444_4444_0000; -/// 131072 bytes -// pub const HEAP_MULTIPLIER: usize = 1024; -pub const HEAP_MULTIPLIER: usize = 100000; - -pub const HEAP_BASE: usize = 100; - -pub const HEAP_SIZE: usize = HEAP_BASE * HEAP_MULTIPLIER; - use linked_list_allocator::LockedHeap; +pub const HEAP_START: usize = 0x_4444_4444_0000; +pub const HEAP_MULTIPLIER: usize = 100000; +pub const HEAP_BASE: usize = 100; +pub const HEAP_SIZE: usize = HEAP_BASE * HEAP_MULTIPLIER; + #[global_allocator] pub static ALLOCATOR: LockedHeap = LockedHeap::empty(); #[alloc_error_handler] fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! { - // error!("allocation error: {:?}", layout); - panic!("allocation error: {:?}", layout) } diff --git a/ableos/src/arch/aarch64/drivers/allocator.rs b/ableos/src/arch/aarch64/drivers/allocator.rs index 7b5f9d5..cf68c09 100644 --- a/ableos/src/arch/aarch64/drivers/allocator.rs +++ b/ableos/src/arch/aarch64/drivers/allocator.rs @@ -2,7 +2,6 @@ use alloc::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; pub struct Dummy; - unsafe impl GlobalAlloc for Dummy { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() diff --git a/ableos/src/arch/aarch64/drivers/graphics.rs b/ableos/src/arch/aarch64/drivers/graphics.rs index 66ad297..fddd6e2 100644 --- a/ableos/src/arch/aarch64/drivers/graphics.rs +++ b/ableos/src/arch/aarch64/drivers/graphics.rs @@ -7,21 +7,27 @@ impl Graphics for GraphicsBuffer { fn put_line(coords_start: Point, coords_end: Point, thickness: u32, color: Rgb) { todo!() } + fn put_rect(coords_start: Point, coords_end: Point, color: Rgb) { todo!() } + fn put_circle(coords: Point, radius: u32) { todo!() } + fn put_triangle(coords_1: Point, coords_2: Point, coords_3: Point, thickness: u32, color: Rgb) { todo!(); } + fn put_pixel(coords: Point, color: Rgb) { todo!() } + fn paint_cursor(coords: Point) { todo!() } + fn hide_cursor() {} fn show_cursor() {} fn draw() {} diff --git a/ableos/src/arch/aarch64/drivers/nrf52.rs b/ableos/src/arch/aarch64/drivers/nrf52.rs index 1aa8348..9675faf 100644 --- a/ableos/src/arch/aarch64/drivers/nrf52.rs +++ b/ableos/src/arch/aarch64/drivers/nrf52.rs @@ -1,36 +1,8 @@ +//! A not-very-useful abstraction of GPIOs in Rust #![allow(dead_code)] -// A not-very-useful abstraction of GPIOs in Rust - use core::sync::atomic::{AtomicBool, Ordering::SeqCst}; -/// A struct that represents an nRF52 Pin -pub struct Pin(u8); - -/// A struct that represents P0 of the nRF52 -pub struct Pins { - pub p0_31: Pin, -} - -impl Pins { - /// A function to obtain a Port 0 singleton structure - pub fn take() -> Self { - static TAKEN: AtomicBool = AtomicBool::new(false); - - // Enforce this as a singleton - assert!(!TAKEN.swap(true, SeqCst)); - - Self { p0_31: Pin(31) } - } -} - -/// The level of a GPIO -#[derive(Copy, Clone)] -pub enum Level { - Low, - High, -} - const REG_P0_PIN_CNF_BASE: *mut u32 = 0x5000_0700 as *mut u32; const REG_P0_OUT_SET: *mut u32 = 0x5000_0508 as *mut u32; const REG_P0_OUT_CLR: *mut u32 = 0x5000_050C as *mut u32; @@ -40,7 +12,8 @@ const PIN_CNF_INPUT_CONNECT: u32 = 0x0000_0000; const PIN_CNF_PULL_DISABLED: u32 = 0x0000_0000; const PIN_CNF_DRIVE_S0S1: u32 = 0x0000_0000; const PIN_CNF_SENSE_DISABLED: u32 = 0x0000_0000; - +/// A struct that represents an nRF52 Pin +pub struct Pin(u8); impl Pin { /// Set a pin to be a push pull output pub fn set_push_pull_output(&mut self, level: Level) { @@ -71,3 +44,27 @@ impl Pin { unsafe { core::ptr::write_volatile(REG_P0_OUT_CLR, 1 << (self.0 as u32)) } } } + +/// The level of a GPIO +#[derive(Copy, Clone)] +pub enum Level { + Low, + High, +} + +/// A struct that represents P0 of the nRF52 +pub struct Pins { + pub p0_31: Pin, +} + +impl Pins { + /// A function to obtain a Port 0 singleton structure + pub fn take() -> Self { + static TAKEN: AtomicBool = AtomicBool::new(false); + + // Enforce this as a singleton + assert!(!TAKEN.swap(true, SeqCst)); + + Self { p0_31: Pin(31) } + } +} diff --git a/ableos/src/arch/aarch64/mod.rs b/ableos/src/arch/aarch64/mod.rs index 5b045bb..04aeecb 100644 --- a/ableos/src/arch/aarch64/mod.rs +++ b/ableos/src/arch/aarch64/mod.rs @@ -1,11 +1,10 @@ -use core::ptr; - -// mod panic; pub mod drivers; pub mod init; use crate::arch::drivers::nrf52::{Level, Pins}; +use core::ptr; use core::ptr::write_volatile; + global_asm!(include_str!("boot.s")); fn delay(ticks: usize) { @@ -33,7 +32,6 @@ pub extern "C" fn not_main() { } } - // // let gpios = Pins::take(); // let mut led = gpios.p0_31; // @@ -46,14 +44,15 @@ pub extern "C" fn not_main() { // } // // led.set_push_pull_output(Level::Low); - crate::kmain::kernel_main(); + crate::kmain::kernel_main(); sloop(); } pub fn sloop() -> ! { loop {} } + pub fn print() { for byte in b"ableOS Arm 64" { const UART0: *mut u8 = 0x0900_0000 as *mut u8; diff --git a/ableos/src/arch/riscv/drivers/allocator.rs b/ableos/src/arch/riscv/drivers/allocator.rs index 7b5f9d5..cf68c09 100644 --- a/ableos/src/arch/riscv/drivers/allocator.rs +++ b/ableos/src/arch/riscv/drivers/allocator.rs @@ -2,7 +2,6 @@ use alloc::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; pub struct Dummy; - unsafe impl GlobalAlloc for Dummy { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() diff --git a/ableos/src/arch/riscv/drivers/graphics.rs b/ableos/src/arch/riscv/drivers/graphics.rs index 66ad297..fddd6e2 100644 --- a/ableos/src/arch/riscv/drivers/graphics.rs +++ b/ableos/src/arch/riscv/drivers/graphics.rs @@ -7,21 +7,27 @@ impl Graphics for GraphicsBuffer { fn put_line(coords_start: Point, coords_end: Point, thickness: u32, color: Rgb) { todo!() } + fn put_rect(coords_start: Point, coords_end: Point, color: Rgb) { todo!() } + fn put_circle(coords: Point, radius: u32) { todo!() } + fn put_triangle(coords_1: Point, coords_2: Point, coords_3: Point, thickness: u32, color: Rgb) { todo!(); } + fn put_pixel(coords: Point, color: Rgb) { todo!() } + fn paint_cursor(coords: Point) { todo!() } + fn hide_cursor() {} fn show_cursor() {} fn draw() {} diff --git a/ableos/src/arch/riscv/drivers/mmio.rs b/ableos/src/arch/riscv/drivers/mmio.rs index c34a297..a25e766 100644 --- a/ableos/src/arch/riscv/drivers/mmio.rs +++ b/ableos/src/arch/riscv/drivers/mmio.rs @@ -3,7 +3,6 @@ /// We label the mmio function unsafe since /// we will be working with raw memory. Rust cannot /// make any guarantees when we do this. -/// #[inline(always)] fn mmio_write(address: usize, offset: usize, value: u8) { // Set the pointer based off of the address diff --git a/ableos/src/arch/riscv/drivers/uart.rs b/ableos/src/arch/riscv/drivers/uart.rs index 2ca6598..6751aa8 100644 --- a/ableos/src/arch/riscv/drivers/uart.rs +++ b/ableos/src/arch/riscv/drivers/uart.rs @@ -1,6 +1,4 @@ -use core::fmt::Write; - -use core::fmt::Error; +use core::fmt::{Error, Write}; /// Initialize the UART driver by setting /// the word length, FIFOs, and interrupts @@ -113,6 +111,7 @@ impl Uart { uart_init(self.base_address); } } + // This is a slightly different syntax. Write is this "trait", meaning it is much like // an interface where we're just guaranteeing a certain function signature. In the Write // trait, one is absolutely required to be implemented, which is write_str. There are other diff --git a/ableos/src/arch/riscv/mod.rs b/ableos/src/arch/riscv/mod.rs index 8745d9d..445b13b 100644 --- a/ableos/src/arch/riscv/mod.rs +++ b/ableos/src/arch/riscv/mod.rs @@ -1,5 +1,10 @@ pub mod drivers; pub mod init; + +use crate::print; +use crate::println; +use core::arch::asm; + #[naked] #[no_mangle] unsafe extern "C" fn _boot() -> ! { @@ -31,9 +36,10 @@ unsafe extern "C" fn _boot() -> ! { } extern "C" fn _start() -> ! { + use crate::serial_println; + let uart = crate::arch::drivers::uart::Uart::new(0x1000_0000); uart.init(); - use crate::serial_println; serial_println!("Hello, world!\r"); loop { @@ -53,7 +59,6 @@ extern "C" fn _start() -> ! { } serial_println!("Serial connection closed.\r"); - sloop() } @@ -64,13 +69,8 @@ pub fn sloop() -> ! { }; } } -use core::arch::asm; pub fn shutdown() {} - -use crate::print; -use crate::println; - pub fn generate_process_pass() -> u128 { 123 } diff --git a/ableos/src/arch/x86_64/drivers/allocator.rs b/ableos/src/arch/x86_64/drivers/allocator.rs index 353e0e0..b1057be 100644 --- a/ableos/src/arch/x86_64/drivers/allocator.rs +++ b/ableos/src/arch/x86_64/drivers/allocator.rs @@ -1,6 +1,5 @@ -use alloc::alloc::{GlobalAlloc, Layout}; - use crate::allocator::{HEAP_SIZE, HEAP_START}; +use alloc::alloc::{GlobalAlloc, Layout}; use core::ptr::null_mut; use x86_64::{ structures::paging::{ @@ -9,7 +8,6 @@ use x86_64::{ VirtAddr, }; pub struct Dummy; - unsafe impl GlobalAlloc for Dummy { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() diff --git a/ableos/src/arch/x86_64/drivers/graphics.rs b/ableos/src/arch/x86_64/drivers/graphics.rs index b78999f..5933ed6 100644 --- a/ableos/src/arch/x86_64/drivers/graphics.rs +++ b/ableos/src/arch/x86_64/drivers/graphics.rs @@ -8,25 +8,32 @@ impl Graphics for GraphicsBuffer { fn put_line(coords_start: Point, coords_end: Point, thickness: u32, color: Rgb) { todo!() } + fn put_rect(coords_start: Point, coords_end: Point, color: Rgb) {} + fn put_circle(coords: Point, radius: u32) { todo!() } + fn put_triangle(coords_1: Point, coords_2: Point, coords_3: Point, thickness: u32, color: Rgb) { todo!(); } + fn put_pixel(coords: Point, color: Rgb) { todo!() } + fn paint_cursor(coords: Point) { todo!() } + fn hide_cursor() { unsafe { outw(0x0A, 0x3D4); outw(0x20, 0x3D5); } } + fn show_cursor() {} fn draw() {} fn clear() { diff --git a/ableos/src/arch/x86_64/drivers/mod.rs b/ableos/src/arch/x86_64/drivers/mod.rs index 3872f69..75821e2 100644 --- a/ableos/src/arch/x86_64/drivers/mod.rs +++ b/ableos/src/arch/x86_64/drivers/mod.rs @@ -1,8 +1,7 @@ pub mod allocator; pub mod graphics; pub mod serial; - pub mod timer; -// #[deprecated(note = "The use of hardware specific drivers for VGA is discouraged")] +#[deprecated(note = "The use of hardware specific drivers for VGA is discouraged")] pub mod vga; diff --git a/ableos/src/arch/x86_64/drivers/serial.rs b/ableos/src/arch/x86_64/drivers/serial.rs index dc47c9c..fb5eb18 100644 --- a/ableos/src/arch/x86_64/drivers/serial.rs +++ b/ableos/src/arch/x86_64/drivers/serial.rs @@ -15,6 +15,7 @@ pub fn _print(args: ::core::fmt::Arguments) { .write_fmt(args) .expect("Printing to serial failed"); } + /// Prints to the host through the serial interface. #[macro_export] macro_rules! sprint { @@ -22,6 +23,7 @@ macro_rules! sprint { $crate::arch::drivers::serial::_print(format_args!($($arg)*)); }; } + /// Prints to the host through the serial interface, appending a newline. #[macro_export] macro_rules! sprintln { diff --git a/ableos/src/arch/x86_64/drivers/vga.rs b/ableos/src/arch/x86_64/drivers/vga.rs index a157353..3fcde93 100644 --- a/ableos/src/arch/x86_64/drivers/vga.rs +++ b/ableos/src/arch/x86_64/drivers/vga.rs @@ -1,3 +1,10 @@ +use core::fmt; +use spin::{Lazy, Mutex}; +use volatile::Volatile; + +const BUFFER_HEIGHT: usize = 25; +const BUFFER_WIDTH: usize = 80; + #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] @@ -19,6 +26,7 @@ pub enum Color { Yellow = 14, White = 15, } + #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(transparent)] struct ColorCode(u8); @@ -27,23 +35,25 @@ impl ColorCode { ColorCode((background as u8) << 4 | (foreground as u8)) } } + #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(C)] struct ScreenChar { ascii_character: u8, color_code: ColorCode, } -const BUFFER_HEIGHT: usize = 25; -const BUFFER_WIDTH: usize = 80; + #[repr(transparent)] struct Buffer { chars: [[Volatile; BUFFER_WIDTH]; BUFFER_HEIGHT], } + pub struct Writer { column_position: usize, color_code: ColorCode, buffer: &'static mut Buffer, } + impl Writer { pub fn write_byte(&mut self, byte: u8) { match byte { @@ -63,6 +73,7 @@ impl Writer { } } } + pub fn write_string(&mut self, s: &str) { for byte in s.bytes() { match byte { @@ -73,6 +84,7 @@ impl Writer { } } } + fn new_line(&mut self) { for row in 1..BUFFER_HEIGHT { for col in 0..BUFFER_WIDTH { @@ -83,6 +95,7 @@ impl Writer { self.clear_row(BUFFER_HEIGHT - 1); self.column_position = 0; } + fn clear_row(&mut self, row: usize) { let blank = ScreenChar { ascii_character: b' ', @@ -108,6 +121,7 @@ impl Writer { } } } + impl fmt::Write for Writer { fn write_str(&mut self, s: &str) -> fmt::Result { self.write_string(s); @@ -123,20 +137,17 @@ pub static WRITER: Lazy> = Lazy::new(|| { }) }); -use core::fmt; -use spin::{Lazy, Mutex}; - -use volatile::Volatile; - #[macro_export] macro_rules! kprint { ($($arg:tt)*) => ($crate::arch::drivers::vga::_kprint(format_args!($($arg)*))); } + #[macro_export] macro_rules! kprintln { () => ($crate::kprint!("\n")); ($($arg:tt)*) => ($crate::kprint!("{}\n", format_args!($($arg)*))); } + #[doc(hidden)] pub fn _kprint(args: fmt::Arguments) { use core::fmt::Write; diff --git a/ableos/src/arch/x86_64/gdt.rs b/ableos/src/arch/x86_64/gdt.rs index 96b7c42..5758117 100644 --- a/ableos/src/arch/x86_64/gdt.rs +++ b/ableos/src/arch/x86_64/gdt.rs @@ -2,8 +2,14 @@ use spin::Lazy; use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector}; use x86_64::structures::tss::TaskStateSegment; use x86_64::VirtAddr; + pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; +struct Selectors { + code_selector: SegmentSelector, + tss_selector: SegmentSelector, +} + static TSS: Lazy = Lazy::new(|| { let mut tss = TaskStateSegment::new(); tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = { @@ -29,11 +35,6 @@ static GDT: Lazy<(GlobalDescriptorTable, Selectors)> = Lazy::new(|| { ) }); -struct Selectors { - code_selector: SegmentSelector, - tss_selector: SegmentSelector, -} - pub fn init() { use x86_64::instructions::segmentation::{Segment, CS}; use x86_64::instructions::tables::load_tss; diff --git a/ableos/src/arch/x86_64/init.rs b/ableos/src/arch/x86_64/init.rs index cd228fa..4da5aeb 100644 --- a/ableos/src/arch/x86_64/init.rs +++ b/ableos/src/arch/x86_64/init.rs @@ -1,16 +1,17 @@ // #![allow(clippy::print_literal)] +use super::{gdt, interrupts}; use crate::{ logger, scheduler::{capabilities::Capabilities, SCHEDULER}, serial_println, }; -use super::{gdt, interrupts}; - /// x86_64 initialization pub fn init() { - use crate::network::socket::SimpleSock; - use crate::relib::network::socket::Socket; + use crate::{ + network::socket::SimpleSock, relib::network::socket::Socket, + scheduler::priority::Priority::High, stdio::StdIO, + }; let mut log_socket_id = SimpleSock::new(); log_socket_id.register_protocol("Logger".to_string()); @@ -22,10 +23,9 @@ pub fn init() { } Err(err) => error!("{}", err), } + gdt::init(); - use crate::scheduler::priority::Priority::High; - use crate::stdio::StdIO; let mut scheduler = SCHEDULER.lock(); let process_0 = scheduler.new_process( Capabilities::empty(), @@ -34,11 +34,9 @@ pub fn init() { StdIO::new("null".to_string()), ); scheduler.add_process(process_0); - drop(scheduler); interrupts::init_idt(); - unsafe { interrupts::PICS.lock().initialize() }; x86_64::instructions::interrupts::enable(); } diff --git a/ableos/src/arch/x86_64/interrupts.rs b/ableos/src/arch/x86_64/interrupts.rs index 28c4822..fd31b7f 100644 --- a/ableos/src/arch/x86_64/interrupts.rs +++ b/ableos/src/arch/x86_64/interrupts.rs @@ -4,13 +4,14 @@ use crate::{ print, println, rhai_shell::KEYBUFF, }; - use cpuio::outb; use pic8259::ChainedPics; use spin::Lazy; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame}; + pub const PIC_1_OFFSET: u8 = 32; pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8; + pub static PICS: spin::Mutex = spin::Mutex::new(unsafe { ChainedPics::new(PIC_1_OFFSET, PIC_2_OFFSET) }); @@ -23,6 +24,7 @@ pub enum InterruptIndex { // SecondInterrupt = PIC_2_OFFSET, Cmos = 0x70, } + impl InterruptIndex { fn as_u8(self) -> u8 { self as u8 @@ -31,9 +33,6 @@ impl InterruptIndex { usize::from(self.as_u8()) } } -pub fn init_idt() { - IDT.load(); -} static IDT: Lazy = Lazy::new(|| { let mut idt = InterruptDescriptorTable::new(); @@ -58,7 +57,7 @@ static IDT: Lazy = Lazy::new(|| { extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) { println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame); } -// new + extern "x86-interrupt" fn double_fault_handler( stack_frame: InterruptStackFrame, error_code: u64, @@ -68,6 +67,7 @@ extern "x86-interrupt" fn double_fault_handler( error_code, stack_frame ); } + extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) { kernel::tick(); unsafe { @@ -75,6 +75,7 @@ extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFr .notify_end_of_interrupt(InterruptIndex::Timer.as_u8()); } } + extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) { use crate::keyboard::{ CustomLayout, CustomScancodeSet, DecodedKey, DecodedKeyKind, HandleControl, KeyCode, @@ -146,6 +147,10 @@ extern "x86-interrupt" fn floppy_disk_interrupt_handler(_stack_frame: InterruptS println!("EXCEPTION: FLOPPY DISK"); } +pub fn init_idt() { + IDT.load(); +} + fn set_pit_frequency(freq: u32) { let divisor: u16 = (1193180 / freq).try_into().unwrap(); diff --git a/ableos/src/arch/x86_64/memory.rs b/ableos/src/arch/x86_64/memory.rs index 10725d0..338daae 100644 --- a/ableos/src/arch/x86_64/memory.rs +++ b/ableos/src/arch/x86_64/memory.rs @@ -74,7 +74,6 @@ pub fn create_example_mapping( } pub struct EmptyFrameAllocator; - unsafe impl FrameAllocator for EmptyFrameAllocator { fn allocate_frame(&mut self) -> Option> { None diff --git a/ableos/src/arch/x86_64/mod.rs b/ableos/src/arch/x86_64/mod.rs index 94dfd80..35e70c7 100644 --- a/ableos/src/arch/x86_64/mod.rs +++ b/ableos/src/arch/x86_64/mod.rs @@ -1,16 +1,13 @@ -use crate::arch::drivers::allocator; -use bootloader::{entry_point, BootInfo}; -use x86_64::{ - instructions::hlt, - {structures::paging::Page, VirtAddr}, -}; - pub mod drivers; pub mod gdt; pub mod init; pub mod interrupts; pub mod memory; +use crate::arch::drivers::allocator; +use bootloader::{entry_point, BootInfo}; +use x86_64::{instructions::hlt, VirtAddr}; + entry_point![start]; #[no_mangle] pub fn start(boot_info: &'static BootInfo) -> ! { @@ -19,13 +16,12 @@ pub fn start(boot_info: &'static BootInfo) -> ! { let mut mapper = unsafe { memory::init(phys_mem_offset) }; let mut frame_allocator = unsafe { memory::BootInfoFrameAllocator::init(&boot_info.memory_map) }; - if false { - let page = Page::containing_address(VirtAddr::new(0xdeadbeaf000)); - memory::create_example_mapping(page, &mut mapper, &mut frame_allocator); - let page_ptr: *mut u64 = page.start_address().as_mut_ptr(); - unsafe { page_ptr.offset(400).write_volatile(0xf021_f077_f065_804e) }; - } + // let page = Page::containing_address(VirtAddr::new(0xdeadbeaf000)); + // memory::create_example_mapping(page, &mut mapper, &mut frame_allocator); + // + // let page_ptr: *mut u64 = page.start_address().as_mut_ptr(); + // unsafe { page_ptr.offset(400).write_volatile(0xf021_f077_f065_804e) }; allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed"); diff --git a/ableos/src/devices/character_devs/dev_null.rs b/ableos/src/devices/character_devs/dev_null.rs index cb9dff7..eef0d3b 100644 --- a/ableos/src/devices/character_devs/dev_null.rs +++ b/ableos/src/devices/character_devs/dev_null.rs @@ -1,9 +1,7 @@ use kernel::device_interface::character::CharacterDevice; #[derive(Debug, Clone, Copy, PartialEq, Eq)] - pub struct DevNull; - impl CharacterDevice for DevNull { fn can_read(&self) -> bool { true diff --git a/ableos/src/devices/character_devs/dev_unicode.rs b/ableos/src/devices/character_devs/dev_unicode.rs index 0ba0319..839c1b7 100644 --- a/ableos/src/devices/character_devs/dev_unicode.rs +++ b/ableos/src/devices/character_devs/dev_unicode.rs @@ -44,5 +44,6 @@ fn add1_char(c: char) -> char { if c == char::MAX { return 0x00 as char; } + char::from_u32(c as u32 + 1).unwrap() } diff --git a/ableos/src/devices/character_devs/dev_zero.rs b/ableos/src/devices/character_devs/dev_zero.rs index f5cc3b6..ad26d1d 100644 --- a/ableos/src/devices/character_devs/dev_zero.rs +++ b/ableos/src/devices/character_devs/dev_zero.rs @@ -2,7 +2,6 @@ use kernel::device_interface::character::CharacterDevice; #[derive(Debug)] pub struct DevZero; - impl CharacterDevice for DevZero { fn can_read(&self) -> bool { true diff --git a/ableos/src/devices/character_devs/mod.rs b/ableos/src/devices/character_devs/mod.rs index 50c9169..9a2f294 100644 --- a/ableos/src/devices/character_devs/mod.rs +++ b/ableos/src/devices/character_devs/mod.rs @@ -1,6 +1,5 @@ pub mod dev_null; pub mod dev_unicode; - pub mod dev_zero; pub use kernel::device_interface::character::CharacterDevice; diff --git a/ableos/src/devices/dev_vterm.rs b/ableos/src/devices/dev_vterm.rs index 123738f..2825c84 100644 --- a/ableos/src/devices/dev_vterm.rs +++ b/ableos/src/devices/dev_vterm.rs @@ -1,13 +1,19 @@ // ! A virtual terminal device. -use kernel::device_interface::character::CharacterDevice; - use core::ops::Not; +use core::sync::atomic::AtomicU32; +use core::sync::atomic::Ordering; +use kernel::device_interface::character::CharacterDevice; use shadeable::pixel_format::Rgba64; + pub const VTERM_HEIGHT: u32 = 40; pub const VTERM_WIDTH: u32 = 100; + +pub static VIRTUAL_TERMINAL_COUNT: AtomicU32 = AtomicU32::new(0); + /// Fg and bg colors for vterm pub type ColorCharacter = (Rgba64, Rgba64); + /// A vterm representation of a character #[derive(Debug, Clone, Copy)] pub struct VtermCharacter { @@ -25,21 +31,27 @@ impl Style { pub fn bold(&self) -> bool { (self.0 & 0x01) > 0 } + pub fn underlined(&self) -> bool { (self.0 & 0x02) > 0 } + pub fn italic(&self) -> bool { (self.0 & 0x04) > 0 } + pub fn blinking(&self) -> bool { (self.0 & 0x08) > 0 } + pub fn reversed(&self) -> bool { (self.0 & 0x10) > 0 } + pub fn struck(&self) -> bool { (self.0 & 0x20) > 0 } + #[must_use] pub fn set_bold(mut self, v: bool) -> Self { if v { @@ -49,6 +61,7 @@ impl Style { } self } + #[must_use] pub fn set_underlined(mut self, v: bool) -> Self { if v { @@ -58,6 +71,7 @@ impl Style { } self } + #[must_use] pub fn set_italic(mut self, v: bool) -> Self { if v { @@ -67,6 +81,7 @@ impl Style { } self } + #[must_use] pub fn set_blinking(mut self, v: bool) -> Self { if v { @@ -76,6 +91,7 @@ impl Style { } self } + #[must_use] pub fn set_reversed(mut self, v: bool) -> Self { if v { @@ -85,6 +101,7 @@ impl Style { } self } + #[must_use] pub fn set_struck(mut self, v: bool) -> Self { if v { @@ -95,18 +112,23 @@ impl Style { self } } + #[derive(Debug)] pub struct VTerm { + pub characters: [[VtermCharacter; VTERM_WIDTH as usize]; VTERM_HEIGHT as usize], + pub cursor_visible: bool, + /// Internal ID of the vterm iid: u32, - pub characters: [[VtermCharacter; VTERM_WIDTH as usize]; VTERM_HEIGHT as usize], + /// The internal representation of the vterm style: Style, + /// The cursor position in layout x,y cursor_position: (u32, u32), - pub cursor_visible: bool, key_buff: Vec, } + impl Default for VTerm { fn default() -> Self { VTerm { @@ -150,6 +172,7 @@ impl VTerm { self.cursor_position.1 = y; } } + /// Set the vterm style pub fn set_vterm_style(&mut self, style: Style) { self.style = style; @@ -229,6 +252,7 @@ impl CharacterDevice for VTerm { char_color: (0xff_ff_ff_ff, 0x00_00_00_00), style: Style::default(), }; VTERM_WIDTH as usize]; VTERM_HEIGHT as usize]; + self.cursor_position = (0, 0); self.cursor_visible = true; self.style = Style::default(); @@ -238,7 +262,3 @@ impl CharacterDevice for VTerm { true } } - -pub static VIRTUAL_TERMINAL_COUNT: AtomicU32 = AtomicU32::new(0); -use core::sync::atomic::AtomicU32; -use core::sync::atomic::Ordering; diff --git a/ableos/src/devices/id.rs b/ableos/src/devices/id.rs index f2f286d..cfff8a2 100644 --- a/ableos/src/devices/id.rs +++ b/ableos/src/devices/id.rs @@ -1,15 +1,14 @@ #[derive(Debug)] pub enum Vendor { Unknown = 0, - Ati = 1002, } pub fn match_vendor(id: u16) -> Vendor { use Vendor::*; + match id { 1002 => Ati, - _ => Unknown, } } diff --git a/ableos/src/devices/mod.rs b/ableos/src/devices/mod.rs index 4270540..d97c8df 100644 --- a/ableos/src/devices/mod.rs +++ b/ableos/src/devices/mod.rs @@ -2,39 +2,52 @@ pub mod character_devs; pub mod id; pub mod pci_inner; -use hashbrown::HashMap; -use spin::Lazy; mod dev_vterm; + +pub use self::Device::*; + use crate::devices::dev_vterm::VTerm; +use character_devs::{dev_null::DevNull, dev_unicode::DevUnicode, dev_zero::DevZero}; +use hashbrown::HashMap; use kernel::device_interface::character::CharacterDevice; +use spin::Lazy; + +pub static DEVICE_TABLE: Lazy> = + Lazy::new(|| spin::Mutex::new(DeviceTable::new())); + // FIXME: This is a hack to hold a device. // #[derive(Debug)] pub enum Device { Character(Box), Vterm(Box), } + unsafe impl Sync for Device {} unsafe impl Send for Device {} pub struct DeviceTable { pub devices: HashMap, } -use self::character_devs::{dev_null::DevNull, dev_unicode::DevUnicode, dev_zero::DevZero}; -pub use self::Device::*; + impl DeviceTable { pub fn new() -> Self { - let mut table: HashMap = HashMap::new(); - table.insert("null".to_string(), Character(Box::new(DevNull))); - table.insert("zero".to_string(), Character(Box::new(DevZero))); - table.insert( - "unicode".to_string(), - Character(Box::new(DevUnicode { - next_write_char: 0x00 as char, - next_read_char: 0x00 as char, - })), - ); - table.insert("kvterm".to_string(), Vterm(Box::new(VTerm::new()))); - DeviceTable { devices: table } + DeviceTable { + devices: [ + ("null", Character(Box::new(DevNull))), + ("zero", Character(Box::new(DevZero))), + ( + "unicode", + Character(Box::new(DevUnicode { + next_write_char: 0x00 as char, + next_read_char: 0x00 as char, + })), + ), + ("kvterm", Vterm(Box::new(VTerm::new()))), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(), + } } } @@ -43,6 +56,3 @@ impl Default for DeviceTable { Self::new() } } - -pub static DEVICE_TABLE: Lazy> = - Lazy::new(|| spin::Mutex::new(DeviceTable::new())); diff --git a/ableos/src/devices/pci_inner.rs b/ableos/src/devices/pci_inner.rs index a85c832..3884885 100644 --- a/ableos/src/devices/pci_inner.rs +++ b/ableos/src/devices/pci_inner.rs @@ -2,9 +2,6 @@ //! //! -#[allow(dead_code)] -fn scan_pci_bus() {} - pub enum Vendors { ThreeDfxInteractiveInc = 0x121a, ThreeDLabs = 0x3d3d, @@ -53,3 +50,6 @@ pub enum Vendors { pub struct PciDevice { pub vendor: Vendors, } + +#[allow(dead_code)] +fn scan_pci_bus() {} diff --git a/ableos/src/driver_traits/graphics.rs b/ableos/src/driver_traits/graphics.rs index 88fde1a..8d171e2 100644 --- a/ableos/src/driver_traits/graphics.rs +++ b/ableos/src/driver_traits/graphics.rs @@ -1,16 +1,21 @@ #![allow(unused)] + +pub const REFRESH_RATE: u8 = 60; + +pub type RefreshRate = u8; +pub type Resolution = (usize, usize); +pub type Point = (GCoord, GCoord); +pub type GCoord = usize; + pub enum GModes { Vga800x600, Custom(u16, u16), } -pub type GCoord = usize; // TODO remap to a bitmasked u32 -/* REASON: More effecient memory wise so less overhead on the wasm memory -Current: u32+u32+u32 -Proposed: u32 with bitmaps -*/ - +// REASON: More effecient memory wise so less overhead on the wasm memory +// Current: u32+u32+u32 +// Proposed: u32 with bitmaps pub struct Rgb { pub r: u32, pub g: u32, @@ -22,13 +27,8 @@ impl Rgb { todo!(); } } -pub type RefreshRate = u8; -pub const REFRESH_RATE: u8 = 60; -pub type Resolution = (usize, usize); -pub type Point = (GCoord, GCoord); pub struct FrameBuffer; -// [[Rgb; 5]; 5] pub trait Graphics { fn put_line(coords_start: Point, coords_end: Point, thickness: u32, color: Rgb); fn put_rect(coords_start: Point, coords_end: Point, color: Rgb); diff --git a/ableos/src/driver_traits/mouse.rs b/ableos/src/driver_traits/mouse.rs index ec624dc..89e0f07 100644 --- a/ableos/src/driver_traits/mouse.rs +++ b/ableos/src/driver_traits/mouse.rs @@ -1,5 +1,3 @@ - - // TODO: Bitmasking pub enum Mouse { Button1, diff --git a/ableos/src/driver_traits/serial.rs b/ableos/src/driver_traits/serial.rs index 56f87ac..8e7aa15 100644 --- a/ableos/src/driver_traits/serial.rs +++ b/ableos/src/driver_traits/serial.rs @@ -3,6 +3,7 @@ use kernel::device_interface::character::CharacterDevice; pub struct Serial { pub base: usize, } + impl CharacterDevice for Serial { fn can_read(&self) -> bool { true @@ -28,6 +29,7 @@ impl CharacterDevice for Serial { false } } + pub fn new_serial_test() { let mut serial = Serial { base: 0x3F8 }; serial.initialize(); diff --git a/ableos/src/experiments/absi.rs b/ableos/src/experiments/absi.rs index 36cbfa1..6c63f81 100644 --- a/ableos/src/experiments/absi.rs +++ b/ableos/src/experiments/absi.rs @@ -1,5 +1,6 @@ -// TODO improve tokenizer/parser +use logos::{Lexer, Logos}; +// TODO improve tokenizer/parser pub fn colorify(eval: &str) { let y = eval.split('$'); for z in y { @@ -62,8 +63,6 @@ pub fn colorify(eval: &str) { } } -use logos::Logos; - #[derive(Logos, Debug, PartialEq)] pub enum Token { // Hex(u32), @@ -80,6 +79,7 @@ pub enum Token { #[regex(r"[ \t\n\f]+", logos::skip)] Error, } + pub fn colorify_2(eval: &str) { let lexer = Token::lexer(eval); for token in lexer { @@ -100,9 +100,7 @@ pub fn colorify_2(eval: &str) { } } } -use logos::Lexer; -// use crate::kprint; fn parse_text(lex: &mut Lexer) -> Option { let slice = lex.slice(); Some(String::from(slice)) diff --git a/ableos/src/experiments/clip.rs b/ableos/src/experiments/clip.rs index 6a72587..9dd3eb7 100644 --- a/ableos/src/experiments/clip.rs +++ b/ableos/src/experiments/clip.rs @@ -1,6 +1,6 @@ use alloc::{string::String, vec, vec::Vec}; -// use crate::String; -// use crate::Vec; + +pub static CLIPBOARD: spin::Mutex = spin::Mutex::new(Clipboard::new()); #[derive(Debug)] pub enum Mime { @@ -8,8 +8,6 @@ pub enum Mime { Text(String), } -pub static CLIPBOARD: spin::Mutex = spin::Mutex::new(Clipboard::new()); - // ctrl+v paste but not pop and pastes // ctrl+shift+v pops from the stack and pastes // ctrl+c pushes to the stack @@ -20,6 +18,7 @@ pub struct Clipboard { pub index: usize, pub pages: Vec, } + impl Clipboard { pub const fn new() -> Clipboard { Clipboard { diff --git a/ableos/src/experiments/futex.rs b/ableos/src/experiments/futex.rs index 6453a5f..3252d6f 100644 --- a/ableos/src/experiments/futex.rs +++ b/ableos/src/experiments/futex.rs @@ -1,9 +1,6 @@ use core::time::Duration; -// pub struct Duration {} - pub struct AtomicU32(u32); - impl AtomicU32 { //if v != current value pub fn wait(&self, _v: u32) { @@ -21,9 +18,8 @@ impl AtomicU32 { } } /* - -SUPER HANDWAVEY -YOU WILL NEED LOCKING THAT I DIDNT WRITE OUT (you == zuurr#9735) +// SUPER HANDWAVEY +// YOU WILL NEED LOCKING THAT I DIDNT WRITE OUT (you == zuurr#9735) // all the red is by design pub fn futex_wait(atom: &AtomicU32, value: usize, current_thread: ThreadID) { @@ -44,7 +40,6 @@ pub fn futex_wake(atom: &AtomicU32, threads_to_wake: usize) { waiting_thread.wake() } } - */ struct FutexWaitlist { diff --git a/ableos/src/experiments/info.rs b/ableos/src/experiments/info.rs index be9ede0..b5b8ff2 100644 --- a/ableos/src/experiments/info.rs +++ b/ableos/src/experiments/info.rs @@ -1,8 +1,3 @@ -#![cfg_attr( - not(any(target_arch = "x86_64", target_arch = "x86")), - allow(dead_code) -)] - //! ``` //! extern crate cupid; //! @@ -17,10 +12,50 @@ //! } //! ``` +#![cfg_attr( + not(any(target_arch = "x86_64", target_arch = "x86")), + allow(dead_code) +)] + use core::arch::asm; use core::ops::Deref; use core::{fmt, slice, str}; +// 3 calls of 4 registers of 4 bytes +const BRAND_STRING_LENGTH: usize = 3 * 4 * 4; + +macro_rules! bit { + ($reg:ident, {$($idx:expr => $name:ident),+ $(,)?}) => { + $(pub fn $name(self) -> bool { + ((self.$reg >> $idx) & 1) != 0 + })+ + } +} + +macro_rules! dump { + ($me:expr, $f: expr, $sname:expr, {$($name:ident),+ $(,)?}) => { + $f.debug_struct($sname) + $(.field(stringify!($name), &$me.$name()))+ + .finish() + } +} + +macro_rules! delegate_flag { + ($item:ident, {$($name:ident),+ $(,)?}) => { + $(pub fn $name(&self) -> bool { + self.$item.map(|i| i.$name()).unwrap_or(false) + })+ + } +} + +macro_rules! master_attr_reader { + ($name:ident, $kind:ty) => { + pub fn $name(&self) -> Option<&$kind> { + self.$name.as_ref() + } + }; +} + #[repr(u32)] pub enum RequestType { BasicInformation = 0x00000000, @@ -32,7 +67,7 @@ pub enum RequestType { BrandString1 = 0x80000002, BrandString2 = 0x80000003, BrandString3 = 0x80000004, - // reserved = 0x80000005, + // reserved = 0x80000005, CacheLine = 0x80000006, TimeStampCounter = 0x80000007, PhysicalAddressSize = 0x80000008, @@ -70,7 +105,6 @@ pub fn master() -> Option { // The bit positions are inclusive. fn bits_of(val: u32, start_bit: u8, end_bit: u8) -> u32 { let mut silly = 0; - for _ in start_bit..end_bit + 1 { silly <<= 1; silly |= 1; @@ -85,38 +119,6 @@ pub fn as_bytes(v: &u32) -> &[u8] { unsafe { slice::from_raw_parts(start, 4) } } -macro_rules! bit { - ($reg:ident, {$($idx:expr => $name:ident),+}) => { - $(pub fn $name(self) -> bool { - ((self.$reg >> $idx) & 1) != 0 - })+ - } -} - -macro_rules! dump { - ($me:expr, $f: expr, $sname:expr, {$($name:ident),+}) => { - $f.debug_struct($sname) - $(.field(stringify!($name), &$me.$name()))+ - .finish() - } -} - -macro_rules! delegate_flag { - ($item:ident, {$($name:ident),+}) => { - $(pub fn $name(&self) -> bool { - self.$item.map(|i| i.$name()).unwrap_or(false) - })+ - } -} - -macro_rules! master_attr_reader { - ($name:ident, $kind:ty) => { - pub fn $name(&self) -> Option<&$kind> { - self.$name.as_ref() - } - }; -} - #[derive(Copy, Clone)] pub struct VersionInformation { eax: u32, @@ -246,8 +248,8 @@ impl VersionInformation { 27 => osxsave, 28 => avx, 29 => f16c, - 30 => rdrand - // 31 - unused + 30 => rdrand, + // 31 - unused, }); bit!(edx, { @@ -282,7 +284,7 @@ impl VersionInformation { 28 => htt, 29 => tm, // 30 -reserved - 31 => pbe + 31 => pbe, }); } @@ -357,7 +359,7 @@ impl fmt::Debug for VersionInformation { ss, htt, tm, - pbe + pbe, }) } } @@ -379,7 +381,7 @@ impl ExtendedProcessorSignature { // 1-4 reserved 5 => lzcnt, // 6-7 reserved - 8 => prefetchw + 8 => prefetchw, // 9-31 reserved }); @@ -392,7 +394,7 @@ impl ExtendedProcessorSignature { 26 => gigabyte_pages, 27 => rdtscp_and_ia32_tsc_aux, // 28 reserved - 29 => intel_64_bit_architecture + 29 => intel_64_bit_architecture, // 30-31 reserved }); } @@ -407,14 +409,11 @@ impl fmt::Debug for ExtendedProcessorSignature { execute_disable, gigabyte_pages, rdtscp_and_ia32_tsc_aux, - intel_64_bit_architecture + intel_64_bit_architecture, }) } } -// 3 calls of 4 registers of 4 bytes -const BRAND_STRING_LENGTH: usize = 3 * 4 * 4; - pub struct BrandString { bytes: [u8; BRAND_STRING_LENGTH], } @@ -507,7 +506,7 @@ impl ThermalPowerManagementInformation { 9 => hwp_activity_window, 10 => hwp_energy_performance_preference, // 12 - reserved - 13 => hdc + 13 => hdc, }); pub fn number_of_interrupt_thresholds(self) -> u32 { @@ -535,9 +534,7 @@ impl fmt::Debug for ThermalPowerManagementInformation { hwp_activity_window, hwp_energy_performance_preference, hdc, - number_of_interrupt_thresholds, - hardware_coordination_feedback, performance_energy_bias }) @@ -578,7 +575,7 @@ impl StructuredExtendedInformation { 19 => adx, 20 => smap, // 21-24 - reserved - 25 => intel_processor_trace + 25 => intel_processor_trace, // 26-31 - reserved }); @@ -607,7 +604,7 @@ impl fmt::Debug for StructuredExtendedInformation { adx, smap, intel_processor_trace, - prefetchwt1 + prefetchwt1, }) } } @@ -625,7 +622,6 @@ pub enum CacheLineAssociativity { #[derive(Copy, Clone)] pub struct CacheLine(u32); - impl CacheLine { fn new() -> CacheLine { let (_, _, c, _) = cpuid(RequestType::CacheLine); @@ -690,7 +686,6 @@ impl fmt::Debug for TimeStampCounter { #[derive(Copy, Clone)] pub struct PhysicalAddressSize(u32); - impl PhysicalAddressSize { fn new() -> PhysicalAddressSize { let (a, _, _, _) = cpuid(RequestType::PhysicalAddressSize); @@ -874,7 +869,7 @@ impl Master { ss, htt, tm, - pbe + pbe, }); delegate_flag!(thermal_power_management_information, { @@ -890,7 +885,7 @@ impl Master { hwp_energy_performance_preference, hdc, hardware_coordination_feedback, - performance_energy_bias + performance_energy_bias, }); delegate_flag!(structured_extended_information, { @@ -922,7 +917,7 @@ impl Master { execute_disable, gigabyte_pages, rdtscp_and_ia32_tsc_aux, - intel_64_bit_architecture + intel_64_bit_architecture, }); delegate_flag!(time_stamp_counter, { invariant_tsc }); @@ -933,6 +928,7 @@ impl Default for Master { Self::new() } } + /* cfg_if! { if #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] { diff --git a/ableos/src/experiments/kinfo.rs b/ableos/src/experiments/kinfo.rs index 039201d..fd31a80 100644 --- a/ableos/src/experiments/kinfo.rs +++ b/ableos/src/experiments/kinfo.rs @@ -1,15 +1,5 @@ -// Can be standardized -// NOTE: Move this to relib -pub struct SemanticVersion { - pub major: u8, - pub minor: u8, - pub patch: u8, -} -impl core::fmt::Display for SemanticVersion { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - write!(f, "v{}.{}.{}", self.major, self.minor, self.patch) - } -} +use super::systeminfo::SystemMemory; + // NOTE: Move to somewhere else pub static KINFO: KernelInfo = KernelInfo { kernel_version: SemanticVersion { @@ -19,6 +9,21 @@ pub static KINFO: KernelInfo = KernelInfo { }, memory: SystemMemory { used: 0, total: 0 }, }; + +// Can be standardized +// NOTE: Move this to relib +pub struct SemanticVersion { + pub major: u8, + pub minor: u8, + pub patch: u8, +} + +impl core::fmt::Display for SemanticVersion { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + write!(f, "v{}.{}.{}", self.major, self.minor, self.patch) + } +} + /// simple info you would want to know in a neofetch like program pub struct KernelInfo { // os: String, @@ -28,4 +33,3 @@ pub struct KernelInfo { // gpu: String, pub memory: SystemMemory, } -use super::systeminfo::SystemMemory; diff --git a/ableos/src/experiments/mail.rs b/ableos/src/experiments/mail.rs index 0613498..06bdfda 100644 --- a/ableos/src/experiments/mail.rs +++ b/ableos/src/experiments/mail.rs @@ -5,6 +5,7 @@ pub struct MailBoxes { flags: u8, mailboxes: [u64; 4], } + impl MailBoxes { pub fn new() -> Self { Self { @@ -12,15 +13,18 @@ impl MailBoxes { mailboxes: [0; 4], } } + pub fn reset(&mut self) { self.flags = 0b0000_0000; self.mailboxes = [0; 4]; } + pub fn set_mailbox(&mut self, mailbox_num: u8, mailbox_data: u64) { if let 0..=3 = mailbox_num { self.mailboxes[mailbox_num as usize] = mailbox_data } } + pub fn set_flag(&mut self, flag_num: u8) { match flag_num { 0 => { diff --git a/ableos/src/experiments/mod.rs b/ableos/src/experiments/mod.rs index f05b28c..f1c8bf5 100644 --- a/ableos/src/experiments/mod.rs +++ b/ableos/src/experiments/mod.rs @@ -3,7 +3,6 @@ pub mod absi; pub mod clip; pub mod futex; -// pub mod info; pub mod info; pub mod kinfo; pub mod mail; @@ -11,4 +10,5 @@ pub mod server; pub mod systeminfo; pub mod virtual_memory; pub mod y_compositor; + pub const BANNER: &str = include_str!("banner.txt"); diff --git a/ableos/src/experiments/notification.rs b/ableos/src/experiments/notification.rs index 51a08de..fc49825 100644 --- a/ableos/src/experiments/notification.rs +++ b/ableos/src/experiments/notification.rs @@ -5,4 +5,3 @@ pub struct Notification { text_body: String, time: u64, } -impl Notification {} diff --git a/ableos/src/experiments/pkg.rs b/ableos/src/experiments/pkg.rs index ef3f54e..a0f9512 100644 --- a/ableos/src/experiments/pkg.rs +++ b/ableos/src/experiments/pkg.rs @@ -1,8 +1,9 @@ -pub type PackageName = String; use crate::experiments::kinfo::SemanticVersion; // Scuffed pub type Hash = u8; +pub type PackageName = String; + pub struct MetaPackage { pub name: u8, pub version: SemanticVersion, diff --git a/ableos/src/experiments/server.rs b/ableos/src/experiments/server.rs index c857606..4e8f217 100644 --- a/ableos/src/experiments/server.rs +++ b/ableos/src/experiments/server.rs @@ -1,10 +1,13 @@ pub trait Server { /// Initialize the server and return a number fn initialize() -> u32; + /// kill the server fn kill() -> bool; + // put data in the servers outbox fn send(); + // put data in the servers inbox and notify it fn recieve(); } diff --git a/ableos/src/experiments/systeminfo.rs b/ableos/src/experiments/systeminfo.rs index cb7de27..1e815d4 100644 --- a/ableos/src/experiments/systeminfo.rs +++ b/ableos/src/experiments/systeminfo.rs @@ -1,36 +1,6 @@ // Can be standardized // NOTE: move the file to the src/ dir -pub struct SystemMemory { - pub used: u64, - pub total: u64, -} -impl core::fmt::Display for SystemMemory { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - write!(f, "{} Bytes / {} Bytes", self.used, self.total) - } -} -/* -pub fn format_system_info() -> core::string::String { - let x = format!( - "{} -OS: AbleOS -Host: ComputAble -Kernel: {} -Uptime: 0:0:0 -Packages: 0 -Shell: Ashell -Gpu: MIPS32 R4000 R4k -Cpu: {} -Memory: {} -", - crate::experiments::BANNER, - crate::experiments::kinfo::KINFO.kernel_version, - crate::arch::ARCH, - crate::experiments::kinfo::KINFO.memory - ); - return x; -} -// */ + pub const KERNEL_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg(debug_assertions)] /// A constant to check if the kernel is in debug mode @@ -38,3 +8,14 @@ pub const RELEASE_TYPE: &str = "debug"; #[cfg(not(debug_assertions))] /// A constant to check if the kernel is in release mode pub const RELEASE_TYPE: &str = "release"; + +pub struct SystemMemory { + pub used: u64, + pub total: u64, +} + +impl core::fmt::Display for SystemMemory { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + write!(f, "{} Bytes / {} Bytes", self.used, self.total) + } +} diff --git a/ableos/src/experiments/virtual_memory.rs b/ableos/src/experiments/virtual_memory.rs index dd791e4..7cbf37a 100644 --- a/ableos/src/experiments/virtual_memory.rs +++ b/ableos/src/experiments/virtual_memory.rs @@ -4,4 +4,4 @@ pub struct Scheduler { executables: usize, } -pub struct RunQueue {} +pub struct RunQueue; diff --git a/ableos/src/experiments/y_compositor/compositor.rs b/ableos/src/experiments/y_compositor/compositor.rs index 03fb0be..ee5e63b 100644 --- a/ableos/src/experiments/y_compositor/compositor.rs +++ b/ableos/src/experiments/y_compositor/compositor.rs @@ -1,5 +1,4 @@ pub struct Compositor; - impl Compositor { pub fn new() -> Self { Self diff --git a/ableos/src/experiments/y_compositor/window.rs b/ableos/src/experiments/y_compositor/window.rs index 6e4a44f..82301e3 100644 --- a/ableos/src/experiments/y_compositor/window.rs +++ b/ableos/src/experiments/y_compositor/window.rs @@ -1,16 +1,17 @@ use crate::driver_traits::graphics::Point; +pub type MenuBar = Vec; + pub struct MenuOption { symbol: char, } -pub type MenuBar = Vec; - pub struct Window { title: String, position: Point, fullscreen: bool, } + // all of these should return a result impl Window { pub fn new(title: String, position: Point, fullscreen: bool) -> Self { diff --git a/ableos/src/experiments/y_compositor/wm.rs b/ableos/src/experiments/y_compositor/wm.rs index 8b13789..e69de29 100644 --- a/ableos/src/experiments/y_compositor/wm.rs +++ b/ableos/src/experiments/y_compositor/wm.rs @@ -1 +0,0 @@ - diff --git a/ableos/src/filesystem/mod.rs b/ableos/src/filesystem/mod.rs index f564f18..b712e68 100644 --- a/ableos/src/filesystem/mod.rs +++ b/ableos/src/filesystem/mod.rs @@ -8,14 +8,8 @@ use ext2::{ }; use spin::Lazy; -fn load_fs() -> Synced>> { - let mut volume = Vec::new(); - volume.extend_from_slice(include_bytes!("../../../userland/root_fs/ext2.img")); - - Synced::>::new(volume).unwrap() -} - -// use serde::__private::from_utf8_lossy; +pub static FILE_SYSTEM: Lazy>>>> = + Lazy::new(|| spin::Mutex::new(load_fs())); pub fn walk>( fs: &Synced>, @@ -40,5 +34,9 @@ pub fn walk>( } } -pub static FILE_SYSTEM: Lazy>>>> = - Lazy::new(|| spin::Mutex::new(load_fs())); +fn load_fs() -> Synced>> { + let mut volume = Vec::new(); + volume.extend_from_slice(include_bytes!("../../../userland/root_fs/ext2.img")); + + Synced::>::new(volume).unwrap() +} diff --git a/ableos/src/graphics/mod.rs b/ableos/src/graphics/mod.rs index 2275124..c7dbd8b 100644 --- a/ableos/src/graphics/mod.rs +++ b/ableos/src/graphics/mod.rs @@ -1,9 +1,13 @@ -// use crate::vga_e::VGAE; use ab_glyph::{Font, FontRef, Glyph}; - use shadeable::{evaluate_shader, pixel_format::Rgba64}; use spin::Lazy; -// use vga::{colors::Color16, writers::GraphicsWriter}; + +pub static SCREEN_BUFFER: Lazy> = + Lazy::new(|| spin::Mutex::new(ScreenBuffer::new(640, 480))); + +const FONT_SCALE: f32 = 1.6; +const GLYPH_HEIGHT: f32 = 18.0; +const GLYPH_WIDTH: f32 = 10.0; #[derive(Debug)] pub struct ScreenSize { @@ -11,13 +15,6 @@ pub struct ScreenSize { pub y: usize, } -const FONT_SCALE: f32 = 1.6; -const GLYPH_HEIGHT: f32 = 18.0; -const GLYPH_WIDTH: f32 = 10.0; - -pub static SCREEN_BUFFER: Lazy> = - Lazy::new(|| spin::Mutex::new(ScreenBuffer::new(640, 480))); - impl ScreenSize { pub fn new(x: usize, y: usize) -> Self { Self { x, y } @@ -32,7 +29,7 @@ pub enum GraphicsReturn { pub struct ScreenBuffer { pub size: ScreenSize, pub clear_color: Rgba64, - pub buff: Box<[Rgba64]>, // Vec, + pub buff: Box<[Rgba64]>, } impl ScreenBuffer { @@ -69,6 +66,7 @@ impl ScreenBuffer { } pub fn blit(&mut self, _width: usize, _height: usize) {} + pub fn draw_filled_rect(&mut self, x1: usize, y1: usize, x2: usize, y2: usize, color: Rgba64) { for y in y1..y2 { for x in x1..x2 { @@ -198,38 +196,6 @@ impl ScreenBuffer { } } } -/* - -pub trait VgaBuffer { - fn copy_to_buffer(&self) -> GraphicsReturn; -} -impl VgaBuffer for ScreenBuffer { - fn copy_to_buffer(&self) -> GraphicsReturn { - let mode = VGAE.lock(); - for y in 0..self.size.y { - for x in 0..self.size.x { - - use shadeable::pixel_format::into_vga_16; - let vga_color = into_vga_16(self.buff[y * self.size.x + x]); - // let vga_color = vga::colors::Color16::Cyan; - - if Color16::Cyan != vga_color { - mode.set_pixel(x, y, vga_color); - } - - - - - - } - } - - GraphicsReturn::Ok - } -} - - -*/ pub fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<(usize, usize)> { let mut coordinates: Vec<(usize, usize)> = vec![]; @@ -271,5 +237,6 @@ pub fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<(usize, usize) current_y += sy; } } + coordinates } diff --git a/ableos/src/keyboard/abstractions/custom_layout.rs b/ableos/src/keyboard/abstractions/custom_layout.rs index 9939c24..956be88 100644 --- a/ableos/src/keyboard/abstractions/custom_layout.rs +++ b/ableos/src/keyboard/abstractions/custom_layout.rs @@ -2,104 +2,382 @@ use crate::{ DecodedKey, HandleControl, KeyCode, KeyboardLayout, LayoutEntry, LayoutEntryKind, Modifiers, }; -// Do not edit this file directly. Instead, create a `Keyboard` and modify that. - pub struct CustomLayout { mapping: [LayoutEntry; 256], } + impl Default for CustomLayout { fn default() -> Self { Self::new_us104key() } } -#[rustfmt::skip] + impl CustomLayout { - pub fn new_us104key() -> Self { - let mut mapping = Self { - mapping: [LayoutEntry::default(); 256], - }; - mapping.set(KeyCode::BackTick, LayoutEntry::regular().unshifted('`').shifted('`')); - mapping.set(KeyCode::Escape, LayoutEntry::regular().unshifted('\x1B')); - mapping.set(KeyCode::Key0, LayoutEntry::regular().unshifted('0').shifted(')')); - mapping.set(KeyCode::Key1, LayoutEntry::regular().unshifted('1').shifted('!')); - mapping.set(KeyCode::Key2, LayoutEntry::regular().unshifted('2').shifted('@')); - mapping.set(KeyCode::Key3, LayoutEntry::regular().unshifted('3').shifted('#')); - mapping.set(KeyCode::Key4, LayoutEntry::regular().unshifted('4').shifted('$')); - mapping.set(KeyCode::Key5, LayoutEntry::regular().unshifted('5').shifted('%')); - mapping.set(KeyCode::Key6, LayoutEntry::regular().unshifted('6').shifted('^')); - mapping.set(KeyCode::Key7, LayoutEntry::regular().unshifted('7').shifted('&')); - mapping.set(KeyCode::Key8, LayoutEntry::regular().unshifted('8').shifted('*')); - mapping.set(KeyCode::Key9, LayoutEntry::regular().unshifted('9').shifted('(')); - mapping.set(KeyCode::Minus, LayoutEntry::regular().unshifted('-').shifted('_')); - mapping.set(KeyCode::Equals, LayoutEntry::regular().unshifted('=').shifted('+')); - mapping.set(KeyCode::Backspace, LayoutEntry::regular().all('\x08')); - mapping.set(KeyCode::Tab, LayoutEntry::regular().all('\x09')); - mapping.set(KeyCode::Q, LayoutEntry::alphabet().low('q').high('Q').raw_unicode('\u{0011}')); - mapping.set(KeyCode::W, LayoutEntry::alphabet().low('w').high('W').raw_unicode('\u{0017}')); - mapping.set(KeyCode::E, LayoutEntry::alphabet().low('e').high('E').raw_unicode('\u{0005}')); - mapping.set(KeyCode::R, LayoutEntry::alphabet().low('r').high('R').raw_unicode('\u{0012}')); - mapping.set(KeyCode::T, LayoutEntry::alphabet().low('t').high('T').raw_unicode('\u{0014}')); - mapping.set(KeyCode::Y, LayoutEntry::alphabet().low('y').high('Y').raw_unicode('\u{0019}')); - mapping.set(KeyCode::U, LayoutEntry::alphabet().low('u').high('U').raw_unicode('\u{0015}')); - mapping.set(KeyCode::I, LayoutEntry::alphabet().low('i').high('I').raw_unicode('\u{0009}')); - mapping.set(KeyCode::O, LayoutEntry::alphabet().low('o').high('O').raw_unicode('\u{000F}')); - mapping.set(KeyCode::P, LayoutEntry::alphabet().low('p').high('P').raw_unicode('\u{0010}')); - mapping.set(KeyCode::A, LayoutEntry::alphabet().low('a').high('A').raw_unicode('\u{0001}')); - mapping.set(KeyCode::S, LayoutEntry::alphabet().low('s').high('S').raw_unicode('\u{0013}')); - mapping.set(KeyCode::D, LayoutEntry::alphabet().low('d').high('D').raw_unicode('\u{0004}')); - mapping.set(KeyCode::F, LayoutEntry::alphabet().low('f').high('F').raw_unicode('\u{0006}')); - mapping.set(KeyCode::G, LayoutEntry::alphabet().low('g').high('G').raw_unicode('\u{0007}')); - mapping.set(KeyCode::H, LayoutEntry::alphabet().low('h').high('H').raw_unicode('\u{0008}')); - mapping.set(KeyCode::J, LayoutEntry::alphabet().low('j').high('J').raw_unicode('\u{000A}')); - mapping.set(KeyCode::K, LayoutEntry::alphabet().low('k').high('K').raw_unicode('\u{000B}')); - mapping.set(KeyCode::L, LayoutEntry::alphabet().low('l').high('L').raw_unicode('\u{000C}')); - mapping.set(KeyCode::Z, LayoutEntry::alphabet().low('z').high('Z').raw_unicode('\u{001A}')); - mapping.set(KeyCode::X, LayoutEntry::alphabet().low('x').high('X').raw_unicode('\u{0018}')); - mapping.set(KeyCode::C, LayoutEntry::alphabet().low('c').high('C').raw_unicode('\u{0003}')); - mapping.set(KeyCode::V, LayoutEntry::alphabet().low('v').high('V').raw_unicode('\u{0016}')); - mapping.set(KeyCode::B, LayoutEntry::alphabet().low('b').high('B').raw_unicode('\u{0002}')); - mapping.set(KeyCode::N, LayoutEntry::alphabet().low('n').high('N').raw_unicode('\u{000E}')); - mapping.set(KeyCode::M, LayoutEntry::alphabet().low('m').high('M').raw_unicode('\u{000D}')); - mapping.set(KeyCode::BracketSquareLeft, LayoutEntry::regular().unshifted('{').shifted('[')); - mapping.set(KeyCode::BracketSquareRight, LayoutEntry::regular().unshifted('}').shifted(']')); - mapping.set(KeyCode::BackSlash, LayoutEntry::regular().unshifted('|').shifted('\\')); - mapping.set(KeyCode::SemiColon, LayoutEntry::regular().unshifted(';').shifted(':')); - mapping.set(KeyCode::Quote, LayoutEntry::regular().unshifted('\'').shifted('"')); - mapping.set(KeyCode::Enter, LayoutEntry::regular().all('\x0A')); - mapping.set(KeyCode::Comma, LayoutEntry::regular().unshifted(',').shifted('<')); - mapping.set(KeyCode::Fullstop, LayoutEntry::regular().unshifted('.').shifted('>')); - mapping.set(KeyCode::Slash, LayoutEntry::regular().unshifted('/').shifted('?')); - mapping.set(KeyCode::Spacebar, LayoutEntry::regular().all(' ')); - mapping.set(KeyCode::Delete, LayoutEntry::regular().all('\x7F')); - mapping.set(KeyCode::NumpadSlash, LayoutEntry::numpad().all('/')); - mapping.set(KeyCode::NumpadStar, LayoutEntry::numpad().all('*')); - mapping.set(KeyCode::NumpadMinus, LayoutEntry::numpad().all('-')); - mapping.set(KeyCode::Numpad7, LayoutEntry::numpad().low('7').high(KeyCode::Home)); - mapping.set(KeyCode::Numpad8, LayoutEntry::numpad().low('8').high(KeyCode::ArrowUp)); - mapping.set(KeyCode::Numpad9, LayoutEntry::numpad().low('9').high(KeyCode::PageUp)); - mapping.set(KeyCode::NumpadPlus, LayoutEntry::numpad().all('+')); - mapping.set(KeyCode::Numpad4, LayoutEntry::numpad().low('4').high(KeyCode::ArrowLeft)); - mapping.set(KeyCode::Numpad5, LayoutEntry::numpad().all('5')); - mapping.set(KeyCode::Numpad6, LayoutEntry::numpad().low('6').high(KeyCode::ArrowRight)); - mapping.set(KeyCode::Numpad1, LayoutEntry::numpad().low('1').high(KeyCode::End)); - mapping.set(KeyCode::Numpad2, LayoutEntry::numpad().low('2').high(KeyCode::ArrowDown)); - mapping.set(KeyCode::Numpad3, LayoutEntry::numpad().low('3').high(KeyCode::PageDown)); - mapping.set(KeyCode::Numpad0, LayoutEntry::numpad().low('0').high(KeyCode::Insert)); - mapping.set(KeyCode::NumpadPeriod, LayoutEntry::numpad().low('.').high('\x7F')); - mapping.set(KeyCode::NumpadEnter, LayoutEntry::numpad().all('\x0A')); - mapping - } - pub fn new_us105key() -> Self { - let mut mapping = Self::new_us104key(); - mapping.set(KeyCode::BackTick, LayoutEntry::regular().unshifted('`').shifted('¬').altgr('|')); - mapping.set(KeyCode::Key2, LayoutEntry::regular().unshifted('2').shifted('"')); - mapping.set(KeyCode::Quote, LayoutEntry::regular().unshifted('\'').shifted('@')); - mapping.set(KeyCode::Key3, LayoutEntry::regular().unshifted('3').shifted('£')); - mapping.set(KeyCode::BackTick, LayoutEntry::regular().unshifted('4').shifted('$').altgr('€')); - mapping.set(KeyCode::HashTilde, LayoutEntry::regular().unshifted('#').shifted('~')); - mapping - } + pub fn new_us104key() -> Self { + let mut mapping = Self { + mapping: [LayoutEntry::default(); 256], + }; + + mapping.set( + KeyCode::BackTick, + LayoutEntry::regular().unshifted('`').shifted('`'), + ); + mapping.set(KeyCode::Escape, LayoutEntry::regular().unshifted('\x1B')); + mapping.set( + KeyCode::Key0, + LayoutEntry::regular().unshifted('0').shifted(')'), + ); + mapping.set( + KeyCode::Key1, + LayoutEntry::regular().unshifted('1').shifted('!'), + ); + mapping.set( + KeyCode::Key2, + LayoutEntry::regular().unshifted('2').shifted('@'), + ); + mapping.set( + KeyCode::Key3, + LayoutEntry::regular().unshifted('3').shifted('#'), + ); + mapping.set( + KeyCode::Key4, + LayoutEntry::regular().unshifted('4').shifted('$'), + ); + mapping.set( + KeyCode::Key5, + LayoutEntry::regular().unshifted('5').shifted('%'), + ); + mapping.set( + KeyCode::Key6, + LayoutEntry::regular().unshifted('6').shifted('^'), + ); + mapping.set( + KeyCode::Key7, + LayoutEntry::regular().unshifted('7').shifted('&'), + ); + mapping.set( + KeyCode::Key8, + LayoutEntry::regular().unshifted('8').shifted('*'), + ); + mapping.set( + KeyCode::Key9, + LayoutEntry::regular().unshifted('9').shifted('('), + ); + mapping.set( + KeyCode::Minus, + LayoutEntry::regular().unshifted('-').shifted('_'), + ); + mapping.set( + KeyCode::Equals, + LayoutEntry::regular().unshifted('=').shifted('+'), + ); + mapping.set(KeyCode::Backspace, LayoutEntry::regular().all('\x08')); + mapping.set(KeyCode::Tab, LayoutEntry::regular().all('\x09')); + mapping.set( + KeyCode::Q, + LayoutEntry::alphabet() + .low('q') + .high('Q') + .raw_unicode('\u{0011}'), + ); + mapping.set( + KeyCode::W, + LayoutEntry::alphabet() + .low('w') + .high('W') + .raw_unicode('\u{0017}'), + ); + mapping.set( + KeyCode::E, + LayoutEntry::alphabet() + .low('e') + .high('E') + .raw_unicode('\u{0005}'), + ); + mapping.set( + KeyCode::R, + LayoutEntry::alphabet() + .low('r') + .high('R') + .raw_unicode('\u{0012}'), + ); + mapping.set( + KeyCode::T, + LayoutEntry::alphabet() + .low('t') + .high('T') + .raw_unicode('\u{0014}'), + ); + mapping.set( + KeyCode::Y, + LayoutEntry::alphabet() + .low('y') + .high('Y') + .raw_unicode('\u{0019}'), + ); + mapping.set( + KeyCode::U, + LayoutEntry::alphabet() + .low('u') + .high('U') + .raw_unicode('\u{0015}'), + ); + mapping.set( + KeyCode::I, + LayoutEntry::alphabet() + .low('i') + .high('I') + .raw_unicode('\u{0009}'), + ); + mapping.set( + KeyCode::O, + LayoutEntry::alphabet() + .low('o') + .high('O') + .raw_unicode('\u{000F}'), + ); + mapping.set( + KeyCode::P, + LayoutEntry::alphabet() + .low('p') + .high('P') + .raw_unicode('\u{0010}'), + ); + mapping.set( + KeyCode::A, + LayoutEntry::alphabet() + .low('a') + .high('A') + .raw_unicode('\u{0001}'), + ); + mapping.set( + KeyCode::S, + LayoutEntry::alphabet() + .low('s') + .high('S') + .raw_unicode('\u{0013}'), + ); + mapping.set( + KeyCode::D, + LayoutEntry::alphabet() + .low('d') + .high('D') + .raw_unicode('\u{0004}'), + ); + mapping.set( + KeyCode::F, + LayoutEntry::alphabet() + .low('f') + .high('F') + .raw_unicode('\u{0006}'), + ); + mapping.set( + KeyCode::G, + LayoutEntry::alphabet() + .low('g') + .high('G') + .raw_unicode('\u{0007}'), + ); + mapping.set( + KeyCode::H, + LayoutEntry::alphabet() + .low('h') + .high('H') + .raw_unicode('\u{0008}'), + ); + mapping.set( + KeyCode::J, + LayoutEntry::alphabet() + .low('j') + .high('J') + .raw_unicode('\u{000A}'), + ); + mapping.set( + KeyCode::K, + LayoutEntry::alphabet() + .low('k') + .high('K') + .raw_unicode('\u{000B}'), + ); + mapping.set( + KeyCode::L, + LayoutEntry::alphabet() + .low('l') + .high('L') + .raw_unicode('\u{000C}'), + ); + mapping.set( + KeyCode::Z, + LayoutEntry::alphabet() + .low('z') + .high('Z') + .raw_unicode('\u{001A}'), + ); + mapping.set( + KeyCode::X, + LayoutEntry::alphabet() + .low('x') + .high('X') + .raw_unicode('\u{0018}'), + ); + mapping.set( + KeyCode::C, + LayoutEntry::alphabet() + .low('c') + .high('C') + .raw_unicode('\u{0003}'), + ); + mapping.set( + KeyCode::V, + LayoutEntry::alphabet() + .low('v') + .high('V') + .raw_unicode('\u{0016}'), + ); + mapping.set( + KeyCode::B, + LayoutEntry::alphabet() + .low('b') + .high('B') + .raw_unicode('\u{0002}'), + ); + mapping.set( + KeyCode::N, + LayoutEntry::alphabet() + .low('n') + .high('N') + .raw_unicode('\u{000E}'), + ); + mapping.set( + KeyCode::M, + LayoutEntry::alphabet() + .low('m') + .high('M') + .raw_unicode('\u{000D}'), + ); + mapping.set( + KeyCode::BracketSquareLeft, + LayoutEntry::regular().unshifted('{').shifted('['), + ); + mapping.set( + KeyCode::BracketSquareRight, + LayoutEntry::regular().unshifted('}').shifted(']'), + ); + mapping.set( + KeyCode::BackSlash, + LayoutEntry::regular().unshifted('|').shifted('\\'), + ); + mapping.set( + KeyCode::SemiColon, + LayoutEntry::regular().unshifted(';').shifted(':'), + ); + mapping.set( + KeyCode::Quote, + LayoutEntry::regular().unshifted('\'').shifted('"'), + ); + mapping.set(KeyCode::Enter, LayoutEntry::regular().all('\x0A')); + mapping.set( + KeyCode::Comma, + LayoutEntry::regular().unshifted(',').shifted('<'), + ); + mapping.set( + KeyCode::Fullstop, + LayoutEntry::regular().unshifted('.').shifted('>'), + ); + mapping.set( + KeyCode::Slash, + LayoutEntry::regular().unshifted('/').shifted('?'), + ); + mapping.set(KeyCode::Spacebar, LayoutEntry::regular().all(' ')); + mapping.set(KeyCode::Delete, LayoutEntry::regular().all('\x7F')); + mapping.set(KeyCode::NumpadSlash, LayoutEntry::numpad().all('/')); + mapping.set(KeyCode::NumpadStar, LayoutEntry::numpad().all('*')); + mapping.set(KeyCode::NumpadMinus, LayoutEntry::numpad().all('-')); + mapping.set( + KeyCode::Numpad7, + LayoutEntry::numpad().low('7').high(KeyCode::Home), + ); + mapping.set( + KeyCode::Numpad8, + LayoutEntry::numpad().low('8').high(KeyCode::ArrowUp), + ); + mapping.set( + KeyCode::Numpad9, + LayoutEntry::numpad().low('9').high(KeyCode::PageUp), + ); + mapping.set(KeyCode::NumpadPlus, LayoutEntry::numpad().all('+')); + mapping.set( + KeyCode::Numpad4, + LayoutEntry::numpad().low('4').high(KeyCode::ArrowLeft), + ); + mapping.set(KeyCode::Numpad5, LayoutEntry::numpad().all('5')); + mapping.set( + KeyCode::Numpad6, + LayoutEntry::numpad().low('6').high(KeyCode::ArrowRight), + ); + mapping.set( + KeyCode::Numpad1, + LayoutEntry::numpad().low('1').high(KeyCode::End), + ); + mapping.set( + KeyCode::Numpad2, + LayoutEntry::numpad().low('2').high(KeyCode::ArrowDown), + ); + mapping.set( + KeyCode::Numpad3, + LayoutEntry::numpad().low('3').high(KeyCode::PageDown), + ); + mapping.set( + KeyCode::Numpad0, + LayoutEntry::numpad().low('0').high(KeyCode::Insert), + ); + mapping.set( + KeyCode::NumpadPeriod, + LayoutEntry::numpad().low('.').high('\x7F'), + ); + mapping.set(KeyCode::NumpadEnter, LayoutEntry::numpad().all('\x0A')); + mapping + } + pub fn new_us105key() -> Self { + let mut mapping = Self::new_us104key(); + mapping.set( + KeyCode::BackTick, + LayoutEntry::regular() + .unshifted('`') + .shifted('¬') + .altgr('|'), + ); + mapping.set( + KeyCode::Key2, + LayoutEntry::regular().unshifted('2').shifted('"'), + ); + mapping.set( + KeyCode::Quote, + LayoutEntry::regular().unshifted('\'').shifted('@'), + ); + mapping.set( + KeyCode::Key3, + LayoutEntry::regular().unshifted('3').shifted('£'), + ); + mapping.set( + KeyCode::BackTick, + LayoutEntry::regular() + .unshifted('4') + .shifted('$') + .altgr('€'), + ); + mapping.set( + KeyCode::HashTilde, + LayoutEntry::regular().unshifted('#').shifted('~'), + ); + mapping + } + + pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) { + self.mapping[pos as usize] = entry; + } } + impl KeyboardLayout for CustomLayout { fn map_keycode( &self, @@ -164,13 +442,3 @@ impl KeyboardLayout for CustomLayout { } } } - -// Note(elfein) Not super hard to get right, but still- DO NOT TOUCH -impl CustomLayout { - // See how hard this is to get right? - // See the complexity of all the methods? - // Yeah- if you don't know what you're doing, ask before you touch! - pub fn set(&mut self, pos: KeyCode, entry: LayoutEntry) { - self.mapping[pos as usize] = entry; - } -} diff --git a/ableos/src/keyboard/abstractions/custom_scancode_set.rs b/ableos/src/keyboard/abstractions/custom_scancode_set.rs index 8cb6950..25b08e2 100644 --- a/ableos/src/keyboard/abstractions/custom_scancode_set.rs +++ b/ableos/src/keyboard/abstractions/custom_scancode_set.rs @@ -6,17 +6,20 @@ pub struct CustomScancodeSet { single_byte: [Option; 256], extended: [Option; 256], } + impl Default for CustomScancodeSet { fn default() -> Self { Self::scancode_set1() } } + impl CustomScancodeSet { pub fn scancode_set1() -> Self { let mut scancode_set = Self { single_byte: [None; 256], extended: [None; 256], }; + scancode_set.single_byte[0x01] = Some(KeyCode::Escape); // 01 scancode_set.single_byte[0x02] = Some(KeyCode::Key1); // 02 scancode_set.single_byte[0x03] = Some(KeyCode::Key2); // 03 @@ -181,6 +184,7 @@ impl CustomScancodeSet { } scancode_set } + pub fn scancode_set2() -> Self { Self { single_byte: [None; 256], @@ -188,6 +192,7 @@ impl CustomScancodeSet { } } } + impl ScancodeSet for CustomScancodeSet { fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result, Error> { match *state { @@ -238,6 +243,7 @@ impl ScancodeSet for CustomScancodeSet { } } } + fn map_scancode(&self, code: u8) -> Result { if let Some(kc) = self.single_byte[code as usize] { Ok(kc) @@ -245,6 +251,7 @@ impl ScancodeSet for CustomScancodeSet { Err(Error::UnknownKeyCode) } } + fn map_extended_scancode(&self, code: u8) -> Result { if let Some(kc) = self.extended[code as usize] { Ok(kc) diff --git a/ableos/src/keyboard/abstractions/layout_entry.rs b/ableos/src/keyboard/abstractions/layout_entry.rs index a24af3a..e338def 100644 --- a/ableos/src/keyboard/abstractions/layout_entry.rs +++ b/ableos/src/keyboard/abstractions/layout_entry.rs @@ -1,4 +1,4 @@ -use super::DecodedKey; +use crate::DecodedKey; #[derive(Debug, Clone, Copy)] pub enum LayoutEntryKind { @@ -32,6 +32,7 @@ impl LayoutEntry { ..Default::default() } } + #[must_use] pub fn numpad() -> Self { Self { @@ -39,6 +40,7 @@ impl LayoutEntry { ..Default::default() } } + #[must_use] pub fn alphabet() -> Self { Self { @@ -46,36 +48,43 @@ impl LayoutEntry { ..Default::default() } } + #[must_use] pub fn unshifted(mut self, c: impl Into) -> Self { self.unshifted = Some(c.into()); self } + #[must_use] pub fn shifted(mut self, c: impl Into) -> Self { self.shifted = Some(c.into()); self } + #[must_use] pub fn altgr(mut self, c: impl Into) -> Self { self.altgr = Some(c.into()); self } + #[must_use] pub fn raw_unicode(mut self, c: impl Into) -> Self { self.raw_unicode = Some(c.into()); self } + #[must_use] pub fn locked(mut self, c: impl Into) -> Self { self.locked = Some(c.into()); self } + #[must_use] pub fn locked_shifted(mut self, c: impl Into) -> Self { self.locked_shifted = Some(c.into()); self } + #[must_use] pub fn common(self, c: impl Into + Clone) -> Self { self.unshifted(c.clone()) @@ -83,14 +92,17 @@ impl LayoutEntry { .locked(c.clone()) .locked_shifted(c) } + #[must_use] pub fn low(self, c: impl Into + Clone) -> Self { self.unshifted(c.clone()).locked_shifted(c) } + #[must_use] pub fn high(self, c: impl Into + Clone) -> Self { self.shifted(c.clone()).locked(c) } + #[must_use] pub fn all(self, c: impl Into + Clone) -> Self { self.unshifted(c.clone()) diff --git a/ableos/src/keyboard/abstractions/mod.rs b/ableos/src/keyboard/abstractions/mod.rs index 38f49fa..d80e687 100644 --- a/ableos/src/keyboard/abstractions/mod.rs +++ b/ableos/src/keyboard/abstractions/mod.rs @@ -1,5 +1,3 @@ -use super::*; - mod custom_layout; mod custom_scancode_set; mod layout_entry; diff --git a/ableos/src/keyboard/mod.rs b/ableos/src/keyboard/mod.rs index c669dc6..5ca5bca 100644 --- a/ableos/src/keyboard/mod.rs +++ b/ableos/src/keyboard/mod.rs @@ -1,13 +1,17 @@ #![allow(dead_code)] + mod abstractions; mod small_types; mod traits; + pub use abstractions::*; pub use small_types::*; pub use traits::*; -const KEYCODE_BITS: u8 = 11; + const EXTENDED_KEY_CODE: u8 = 0xE0; +const KEYCODE_BITS: u8 = 11; const KEY_RELEASE_CODE: u8 = 0xF0; + #[derive(Debug)] pub struct Keyboard where @@ -22,6 +26,7 @@ where layout: T, set: S, } + impl Keyboard where T: KeyboardLayout + Default, @@ -47,14 +52,17 @@ where set: S::default(), } } - // /// Change the Ctrl key mapping. + + /// Change the Ctrl key mapping. pub fn set_ctrl_handling(&mut self, new_value: HandleControl) { self.handle_ctrl = new_value; } - // /// Get the current Ctrl key mapping. + + /// Get the current Ctrl key mapping. pub fn get_ctrl_handling(&self) -> HandleControl { self.handle_ctrl } + /// Clears the bit register. /// /// Call this when there is a timeout reading data from the keyboard. @@ -63,6 +71,7 @@ where self.num_bits = 0; self.decode_state = DecodeState::Start; } + /// Processes a 16-bit word from the keyboard. /// /// * The start bit (0) must be in bit 0. @@ -74,6 +83,7 @@ where let byte = self.check_word(word)?; self.add_byte(byte) } + /// Processes an 8-bit byte from the keyboard. /// /// We assume the start, stop and parity bits have been processed and @@ -81,6 +91,7 @@ where pub fn add_byte(&mut self, byte: u8) -> Result, Error> { self.set.advance_state(&mut self.decode_state, byte) } + /// Shift a bit into the register. /// /// Call this /or/ call `add_word` - don't call both. @@ -97,6 +108,7 @@ where Ok(None) } } + /// Processes a `KeyEvent` returned from `add_bit`, `add_byte` or `add_word` /// and produces a decoded key. /// @@ -199,12 +211,15 @@ where _ => None, } } + fn get_bit(&self, word: u16, offset: usize) -> bool { ((word >> offset) & 0x0001) != 0 } + fn has_even_number_bits(&self, data: u8) -> bool { (data.count_ones() % 2) == 0 } + /// Check 11-bit word has 1 start bit, 1 stop bit and an odd parity bit. fn check_word(&self, word: u16) -> Result { let start_bit = self.get_bit(word, 0); @@ -222,9 +237,11 @@ where if need_parity != parity_bit { return Err(Error::ParityError); } + Ok(data) } } + pub fn parse_format() { let test = include_str!("../../keymaps/qwerty.keymap").lines(); // r#"0-NONE\n1-HI#Says HI"# diff --git a/ableos/src/keyboard/small_types.rs b/ableos/src/keyboard/small_types.rs index 1ab5bfe..31661a6 100644 --- a/ableos/src/keyboard/small_types.rs +++ b/ableos/src/keyboard/small_types.rs @@ -1,4 +1,5 @@ #![allow(non_snake_case)] + #[derive(Debug)] pub struct Modifiers { pub lshift: bool, @@ -9,17 +10,21 @@ pub struct Modifiers { pub capslock: bool, pub alt_gr: bool, } + impl Modifiers { pub fn is_shifted(&self) -> bool { self.lshift | self.rshift } + pub fn is_ctrl(&self) -> bool { self.lctrl | self.rctrl } + pub fn is_caps(&self) -> bool { self.capslock } } + #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum KeyState { Up, @@ -30,11 +35,13 @@ pub struct KeyEvent { pub code: KeyCode, pub state: KeyState, } + impl KeyEvent { pub fn new(code: KeyCode, state: KeyState) -> KeyEvent { KeyEvent { code, state } } } + #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum HandleControl { /// If either Ctrl key is held down, convert the letters A through Z into @@ -45,6 +52,7 @@ pub enum HandleControl { /// and leave the letters as letters. Ignore, } + #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum DecodeState { Start, @@ -52,6 +60,7 @@ pub enum DecodeState { Release, ExtendedRelease, } + /// Indicates different error conditions. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Error { @@ -61,6 +70,7 @@ pub enum Error { UnknownKeyCode, InvalidState, } + #[derive(Debug, PartialEq, Eq, Copy, Clone)] #[repr(u8)] pub enum DecodedKeyKind { @@ -73,6 +83,7 @@ pub struct DecodedKey { pub kind: DecodedKeyKind, pub value: u32, } + impl From for DecodedKey { fn from(ch: char) -> Self { Self { @@ -81,6 +92,7 @@ impl From for DecodedKey { } } } + impl From for DecodedKey { fn from(kc: KeyCode) -> Self { Self { @@ -89,6 +101,7 @@ impl From for DecodedKey { } } } + impl DecodedKey { pub const ZERO: Self = Self { kind: DecodedKeyKind::Unicode, @@ -107,6 +120,7 @@ impl DecodedKey { } } } + macro_rules! keycode_enum { (@get_last $Variant:ident) => { Self::$Variant @@ -134,6 +148,7 @@ macro_rules! keycode_enum { keycode_enum!($($Variant=$Value,)* ); }; } + // This will be a way to map keys to other keys / keyyngs / macros keycode_enum! { AltLeft = 0x00, diff --git a/ableos/src/keyboard/traits.rs b/ableos/src/keyboard/traits.rs index 789464e..9be9296 100644 --- a/ableos/src/keyboard/traits.rs +++ b/ableos/src/keyboard/traits.rs @@ -1,13 +1,18 @@ -use super::*; +use super::Error; +use crate::{DecodeState, DecodedKey, HandleControl, KeyCode, KeyEvent, Modifiers}; + pub trait ScancodeSet { /// Handles the state logic for the decoding of scan codes into key events. fn advance_state(&self, state: &mut DecodeState, code: u8) -> Result, Error>; + /// Convert a Scan Code set X byte to our 'KeyType' enum fn map_scancode(&self, code: u8) -> Result; + /// Convert a Scan Code Set X extended byte (prefixed E0) to our `KeyType` /// enum. fn map_extended_scancode(&self, code: u8) -> Result; } + pub trait KeyboardLayout { /// Convert a `KeyType` enum to a Unicode character, if possible. /// `KeyType::A` maps to `Some('a')` (or `Some('A')` if shifted), while diff --git a/ableos/src/kmain.rs b/ableos/src/kmain.rs index 567c039..5f2850a 100644 --- a/ableos/src/kmain.rs +++ b/ableos/src/kmain.rs @@ -1,15 +1,14 @@ #![allow(clippy::empty_loop)] -// use acpi::AcpiTables; -// use x86_64::instructions::interrupts::{disable, enable}; - -// use crate::{scratchpad, SCHEDULER, SCREEN_BUFFER}; - +use crate::info::master; +use crate::scheduler::SCHEDULER; use crate::{ arch::{init, sloop}, relib::network::socket::{SimpleSock, Socket}, scratchpad, }; +use crate::{boot_conf::KernelConfig, systeminfo::RELEASE_TYPE}; +use kernel::KERNEL_VERSION; use spin::Lazy; // TODO: Change this structure to allow for multiple cores loaded @@ -53,10 +52,3 @@ pub fn log_version_data() { master().unwrap().brand_string().unwrap() ); } - -use crate::info::master; - -use kernel::KERNEL_VERSION; - -use crate::scheduler::SCHEDULER; -use crate::{boot_conf::KernelConfig, systeminfo::RELEASE_TYPE}; diff --git a/ableos/src/lib.rs b/ableos/src/lib.rs index ff09163..bf46f74 100644 --- a/ableos/src/lib.rs +++ b/ableos/src/lib.rs @@ -4,109 +4,80 @@ //! #![no_std] -#![feature( - abi_x86_interrupt, - asm_sym, - alloc_error_handler, - core_intrinsics, - exclusive_range_pattern, - lang_items, - naked_functions, - slice_pattern, - prelude_import -)] +#![feature(abi_x86_interrupt)] +#![feature(alloc_error_handler)] +#![feature(prelude_import)] + +#[macro_use] +pub extern crate log; + +pub extern crate alloc; +pub extern crate externc_libm as libm; /// Contains architecture specific code for aarch64. #[cfg(target_arch = "aarch64")] #[path = "arch/aarch64/mod.rs"] pub mod arch; -/// Contains architecture specific code for x86_64. -#[cfg(target_arch = "x86_64")] -#[path = "arch/x86_64/mod.rs"] -pub mod arch; - /// Contains architecture specific code for riscv64. #[cfg(target_arch = "riscv64")] #[path = "arch/riscv/mod.rs"] pub mod arch; -#[macro_use] -pub mod print; -pub mod devices; -pub mod rhai_shell; -pub mod wasm_jumploader; +/// Contains architecture specific code for x86_64. +#[cfg(target_arch = "x86_64")] +#[path = "arch/x86_64/mod.rs"] +pub mod arch; #[cfg(target_arch = "x86_64")] pub mod port_io; #[macro_use] -pub mod serial_print; -pub mod time; +pub mod print; #[macro_use] -pub extern crate log; +pub mod serial_print; -///////////// -// Modules // -///////////// pub mod allocator; +pub mod boot_conf; +pub mod devices; pub mod driver_traits; pub mod experiments; +pub mod filesystem; pub mod graphics; pub mod kernel_state; pub mod keyboard; pub mod kmain; pub mod logger; +pub mod prelude; pub mod relib; +pub mod rhai_shell; pub mod scheduler; -mod unicode_utils; +pub mod scratchpad; +pub mod stdio; +pub mod time; pub mod utils; -// pub mod vga_e; +pub mod virtio; pub mod wasm; +pub mod wasm_jumploader; -pub extern crate alloc; -pub extern crate externc_libm as libm; +mod unicode_utils; -////////////////// -// Re-exports /// -//////////////// pub use allocator::*; pub use driver_traits::*; pub use experiments::*; pub use graphics::*; +pub use kernel; +pub use kernel::messaging; +pub use kernel::panic; pub use kernel_state::*; pub use keyboard::*; pub use logger::*; pub use relib::*; -// pub use scheduler::*; -pub use utils::*; -// pub use vga_e::*; -pub use wasm::*; -pub mod boot_conf; -pub mod virtio; -pub use virtio::*; - -// pub mod alias_table; -// pub use alias_table::*; - -// pub mod tests; -// pub use tests::*; - -pub mod scratchpad; pub use scratchpad::*; -pub mod filesystem; - -/////////////// -/// Kernel /// -///////////// -pub use kernel; -pub use kernel::messaging; -pub use kernel::panic; - -pub mod prelude; +pub use utils::*; +pub use virtio::*; +pub use wasm::*; #[prelude_import] pub use prelude::rust_2021::*; - -pub mod stdio; diff --git a/ableos/src/logger.rs b/ableos/src/logger.rs index da830e2..a42b0f8 100644 --- a/ableos/src/logger.rs +++ b/ableos/src/logger.rs @@ -1,14 +1,15 @@ use crate::kmain::KERNEL_CONF; use crate::network::socket::{SimpleSock, Socket}; use crate::time::fetch_time; - use lliw::{Fg, Reset}; use log::{Level, Metadata, Record}; +use log::{LevelFilter, SetLoggerError}; -struct SimpleLogger; +static LOGGER: SimpleLogger = SimpleLogger; // TODO: Rebuild this to take advantage of sockets // DETAIL: Log to a socket instead of the screen -// So that we can log in the kernel and display it in userland +// So that we can log in the kernel and display it in userland +struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= Level::Trace @@ -62,10 +63,6 @@ impl log::Log for SimpleLogger { fn flush(&self) {} } -use log::{LevelFilter, SetLoggerError}; - -static LOGGER: SimpleLogger = SimpleLogger; - pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Trace)) } diff --git a/ableos/src/port_io.rs b/ableos/src/port_io.rs index 15b6d66..ad5fcc6 100644 --- a/ableos/src/port_io.rs +++ b/ableos/src/port_io.rs @@ -3,6 +3,7 @@ use cpuio::{inb, inl, outb, outl}; pub fn read32(reg: u16) -> u32 { unsafe { inl(reg) } } + pub fn read8(reg: u16) -> u8 { unsafe { inb(reg) } } diff --git a/ableos/src/prelude/rust_2021.rs b/ableos/src/prelude/rust_2021.rs index 502037f..1bfe654 100644 --- a/ableos/src/prelude/rust_2021.rs +++ b/ableos/src/prelude/rust_2021.rs @@ -1,10 +1,7 @@ +pub use crate::print::*; +pub use crate::serial_print::*; +pub use alloc::{boxed::Box, format, string::*, vec, vec::*}; pub use core::arch::asm; pub use core::prelude::rust_2021::*; pub use core::prelude::v1::*; - -pub use crate::print::*; -pub use crate::serial_print::*; - pub use log::{debug, info, trace, warn}; - -pub use alloc::{boxed::Box, format, string::*, vec, vec::*}; diff --git a/ableos/src/print.rs b/ableos/src/print.rs index c87e7df..b2fd0b0 100644 --- a/ableos/src/print.rs +++ b/ableos/src/print.rs @@ -1,8 +1,10 @@ // TODO: refactor this file // TODO: make STDOUT redirect to a socket owned // by the process named "stdout" -pub struct Stdout; + use core::fmt::{Arguments, Error}; + +pub struct Stdout; impl Stdout { pub fn write_fmt(&mut self, arg: Arguments<'_>) /*-> Result<(), Error> */ { @@ -10,6 +12,7 @@ impl Stdout { // Ok(()) } } + impl core::fmt::Write for Stdout { #[cfg(target_arch = "aarch64")] fn write_str(&mut self, s: &str) -> Result<(), Error> { @@ -33,6 +36,7 @@ impl core::fmt::Write for Stdout { core::fmt::write(&mut self, args) } } + #[macro_export] macro_rules! print { () => { diff --git a/ableos/src/relib/clparse/mod.rs b/ableos/src/relib/clparse/mod.rs index ef4b370..d280f2f 100644 --- a/ableos/src/relib/clparse/mod.rs +++ b/ableos/src/relib/clparse/mod.rs @@ -1,9 +1,6 @@ -/* -clparse -* A simple command line parser for ableOS -*/ +/// # clparse +/// simple command line parser for ableOS -// use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Argument { key: String, @@ -53,6 +50,7 @@ impl Command { } } } + pub fn test() { let x = Command::parse("hi?there=uwu&hi=abc".to_string()); diff --git a/ableos/src/relib/encoding/rle.rs b/ableos/src/relib/encoding/rle.rs index abcd216..f1d4953 100644 --- a/ableos/src/relib/encoding/rle.rs +++ b/ableos/src/relib/encoding/rle.rs @@ -17,13 +17,12 @@ pub fn encode(bytes: &[u8]) -> Vec { } encoding.push(occurrences); - encoding } /// Read a run-length encoding and return its decoded contents. /// -/// * `bytes` - The bytes to be decoded. +/// - `bytes` - The bytes to be decoded. pub fn decode(bytes: &[u8]) -> Vec { let mut decoding = Vec::::new(); diff --git a/ableos/src/relib/image/mod.rs b/ableos/src/relib/image/mod.rs index bd47023..51c18fa 100644 --- a/ableos/src/relib/image/mod.rs +++ b/ableos/src/relib/image/mod.rs @@ -1,3 +1 @@ pub mod mono_bitmap; - -pub mod stupid_simple_image; diff --git a/ableos/src/relib/image/mono_bitmap.rs b/ableos/src/relib/image/mono_bitmap.rs index 4186c15..dea1e93 100644 --- a/ableos/src/relib/image/mono_bitmap.rs +++ b/ableos/src/relib/image/mono_bitmap.rs @@ -1,10 +1,8 @@ -use shadeable::pixel_format::new_rgba64; - use crate::{ graphics::SCREEN_BUFFER, relib::encoding::rle::{decode, encode}, }; -// use super::qoi; +use shadeable::pixel_format::new_rgba64; pub fn bruh() { #[rustfmt::skip] diff --git a/ableos/src/relib/image/stupid_simple_image/mod.rs b/ableos/src/relib/image/stupid_simple_image/mod.rs deleted file mode 100644 index fd6b2a0..0000000 --- a/ableos/src/relib/image/stupid_simple_image/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -/* -r[255,0,0] -g[0,0,0] -b[0,0,0] -a[0,0,0] -*/ diff --git a/ableos/src/relib/network/socket.rs b/ableos/src/relib/network/socket.rs index 0a546f0..b1187e2 100644 --- a/ableos/src/relib/network/socket.rs +++ b/ableos/src/relib/network/socket.rs @@ -1,3 +1,6 @@ +pub static SOCKETS: spin::Mutex = spin::Mutex::new(vec![]); + +pub type SocketState = Vec; pub type Stream = Vec; #[derive(Debug)] @@ -32,9 +35,6 @@ impl Socket for SocketID { } } -pub type SocketState = Vec; -pub static SOCKETS: spin::Mutex = spin::Mutex::new(vec![]); - pub trait Socket { fn peek(&mut self) -> SocketReturns; @@ -47,6 +47,7 @@ pub trait Socket { fn close(&mut self) {} } + #[derive(Debug)] pub enum SocketReturns { ReadOk(Stream), @@ -113,6 +114,7 @@ impl Socket for SimpleSock { } SocketReturns::ReadOk(return_vec) } + fn read(&mut self, length: usize) -> SocketReturns { let mut return_vec = vec![]; if length > self.stream.len() { @@ -125,9 +127,11 @@ impl Socket for SimpleSock { SocketReturns::ReadOk(return_vec) } } + fn register_protocol(&mut self, protocol_name: String) { self.protocol = Some(protocol_name); } + fn check_protocol(&mut self, protocol_name: String) -> bool { if self.protocol == Some(protocol_name) { return true; @@ -135,11 +139,13 @@ impl Socket for SimpleSock { false } + fn write(&mut self, stream: Stream) -> SocketReturns { for byte in stream { self.stream.push(byte); } SocketReturns::WriteOk } + fn close(&mut self) {} } diff --git a/ableos/src/relib/time/kilotime.rs b/ableos/src/relib/time/kilotime.rs index c180f9f..7774a61 100644 --- a/ableos/src/relib/time/kilotime.rs +++ b/ableos/src/relib/time/kilotime.rs @@ -1,8 +1,27 @@ use super::Time; use core::fmt::{Display, Error, Formatter}; + #[derive(Debug, Clone, Copy)] #[repr(transparent)] pub struct Kilosecond(usize); +impl Kilosecond { + pub fn from_ms(ms: usize) -> Self { + Self(ms) + } + pub fn from_sec(sec: usize) -> Self { + Self(sec * 1000) + } + pub fn from_minutes(min: usize) -> Self { + Self(min * 60 * 1000) + } + pub fn from_hours(hrs: usize) -> Self { + Self(hrs * 60 * 60 * 1000) + } + pub fn from_days(days: usize) -> Self { + Self(days * 24 * 60 * 60 * 1000) + } +} + impl Display for Kilosecond { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { let mut reg = self.0; @@ -36,37 +55,23 @@ impl Display for Kilosecond { Ok(()) } } + impl core::ops::Add for Kilosecond { type Output = Self; fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) } } + impl core::ops::Sub for Kilosecond { type Output = Self; fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) } } + impl From