editor #6

Merged
zxq5 merged 4 commits from editor into dev 2025-02-28 03:05:38 +00:00
34 changed files with 665 additions and 130 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
[build] [build]
target = "x86_64-kernel" target = "x86_64-kernel.json"
target-dir = "build/target" target-dir = "build/target"
[unstable] [unstable]
+2
View File
@@ -4,6 +4,8 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/kernel/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/kernel/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/lib_example/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/lib_example/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/libk/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/libm/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" /> <excludeFolder url="file://$MODULE_DIR$/target" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
+3 -1
View File
@@ -1 +1,3 @@
{} {
"cssTheme": "Dark Moss"
}
+1
View File
@@ -0,0 +1 @@
[]
File diff suppressed because one or more lines are too long
@@ -0,0 +1,12 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.8.3",
"minAppVersion": "1.1.6",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://www.zsolt.blog",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
}
File diff suppressed because one or more lines are too long
+20 -33
View File
@@ -4,41 +4,21 @@
"type": "split", "type": "split",
"children": [ "children": [
{ {
"id": "a20540b7c1ddbfca", "id": "c178a2dff57ae0aa",
"type": "tabs", "type": "tabs",
"children": [ "children": [
{ {
"id": "e1fb15cab546d0b6", "id": "6d395e6a4c72e1c8",
"type": "leaf", "type": "leaf",
"state": { "state": {
"type": "markdown", "type": "markdown",
"state": { "state": {
"file": "Usage/Building The Kernel.md", "file": "Planning & To-Dos.md",
"mode": "source", "mode": "source",
"source": false "source": false
}, },
"icon": "lucide-file", "icon": "lucide-file",
"title": "Building The Kernel" "title": "Planning & To-Dos"
}
}
]
},
{
"id": "6bf1f87bf81a3031",
"type": "tabs",
"children": [
{
"id": "add883d295e04659",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "Usage/Building The Kernel.md",
"mode": "preview",
"source": false
},
"icon": "lucide-file",
"title": "Building The Kernel"
} }
} }
] ]
@@ -73,7 +53,7 @@
"state": { "state": {
"type": "search", "type": "search",
"state": { "state": {
"query": "tag:#usage", "query": "",
"matchingCase": false, "matchingCase": false,
"explainSearch": false, "explainSearch": false,
"collapseAll": false, "collapseAll": false,
@@ -98,8 +78,7 @@
} }
], ],
"direction": "horizontal", "direction": "horizontal",
"width": 200, "width": 307.5
"collapsed": true
}, },
"right": { "right": {
"id": "baa2a8e61b737fa6", "id": "baa2a8e61b737fa6",
@@ -177,7 +156,8 @@
} }
], ],
"direction": "horizontal", "direction": "horizontal",
"width": 300 "width": 300,
"collapsed": true
}, },
"left-ribbon": { "left-ribbon": {
"hiddenItems": { "hiddenItems": {
@@ -185,14 +165,21 @@
"graph:Open graph view": false, "graph:Open graph view": false,
"canvas:Create new canvas": false, "canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false, "daily-notes:Open today's daily note": false,
"templates:Insert template": false, "command-palette:Open command palette": false,
"command-palette:Open command palette": false "templates:Insert template": false
} }
}, },
"active": "add883d295e04659", "active": "6d395e6a4c72e1c8",
"lastOpenFiles": [ "lastOpenFiles": [
"Usage/Building The Kernel.md",
"Planning & To-Dos.md",
"structure/idk.canvas",
"structure/kernel.md",
"structure/libk.md",
"structure/libm.md",
"structure/libk",
"structure",
"Usage", "Usage",
"Welcome.md", "Welcome.md"
"Usage/Building The Kernel.md"
] ]
} }
+130
View File
@@ -0,0 +1,130 @@
> [!todo] Testing
> - [ ] setup custom test frameworks (Use CrystalOS-V2 as a reference)
> - [ ] write a sub-crate for tests
> - [ ] implement several unit tests on things that we are likely to break often
> - [ ] setup Git CI/CD pipeline with testing
> - [ ] figure out how to run QEMU in the test environment
> - [ ] write a script to run tests
> - [ ] a release should only be published if all tests pass
> [!todo] Allocator
> - [ ] learn about several allocator designs and decide on the optimal one
> - [ ] implementation
> - [ ] implement an allocate method
> - [ ] implement a deallocate method
> - [ ] set the global allocator
> - [ ] testing
> - [ ] write unit tests
> - [ ] many allocations
> - [ ] large allocations
> - [ ] allocating more memory than is available
> - [ ] pass unit tests
> [!todo] Threading
> - [ ] implement thread switching functionality
> - [ ] switch stacks
> - [ ] implement multi-threading
> - [ ] figure out how to turn on another core
> - [ ] Scheduler
> - [ ] which task goes on which thread?
> - [ ] round robin / time slicing algorithm
> - [ ] switch tasks on a given core
> - [ ] push registers
> - [ ] switch stacks
> - [ ] ensure the scheduler knows where to find the stack for each thread
> - [ ] move a given task to a new core
> - [ ] differentiate between kernel threads and user threads
> - [ ] create syscall to create a new thread
> [!todo] Filesystem
> - [ ] AHCI Implementation
> - [ ] figure out what hard drives are attached
> - [ ] read data
> - [ ] write data
> - [ ] FAT32 Implementation
> - [ ] parse FAT header
> - [ ] figure out where files are / what files are what
> - [ ] parse file metadata / figure out type of file
> - [ ] reading the entirety of a file into memory
> - [ ] *(extension)* ext2 Implementation
> - [ ] Syscall API
> - [ ] provide a user program with file read / write access given a filename
> - [ ] translate a filename into a disk location of data & the size of the data
> - [ ] provide an interface to read from a file or write to a file
> [!todo] APIC
> - [ ] Enable APIC
> - [x] Get apic location from MSR
> - [x] Enable APIC bit flag
> - [x] Disable Legacy PIC
> - [ ] Map physical APIC address to virtual memory
>
>> [!error]
>> Page fault exception occurs when APIC is activated
>
>- [ ] Setup Interrupt handlers to handle interrupts generated by the APIC
> - [ ] Timer Interrupts
> - [ ] Keyboard Interrupts
> [!todo] Userspace (req: Threading, Filesystem)
> - [ ] Load program into memory from disk
> - [ ] requires:
> - [ ] Program Loader
> - [ ] Parse ELF File
> - [ ] Load file into memory
> - [ ] Filesystem
> - [ ] Scheduler (to start and manage the process)
> - [ ] Start a user process
> - [ ] switch stacks
> - [ ] jump to user code
>[!todo] User Interface
>- This will be a library so that programs in userspace can provide a user interface rather than relying on text commands from a basic terminal
>- features required:
> - [ ] Rendering frames to a display buffer
> - [ ] requires: Frame rendering Syscall
> - [ ] I/O
> - [ ] syncio
> - [ ] keystrokes
> - [ ] asyncio
> - [ ] keystrokes
> - [ ] requires: I/O Syscalls
> - [ ] Window struct
> - [ ] stores it's size and location
> - [ ] handles rendering pixels to the screen
> - [ ] Widgets
> - [ ] textbox / label
> - [ ] single line text input
> - [ ] how do we capture keyboard inputs?
> - [ ] multiline text input
> - [ ] how do we capture keyboard inputs?
> - [ ] button
> - [ ] dialog
> - [ ] box widget
> - [ ] figure out how to nest other widgets inside it
>```rust
>pub struct Window {
> position;
> dimensions;
>}
>
>impl Window {
> fn display(&self, frame: &Frame) -> Result<(), RenderError>;
>}
>
>pub struct Frame<'a> {
> window: &'a Window,
> data: <"... a suitable type to store pixels">
>}
>
>impl<'a> Frame<'a> {
> pub fn display(&self) -> Result<(), RenderError> {
> self.window.display(self)
> }
>}
>
> pub trait Widget {
> fn render(&self) -> Frame;
> }
>```
+41
View File
@@ -0,0 +1,41 @@
{
"nodes":[
{"id":"8391ed519ab6cb3d","type":"group","x":-920,"y":600,"width":1595,"height":360,"label":"Hardware Layer"},
{"id":"967decfbdbf166e2","type":"group","x":-920,"y":120,"width":1595,"height":320,"label":"Kernel Layer (kernelspace)"},
{"id":"efd3cf75db396678","type":"group","x":-920,"y":-280,"width":1595,"height":240,"label":"System Layer (userspace)"},
{"id":"d577e6c4fa3d7479","type":"group","x":-920,"y":-600,"width":1595,"height":140,"label":"User Layer (userspace)"},
{"id":"549099b4188ff073","type":"text","text":"Interrupt handling & initialisation","x":-204,"y":320,"width":250,"height":60,"color":"2"},
{"id":"d0c73e9e86edba62","type":"text","text":"Kernel #kernel","x":-220,"y":260,"width":281,"height":140,"color":"2"},
{"id":"4fdc8ae730503ad0","type":"text","text":"libk #kernel","x":-880,"y":260,"width":280,"height":140,"color":"2"},
{"id":"4839a4f4f0980254","type":"text","text":"System Libraries #userspace","x":-220,"y":-240,"width":281,"height":160,"color":"3"},
{"id":"ba48ee2ccc891a62","type":"text","text":"Scheduler","x":-880,"y":160,"width":280,"height":60,"color":"2"},
{"id":"3d31fc276e0ba4a0","type":"text","text":"UI Shell #userspace","x":-880,"y":-560,"width":280,"height":60,"color":"4"},
{"id":"6b5e17c10589a7b6","type":"text","text":"Generic Application #userspace","x":-219,"y":-560,"width":281,"height":60,"color":"4"},
{"id":"0a47f47a2c7b3609","type":"text","text":"CPU #hardware","x":-880,"y":640,"width":280,"height":280,"color":"1"},
{"id":"a7002e4427f0540d","type":"text","text":"lib_io","x":-200,"y":-160,"width":122,"height":60,"color":"3"},
{"id":"e09d0bccffd19ed9","type":"text","text":"lib_ui","x":-78,"y":-160,"width":118,"height":60,"color":"3"},
{"id":"cbfeda8989b260d8","type":"text","text":"Userspace Drivers #userspace","x":360,"y":-240,"width":281,"height":160,"color":"3"},
{"id":"3acced35498279a0","type":"text","text":"Hardware #hardware\n- Display\n- Hard drives\n- Keyboard\n- Mouse","x":360,"y":640,"width":281,"height":280,"color":"1"},
{"id":"31548bb91b4977eb","type":"text","text":"Syscall API","x":-219,"y":160,"width":281,"height":60,"color":"2"},
{"id":"110b7bee2ba99819","type":"text","text":"Drivers & low level kernel libraries","x":-860,"y":320,"width":240,"height":60,"color":"2"}
],
"edges":[
{"id":"6a8d6b7540c2898d","fromNode":"3d31fc276e0ba4a0","fromSide":"right","toNode":"4839a4f4f0980254","toSide":"left","color":"3"},
{"id":"57aedf427a150ff1","fromNode":"6b5e17c10589a7b6","fromSide":"bottom","toNode":"4839a4f4f0980254","toSide":"top","color":"3","label":"Applications are statically \nlinked to system libraries"},
{"id":"d292a19f88032809","fromNode":"4839a4f4f0980254","fromSide":"bottom","toNode":"31548bb91b4977eb","toSide":"top","color":"2","label":"system libraries make syscalls"},
{"id":"8b437f1c08e1caf2","fromNode":"ba48ee2ccc891a62","fromSide":"top","toNode":"3d31fc276e0ba4a0","toSide":"bottom","color":"4","label":"Scheduler Starts\nUI in userspace"},
{"id":"3e2c6f6d5dcd7613","fromNode":"4839a4f4f0980254","fromSide":"right","toNode":"cbfeda8989b260d8","toSide":"left","color":"3"},
{"id":"88f6e95c288c933d","fromNode":"31548bb91b4977eb","fromSide":"top","toNode":"4839a4f4f0980254","toSide":"bottom","color":"2"},
{"id":"156c8a89b537e219","fromNode":"cbfeda8989b260d8","fromSide":"left","toNode":"4839a4f4f0980254","toSide":"right","color":"3","label":"some libs talk to\nhardware through\nuserspace drivers"},
{"id":"0d04c5b0f76a5d9b","fromNode":"cbfeda8989b260d8","fromSide":"bottom","toNode":"3acced35498279a0","toSide":"top","fromEnd":"arrow","color":"1","label":"Userspace drivers can talk\ndirectly to hardware so\nin the case of a driver crash\nthe kernel is unaffected"},
{"id":"e9f1afb45bf17b77","fromNode":"4fdc8ae730503ad0","fromSide":"bottom","toNode":"3acced35498279a0","toSide":"left","fromEnd":"arrow","color":"1","label":"Libk handles most hardware\ninteraction, keeping the core kernel codebase as minimal\nas possible"},
{"id":"99414d640e519c8c","fromNode":"4fdc8ae730503ad0","fromSide":"right","toNode":"d0c73e9e86edba62","toSide":"left","fromEnd":"arrow","color":"2","label":"kernel static linked to libk\nmost kernel functionality\nisfound in libk"},
{"id":"85cd865c914dd125","fromNode":"549099b4188ff073","fromSide":"top","toNode":"d0c73e9e86edba62","toSide":"top","color":"2"},
{"id":"e882694ec774c0d6","fromNode":"4fdc8ae730503ad0","fromSide":"top","toNode":"ba48ee2ccc891a62","toSide":"bottom","color":"2"},
{"id":"c689b667be8cdfab","fromNode":"d0c73e9e86edba62","fromSide":"top","toNode":"31548bb91b4977eb","toSide":"bottom","color":"2"},
{"id":"0c9da0cce11e4bd1","fromNode":"ba48ee2ccc891a62","fromSide":"bottom","toNode":"4fdc8ae730503ad0","toSide":"top","color":"2"},
{"id":"c45efb0ad498f8a8","fromNode":"ba48ee2ccc891a62","fromSide":"right","toNode":"6b5e17c10589a7b6","toSide":"left","color":"4","label":"Scheduler\nstarts applications"},
{"id":"aee2cd6ef9682f0f","fromNode":"31548bb91b4977eb","fromSide":"left","toNode":"ba48ee2ccc891a62","toSide":"right","color":"2","label":"system libs can talk to\nthe scheduler to manage\nprocesses"},
{"id":"b1b2b96d8ac2b490","fromNode":"4fdc8ae730503ad0","fromSide":"bottom","toNode":"0a47f47a2c7b3609","toSide":"top","fromEnd":"arrow","color":"1"}
]
}
View File
View File
+16
View File
@@ -0,0 +1,16 @@
- contains all proc macros for building the kernel
## Current Features
### font importer:
- a macro that takes a filename to a font file and turns it into a font.
```rust
pub struct Font {
width: usize,
height: usize,
length: u16,
data: [[u8; 16]; 512],
}
pub static FONT_CP850_8X16: Font =
Font::new(include_font!("./libk/resources/font/cp850-8x16.psf"));
```
+4 -5
View File
@@ -8,7 +8,6 @@ use x86_64::structures::paging::{FrameAllocator, Mapper, Page, PageTableFlags, S
use spin::{Lazy, Mutex}; use spin::{Lazy, Mutex};
use super::apic::enable_apic;
use super::gdt; use super::gdt;
static IDT: Lazy<InterruptDescriptorTable> = Lazy::new(|| { static IDT: Lazy<InterruptDescriptorTable> = Lazy::new(|| {
@@ -92,7 +91,7 @@ extern "x86-interrupt" fn double_fault_handler(
} }
extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) { extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
use pc_keyboard::{HandleControl, Keyboard, ScancodeSet1, layouts}; use pc_keyboard::{layouts, HandleControl, Keyboard, ScancodeSet1};
// use pc_keyboard::DecodedKey; // use pc_keyboard::DecodedKey;
use spin::Mutex; use spin::Mutex;
use x86_64::instructions::port::Port; use x86_64::instructions::port::Port;
@@ -125,13 +124,13 @@ extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFr
} }
extern "x86-interrupt" fn page_fault_handler( extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame, _stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode, _error_code: PageFaultErrorCode,
) { ) {
// serial_println!("Exception: Page Fault"); // serial_println!("Exception: Page Fault");
// serial_println!("Accessed Address: {:?}", Cr2::read()); // serial_println!("Accessed Address: {:?}", Cr2::read());
// serial_println!("Error Code: {:?}", error_code); // serial_println!("Error Code: {:?}", error_code);
// serial_println!("{:#?}", stack_frame); // serial_println!("{:#?}", _stack_frame);
if let Some(frame_allocator) = FRAME_ALLOCATOR.get() { if let Some(frame_allocator) = FRAME_ALLOCATOR.get() {
let mut f = frame_allocator.lock(); let mut f = frame_allocator.lock();
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn boot() -> Result<(), &'static str> {
print_log!(" Initialising Memory Subsystem... "); print_log!(" Initialising Memory Subsystem... ");
let physical_memory_offset = VirtAddr::new(*memmap::PHYSICAL_MEMORY_OFFSET); let physical_memory_offset = VirtAddr::new(*memmap::PHYSICAL_MEMORY_OFFSET);
let mut l4_table = memory::init_page_table(physical_memory_offset); memory::init_page_table(physical_memory_offset);
println_log!("[Success]"); println_log!("[Success]");
print_log!(" Setting Up Page Table... "); print_log!(" Setting Up Page Table... ");
+4 -8
View File
@@ -3,10 +3,11 @@
extern crate alloc; extern crate alloc;
use alloc::vec;
use libk::{ use libk::{
drivers::{ drivers::{
async_io::task::{Executor, Task}, async_io::task::{Executor, Task},
io, io::{self, framebuffer::colour::Colour},
}, },
prelude::*, prelude::*,
util::shell::shell, util::shell::shell,
@@ -28,13 +29,8 @@ extern "C" fn kmain() -> ! {
println!("Dimensions: {}x{} (chars)", dimensions.0, dimensions.1); println!("Dimensions: {}x{} (chars)", dimensions.0, dimensions.1);
let mut executor = Executor::new(); let mut executor = Executor::new();
let mut v = Vec::with_capacity(1000 * 1000);
for i in 0..1000 * 1000 {
v.push(i);
}
println!("v.len(): {}", v.len());
executor.spawn(Task::new(shell())); executor.spawn(Task::new(shell()));
executor.run(); executor.run();
loop {}
} }
+1 -1
View File
@@ -18,5 +18,5 @@ spin = "0.9.8"
futures-util = { version = "0.3.31", default-features = false, features = [ futures-util = { version = "0.3.31", default-features = false, features = [
"alloc", "alloc",
] } ] }
linked_list_allocator = "0.10.5" linked_list_allocator = { version = "0.10.5", features = ["use_spin"] }
libm = { path = "../libm" } libm = { path = "../libm" }
+1 -1
View File
@@ -12,7 +12,7 @@ libk is an attempt to move away from the godforsaken git submodules that plagued
A lot of things must be improved and worked on, feel free to add extra TODOs below. A lot of things must be improved and worked on, feel free to add extra TODOs below.
[] Create a kernel logging abstraction similar to Linux. (this should probably just use the serial drivers) - [] Create a kernel logging abstraction similar to Linux. (this should probably just use the serial drivers)
The rationale behind this is that we want some sort of debug log/tracing support so we aren't just printf debugging forever. The rationale behind this is that we want some sort of debug log/tracing support so we aren't just printf debugging forever.
+1 -1
View File
@@ -72,7 +72,7 @@ impl Writer {
} }
// Get the character data from the font array. -- each byte is a row of pixels // Get the character data from the font array. -- each byte is a row of pixels
let data: &[u8] = &self.font.0[c as usize]; let data: &[u8] = self.font.glyph_for(c as u16);
if let Some(writer) = FRAMEBUFFER_WRITER.lock().as_mut() { if let Some(writer) = FRAMEBUFFER_WRITER.lock().as_mut() {
for (row, line) in data.iter().enumerate().take(16) { for (row, line) in data.iter().enumerate().take(16) {
+9 -2
View File
@@ -61,9 +61,16 @@ impl FramebufferWriter {
} }
} }
pub fn render_frame(&self, buffer: &[Colour; 1280 * 800]) { pub fn render_frame(&self, buffer: &[&[Colour]]) {
for (y, row) in buffer.chunks(1280).enumerate() { // TODO: this should return errors
for (y, &row) in buffer.iter().enumerate() {
if y >= self.height() as usize {
break;
}
for (x, pixel) in row.iter().enumerate() { for (x, pixel) in row.iter().enumerate() {
if x >= self.width() as usize {
break;
}
self.write_pixel(x, y, *pixel); self.write_pixel(x, y, *pixel);
} }
} }
+4 -51
View File
@@ -1,15 +1,7 @@
use linked_list_allocator::LockedHeap; use linked_list_allocator::LockedHeap;
use x86_64::{ use x86_64::structures::paging::{
VirtAddr, mapper::MapToError,
structures::paging::{ Size4KiB,
FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB,
mapper::{MapToError, MapperFlushAll},
},
};
use crate::{
drivers::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE},
serial_print, serial_println,
}; };
/// We are currently using a linked list heap allocator which uses our underlying page allocator. /// We are currently using a linked list heap allocator which uses our underlying page allocator.
@@ -24,46 +16,7 @@ pub const HEAP_SIZE: usize = 1024 * 1024 * 1024;
/// Sets up the heap using the backing page frame allocator. /// Sets up the heap using the backing page frame allocator.
pub fn init_heap() -> Result<(), MapToError<Size4KiB>> { pub fn init_heap() -> Result<(), MapToError<Size4KiB>> {
// let mut frame_allocator = if let Some(f) = FRAME_ALLOCATOR.get() { // code to allocate frames is now done in the page fault interrupt handler!
// f.lock()
// } else {
// return Err(MapToError::FrameAllocationFailed);
// };
// let mut mapper = if let Some(m) = OFFSET_PAGE_TABLE.get() {
// m.lock()
// } else {
// return Err(MapToError::FrameAllocationFailed);
// };
// let range = {
// let heap_start = VirtAddr::new(HEAP_START as u64);
// let heap_end = heap_start + HEAP_SIZE as u64 - 1u64;
// let heap_start_page = Page::<Size4KiB>::containing_address(heap_start);
// let heap_end_page = Page::<Size4KiB>::containing_address(heap_end);
// Page::range_inclusive(heap_start_page, heap_end_page)
// };
// let usable_frames = frame_allocator.count_usable_frames();
// serial_println!("usable frames: {}", usable_frames);
// let mut i = 0;
// for page in range {
// i += 1;
// if i % 128 == 0 {
// serial_println!("allocated {} pages", i);
// }
// let frame = frame_allocator
// .allocate_frame()
// .ok_or(MapToError::FrameAllocationFailed)?;
// let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
// unsafe {
// // IMPORTANT: make sure to flush the mapper!!!!
// let _ = mapper.map_to(page, frame, flags, &mut *frame_allocator)?;
// }
// }
// MapperFlushAll::new().flush_all();
unsafe { unsafe {
ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_SIZE); ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_SIZE);
+5 -5
View File
@@ -2,12 +2,12 @@
use limine::{memory_map::EntryType, response::MemoryMapResponse}; use limine::{memory_map::EntryType, response::MemoryMapResponse};
use spin::{Mutex, Once}; use spin::{Mutex, Once};
use x86_64::{ use x86_64::{
PhysAddr, VirtAddr, registers::control::Cr3, structures::paging::{
registers::control::Cr3, FrameAllocator, OffsetPageTable, PageTable, PhysFrame, Size4KiB
structures::paging::{ ,
FrameAllocator, Mapper, OffsetPageTable, Page, PageTable, PhysFrame, Size4KiB,
page_table::FrameError,
}, },
PhysAddr,
VirtAddr,
}; };
pub static FRAME_ALLOCATOR: Once<Mutex<FoundryOSFrameAllocator>> = Once::new(); pub static FRAME_ALLOCATOR: Once<Mutex<FoundryOSFrameAllocator>> = Once::new();
+42 -7
View File
@@ -2,12 +2,47 @@ use libm::include_font;
pub mod ibm_vga_8x16; pub mod ibm_vga_8x16;
pub static FONT_SPLEEN_8X16: Font = Font(include_font!( pub static FONT_SPLEEN_8X16: Font =
"./libk/resources/font/spleen-8x16.psf" Font::new(include_font!("./libk/resources/font/spleen-8x16.psf"));
));
pub static FONT_CP850_8X16: Font = Font(include_font!( pub static FONT_CP850_8X16: Font = Font::new(include_font!("./libk/resources/font/cp850-8x16.psf"));
"./libk/resources/font/cp850-8x16.psf"
));
pub struct Font(pub [[u8; 16]; 512]); // pub struct Font(pub [[u8; 16]; 512]);
pub struct Font {
width: usize,
height: usize,
length: u16,
data: [[u8; 16]; 512],
}
impl Font {
pub const fn new(data: [[u8; 16]; 512]) -> Font {
Font {
width: 8,
height: 16,
length: data.len() as u16,
data,
}
}
pub const fn glyph_for(&self, c: u16) -> &[u8] {
if c > self.length {
return &self.data[0];
}
&self.data[c as usize]
}
pub const fn width(&self) -> usize {
self.width
}
pub const fn height(&self) -> usize {
self.height
}
pub const fn default() -> &'static Font {
&FONT_CP850_8X16
}
}
+3 -3
View File
@@ -1,8 +1,8 @@
use crate::prelude::*; use crate::prelude::*;
mod frame; pub mod frame;
mod render; pub mod render;
mod window; pub mod window;
pub trait Application { pub trait Application {
type Output; type Output;
+26 -5
View File
@@ -1,19 +1,40 @@
use crate::{drivers::io::framebuffer::colour::Colour, std::maths::geometry::Vec2};
use super::{ use super::{
render::{ColouredChar, RenderError}, render::{ColouredChar, RenderError},
window::Window, window::{self, Window},
}; };
use alloc::vec::Vec; use alloc::{vec, vec::Vec};
pub struct Frame<'f> { pub struct Frame<'f> {
data: Vec<Vec<ColouredChar>>, data: Vec<Vec<Colour>>,
window: &'f Window, window: &'f Window,
} }
impl Frame<'_> { impl<'a> Frame<'a> {
pub fn new(window: &'a Window) -> Self {
Self {
data: vec![vec![Colour::Black; window.dimensions().x()]; window.dimensions().y()],
window,
}
}
pub fn render(&self) -> Result<(), RenderError> { pub fn render(&self) -> Result<(), RenderError> {
let data: Vec<&[ColouredChar]> = self.data.iter().map(|v| v.as_slice()).collect::<Vec<_>>(); let data: Vec<&[Colour]> = self.data.iter().map(|v| v.as_slice()).collect::<Vec<_>>();
self.window self.window
.render(data.as_slice()) .render(data.as_slice())
.map_err(|_| RenderError::Generic) .map_err(|_| RenderError::Generic)
} }
pub fn write_pixel(&mut self, x: usize, y: usize, color: Colour) -> Result<(), RenderError> {
if x >= self.window.dimensions().x() || y >= self.window.dimensions().y() {
return Err(RenderError::Generic);
}
self.data[y][x] = color;
Ok(())
}
pub const fn dimensions(&self) -> Vec2<usize> {
self.window.dimensions()
}
} }
+14 -4
View File
@@ -1,6 +1,12 @@
use crate::{prelude::*, std::maths::geometry::Vec2}; use limine::framebuffer;
use super::render::{ColouredChar, RenderError}; use crate::{
drivers::io::framebuffer::{colour::Colour, display::FRAMEBUFFER_WRITER},
prelude::*,
std::maths::geometry::Vec2,
};
use super::render::RenderError;
pub struct Window { pub struct Window {
dimensions: Vec2<usize>, dimensions: Vec2<usize>,
@@ -21,8 +27,12 @@ impl Window {
} }
} }
pub fn render(&self, _data: &[&[ColouredChar]]) -> Result<(), RenderError> { pub fn render(&self, _data: &[&[Colour]]) -> Result<(), RenderError> {
todo!(); // TODO: error handling!! the kernel should return an error in some cases
if let Some(fb) = FRAMEBUFFER_WRITER.lock().as_mut() {
fb.render_frame(_data);
}
Ok(())
} }
pub const fn is_bordered(&self) -> bool { pub const fn is_bordered(&self) -> bool {
+57
View File
@@ -0,0 +1,57 @@
use crate::{drivers::io::framebuffer::colour::Colour, resources::font::Font};
use super::{
application::{frame::Frame, render::RenderError},
maths::geometry::Vec2,
};
pub struct Writer<'a> {
font: &'a Font,
}
impl<'a> Writer<'a> {
pub const fn new(font: &'a Font) -> Self {
Self { font }
}
pub const fn set_font(&mut self, font: &'a Font) {
self.font = font;
}
pub const fn font_size(&self) -> Vec2<usize> {
Vec2::new(self.font.width(), self.font.height())
}
pub fn render_glyph(
&self,
frame: &mut Frame,
pos: Vec2<usize>,
c: u8,
scale: usize,
) -> Result<(), RenderError> {
// get a reference to the character glyph from the font.
let data: &[u8] = self.font.glyph_for(c as u16);
if pos.x() + self.font.width() * scale > frame.dimensions().x()
|| pos.y() + self.font.height() * scale > frame.dimensions().y()
{
return Err(RenderError::Generic);
}
for (row, line) in data.iter().enumerate().take(self.font.height()) {
for col in 0..self.font.width() {
let pixel_x: usize = pos.x() + col * scale;
let pixel_y: usize = pos.y() + row * scale;
if line & (0x80 >> col) != 0 {
for i in 0..scale {
for j in 0..scale {
frame.write_pixel(pixel_x + i, pixel_y + j, Colour::White)?;
}
}
}
}
}
Ok(())
}
}
+6
View File
@@ -71,3 +71,9 @@ impl<T: Coordinate> DivAssign<T> for Vec2<T> {
self.y /= rhs; self.y /= rhs;
} }
} }
impl<T: Coordinate> From<Vec2<T>> for (T, T) {
fn from(value: Vec2<T>) -> Self {
(value.x, value.y)
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod application; pub mod application;
pub mod ascii;
pub mod io; pub mod io;
pub mod maths; pub mod maths;
+235
View File
@@ -0,0 +1,235 @@
use crate::drivers::io::keyboard::{KeyStroke, get_keystroke_async};
use crate::prelude::*;
use crate::resources::font::{FONT_CP850_8X16, FONT_SPLEEN_8X16, Font};
use crate::std::application::frame::Frame;
use crate::std::application::render::RenderError;
use crate::std::application::window::Window;
use crate::std::application::{Application, Error};
use crate::std::ascii::Writer;
use crate::std::maths::geometry::Vec2;
use alloc::string::ToString;
pub struct Editor {
cursor_line: usize,
cursor_col: usize,
mode: Mode,
buffer: String,
window: Window,
}
impl Default for Editor {
fn default() -> Self {
Self::new()
}
}
impl<'a> Editor {
const PADDING: usize = 8;
pub const fn new() -> Self {
Self {
cursor_line: 0,
cursor_col: 0,
mode: Mode::Nor,
buffer: String::new(),
window: Window::new(),
}
}
fn render(&'a self) -> Result<Frame<'a>, RenderError> {
let mut frame = Frame::new(&self.window);
let writer = Writer::new(Font::default());
let (width, height) = writer.font_size().into();
let mut col = 0;
let mut line = 0;
let mut scale = 1;
for ch in self.buffer.chars() {
if ch == '\n' {
line += scale;
col = 0;
scale = 1;
continue;
}
if width * (col + 1) > frame.dimensions().x() - 2 * Self::PADDING {
line += scale;
col = 0;
}
writer.render_glyph(
&mut frame,
Vec2::new(col * width + Self::PADDING, line * height + Self::PADDING),
ch as u8,
scale,
)?;
col += scale;
}
writer.render_glyph(
&mut frame,
Vec2::new(
self.cursor_col * width + Self::PADDING,
self.cursor_line * height + Self::PADDING,
),
b'_',
scale,
);
Ok(frame)
}
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
fn get_lines(&self) -> Vec<&str> {
self.buffer.split('\n').collect::<Vec<&str>>()
}
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
fn move_cursor(&mut self, x: i32, y: i32) {
self.cursor_line = self
.cursor_line
.checked_add_signed(y as isize)
.unwrap_or(self.cursor_line);
self.cursor_col = self
.cursor_col
.checked_add_signed(x as isize)
.unwrap_or(self.cursor_col);
}
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
fn delete_char(&mut self) {
let i = self.get_char_idx();
self.buffer.remove(i);
}
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
fn insert_char(&mut self, c: char) {
let i = self.get_char_idx();
self.buffer.insert(i, c);
}
#[allow(unused_variables, dead_code, clippy::needless_pass_by_ref_mut)]
fn splitline(&mut self) {
let i = self.get_char_idx();
self.buffer.insert(i, '\n');
}
fn get_char_idx(&self) -> usize {
let frame = Frame::new(&self.window);
let writer = Writer::new(Font::default());
let (width, _height) = writer.font_size().into();
let mut col = 0;
let mut line = 0;
let mut scale = 1;
for (i, ch) in self.buffer.chars().enumerate() {
if ch == '\n' {
line += scale;
col = 0;
scale = 1;
continue;
}
if width * (col + 1) > frame.dimensions().x() - 2 * Self::PADDING {
line += scale;
col = 0;
}
if col == self.cursor_col && line == self.cursor_line {
return i;
}
col += scale;
}
0
}
}
impl Application for Editor {
type Output = ();
async fn run(&mut self, _args: Vec<alloc::string::String>) -> Result<Self::Output, Error> {
self.window.set_dimensions(Vec2::new(1280, 800));
self.window.set_position(Vec2::new(0, 0));
self.window.open();
self.buffer = "Hello world, this is a test init. idk test \n ewntuiewi gjk gfdfg gndf ngdfgnmdfg ndfgmndfg gdfndfnkg njkdgjkndfjnkg ngnjfgnfgnfg fgn fn gfj gnfg jnfgjfngjk fgnjfgnjk jnkdgjnkdfg gfnd njkgdfgjn d fjnkgjkndfgjkndfgjn gndfjnk njkgdfng jnkfgdjknd jnfkgnjk".to_string();
loop {
if let Err(_err) = self.render().and_then(|frame| frame.render()) {
// TODO: Handle error
return Err(Error::ApplicationFailed("Rendering failed".to_string()));
}
let keystroke = get_keystroke_async().await;
match self.mode {
Mode::Nor => match keystroke {
KeyStroke::Char('i') => self.mode = Mode::Ins,
KeyStroke::Char('`') => return Ok(()),
_ => {}
},
Mode::Ins => {
match keystroke {
KeyStroke::Char(c) => {
match c {
// escape
'\x1B' => self.mode = Mode::Nor,
// delete
'\x7F' => self.delete_char(),
// backspace
'\x08' => {
self.move_cursor(-1, 0);
self.delete_char();
}
// enter
'\n' => self.splitline(),
_ => {
self.insert_char(c);
self.move_cursor(1, 0);
}
}
}
KeyStroke::Left => {
serial_println!("Left\n");
self.move_cursor(-1, 0);
}
KeyStroke::Right => {
serial_println!("Right\n");
self.move_cursor(1, 0);
}
KeyStroke::Up => {
serial_println!("Up\n");
self.move_cursor(0, -1);
}
KeyStroke::Down => {
serial_println!("Down\n");
self.move_cursor(0, 1);
}
KeyStroke::None => {}
_ => {}
}
}
}
}
}
}
pub enum Mode {
Nor,
Ins,
}
impl core::fmt::Display for Mode {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Nor => write!(f, "Normal"),
Self::Ins => write!(f, "Insert"),
}
}
}
+1
View File
@@ -1 +1,2 @@
pub mod editor;
pub mod shell; pub mod shell;
+10 -1
View File
@@ -1,6 +1,11 @@
// use x86_64::registers::rflags::read; // use x86_64::registers::rflags::read;
use crate::{drivers::io::ascii::clear_screen, prelude::stdin::read_line, print, println}; use alloc::vec::Vec;
use crate::{
drivers::io::ascii::clear_screen, prelude::stdin::read_line, print, println,
std::application::Application, util::editor::Editor,
};
static FETCH: &str = " static FETCH: &str = "
$$$$$$$$\\ $$\\ $$$$$$$$\\ $$\\
@@ -31,6 +36,10 @@ pub async fn shell() {
"fetch" => { "fetch" => {
println!("{}", FETCH); println!("{}", FETCH);
} }
"editor" => {
let mut editor = Editor::new();
editor.run(Vec::new()).await.unwrap();
}
"clear" => clear_screen(), "clear" => clear_screen(),
_ => { _ => {
println!("Unknown command: {}", line); println!("Unknown command: {}", line);
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "nightly"
targets = ["x86_64-linux-gnu"]