ona/src/sys.zig

709 lines
23 KiB
Zig

const ext = @cImport({
@cInclude("SDL2/SDL.h");
});
const io = @import("./io.zig");
const mem = @import("./mem.zig");
const stack = @import("./stack.zig");
const std = @import("std");
///
/// A thread-safe platform abstraction over multiplexing system I/O processing and event handling.
///
pub const EventLoop = opaque {
///
/// Linked list of messages chained together to be processed by the internal file system message
/// processor of an [EventLoop].
///
const FileSystemMessage = struct {
next: ?*FileSystemMessage = null,
frame: anyframe,
request: union(enum) {
exit,
close: struct {
file_access: *FileAccess,
},
log: struct {
message: []const u8,
kind: LogKind,
},
open: struct {
mode: OpenMode,
file_system_path: *const FileSystem.Path,
result: OpenError!*FileAccess = error.NotFound,
},
read_file: struct {
file_access: *FileAccess,
buffer: []const u8,
result: FileError!usize = error.Inaccessible,
},
seek_file: struct {
file_access: *FileAccess,
origin: SeekOrigin,
offset: usize,
result: FileError!void = error.Inaccessible,
},
tell_file: struct {
file_access: *FileAccess,
result: FileError!usize = error.Inaccessible,
},
},
};
///
/// Internal state of the event loop hidden from the API consumer.
///
const Implementation = struct {
user_prefix: []u8,
file_system_semaphore: *ext.SDL_sem,
file_system_mutex: *ext.SDL_mutex,
file_system_thread: ?*ext.SDL_Thread,
file_system_messages: ?*FileSystemMessage = null,
///
///
///
const InitError = error {
OutOfSemaphores,
OutOfMutexes,
OutOfMemory,
};
///
///
///
const StartError = error {
OutOfThreads,
AlreadyStarted,
};
///
/// Casts `event_loop` to a [Implementation] reference.
///
/// *Note* that if `event_loop` does not have the same alignment as [Implementation],
/// safety-checked undefined behavior will occur.
///
fn cast(event_loop: *EventLoop) *Implementation {
return @ptrCast(*Implementation, @alignCast(@alignOf(Implementation), event_loop));
}
///
///
///
fn deinit(implementation: *Implementation) void {
var message = FileSystemMessage{
.frame = @frame(),
.request = .exit,
};
implementation.enqueueFileSystemMessage(&message);
{
var status = @as(c_int, 0);
// SDL2 defines waiting on a null thread reference as a no-op. See
// https://wiki.libsdl.org/SDL_WaitThread for more information
ext.SDL_WaitThread(implementation.file_system_thread, &status);
if (status != 0) {
// TODO: Error check this.
}
}
ext.SDL_free(implementation.user_prefix.ptr);
ext.SDL_DestroyMutex(implementation.file_system_mutex);
ext.SDL_DestroySemaphore(implementation.file_system_semaphore);
}
///
/// Enqueues `message` to the file system message processor of `implementation` to be
/// processed at a later, non-deterministic point.
///
fn enqueueFileSystemMessage(implementation: *Implementation,
message: *FileSystemMessage) void {
// TODO: Error check this.
_ = ext.SDL_LockMutex(implementation.file_system_mutex);
if (implementation.file_system_messages) |messages| {
messages.next = message;
} else {
implementation.file_system_messages = message;
}
// TODO: Error check these.
_ = ext.SDL_UnlockMutex(implementation.file_system_mutex);
_ = ext.SDL_SemPost(implementation.file_system_semaphore);
}
///
///
///
fn init() InitError!Implementation {
return Implementation{
.user_prefix = create_pref_path: {
const path = ext.SDL_GetPrefPath("ona", "ona") orelse {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to load user path");
return error.OutOfMemory;
};
break: create_pref_path path[0 .. std.mem.len(path)];
},
.file_system_semaphore = ext.SDL_CreateSemaphore(0)
orelse return error.OutOfSemaphores,
.file_system_mutex = ext.SDL_CreateMutex() orelse return error.OutOfMutexes,
.file_system_thread = null,
};
}
///
/// [FileSystemMessage] processing function used by a dedicated worker thread, where `data`
/// is a type-erased reference to a [EventLoop].
///
/// The processor returns `0` if it exited normally or any other value if an erroneous exit
/// occured.
///
fn processFileSystemMessages(data: ?*anyopaque) callconv(.C) c_int {
const implementation = Implementation.cast(@ptrCast(*EventLoop, data orelse unreachable));
while (true) {
while (implementation.file_system_messages) |messages| {
switch (messages.request) {
.exit => return 0,
.log => |*log_request| ext.SDL_LogMessage(ext.SDL_LOG_CATEGORY_APPLICATION,
@enumToInt(log_request.kind), log_request.message.ptr),
.open => |*open_request| {
switch (open_request.file_system_path.file_system) {
.data => {
// TODO: Implement
open_request.result = error.NotFound;
},
.user => {
var path_buffer = std.mem.zeroes([4096]u8);
var path = stack.Fixed(u8){.buffer = path_buffer[0 .. ]};
path.pushAll(implementation.user_prefix) catch {
open_request.result = error.NotFound;
continue;
};
if (!open_request.file_system_path.write(path.writer())) {
open_request.result = error.NotFound;
continue;
}
if (ext.SDL_RWFromFile(&path_buffer, switch (open_request.mode) {
.readonly => "rb",
.overwrite => "wb",
.append => "ab",
})) |rw_ops| {
open_request.result = @ptrCast(*FileAccess, rw_ops);
} else {
open_request.result = error.NotFound;
}
},
}
},
.close => |*close_request| {
// TODO: Use this result somehow.
_ = ext.SDL_RWclose(@ptrCast(*ext.SDL_RWops, @alignCast(
@alignOf(ext.SDL_RWops), close_request.file_access)));
},
.read_file => |read_request| {
// TODO: Implement.
_ = read_request;
},
.seek_file => |seek_request| {
// TODO: Implement.
_ = seek_request;
},
.tell_file => |tell_request| {
// TODO: Implement.
_ = tell_request;
},
}
resume messages.frame;
implementation.file_system_messages = messages.next;
}
// TODO: Error check this.
_ = ext.SDL_SemWait(implementation.file_system_semaphore);
}
}
///
///
///
fn start(implementation: *Implementation) StartError!void {
if (implementation.file_system_thread != null) return error.AlreadyStarted;
implementation.file_system_thread = ext.SDL_CreateThread(processFileSystemMessages,
"File System Worker", implementation) orelse {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to create file-system work processor");
return error.OutOfThreads;
};
}
};
///
/// [LogKind.info] represents a log message which is purely informative and does not indicate
/// any kind of issue.
///
/// [LogKind.debug] represents a log message which is purely for debugging purposes and will
/// only occurs in debug builds.
///
/// [LogKind.warning] represents a log message which is a warning about a issue that does not
/// break anything important but is not ideal.
///
pub const LogKind = enum(u32) {
info = ext.SDL_LOG_PRIORITY_INFO,
debug = ext.SDL_LOG_PRIORITY_DEBUG,
warning = ext.SDL_LOG_PRIORITY_WARN,
};
///
/// [OpenError.NotFound] is a catch-all for when a file could not be located to be opened. This
/// may be as simple as it doesn't exist or the because the underlying file-system will not /
/// cannot give access to it at this time.
///
pub const OpenError = error {
NotFound,
};
///
/// [OpenMode.readonly] indicates that an existing file is opened in a read-only state,
/// disallowing write access.
///
/// [OpenMode.overwrite] indicates that an empty file has been created or an existing file has
/// been completely overwritten into.
///
/// [OpenMode.append] indicates that an existing file that has been opened for reading from and
/// writing to on the end of existing data.
///
pub const OpenMode = enum {
readonly,
overwrite,
append,
};
///
/// [SeekOrigin.head] indicates that a seek operation will seek from the offset origin of the
/// file beginning, or "head".
///
/// [SeekOrigin.tail] indicates that a seek operation will seek from the offset origin of the
/// file end, or "tail".
///
/// [SeekOrigin.cursor] indicates that a seek operation will seek from the current position of
/// the file cursor.
///
pub const SeekOrigin = enum {
head,
tail,
cursor,
};
///
/// Closes access to the file referenced by `file_access` via `event_loop`.
///
/// *Note* that nothing happens to `file_access` if it is already closed.
///
pub fn close(event_loop: *EventLoop, file_access: *FileAccess) void {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{.close = .{.file_access = file_access}},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
}
///
/// Writes `message` to the application log with `kind` via `event_loop`.
///
/// *Note* that `message` is not guaranteed to be partly, wholely, or at all written.
///
pub fn log(event_loop: *EventLoop, kind: LogKind, message: []const u8) void {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{.log = .{
.message = message,
.kind = kind,
}},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
}
///
/// Attempts to open access to a file referenced at `file_system_path` using `mode` as the way
/// to open it via `event_loop`.
///
/// A [FileAccess] pointer is returned referencing the opened file or a [OpenError] if the file
/// could not be opened.
///
/// *Note* that all files are opened in "binary-mode", or Unix-mode. There are no conversions
/// applied when data is accessed from a file.
///
pub fn open(event_loop: *EventLoop, mode: OpenMode,
file_system_path: FileSystem.Path) OpenError!*FileAccess {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{.open = .{
.mode = mode,
.file_system_path = &file_system_path,
}},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
return file_system_message.request.open.result;
}
///
/// Attempts to read the contents of the file referenced by `file_access` at the current file
/// cursor position into `buffer`.
///
/// The number of bytes that could be read / fitted into `buffer` is returned or a [FileError]
/// if the file failed to be read.
///
pub fn readFile(event_loop: *EventLoop, file_access: *FileAccess,
buffer: []const u8) FileError!usize {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{.read_file = .{
.file_access = file_access,
.buffer = buffer,
}},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
return file_system_message.request.read_file.result;
}
///
/// Attempts to tell the current file cursor position for the file referenced by `file_access`.
///
/// Returns the number of bytes into the file that the cursor is relative to its beginning or a
/// [FileError] if the file failed to be queried.
///
pub fn queryFile(event_loop: *EventLoop, file_access: *FileAccess) FileError!usize {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{.tell_file = .{.file_access = file_access}},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
return file_system_message.request.tell_file.result;
}
///
/// Attempts to seek the file cursor through the file referenced by `file_access` from `origin`
/// to `offset` via `event_loop`, returning a [FileError] if the file failed to be sought.
///
pub fn seekFile(event_loop: *EventLoop, file_access: *FileAccess,
origin: SeekOrigin, offset: usize) FileError!void {
var file_system_message = FileSystemMessage{
.frame = @frame(),
.request = .{
.seek_file = .{
.file_access = file_access,
.origin = origin,
.offset = offset,
},
},
};
suspend Implementation.cast(event_loop).enqueueFileSystemMessage(&file_system_message);
return file_system_message.request.seek_file.result;
}
};
///
/// File-system agnostic abstraction for manipulating a file.
///
pub const FileAccess = opaque {
///
/// Scans the number of bytes in the file referenced by `file_access` via `event_loop`, returing
/// its byte size or a [FileError] if it failed.
///
pub fn size(file_access: *FileAccess, event_loop: *EventLoop) FileError!usize {
// Save cursor to return to it later.
const origin_cursor = try event_loop.queryFile(file_access);
try event_loop.seekFile(file_access, .tail, 0);
const ending_cursor = try event_loop.queryFile(file_access);
// Return to original cursor.
try event_loop.seekFile(file_access, .head, origin_cursor);
return ending_cursor;
}
};
///
/// With files typically being backed by a block device, they can produce a variety of errors -
/// from physical to virtual errors - these are all encapsulated by the API as general
/// [Error.Inaccessible] errors.
///
pub const FileError = error {
Inaccessible,
};
///
/// Platform-agnostic mechanism for working with an abstraction of the underlying file-system(s)
/// available to the application in a sandboxed environment.
///
pub const FileSystem = enum {
data,
user,
///
/// Platform-agnostic mechanism for referencing files and directories on a [FileSystem].
///
pub const Path = struct {
file_system: FileSystem,
length: u16,
buffer: [max]u8,
///
/// Returns `true` if the length of `path` is empty, otherwise `false`.
///
pub fn isEmpty(path: Path) bool {
return (path.length == 0);
}
///
/// Returns `true` if `this` is equal to `that`, otherwise `false`.
///
pub fn equals(this: Path, that: Path) bool {
return std.mem.eql(u8, this.buffer[0 .. this.length], that.buffer[0 .. that.length]);
}
///
/// The maximum possible byte-length of a [Path].
///
/// Note that paths are encoded using UTF-8, meaning that a character may be bigger than one
/// byte. Because of this, it is not safe to asume that a path may hold [max] individual
/// characters.
///
pub const max = 1000;
///
///
///
pub fn write(path: Path, writer: io.Writer) bool {
return (writer.write(path.buffer[0 .. path.length]) == path.length);
}
};
///
/// [PathError.TooLong] occurs when creating a path that is greater than the maximum size **in
/// bytes**.
///
pub const PathError = error {
TooLong,
};
///
/// Creates and returns a [Path] value in the file system to the location specified by the
/// joining of the `sequences` path values.
///
pub fn joinedPath(file_system: FileSystem, sequences: []const []const u8) PathError!Path {
var path = Path{
.file_system = file_system,
.buffer = std.mem.zeroes([Path.max]u8),
.length = 0,
};
if (sequences.len != 0) {
const last_sequence_index = sequences.len - 1;
for (sequences) |sequence, index| if (sequence.len != 0) {
var components = mem.Spliterator(u8){
.source = sequence,
.delimiter = "/",
};
while (components.next()) |component| if (component.len != 0) {
for (component) |byte| {
if (path.length == Path.max) return error.TooLong;
path.buffer[path.length] = byte;
path.length += 1;
}
if (components.hasNext()) {
if (path.length == Path.max) return error.TooLong;
path.buffer[path.length] = '/';
path.length += 1;
}
};
if (index < last_sequence_index) {
if (path.length == Path.max) return error.TooLong;
path.buffer[path.length] = '/';
path.length += 1;
}
};
}
return path;
}
};
///
///
///
pub const GraphicsContext = opaque {
///
///
///
pub const Event = struct {
keys_up: Keys = std.mem.zeroes(Keys),
keys_down: Keys = std.mem.zeroes(Keys),
keys_held: Keys = std.mem.zeroes(Keys),
const Keys = [256]bool;
};
const Implementation = struct {
event: Event,
};
///
///
///
pub fn poll(graphics_context: *GraphicsContext) ?*const Event {
_ = graphics_context;
return null;
}
///
///
///
pub fn present(graphics_context: *GraphicsContext) void {
// TODO: Implement;
_ = graphics_context;
}
};
///
///
///
pub fn GraphicsRunner(comptime Errors: type) type {
return fn (*EventLoop, *GraphicsContext) callconv(.Async) Errors!void;
}
///
///
///
pub fn runGraphics(comptime Errors: anytype, comptime run: GraphicsRunner(Errors)) Errors!void {
if (ext.SDL_Init(ext.SDL_INIT_EVERYTHING) != 0) {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize runtime");
return error.InitFailure;
}
defer ext.SDL_Quit();
const window = create_window: {
const pos = ext.SDL_WINDOWPOS_UNDEFINED;
var flags = @as(u32, 0);
break: create_window ext.SDL_CreateWindow("Ona", pos, pos, 640, 480, flags) orelse {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to create window");
return error.InitFailure;
};
};
defer ext.SDL_DestroyWindow(window);
const renderer = create_renderer: {
var flags = @as(u32, 0);
break: create_renderer ext.SDL_CreateRenderer(window, -1, flags) orelse {
ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION, "Failed to create renderer");
return error.InitFailure;
};
};
defer ext.SDL_DestroyRenderer(renderer);
var event_loop = EventLoop.Implementation.init() catch |err| {
switch (err) {
error.OutOfMemory => ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to allocate necessary memory"),
error.OutOfMutexes => ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to create file-system work lock"),
error.OutOfSemaphores => ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to create file-system work scheduler"),
}
return error.InitFailure;
};
defer event_loop.deinit();
event_loop.start() catch |err| {
switch (err) {
// Not possible for it to have already been started.
error.AlreadyStarted => unreachable,
error.OutOfThreads => ext.SDL_LogCritical(ext.SDL_LOG_CATEGORY_APPLICATION,
"Failed to start file-system work processor"),
}
return error.InitFailure;
};
var graphics_context = GraphicsContext.Implementation{
.event = .{
},
};
return run(@ptrCast(*EventLoop, &event_loop), @ptrCast(*GraphicsContext, &graphics_context));
}