Compare commits

..

4 Commits

Author SHA1 Message Date
df2aa925cb Add support for system cursors
When a client creates a cursor from the default cursor font, we try to
detect which cursor it is and create a native system cursor based on
that.
2026-05-30 16:07:43 +03:00
feb194f416 Allow sending enter/leave events between different native windows
This fixes hovering on popups
2026-05-30 16:07:43 +03:00
62fc8c8a14 Add initial support for window types
This makes popup windows work much better
2026-05-30 04:06:13 +03:00
c6d3e55e7b Start work on making xbanan portable
This will allow usage of xbanan on non banan-os platforms. I added a
"native" SDL2 port so it can be used without the window manager
2026-05-30 04:06:13 +03:00
19 changed files with 1356 additions and 1484 deletions

View File

@@ -26,14 +26,7 @@ set(CMAKE_CXX_STANDARD 20)
add_compile_definitions(-Dstddbg=stdout)
add_compile_options(-g)
set(PLATFORM "banan-os" CACHE STRING "target platform")
set(VALID_PLATFORMS "banan-os" "SDL3")
if(NOT PLATFORM IN_LIST VALID_PLATFORMS)
message(FATAL_ERROR "platform \"${PLATFORM}\" not known, valid platforms are ${VALID_PLATFORMS}")
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "banan-os")
if(BANAN_OS)
find_library(BAN ban REQUIRED)
add_library(ban SHARED IMPORTED)
set_target_properties(ban PROPERTIES IMPORTED_LOCATION "${BAN}")
@@ -55,10 +48,8 @@ else()
set_target_properties(libc PROPERTIES IMPORTED_LOCATION "${LIBC}")
add_subdirectory(banan-os/BAN)
add_subdirectory(banan-os/userspace/libraries/LibDEFLATE)
if(PLATFORM STREQUAL "banan-os")
add_subdirectory(banan-os/userspace/libraries/LibClipboard)
add_subdirectory(banan-os/userspace/libraries/LibDEFLATE)
add_subdirectory(banan-os/userspace/libraries/LibFont)
add_subdirectory(banan-os/userspace/libraries/LibGUI)
add_subdirectory(banan-os/userspace/libraries/LibImage)
@@ -67,7 +58,6 @@ else()
add_subdirectory(banan-os/userspace/programs/ProgramLauncher)
add_subdirectory(banan-os/userspace/programs/Terminal)
add_subdirectory(banan-os/userspace/programs/WindowServer)
endif()
endif()
add_subdirectory(xbanan)

View File

@@ -1,45 +1,29 @@
# xbanan
A portable X11 compatibility layer. There are 2 officially supported platforms: [banan-os's](https://git.bananymous.com/Bananymous/banan-os) native GUI windowing system and SDL3.
An X11 compatibility layer for [banan-os's](https://git.bananymous.com/Bananymous/banan-os) native GUI windowing system.
## Running on linux
### Prerequisites
You need to have SDL3 development library and X11 headers installed on your system.
### Building
```sh
git clone --recursive https://git.bananymous.com/Bananymous/xbanan.git
cd xbanan
cmake -B build -S . -DPLATFORM=SDL3
cmake --build build --parallel $(nproc)
cd banan-os
git apply ../0001-linux-window-server-sdl2.patch
cd ..
cmake -B build -S . -G Ninja
cmake --build build
```
### Running
To start xbanan, run the following command in project root
To start the WindowServer, run the following command in project root
```sh
./build/xbanan/xbanan
./build/banan-os/userspace/programs/WindowServer/WindowServer
```
To run X11 apps, specify `DISPLAY=:69` environment variable. For example
To run X11 apps specify `DISPLAY=:69` environment variable. For example
```sh
DISPLAY=:69 xeyes
```
## Porting to a new platform
Add your platform to the `VALID_PLATFORMS` list in the root `CMakeLists.txt` file. Create a directory for your platform in `xbanan/<your platform>` and define the needed source files and libraries in `xbanan/CMakeLists.txt` based on your platform.
### Barebones
For the simplest port, you need to implement 3 functions: `initialize`, `create_window` and `invalidate`. Define the variable `g_platform_ops` declared in `xbanan/Platform.h` with function pointers to the your functions. You can look at the existing platforms and the `xbanan/Platform.h` header for help.
### Events
To handle events, you have to hook an event receiver fd for your platform using `register_event_fd` declared in `xbanan/Events.h` and define the `poll_events` function in `g_platform_ops`. When the registered fd becomes readable, xbanan will call your platform's `poll_events` function. This function should drain all of the pending events and call appropriate `on_*_event` function declared in the events header. If your platform does not expose fd(s) that can be polled for events, you can do what the SDL3 port does and create an eventfd/pipe that gets signaled periodically.
### Installation
To install xbanan to sysroot, just copy the `build/xbanan/xbanan` to the destination. xbanan is statically linked against the libraries from this repository so you don't have to care about those. **DO NOT** use the cmake's install target, as that installs banan-os libraries to the root of the sysroot. You also need to have the x11 misc fonts at `FONT_PATH/misc` in your sysroot if you want server side font support. The fonts are shipped (public domain) with xbanan, so you can just copy `fonts/misc` into `FONT_PATH`. You can specify the `FONT_PATH` with cmake using `-DFONT_PATH=...` when configuring.

View File

@@ -8,10 +8,13 @@
#include "SafeGetters.h"
#include "Utils.h"
#include <LibInput/KeyEvent.h>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <time.h>
#include <sys/epoll.h>
struct Selection
{
@@ -25,8 +28,6 @@ CARD16 g_keymask { 0 };
CARD16 g_butmask { 0 };
WINDOW g_focus_window { None };
static WINDOW s_pointer_grab_wid = None;
static const char* s_opcode_to_name[] {
[0] = "none",
[X_CreateWindow] = "X_CreateWindow",
@@ -205,12 +206,12 @@ BAN::ErrorOr<void> setup_client_conneciton(Client& client_info, const xConnClien
};
TRY(encode(client_info.output_buffer, setup_prefix));
ASSERT((client_info.fd >> 20) == 0);
ASSERT((client_info.fd >> 24) == 0);
xConnSetup setup {
.release = 0,
.ridBase = static_cast<CARD32>(client_info.fd << 20),
.ridMask = 0x000FFFFF,
.ridBase = static_cast<CARD32>(client_info.fd << 24),
.ridMask = 0x00FFFFFF,
.motionBufferSize = 0,
.nbytesVendor = 8,
.maxRequestSize = 0xFFFF,
@@ -373,9 +374,6 @@ void invalidate_window(WINDOW wid, int32_t x, int32_t y, int32_t w, int32_t h)
for (;;)
{
if (wid == g_root.windowId)
return;
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
@@ -449,7 +447,7 @@ void send_exposure_recursive(WINDOW wid)
struct PlatformWindowInfo
{
PlatformWindow* parent;
PlatformWindow* transient_for;
WindowType type;
};
@@ -465,7 +463,7 @@ static PlatformWindowInfo get_plaform_window_info(const Object::Window& window)
static const CARD32 _NET_WM_WINDOW_TYPE_UTILITY = g_atoms_name_to_id["_NET_WM_WINDOW_TYPE_UTILITY"_sv];
PlatformWindowInfo info {
.parent = nullptr,
.transient_for = nullptr,
.type = WindowType::Normal,
};
@@ -477,7 +475,7 @@ static PlatformWindowInfo get_plaform_window_info(const Object::Window& window)
const CARD32 type = *reinterpret_cast<const CARD32*>(it->value.data.data());
if (type == _NET_WM_WINDOW_TYPE_NORMAL)
info.type = WindowType::Normal;
else if (type == _NET_WM_WINDOW_TYPE_SPLASH || type == _NET_WM_WINDOW_TYPE_DIALOG)
else if (type == _NET_WM_WINDOW_TYPE_SPLASH || type == _NET_WM_WINDOW_TYPE_UTILITY || type == _NET_WM_WINDOW_TYPE_DIALOG)
info.type = WindowType::Utility;
else
info.type = WindowType::Popup;
@@ -499,7 +497,7 @@ wm_window_type_done:
// FIXME: support child windows
auto& window = it2->value->object.get<Object::Window>();
info.parent = window.platform_window.ptr();
info.transient_for = window.platform_window.ptr();
}
transitient_for_done:
@@ -514,21 +512,14 @@ static BAN::ErrorOr<void> map_window(Client& client_info, WINDOW wid)
auto& window = object.object.get<Object::Window>();
if (window.mapped)
return {};
window.mapped = true;
if (window.parent == g_root.windowId)
{
ASSERT(!window.platform_window);
// NOTE: This is not perfect but seems to work.
// This is used to not display "dummy" event windows
// that should not be visible.
if (window.width <= 10 || window.height <= 10)
return {};
auto info = get_plaform_window_info(window);
window.platform_window = TRY(g_platform_ops.create_window(
info.parent,
info.transient_for,
info.type,
wid,
window.x,
@@ -538,6 +529,8 @@ static BAN::ErrorOr<void> map_window(Client& client_info, WINDOW wid)
));
}
window.mapped = true;
for (auto& pixel : window.pixels)
pixel = window.background;
invalidate_window(wid, 0, 0, window.width, window.height);
@@ -718,26 +711,11 @@ WINDOW find_child_window(WINDOW wid, int32_t& x, int32_t& y)
return wid;
}
xPoint get_window_position(WINDOW wid)
{
xPoint result { .x = 0, .y = 0 };
while (wid != None)
{
const auto& window = g_objects[wid]->object.get<Object::Window>();
result.x += window.x;
result.y += window.y;
wid = window.parent;
}
return result;
}
static PlatformWindow* get_platform_window(const Object::Window& window)
{
if (window.platform_window)
return const_cast<PlatformWindow*>(window.platform_window.ptr());
if (window.parent == None)
if (window.parent == g_root.windowId)
return nullptr;
auto& object = *g_objects[window.parent];
@@ -750,28 +728,30 @@ void update_cursor(WINDOW wid, int32_t x, int32_t y)
if (g_platform_ops.set_cursor == nullptr)
return;
wid = find_child_window(wid, x, y);
if (wid == None)
const auto child_wid = find_child_window(wid, x, y);
if (child_wid == None)
return;
const CURSOR cid = [&wid]() -> CURSOR {
for (;;)
CURSOR cursor = None;
if (child_wid != None)
{
const auto& window = g_objects[wid]->object.get<Object::Window>();
if (window.cursor != None || window.parent == None)
return window.cursor;
wid = window.parent;
auto& object = *g_objects[child_wid];
ASSERT(object.type == Object::Type::Window);
cursor = object.object.get<Object::Window>().cursor;
}
}();
static CURSOR active_cid = None;
if (cid == active_cid)
static CURSOR active_cursor = None;
if (cursor == active_cursor)
return;
const auto& window = g_objects[wid]->object.get<Object::Window>();
g_platform_ops.set_cursor(get_platform_window(window), get_cursor_safe(cid));
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
active_cid = cid;
g_platform_ops.set_cursor(get_platform_window(window), get_cursor_safe(cursor));
active_cursor = window.cursor;
}
static void on_root_client_message(const xEvent& event)
@@ -1030,11 +1010,9 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
}
if (cursor_id.has_value())
{
window.cursor = cursor_id.value();
if (window.hovered)
update_cursor(request.window, window.cursor_x, window.cursor_y);
}
if (background.has_value())
window.background = background.value();
@@ -1253,21 +1231,18 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
}
}
bool send_configure = false;
bool window_changed = false;
const int32_t min_x = BAN::Math::min(window.x, new_x);
const int32_t min_y = BAN::Math::min(window.y, new_y);
const int32_t max_x = BAN::Math::max(window.x + window.width, new_x + new_width);
const int32_t max_y = BAN::Math::max(window.y + window.height, new_y + new_height);
if (new_x != window.x || new_y != window.y)
{
if (window.platform_window)
{
if (g_platform_ops.request_reposition)
g_platform_ops.request_reposition(window.platform_window.ptr(), new_x, new_y);
}
else
{
window.x = new_x;
window.y = new_y;
send_configure = true;
}
window_changed = true;
}
if (new_width != window.width || new_height != window.height)
@@ -1276,20 +1251,22 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
{
if (g_platform_ops.request_resize)
g_platform_ops.request_resize(window.platform_window.ptr(), new_width, new_height);
window_changed = false;
}
else
{
window.width = new_width;
window.height = new_height;
TRY(window.pixels.resize(new_width * new_height));
for (auto& pixel : window.pixels)
pixel = window.background;
window.width = new_width;
window.height = new_height;
send_configure = true;
window_changed = true;
}
}
if (!send_configure)
if (!window_changed)
break;
{
@@ -1813,9 +1790,9 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
(void)TRY_REF(get_window(client_info, wid, X_SendEvent));
Client* target_client = nullptr;
for (auto& [_, thingy] : g_pollables)
for (auto& [_, thingy] : g_epoll_thingies)
{
if (thingy.type != Pollable::Type::Client)
if (thingy.type != EpollThingy::Type::Client)
continue;
auto& other_client = thingy.value.get<Client>();
if (!other_client.objects.contains(wid))
@@ -1851,13 +1828,6 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
dprintln(" cursor: {}", request.cursor);
dprintln(" time: {}", request.time);
auto& window = TRY_REF(get_window(client_info, request.grabWindow, X_GrabPointer));
if (s_pointer_grab_wid != None && !g_objects.contains(s_pointer_grab_wid))
s_pointer_grab_wid = None;
if (s_pointer_grab_wid == None)
{
xGrabPointerReply reply {
.type = X_Reply,
.status = Success,
@@ -1866,23 +1836,6 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
};
TRY(encode(client_info.output_buffer, reply));
if (g_platform_ops.set_pointer_grab)
if (auto* platform_window = get_platform_window(window))
g_platform_ops.set_pointer_grab(platform_window, true);
s_pointer_grab_wid = request.grabWindow;
}
else
{
xGrabPointerReply reply {
.type = X_Reply,
.status = AlreadyGrabbed,
.sequenceNumber = client_info.sequence,
.length = 0,
};
TRY(encode(client_info.output_buffer, reply));
}
break;
}
case X_UngrabPointer:
@@ -1892,16 +1845,6 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
dprintln("UngrabPointer");
dprintln(" time: {}", time);
if (s_pointer_grab_wid == None)
break;
auto it = g_objects.find(s_pointer_grab_wid);
if (it != g_objects.end() && g_platform_ops.set_pointer_grab)
if (auto* platform_window = get_platform_window(it->value->object.get<Object::Window>()))
g_platform_ops.set_pointer_grab(platform_window, false);
s_pointer_grab_wid = None;
break;
}
case X_GrabKeyboard:
@@ -1937,11 +1880,47 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
case X_GrabServer:
{
g_server_grabber_fd = client_info.fd;
for (const auto& [_, thingy] : g_epoll_thingies)
{
if (thingy.type != EpollThingy::Type::Client)
continue;
auto& other_client = thingy.value.get<Client>();
if (client_info.fd == other_client.fd)
continue;
uint32_t events = 0;
if (other_client.has_epollout)
events |= EPOLLOUT;
epoll_event event { .events = events, .data = { .fd = other_client.fd } };
epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, other_client.fd, &event);
}
break;
}
case X_UngrabServer:
{
g_server_grabber_fd = -1;
for (const auto& [_, thingy] : g_epoll_thingies)
{
if (thingy.type != EpollThingy::Type::Client)
continue;
auto& other_client = thingy.value.get<Client>();
if (client_info.fd == other_client.fd)
continue;
uint32_t events = EPOLLIN;
if (other_client.has_epollout)
events |= EPOLLOUT;
epoll_event event { .events = events, .data = { .fd = other_client.fd } };
epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, other_client.fd, &event);
}
break;
}
case X_QueryPointer:
@@ -1953,26 +1932,12 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
const auto& window = TRY_REF(get_window(client_info, wid, opcode));
WINDOW child_wid { None };
for (auto wid_ : window.children)
{
const auto& child_window = g_objects[wid_]->object.get<Object::Window>();
if (!child_window.hovered)
continue;
child_wid = wid_;
break;
}
int32_t root_x, root_y;
int32_t event_x, event_y;
root_x = event_x = window.cursor_x;
root_y = event_y = window.cursor_y;
const auto [root_x, root_y] = get_window_position(wid);
int32_t root_cursor_x, root_cursor_y;
if (g_platform_ops.query_pointer)
g_platform_ops.query_pointer(&root_cursor_x, &root_cursor_y);
else
{
root_cursor_x = root_x + window.cursor_x;
root_cursor_y = root_y + window.cursor_y;
}
const auto child_wid = find_child_window(wid, event_x, event_y);
xQueryPointerReply reply {
.type = X_Reply,
@@ -1980,11 +1945,11 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
.sequenceNumber = client_info.sequence,
.length = 0,
.root = g_root.windowId,
.child = static_cast<CARD32>(child_wid),
.rootX = static_cast<INT16>(root_cursor_x),
.rootY = static_cast<INT16>(root_cursor_y),
.winX = static_cast<INT16>(root_cursor_x - root_x),
.winY = static_cast<INT16>(root_cursor_y - root_y),
.child = static_cast<CARD32>(child_wid == wid ? None : child_wid),
.rootX = static_cast<INT16>(root_x),
.rootY = static_cast<INT16>(root_y),
.winX = static_cast<INT16>(event_x),
.winY = static_cast<INT16>(event_y),
.mask = static_cast<KeyButMask>(g_keymask | g_butmask),
};
TRY(encode(client_info.output_buffer, reply));
@@ -2001,55 +1966,19 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
dprintln(" src_x: {}", request.srcX);
dprintln(" src_y: {}", request.srcY);
(void)TRY_REF(get_window(client_info, request.dstWid, X_TranslateCoords));
(void)TRY_REF(get_window(client_info, request.srcWid, X_TranslateCoords));
const auto [src_x, src_y] = get_window_position(request.srcWid);
const auto [dst_x, dst_y] = get_window_position(request.dstWid);
xTranslateCoordsReply reply {
.type = X_Reply,
.sameScreen = xTrue,
.sequenceNumber = client_info.sequence,
.length = 0,
.child = None, // FIXME
.dstX = static_cast<INT16>(src_x + request.srcX - dst_x),
.dstY = static_cast<INT16>(src_y + request.srcY - dst_y),
.child = None,
.dstX = request.srcX,
.dstY = request.srcY,
};
TRY(encode(client_info.output_buffer, reply));
break;
}
case X_WarpPointer:
{
auto request = decode<xWarpPointerReq>(packet).value();
dprintln("WarpPointer");
dprintln(" src_wid: {}", request.srcWid);
dprintln(" src_x: {}", request.srcX);
dprintln(" src_y: {}", request.srcY);
dprintln(" src_w: {}", request.srcWidth);
dprintln(" src_h: {}", request.srcHeight);
dprintln(" dst_wid: {}", request.dstWid);
dprintln(" dst_x: {}", request.dstX);
dprintln(" dst_y: {}", request.dstY);
if (g_platform_ops.warp_pointer == nullptr)
break;
// TODO: source window :)
if (request.dstWid == None)
g_platform_ops.warp_pointer(request.dstX, request.dstY, true);
else
{
(void)TRY_REF(get_window(client_info, request.dstWid, X_WarpPointer));
const auto [win_x, win_y] = get_window_position(request.dstWid);
g_platform_ops.warp_pointer(win_x + request.dstX, win_y + request.dstY, false);
}
break;
}
case X_QueryKeymap:
{
dprintln("QueryKeymap");
@@ -2123,7 +2052,8 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
.depth = request.depth,
.width = request.width,
.height = request.height,
.data = BAN::move(data),
.data = data.span(),
.owned_data = BAN::move(data),
}
}))
));
@@ -2767,7 +2697,7 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
{
auto request = decode<xQueryBestSizeReq>(packet).value();
dprintln("QueryBestSize");
dprintln("FreeCursor");
dprintln(" class: {}", request.c_class);
dprintln(" drawable: {}", request.drawable);
dprintln(" width: {}", request.width);
@@ -2860,19 +2790,8 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
dprintln(" firstKeyCode: {}", request.firstKeyCode);
dprintln(" count: {}", request.count);
if (request.firstKeyCode < g_keymap_min_keycode || request.firstKeyCode + request.count - 1 > g_keymap_max_keycode)
{
xError error {
.type = X_Error,
.errorCode = BadValue,
.sequenceNumber = client_info.sequence,
.resourceID = 0, // TODO: should this be something meaningful?
.minorCode = 0,
.majorCode = opcode,
};
TRY(encode(client_info.output_buffer, error));
break;
}
ASSERT(g_keymap_min_keycode <= request.firstKeyCode);
ASSERT(g_keymap_max_keycode >= request.firstKeyCode + request.count - 1);
xGetKeyboardMappingReply reply {
.type = X_Reply,
@@ -2881,10 +2800,10 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
.length = static_cast<CARD32>(request.count * g_keymap_layers),
};
TRY(encode(client_info.output_buffer, reply));
TRY(encode(client_info.output_buffer, BAN::Span(
g_keymap + request.firstKeyCode - g_keymap_min_keycode,
request.count
)));
for (size_t i = 0; i < request.count; i++)
for (size_t j = 0; j < g_keymap_layers; j++)
TRY(encode<CARD32>(client_info.output_buffer, g_keymap[request.firstKeyCode + i][j]));
break;
}
@@ -2925,12 +2844,36 @@ BAN::ErrorOr<void> handle_packet(Client& client_info, BAN::ConstByteSpan packet)
xGetModifierMappingReply reply {
.type = X_Reply,
.numKeyPerModifier = g_modifier_layers,
.numKeyPerModifier = 2,
.sequenceNumber = client_info.sequence,
.length = 2 * g_modifier_layers,
.length = 4,
};
TRY(encode(client_info.output_buffer, reply));
TRY(encode(client_info.output_buffer, g_modifier_map));
using LibInput::keycode_normal;
// shift
TRY(encode(client_info.output_buffer, keycode_normal(3, 0))); // lshift
TRY(encode(client_info.output_buffer, keycode_normal(3, 12))); // rshift
// lock
TRY(encode(client_info.output_buffer, keycode_normal(2, 0))); // caps lock
TRY(encode(client_info.output_buffer, static_cast<uint8_t>(0)));
// control
TRY(encode(client_info.output_buffer, keycode_normal(4, 0))); // lcrtl
TRY(encode(client_info.output_buffer, keycode_normal(4, 6))); // rctrl
// mod1
TRY(encode(client_info.output_buffer, keycode_normal(4, 2))); // lalt
TRY(encode(client_info.output_buffer, keycode_normal(4, 5))); // ralt
// mod2 -> mod5
for (size_t i = 2; i <= 5; i++)
{
TRY(encode(client_info.output_buffer, static_cast<uint8_t>(0)));
TRY(encode(client_info.output_buffer, static_cast<uint8_t>(0)));
}
break;
}

View File

@@ -14,8 +14,6 @@ BAN::ErrorOr<void> destroy_window(Client& client_info, WINDOW wid);
WINDOW find_child_window(WINDOW wid, int32_t& x, int32_t& y);
xPoint get_window_position(WINDOW wid);
static constexpr uint32_t COLOR_INVISIBLE = 0x69000000;
extern CARD16 g_keymask;

View File

@@ -6,15 +6,12 @@ set(XBANAN_SOURCES
Extensions.cpp
ExtBigReg.cpp
ExtRANDR.cpp
ExtXRes.cpp
Font.cpp
Image.cpp
Keymap.cpp
SafeGetters.cpp
)
set(FONT_PATH ${CMAKE_SOURCE_DIR}/fonts CACHE STRING "path to X11 fonts")
option(ENABLE_GLX "enable glx extension" ON)
if(ENABLE_GLX)
list(APPEND XBANAN_SOURCES ExtGLX.cpp)
@@ -25,24 +22,29 @@ if(ENABLE_SHM)
list(APPEND XBANAN_SOURCES ExtSHM.cpp)
endif()
set(PLATFORM "banan-os" CACHE STRING "target platform")
set(VALID_PLATFORMS "banan-os" "SDL2")
if(NOT PLATFORM IN_LIST VALID_PLATFORMS)
message(FATAL_ERROR "platform \"${PLATFORM}\" not known, valid platforms are ${VALID_PLATFORMS}")
endif()
if(PLATFORM STREQUAL "banan-os")
list(APPEND XBANAN_SOURCES banan-os/banan-os.cpp)
elseif(PLATFORM STREQUAL "SDL3")
list(APPEND XBANAN_SOURCES SDL3/sdl3.cpp)
elseif(PLATFORM STREQUAL "SDL2")
list(APPEND XBANAN_SOURCES SDL2/sdl2.cpp)
endif()
add_executable(xbanan ${XBANAN_SOURCES})
banan_link_library(xbanan ban)
banan_link_library(xbanan libdeflate)
target_compile_definitions(xbanan PRIVATE FONT_PATH="${FONT_PATH}")
banan_link_library(xbanan libinput)
if(PLATFORM STREQUAL "banan-os")
banan_link_library(xbanan libgui)
banan_link_library(xbanan libinput)
elseif(PLATFORM STREQUAL "SDL3")
find_package(SDL3 REQUIRED)
banan_link_library(xbanan SDL3::SDL3)
elseif(PLATFORM STREQUAL "SDL2")
find_package(SDL2 REQUIRED)
banan_link_library(xbanan SDL2::SDL2)
endif()
target_compile_options(xbanan PRIVATE -Wall -Wextra)
@@ -53,4 +55,7 @@ target_compile_options(xbanan PRIVATE
-Wno-unused-but-set-variable
)
#target_compile_options(xbanan PRIVATE -fsanitize=address)
#target_link_options(xbanan PRIVATE -fsanitize=address)
install(TARGETS xbanan OPTIONAL)

View File

@@ -81,7 +81,8 @@ struct Object
CARD8 depth;
CARD32 width;
CARD32 height;
BAN::Vector<uint8_t> data;
BAN::ByteSpan data;
BAN::Vector<uint8_t> owned_data;
};
struct GraphicsContext
@@ -140,15 +141,15 @@ struct Client
};
int fd;
State state;
bool has_epollout { false };
bool has_bigrequests { false };
CARD16 sequence { 0 };
BAN::Optional<uint32_t> pid;
BAN::Vector<uint8_t> input_buffer;
BAN::Vector<uint8_t> output_buffer;
BAN::HashSet<CARD32> objects;
};
struct Pollable
struct EpollThingy
{
enum class Type
{
@@ -171,6 +172,7 @@ extern BAN::HashMap<BAN::String, ATOM> g_atoms_name_to_id;
extern BAN::HashMap<ATOM, BAN::String> g_atoms_id_to_name;
extern ATOM g_atom_value;
extern BAN::HashMap<int, Pollable> g_pollables;
extern int g_epoll_fd;
extern BAN::HashMap<int, EpollThingy> g_epoll_thingies;
extern int g_server_grabber_fd;

View File

@@ -1,24 +1,31 @@
#include "Base.h"
#include "Definitions.h"
#include "Keymap.h"
#include "Platform.h"
#include "SafeGetters.h"
#include "Utils.h"
#include <X11/X.h>
#include <X11/Xatom.h>
#include <time.h>
#include <sys/epoll.h>
void register_event_fd(int fd, void* data)
{
MUST(g_pollables.insert(fd, {
.type = Pollable::Type::Event,
epoll_event event { .events = EPOLLIN, .data = { .fd = fd } };
epoll_ctl(g_epoll_fd, EPOLL_CTL_ADD, fd, &event);
MUST(g_epoll_thingies.insert(fd, {
.type = EpollThingy::Type::Event,
.value = data,
}));
}
void unregister_event_fd(int fd)
{
g_pollables.remove(fd);
epoll_ctl(g_epoll_fd, EPOLL_CTL_DEL, fd, nullptr);
g_epoll_thingies.remove(fd);
}
void on_window_close_event(WINDOW wid)
@@ -70,8 +77,21 @@ void on_window_close_event(WINDOW wid)
}
}
static void send_window_configure(WINDOW wid, Object::Window& window)
void on_window_resize_event(WINDOW wid, uint32_t new_width, uint32_t new_height)
{
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
{
window.width = new_width;
window.height = new_height;
MUST(window.pixels.resize(new_width * new_height));
for (auto& pixel : window.pixels)
pixel = window.background;
}
{
xEvent event = { .u = {
.configureNotify = {
@@ -111,42 +131,12 @@ static void send_window_configure(WINDOW wid, Object::Window& window)
event.u.u.type = ConfigureNotify;
MUST(parent_window.send_event(event, SubstructureNotifyMask));
}
}
void on_window_resize_event(WINDOW wid, uint32_t new_width, uint32_t new_height)
{
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
{
window.width = new_width;
window.height = new_height;
MUST(window.pixels.resize(new_width * new_height));
for (auto& pixel : window.pixels)
pixel = window.background;
}
send_window_configure(wid, window);
send_exposure_recursive(wid);
invalidate_window(wid, 0, 0, window.width, window.height);
}
void on_window_move_event(WINDOW wid, int32_t x, int32_t y)
{
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
window.x = x;
window.y = y;
send_window_configure(wid, window);
}
void on_window_focus_event(WINDOW wid, bool focused)
{
if (focused)
@@ -231,14 +221,15 @@ void on_window_fullscreen_event(WINDOW wid, bool is_fullscreen)
static void send_key_button_pointer_event(WINDOW root_wid, BYTE detail, uint32_t event_mask, BYTE event_type, KeyButMask state)
{
int32_t root_x, root_y;
int32_t event_x, event_y;
{
auto& object = *g_objects[root_wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
event_x = window.cursor_x;
event_y = window.cursor_y;
root_x = event_x = window.cursor_x;
root_y = event_y = window.cursor_y;
}
const auto child_wid = find_child_window(root_wid, event_x, event_y);
@@ -268,15 +259,14 @@ static void send_key_button_pointer_event(WINDOW root_wid, BYTE detail, uint32_t
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
const auto [root_x, root_y] = get_window_position(wid);
xEvent event { .u = {
.keyButtonPointer = {
.time = static_cast<CARD32>(time(nullptr)),
.root = g_root.windowId,
.event = wid,
.child = static_cast<CARD32>(child_wid == wid ? None : child_wid),
.rootX = static_cast<INT16>(root_x + event_x),
.rootY = static_cast<INT16>(root_y + event_y),
.rootX = static_cast<INT16>(root_x),
.rootY = static_cast<INT16>(root_y),
.eventX = static_cast<INT16>(event_x),
.eventY = static_cast<INT16>(event_y),
.state = state,
@@ -401,15 +391,14 @@ static void send_enter_and_leave_events(WINDOW old_wid, int32_t old_x, int32_t o
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
const auto [root_x, root_y] = get_window_position(wid);
xEvent event { .u = {
.enterLeave = {
.time = static_cast<CARD32>(time(nullptr)),
.root = g_root.windowId,
.event = wid,
.child = first ? static_cast<WINDOW>(None) : old_child_path.back(),
.rootX = static_cast<INT16>(root_x + old_x),
.rootY = static_cast<INT16>(root_y + old_y),
.rootX = static_cast<INT16>(old_x),
.rootY = static_cast<INT16>(old_y),
.eventX = static_cast<INT16>(old_x),
.eventY = static_cast<INT16>(old_y),
.state = static_cast<KeyButMask>(g_keymask | g_butmask),
@@ -442,15 +431,14 @@ static void send_enter_and_leave_events(WINDOW old_wid, int32_t old_x, int32_t o
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
const auto [root_x, root_y] = get_window_position(wid);
xEvent event { .u = {
.enterLeave = {
.time = static_cast<CARD32>(time(nullptr)),
.root = g_root.windowId,
.event = wid,
.child = last ? static_cast<WINDOW>(None) : new_child_path.back(),
.rootX = static_cast<INT16>(root_x + new_x),
.rootY = static_cast<INT16>(root_y + new_y),
.rootX = static_cast<INT16>(new_x),
.rootY = static_cast<INT16>(new_y),
.eventX = static_cast<INT16>(new_x),
.eventY = static_cast<INT16>(new_y),
.state = static_cast<KeyButMask>(g_keymask | g_butmask),
@@ -463,26 +451,14 @@ static void send_enter_and_leave_events(WINDOW old_wid, int32_t old_x, int32_t o
MUST(window.send_event(event, EnterWindowMask));
}
for (const auto wid : old_child_path)
g_objects[wid]->object.get<Object::Window>().hovered = false;
for (const auto wid : new_child_path)
g_objects[wid]->object.get<Object::Window>().hovered = true;
}
static WINDOW s_current_top_level_window = None;
void on_window_leave_event(WINDOW wid)
{
if (s_current_top_level_window != wid)
const auto set_last_entry_hovered = [](const BAN::Vector<WINDOW>& path, bool value) {
if (path.empty())
return;
g_objects[path.back()]->object.get<Object::Window>().hovered = value;
};
auto& object = *g_objects[wid];
ASSERT(object.type == Object::Type::Window);
auto& window = object.object.get<Object::Window>();
send_enter_and_leave_events(wid, window.cursor_x, window.cursor_y, wid, -1, -1);
s_current_top_level_window = None;
set_last_entry_hovered(old_child_path, false);
set_last_entry_hovered(new_child_path, true);
}
void on_mouse_move_event(WINDOW wid, int32_t x, int32_t y)
@@ -493,16 +469,20 @@ void on_mouse_move_event(WINDOW wid, int32_t x, int32_t y)
update_cursor(wid, x, y);
if (auto it = g_objects.find(s_current_top_level_window); it == g_objects.end())
send_enter_and_leave_events(wid, -1, -1, wid, x, y);
else
{
static WINDOW old_wid = g_root.windowId;
auto it = g_objects.find(old_wid);
if (it == g_objects.end())
it = g_objects.find(g_root.windowId);
ASSERT(it->value->type == Object::Type::Window);
auto& old_window = it->value->object.get<Object::Window>();
send_enter_and_leave_events(s_current_top_level_window, old_window.cursor_x, old_window.cursor_y, wid, x, y);
}
s_current_top_level_window = wid;
send_enter_and_leave_events(old_wid, old_window.cursor_x, old_window.cursor_y, wid, x, y);
old_wid = wid;
}
update_cursor_position_recursive(wid, x, y);
@@ -548,16 +528,19 @@ void on_mouse_button_event(WINDOW wid, uint8_t xbutton, bool pressed)
void on_key_event(WINDOW wid, uint8_t scancode, uint8_t xmod, bool pressed)
{
const uint8_t xkeycode = scancode + g_keymap_min_keycode;
if (xkeycode < g_keymap_min_keycode || xkeycode > g_keymap_max_keycode)
if (xkeycode < g_keymap_min_keycode)
{
dwarnln("cannot send keycode {}", xkeycode);
return;
}
{
const uint8_t byte = xkeycode / 8;
const uint8_t mask = 1 << (xkeycode % 8);
const uint8_t bit = xkeycode % 8;
if (pressed)
g_pressed_keys[byte] |= mask;
g_pressed_keys[byte] |= 1 << bit;
else
g_pressed_keys[byte] &= ~mask;
g_pressed_keys[byte] &= ~(1 << bit);
}
const auto old_state = g_keymask | g_butmask;
@@ -572,26 +555,3 @@ void on_key_event(WINDOW wid, uint8_t scancode, uint8_t xmod, bool pressed)
old_state
);
}
void on_keymap_changed()
{
for (auto& [id, object] : g_objects)
{
if (object->type != Object::Type::Window)
continue;
auto& client_info = object->object.get<Object::Window>().owner;
xEvent event {};
event.u.u.type = MappingNotify;
event.u.u.sequenceNumber = client_info.sequence;
event.u.mappingNotify.request = MappingKeyboard,
event.u.mappingNotify.firstKeyCode = g_keymap_min_keycode,
event.u.mappingNotify.count = g_keymap_size,
MUST(encode(client_info.output_buffer, event));
event.u.mappingNotify.request = MappingModifier;
MUST(encode(client_info.output_buffer, event));
}
}

View File

@@ -7,13 +7,9 @@ void unregister_event_fd(int fd);
void on_window_close_event(WINDOW wid);
void on_window_resize_event(WINDOW wid, uint32_t width, uint32_t height);
void on_window_move_event(WINDOW wid, int32_t x, int32_t y);
void on_window_focus_event(WINDOW wid, bool focused);
void on_window_fullscreen_event(WINDOW wid, bool is_fullscreen);
void on_window_leave_event(WINDOW wid);
void on_mouse_move_event(WINDOW wid, int32_t x, int32_t y);
void on_mouse_button_event(WINDOW wid, uint8_t xbutton, bool pressed);
void on_key_event(WINDOW wid, uint8_t scancode, uint8_t xmod, bool pressed);
void on_keymap_changed();

View File

@@ -7,13 +7,42 @@
#include <X11/X.h>
#include <X11/extensions/shmproto.h>
#include <netinet/in.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <unistd.h>
static BYTE s_shm_event_base;
static BYTE s_shm_error_base;
static BYTE s_shm_major_opcode;
static bool is_local_socket(int socket)
{
sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
if (getpeername(socket, reinterpret_cast<sockaddr*>(&addr), &addr_len) == -1)
return false;
switch (addr.ss_family)
{
case AF_UNIX:
return true;
case AF_INET:
{
const auto* addr_in = reinterpret_cast<const sockaddr_in*>(&addr);
const auto ipv4 = ntohl(addr_in->sin_addr.s_addr);
return (ipv4 & IN_CLASSA_NET) == IN_LOOPBACKNET;
}
case AF_INET6:
{
const auto* addr_in6 = reinterpret_cast<const sockaddr_in6*>(&addr);
return IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr);
}
}
return false;
}
static BAN::ErrorOr<void*> get_shmseg(Client& client_info, CARD32 shmseg, BYTE op_major, BYTE op_minor)
{
auto it = g_objects.find(shmseg);
@@ -45,11 +74,11 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
{
case X_ShmQueryVersion:
{
dprintln("ShmQueryVersion");
dwarnln("ShmQueryVersion");
xShmQueryVersionReply reply {
.type = X_Reply,
.sharedPixmaps = false,
.sharedPixmaps = is_local_socket(client_info.fd),
.sequenceNumber = client_info.sequence,
.length = 0,
.majorVersion = 1,
@@ -66,7 +95,7 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
{
auto request = decode<xShmAttachReq>(packet).value();
dprintln("ShmAttach");
dwarnln("ShmAttach");
dprintln(" shmseg: {}", request.shmseg);
dprintln(" shmid: {}", request.shmid);
dprintln(" readOnly: {}", request.readOnly);
@@ -115,7 +144,7 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
{
auto request = decode<xShmDetachReq>(packet).value();
dprintln("ShmDetach");
dwarnln("ShmDetach");
dprintln(" shmseg: {}", request.shmseg);
void* shm_segment = TRY(get_shmseg(client_info, request.shmseg, op_major, op_minor));
@@ -130,7 +159,7 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
{
auto request = decode<xShmPutImageReq>(packet).value();
dprintln("ShmPutImage");
dwarnln("ShmPutImage");
dprintln(" drawable: {}", request.drawable);
dprintln(" gc: {}", request.gc);
dprintln(" totalWidth: {}", request.totalWidth);
@@ -194,7 +223,7 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
{
auto request = decode<xShmGetImageReq>(packet).value();
dprintln("ShmGetImage");
dwarnln("ShmGetImage");
dprintln(" drawable: {}", request.drawable);
dprintln(" x: {}", request.x);
dprintln(" y: {}", request.y);
@@ -236,6 +265,44 @@ static BAN::ErrorOr<void> extension_shm(Client& client_info, BAN::ConstByteSpan
break;
}
case X_ShmCreatePixmap:
{
auto request = decode<xShmCreatePixmapReq>(packet).value();
dwarnln("ShmCreatePixmap");
dprintln(" depth: {}", request.depth);
dprintln(" pid: {}", request.pid);
dprintln(" drawable: {}", request.drawable);
dprintln(" width: {}", request.width);
dprintln(" height: {}", request.height);
dprintln(" shmseg: {}", request.shmseg);
dprintln(" offset: {}", request.offset);
uint8_t bpp = 0;
for (auto format : g_formats)
if (format.depth == request.depth)
bpp = format.bitsPerPixel;
ASSERT(bpp == 32);
void* shm_segment = TRY(get_shmseg(client_info, request.shmseg, op_major, op_minor));
TRY(client_info.objects.insert(request.pid));
TRY(g_objects.insert(
request.pid,
TRY(BAN::UniqPtr<Object>::create(Object {
.type = Object::Type::Pixmap,
.object = Object::Pixmap {
.depth = request.depth,
.width = request.width,
.height = request.height,
.data = BAN::ByteSpan(static_cast<uint8_t*>(shm_segment) + request.offset, request.width * request.height * 4),
.owned_data = {},
}
}))
));
break;
}
default:
dwarnln("unsupported shm minor opcode {}", packet[1]);
break;

View File

@@ -1,119 +0,0 @@
#include "Extensions.h"
#include "Utils.h"
#include <X11/X.h>
#include <X11/extensions/XResproto.h>
template<typename F>
static BAN::ErrorOr<void> for_each_client(uint32_t target_spec, const F& callback)
{
for (auto [fd, thingy] : g_pollables)
{
if (thingy.type != Pollable::Type::Client)
continue;
Client& client_info = thingy.value.get<Client>();
if (target_spec && (target_spec >> 20) != client_info.fd)
continue;
TRY(callback(client_info, target_spec ? target_spec : (client_info.fd << 20)));
}
return {};
}
BAN::ErrorOr<void> extension_xres(Client& client_info, BAN::ConstByteSpan packet)
{
const uint8_t major_opcode = packet[0];
const uint8_t minor_opcode = packet[1];
switch (minor_opcode)
{
case X_XResQueryVersion:
{
auto request = decode<xXResQueryVersionReq>(packet).value();
dprintln("XResQueryVersion");
dprintln(" clientMajor: {}", request.client_major);
dprintln(" clientMinor: {}", request.client_minor);
xXResQueryVersionReply reply {
.type = X_Reply,
.sequenceNumber = client_info.sequence,
.length = 0,
.server_major = 1,
.server_minor = 2,
};
TRY(encode(client_info.output_buffer, reply));
break;
}
case X_XResQueryClientIds:
{
auto request = decode<xXResQueryClientIdsReq>(packet).value();
dprintln("XResQueryClientIds");
dprintln(" numSpecs: {}", request.numSpecs);
uint32_t num_ids { 0 };
BAN::Vector<uint8_t> query_result;
for (size_t i = 0; i < request.numSpecs; i++)
{
auto spec = decode<xXResClientIdSpec>(packet).value();
TRY(for_each_client(spec.client, [&](Client& client_info, uint32_t client_spec) -> BAN::ErrorOr<void> {
if (spec.mask == None || (spec.mask & X_XResClientXIDMask))
{
xXResClientIdValue value {
.spec = {
.client = client_spec,
.mask = X_XResClientXIDMask,
},
.length = 0,
};
TRY(encode(query_result, value));
num_ids++;
}
if ((spec.mask == None || (spec.mask & X_XResLocalClientPIDMask)) && client_info.pid.has_value())
{
xXResClientIdValue value {
.spec = {
.client = client_spec,
.mask = X_XResLocalClientPIDMask,
},
.length = 4,
};
TRY(encode(query_result, value));
TRY(encode(query_result, client_info.pid.value()));
num_ids++;
}
return {};
}));
}
xXResQueryClientIdsReply reply {
.type = X_Reply,
.sequenceNumber = client_info.sequence,
.length = static_cast<uint32_t>(query_result.size() / 4),
.numIds = num_ids,
};
TRY(encode(client_info.output_buffer, reply));
TRY(encode(client_info.output_buffer, query_result));
break;
}
default:
dwarnln("unsupported opcode XRes minor opcode {}", minor_opcode);
break;
}
return {};
}
static struct XResInstaller
{
XResInstaller()
{
install_extension(XRES_NAME, 6, 0, extension_xres);
}
} installer;

View File

@@ -385,7 +385,7 @@ static BAN::ErrorOr<BAN::RefPtr<PCFFont>> parse_font(const BAN::String& path)
font->font_ascent = font->max_bounds.ascent;
font->font_descent = font->max_bounds.descent;
font->is_cursor_font = (path == FONT_PATH "/misc/cursor.pcf.gz"_sv);
font->is_cursor_font = (path == "fonts/misc/cursor.pcf.gz"_sv);
return font;
}
@@ -393,7 +393,7 @@ static BAN::ErrorOr<BAN::RefPtr<PCFFont>> parse_font(const BAN::String& path)
__attribute__((constructor))
static void initialize_fonts()
{
const char* font_path = FONT_PATH "/misc";
const char* font_path = "fonts/misc";
do
{

View File

@@ -60,33 +60,8 @@ void put_image(const PutImageInfo& info)
}
case ZPixmap:
{
bool needs_clipping = true;
if (info.gc.clip_mask == None)
{
needs_clipping = false;
}
else if (info.gc.clip_mask == UINT32_MAX)
{
const uint32_t clip_min_x = min_x - info.gc.clip_origin_x;
const uint32_t clip_min_y = min_y - info.gc.clip_origin_y;
const uint32_t clip_max_x = max_x - info.gc.clip_origin_x;
const uint32_t clip_max_y = max_y - info.gc.clip_origin_y;
for (const auto& rect : info.gc.clip_rects)
{
if (clip_min_x < rect.x || clip_max_x > rect.x + rect.width)
continue;
if (clip_min_y < rect.y || clip_max_y > rect.y + rect.height)
continue;
needs_clipping = false;
break;
}
}
ASSERT(info.left_pad == 0);
if (in_bpp == 32 && !needs_clipping)
if (in_bpp == 32 && info.gc.clip_mask == None)
{
const auto bytes_per_row = (max_x - min_x) * 4;
for (int32_t y = min_y; y < max_y; y++)

View File

@@ -1,5 +1,349 @@
#include "Keymap.h"
uint32_t g_keymap[g_keymap_size][g_keymap_layers] {};
uint8_t g_modifier_map[8][2] {};
#include <BAN/StringView.h>
#include <LibInput/KeyboardLayout.h>
#include <X11/X.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <ctype.h>
#undef None
uint32_t g_keymap[0x100][g_keymap_layers];
uint8_t g_pressed_keys[32] {};
static constexpr uint32_t my_key_to_x_keysym(LibInput::Key key)
{
using LibInput::Key;
switch (key)
{
case Key::A:
return XK_A;
case Key::B:
return XK_B;
case Key::C:
return XK_C;
case Key::D:
return XK_D;
case Key::E:
return XK_E;
case Key::F:
return XK_F;
case Key::G:
return XK_G;
case Key::H:
return XK_H;
case Key::I:
return XK_I;
case Key::J:
return XK_J;
case Key::K:
return XK_K;
case Key::L:
return XK_L;
case Key::M:
return XK_M;
case Key::N:
return XK_N;
case Key::O:
return XK_O;
case Key::P:
return XK_P;
case Key::Q:
return XK_Q;
case Key::R:
return XK_R;
case Key::S:
return XK_S;
case Key::T:
return XK_T;
case Key::U:
return XK_U;
case Key::V:
return XK_V;
case Key::W:
return XK_W;
case Key::X:
return XK_X;
case Key::Y:
return XK_Y;
case Key::Z:
return XK_Z;
case Key::A_Ring:
return XK_Aring;
case Key::A_Umlaut:
return XK_Adiaeresis;
case Key::O_Umlaut:
return XK_Odiaeresis;
case Key::_0:
return XK_0;
case Key::_1:
return XK_1;
case Key::_2:
return XK_2;
case Key::_3:
return XK_3;
case Key::_4:
return XK_4;
case Key::_5:
return XK_5;
case Key::_6:
return XK_6;
case Key::_7:
return XK_7;
case Key::_8:
return XK_8;
case Key::_9:
return XK_9;
case Key::F1:
return XK_F1;
case Key::F2:
return XK_F2;
case Key::F3:
return XK_F3;
case Key::F4:
return XK_F4;
case Key::F5:
return XK_F5;
case Key::F6:
return XK_F6;
case Key::F7:
return XK_F7;
case Key::F8:
return XK_F8;
case Key::F9:
return XK_F9;
case Key::F10:
return XK_F10;
case Key::F11:
return XK_F11;
case Key::F12:
return XK_F12;
case Key::Insert:
return XK_Insert;
case Key::PrintScreen:
return XK_Print;
case Key::Delete:
return XK_Delete;
case Key::Home:
return XK_Home;
case Key::End:
return XK_End;
case Key::PageUp:
return XK_Page_Up;
case Key::PageDown:
return XK_Page_Down;
case Key::Enter:
return XK_Return;
case Key::Space:
return XK_space;
case Key::ExclamationMark:
return XK_exclam;
case Key::DoubleQuote:
return XK_quotedbl;
case Key::Hashtag:
return XK_numbersign;
case Key::Currency:
return XK_currency;
case Key::Percent:
return XK_percent;
case Key::Ampersand:
return XK_ampersand;
case Key::Slash:
return XK_slash;
case Key::Section:
return XK_section;
case Key::Half:
return XK_onehalf;
case Key::OpenParenthesis:
return '(';
case Key::CloseParenthesis:
return ')';
case Key::OpenSquareBracket:
return '[';
case Key::CloseSquareBracket:
return ']';
case Key::OpenCurlyBracket:
return '{';
case Key::CloseCurlyBracket:
return '}';
case Key::Equals:
return '=';
case Key::QuestionMark:
return '?';
case Key::Plus:
return '+';
case Key::BackSlash:
return '\\';
case Key::Acute:
return XK_acute;
case Key::BackTick:
return '`';
case Key::TwoDots:
return XK_diaeresis;
case Key::Cedilla:
return XK_Ccedilla;
case Key::Backspace:
return XK_BackSpace;
case Key::AtSign:
return XK_at;
case Key::Pound:
return XK_sterling;
case Key::Dollar:
return XK_dollar;
case Key::Euro:
return XK_EuroSign;
case Key::Escape:
return XK_Escape;
case Key::Tab:
return XK_Tab;
case Key::CapsLock:
return XK_Caps_Lock;
case Key::LeftShift:
return XK_Shift_L;
case Key::LeftCtrl:
return XK_Control_L;
case Key::Super:
return XK_Super_L;
case Key::LeftAlt:
return XK_Alt_L;
case Key::RightAlt:
return XK_Alt_R;
case Key::RightCtrl:
return XK_Control_R;
case Key::RightShift:
return XK_Shift_R;
case Key::SingleQuote:
return '\'';
case Key::Asterix:
return '*';
case Key::Caret:
return '^';
case Key::Tilde:
return '~';
case Key::ArrowUp:
return XK_Up;
case Key::ArrowDown:
return XK_Down;
case Key::ArrowLeft:
return XK_Left;
case Key::ArrowRight:
return XK_Right;
case Key::Comma:
return ',';
case Key::Semicolon:
return ';';
case Key::Period:
return '.';
case Key::Colon:
return ':';
case Key::Hyphen:
return '-';
case Key::Underscore:
return '_';
case Key::NumLock:
return XK_Num_Lock;
case Key::ScrollLock:
return XK_Scroll_Lock;
case Key::LessThan:
return '<';
case Key::GreaterThan:
return '>';
case Key::Pipe:
return '|';
case Key::Negation:
return XK_notsign;
case Key::BrokenBar:
return XK_brokenbar;
case Key::Numpad0:
return XK_KP_0;
case Key::Numpad1:
return XK_KP_1;
case Key::Numpad2:
return XK_KP_2;
case Key::Numpad3:
return XK_KP_3;
case Key::Numpad4:
return XK_KP_4;
case Key::Numpad5:
return XK_KP_5;
case Key::Numpad6:
return XK_KP_6;
case Key::Numpad7:
return XK_KP_7;
case Key::Numpad8:
return XK_KP_8;
case Key::Numpad9:
return XK_KP_9;
case Key::NumpadPlus:
return XK_KP_Add;
case Key::NumpadMinus:
return XK_KP_Subtract;
case Key::NumpadMultiply:
return XK_KP_Multiply;
case Key::NumpadDivide:
return XK_KP_Divide;
case Key::NumpadEnter:
return XK_KP_Enter;
case Key::NumpadDecimal:
return XK_KP_Decimal;
case Key::VolumeMute:
return XF86XK_AudioMute;
case Key::VolumeUp:
return XF86XK_AudioRaiseVolume;
case Key::VolumeDown:
return XF86XK_AudioLowerVolume;
case Key::Calculator:
return XF86XK_Calculator;
case Key::MediaPlayPause:
return XF86XK_AudioPlay;
case Key::MediaStop:
return XF86XK_AudioStop;
case Key::MediaPrevious:
return XF86XK_AudioPrev;
case Key::MediaNext:
return XF86XK_AudioNext;
case Key::Invalid:
case Key::None:
case Key::Count:
break;
}
return NoSymbol;
}
BAN::ErrorOr<void> initialize_keymap()
{
for (auto& keycode : g_keymap)
for (auto& keysym : keycode)
keysym = NoSymbol;
// FIXME: get this from somewhere (gui command? enviroment? tmp file?)
const auto keymap_path = "./us.keymap"_sv;
TRY(LibInput::KeyboardLayout::initialize());
auto& keyboard_layout = LibInput::KeyboardLayout::get();
TRY(keyboard_layout.load_from_file(keymap_path));
const BAN::Span<const LibInput::Key> my_keymaps[] {
keyboard_layout.keymap_normal(),
keyboard_layout.keymap_shift(),
keyboard_layout.keymap_altgr(),
keyboard_layout.keymap_altgr(), // add shift+altgr map?
};
for (size_t keycode = g_keymap_min_keycode; keycode < g_keymap_max_keycode; keycode++)
for (size_t layer = 0; layer < g_keymap_layers; layer++)
if (auto my_key = my_keymaps[layer][keycode - g_keymap_min_keycode]; my_key != LibInput::Key::None)
if (auto keysym = my_key_to_x_keysym(my_key); keysym != NoSymbol)
g_keymap[keycode][layer] = (layer % 2) ? toupper(keysym) : tolower(keysym);
return {};
}

View File

@@ -1,17 +1,15 @@
#pragma once
#include <BAN/Errors.h>
#include <stddef.h>
#include <stdint.h>
BAN::ErrorOr<void> initialize_keymap();
constexpr size_t g_keymap_min_keycode = 8;
constexpr size_t g_keymap_max_keycode = 255;
constexpr size_t g_keymap_size = g_keymap_max_keycode - g_keymap_min_keycode + 1;
constexpr size_t g_keymap_layers = 4;
extern uint32_t g_keymap[g_keymap_size][g_keymap_layers];
// shift, capslock, control, alt, numlock, level5 shift, super, altgr with 2 keycodes per modifier
constexpr size_t g_modifier_layers = 2;
extern uint8_t g_modifier_map[8][g_modifier_layers];
extern uint32_t g_keymap[0x100][g_keymap_layers];
extern uint8_t g_pressed_keys[32];

View File

@@ -16,9 +16,9 @@ struct PlatformCursor
enum class WindowType
{
Popup,
Normal,
Utility,
Popup,
};
enum class SystemCursorType
@@ -42,8 +42,7 @@ enum class SystemCursorType
ResizeHorizontal,
};
// initialize, create_window and invalidate are required
// poll_events is required when an event fd is registered
// initialize, poll_events, create_window and invalidate are required
struct PlatformOps
{
/* Do platform initialization */
@@ -56,16 +55,8 @@ struct PlatformOps
void (*invalidate)(PlatformWindow*, const uint32_t* pixels, uint32_t x, uint32_t y, uint32_t width, uint32_t height);
/* Request resize of a window, can be async */
void (*request_resize)(PlatformWindow*, uint32_t width, uint32_t height);
/* Request window repositioning */
void (*request_reposition)(PlatformWindow*, int32_t x, int32_t y);
/* Request new fullscreen state, can be async */
void (*request_fullscreen)(PlatformWindow*, bool fullscreen);
/* Warp pointer */
void (*warp_pointer)(int32_t x, int32_t y, bool relative);
/* Get global position of the pointer */
void (*query_pointer)(int32_t* x, int32_t* y);
/* Grab pointer events on window */
void (*set_pointer_grab)(PlatformWindow*, bool grabbed);
/* Create a system cursor */
BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> (*create_system_cursor)(SystemCursorType);
/* Create cursor from custom bitmap */

555
xbanan/SDL2/sdl2.cpp Normal file
View File

@@ -0,0 +1,555 @@
#include "../Events.h"
#include "../Platform.h"
#include <BAN/Atomic.h>
#include <BAN/HashMap.h>
#include <SDL2/SDL.h>
#include <pthread.h>
#include <sys/eventfd.h>
#include <unistd.h>
BAN::HashMap<uint32_t, struct SDLWindow*> s_window_map;
struct SDLWindow final : public PlatformWindow
{
~SDLWindow()
{
if (texture != nullptr)
SDL_DestroyTexture(texture);
if (renderer != nullptr)
SDL_DestroyRenderer(renderer);
if (window != nullptr)
{
s_window_map.remove(SDL_GetWindowID(window));
SDL_DestroyWindow(window);
}
}
WINDOW wid;
uint32_t width;
uint32_t height;
SDL_Window* window { nullptr };
SDL_Renderer* renderer { nullptr };
SDL_Texture* texture { nullptr };
};
struct SDLCursor final : public PlatformCursor
{
~SDLCursor()
{
if (cursor != nullptr)
SDL_FreeCursor(cursor);
}
SDL_Cursor* cursor { nullptr };
};
static int s_eventfd { -1 };
struct Keymap
{
consteval Keymap();
uint8_t map[SDL_NUM_SCANCODES];
};
static Keymap s_sdl_keymap;
static SDL_Cursor* s_default_cursor { nullptr };
static void* sdl2_thread(void*)
{
for (;;)
{
const uint64_t value { 1 };
write(s_eventfd, &value, sizeof(value));
usleep(16'666);
}
return nullptr;
}
static bool sdl2_initialize(uint32_t* display_w, uint32_t* display_h)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) == -1)
{
dwarnln("Could not initialize SDL: {}", SDL_GetError());
return false;
}
SDL_DisplayMode DM;
if (SDL_GetCurrentDisplayMode(0, &DM) == -1)
{
dwarnln("Could not get display mode: {}", SDL_GetError());
return false;
}
*display_w = DM.w;
*display_h = DM.h;
s_default_cursor = SDL_GetCursor();
s_eventfd = eventfd(0, 0);
if (s_eventfd == -1)
{
dwarnln("Could not create eventfd: {}", strerror(errno));
return false;
}
register_event_fd(s_eventfd, nullptr);
pthread_t thread;
pthread_create(&thread, nullptr, sdl2_thread, nullptr);
return true;
}
static BAN::ErrorOr<BAN::UniqPtr<PlatformWindow>> sdl2_create_window(PlatformWindow* parent, WindowType type, WINDOW wid, int32_t x, int32_t y, uint32_t width, uint32_t height)
{
auto window = TRY(BAN::UniqPtr<SDLWindow>::create());
window->wid = wid;
window->width = width;
window->height = height;
if (parent == nullptr || type != WindowType::Popup)
x = y = SDL_WINDOWPOS_UNDEFINED;
else
{
auto& sdl_parent = *static_cast<SDLWindow*>(parent);
int parent_x, parent_y;
SDL_GetWindowPosition(sdl_parent.window, &parent_x, &parent_y);
x += parent_x;
y += parent_y;
}
int flags;
switch (type)
{
case WindowType::Popup:
flags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | SDL_WINDOW_UTILITY;
break;
case WindowType::Utility:
flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_UTILITY;
break;
case WindowType::Normal:
flags = SDL_WINDOW_RESIZABLE;
break;
}
window->window = SDL_CreateWindow("", x, y, width, height, flags);
if (window->window == nullptr)
{
dwarnln("Could not create SDL window: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
window->renderer = SDL_CreateRenderer(window->window, -1, SDL_RENDERER_ACCELERATED);
if (window->renderer == nullptr)
{
dwarnln("Could not create SDL renderer: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
window->texture = SDL_CreateTexture(window->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);
if (window->texture == nullptr)
{
dwarnln("Could not create SDL texture: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
TRY(s_window_map.insert(SDL_GetWindowID(window->window), window.ptr()));
return BAN::UniqPtr<PlatformWindow>(BAN::move(window));
}
static void sdl2_request_resize(PlatformWindow* window, uint32_t width, uint32_t height)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
SDL_SetWindowSize(sdl_window.window, width, height);
}
static void sdl2_poll_events(void*)
{
uint64_t dummy;
read(s_eventfd, &dummy, sizeof(dummy));
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_WINDOWEVENT:
{
auto it = s_window_map.find(event.window.windowID);
if (it == s_window_map.end())
break;
auto& window = *it->value;
switch (event.window.event)
{
case SDL_WINDOWEVENT_CLOSE:
on_window_close_event(window.wid);
break;
case SDL_WINDOWEVENT_SIZE_CHANGED:
window.width = event.window.data1;
window.height = event.window.data2;
SDL_DestroyTexture(window.texture);
window.texture = SDL_CreateTexture(window.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, window.width, window.height);
ASSERT(window.texture);
on_window_resize_event(window.wid, event.window.data1, event.window.data2);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
on_window_focus_event(window.wid, true);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
on_window_focus_event(window.wid, false);
break;
case SDL_WINDOWEVENT_MAXIMIZED:
on_window_fullscreen_event(window.wid, true);
break;
case SDL_WINDOWEVENT_RESTORED:
on_window_fullscreen_event(window.wid, false);
break;
}
break;
}
case SDL_MOUSEMOTION:
{
auto it = s_window_map.find(event.window.windowID);
if (it != s_window_map.end())
on_mouse_move_event(it->value->wid, event.motion.x, event.motion.y);
break;
}
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
{
uint8_t xbutton { 0 };
switch (event.button.button)
{
case SDL_BUTTON_LEFT: xbutton = 1; break;
case SDL_BUTTON_MIDDLE: xbutton = 2; break;
case SDL_BUTTON_RIGHT: xbutton = 3; break;
case SDL_BUTTON_X1: xbutton = 8; break;
case SDL_BUTTON_X2: xbutton = 9; break;
}
auto it = s_window_map.find(event.window.windowID);
if (xbutton && it != s_window_map.end())
on_mouse_button_event(it->value->wid, xbutton, (event.type == SDL_MOUSEBUTTONDOWN));
break;
}
case SDL_MOUSEWHEEL:
{
uint8_t xbutton { 0 };
if (event.wheel.y > 0)
xbutton = 4;
if (event.wheel.y < 0)
xbutton = 5;
auto it = s_window_map.find(event.window.windowID);
if (xbutton && it != s_window_map.end())
{
on_mouse_button_event(it->value->wid, xbutton, true);
on_mouse_button_event(it->value->wid, xbutton, false);
}
break;
}
case SDL_KEYUP:
case SDL_KEYDOWN:
{
uint8_t scancode = s_sdl_keymap.map[event.key.keysym.scancode];
uint8_t xmod { 0 };
if (event.key.keysym.mod & (KMOD_LSHIFT | KMOD_RSHIFT))
xmod |= (1 << 0);
if (event.key.keysym.mod & (KMOD_CAPS))
xmod |= (1 << 1);
if (event.key.keysym.mod & (KMOD_LCTRL | KMOD_RCTRL))
xmod |= (1 << 2);
if (event.key.keysym.mod & (KMOD_LALT | KMOD_RALT))
xmod |= (1 << 3);
auto it = s_window_map.find(event.window.windowID);
if (it != s_window_map.end())
on_key_event(it->value->wid, scancode, xmod, (event.type == SDL_KEYDOWN));
break;
}
}
}
}
static void sdl2_invalidate(PlatformWindow* window, const uint32_t* src_pixels, uint32_t x, uint32_t y, uint32_t width, uint32_t height)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
ASSERT(x < sdl_window.width && width <= sdl_window.width - x);
ASSERT(y < sdl_window.height && height <= sdl_window.height - y);
const SDL_Rect rect {
.x = static_cast<int>(x),
.y = static_cast<int>(y),
.w = static_cast<int>(width),
.h = static_cast<int>(height),
};
void* dst_pixels;
int dst_pitch;
if (SDL_LockTexture(sdl_window.texture, &rect, &dst_pixels, &dst_pitch) == -1)
{
dwarnln("Could not lock texture: {}", SDL_GetError());
return;
}
for (int32_t y_off = 0; y_off < rect.h; y_off++)
{
memcpy(
static_cast<uint8_t*>(dst_pixels) + y_off * dst_pitch,
&src_pixels[(rect.y + y_off) * sdl_window.width + rect.x],
rect.w * sizeof(uint32_t)
);
}
SDL_UnlockTexture(sdl_window.texture);
SDL_RenderClear(sdl_window.renderer);
SDL_RenderCopy(sdl_window.renderer, sdl_window.texture, NULL, NULL);
SDL_RenderPresent(sdl_window.renderer);
}
static void sdl2_request_fullscreen(PlatformWindow* window, bool fullscreen)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
(void)sdl_window;
(void)fullscreen;
}
BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> sdl2_create_system_cursor(SystemCursorType type)
{
SDL_SystemCursor sdl_type;
switch (type)
{
case SystemCursorType::Help:
case SystemCursorType::Pointer:
sdl_type = SDL_SYSTEM_CURSOR_ARROW;
break;
case SystemCursorType::Text:
sdl_type = SDL_SYSTEM_CURSOR_IBEAM;
break;
case SystemCursorType::Wait:
sdl_type = SDL_SYSTEM_CURSOR_WAIT;
break;
case SystemCursorType::Hand:
sdl_type = SDL_SYSTEM_CURSOR_HAND;
break;
case SystemCursorType::Move:
sdl_type = SDL_SYSTEM_CURSOR_SIZEALL;
break;
case SystemCursorType::Forbidden:
sdl_type = SDL_SYSTEM_CURSOR_NO;
break;
case SystemCursorType::ResizeN:
case SystemCursorType::ResizeS:
case SystemCursorType::ResizeVertical:
sdl_type = SDL_SYSTEM_CURSOR_SIZENS;
break;
case SystemCursorType::ResizeE:
case SystemCursorType::ResizeW:
case SystemCursorType::ResizeHorizontal:
sdl_type = SDL_SYSTEM_CURSOR_SIZEWE;
break;
case SystemCursorType::ResizeNW:
case SystemCursorType::ResizeSE:
sdl_type = SDL_SYSTEM_CURSOR_SIZENWSE;
break;
case SystemCursorType::ResizeNE:
case SystemCursorType::ResizeSW:
sdl_type = SDL_SYSTEM_CURSOR_SIZENESW;
break;
}
auto cursor = TRY(BAN::UniqPtr<SDLCursor>::create());
cursor->cursor = SDL_CreateSystemCursor(sdl_type);
if (cursor->cursor == nullptr)
{
dwarnln("Could not create SDL system cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
return BAN::UniqPtr<PlatformCursor>(BAN::move(cursor));
}
BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> sdl2_create_bitmap_cursor(const uint32_t* pixels, uint32_t width, uint32_t height, int32_t origin_x, int32_t origin_y)
{
auto cursor = TRY(BAN::UniqPtr<SDLCursor>::create());
SDL_Surface* surface = SDL_CreateRGBSurfaceWithFormatFrom(const_cast<uint32_t*>(pixels), width, height, 32, width * 4, SDL_PIXELFORMAT_ARGB8888);
if (surface == nullptr)
{
dwarnln("Could not create SDL surface for cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
cursor->cursor = SDL_CreateColorCursor(surface, origin_x, origin_y);
SDL_FreeSurface(surface);
if (cursor->cursor == nullptr)
{
dwarnln("Could not create SDL color cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
return BAN::UniqPtr<PlatformCursor>(BAN::move(cursor));
}
void sdl2_set_cursor(PlatformWindow*, PlatformCursor* cursor)
{
if (cursor == nullptr)
SDL_SetCursor(s_default_cursor);
else
{
auto& sdl_cursor = *static_cast<SDLCursor*>(cursor);
SDL_SetCursor(sdl_cursor.cursor);
}
}
PlatformOps g_platform_ops = {
.initialize = sdl2_initialize,
.poll_events = sdl2_poll_events,
.create_window = sdl2_create_window,
.invalidate = sdl2_invalidate,
.request_resize = sdl2_request_resize,
.request_fullscreen = sdl2_request_fullscreen,
.create_system_cursor = sdl2_create_system_cursor,
.create_bitmap_cursor = sdl2_create_bitmap_cursor,
.set_cursor = sdl2_set_cursor,
};
#include <LibInput/KeyEvent.h>
consteval Keymap::Keymap()
{
for (auto& scancode : map)
scancode = 0;
using LibInput::keycode_normal;
using LibInput::keycode_function;
using LibInput::keycode_numpad;
map[SDL_SCANCODE_GRAVE] = keycode_normal(0, 0);
map[SDL_SCANCODE_1] = keycode_normal(0, 1);
map[SDL_SCANCODE_2] = keycode_normal(0, 2);
map[SDL_SCANCODE_3] = keycode_normal(0, 3);
map[SDL_SCANCODE_4] = keycode_normal(0, 4);
map[SDL_SCANCODE_5] = keycode_normal(0, 5);
map[SDL_SCANCODE_6] = keycode_normal(0, 6);
map[SDL_SCANCODE_7] = keycode_normal(0, 7);
map[SDL_SCANCODE_8] = keycode_normal(0, 8);
map[SDL_SCANCODE_9] = keycode_normal(0, 9);
map[SDL_SCANCODE_0] = keycode_normal(0, 10);
map[SDL_SCANCODE_MINUS] = keycode_normal(0, 11);
map[SDL_SCANCODE_EQUALS] = keycode_normal(0, 12);
map[SDL_SCANCODE_BACKSPACE] = keycode_normal(0, 13);
map[SDL_SCANCODE_TAB] = keycode_normal(1, 0);
map[SDL_SCANCODE_Q] = keycode_normal(1, 1);
map[SDL_SCANCODE_W] = keycode_normal(1, 2);
map[SDL_SCANCODE_E] = keycode_normal(1, 3);
map[SDL_SCANCODE_R] = keycode_normal(1, 4);
map[SDL_SCANCODE_T] = keycode_normal(1, 5);
map[SDL_SCANCODE_Y] = keycode_normal(1, 6);
map[SDL_SCANCODE_U] = keycode_normal(1, 7);
map[SDL_SCANCODE_I] = keycode_normal(1, 8);
map[SDL_SCANCODE_O] = keycode_normal(1, 9);
map[SDL_SCANCODE_P] = keycode_normal(1, 10);
map[SDL_SCANCODE_LEFTBRACKET] = keycode_normal(1, 11);
map[SDL_SCANCODE_RIGHTBRACKET] = keycode_normal(1, 12);
map[SDL_SCANCODE_CAPSLOCK] = keycode_normal(2, 0);
map[SDL_SCANCODE_A] = keycode_normal(2, 1);
map[SDL_SCANCODE_S] = keycode_normal(2, 2);
map[SDL_SCANCODE_D] = keycode_normal(2, 3);
map[SDL_SCANCODE_F] = keycode_normal(2, 4);
map[SDL_SCANCODE_G] = keycode_normal(2, 5);
map[SDL_SCANCODE_H] = keycode_normal(2, 6);
map[SDL_SCANCODE_J] = keycode_normal(2, 7);
map[SDL_SCANCODE_K] = keycode_normal(2, 8);
map[SDL_SCANCODE_L] = keycode_normal(2, 9);
map[SDL_SCANCODE_SEMICOLON] = keycode_normal(2, 10);
map[SDL_SCANCODE_APOSTROPHE] = keycode_normal(2, 11);
map[SDL_SCANCODE_BACKSLASH] = keycode_normal(2, 12);
map[SDL_SCANCODE_RETURN] = keycode_normal(2, 13);
map[SDL_SCANCODE_LSHIFT] = keycode_normal(3, 0);
map[SDL_SCANCODE_NONUSBACKSLASH] = keycode_normal(3, 1);
map[SDL_SCANCODE_Z] = keycode_normal(3, 2);
map[SDL_SCANCODE_X] = keycode_normal(3, 3);
map[SDL_SCANCODE_C] = keycode_normal(3, 4);
map[SDL_SCANCODE_V] = keycode_normal(3, 5);
map[SDL_SCANCODE_B] = keycode_normal(3, 6);
map[SDL_SCANCODE_N] = keycode_normal(3, 7);
map[SDL_SCANCODE_M] = keycode_normal(3, 8);
map[SDL_SCANCODE_COMMA] = keycode_normal(3, 9);
map[SDL_SCANCODE_PERIOD] = keycode_normal(3, 10);
map[SDL_SCANCODE_SLASH] = keycode_normal(3, 11);
map[SDL_SCANCODE_RSHIFT] = keycode_normal(3, 12);
map[SDL_SCANCODE_LCTRL] = keycode_normal(4, 0);
map[SDL_SCANCODE_LGUI] = keycode_normal(4, 1);
map[SDL_SCANCODE_LALT] = keycode_normal(4, 2);
map[SDL_SCANCODE_SPACE] = keycode_normal(4, 3);
map[SDL_SCANCODE_RALT] = keycode_normal(4, 4);
map[SDL_SCANCODE_RCTRL] = keycode_normal(4, 5);
map[SDL_SCANCODE_UP] = keycode_normal(5, 0);
map[SDL_SCANCODE_LEFT] = keycode_normal(5, 1);
map[SDL_SCANCODE_DOWN] = keycode_normal(5, 2);
map[SDL_SCANCODE_RIGHT] = keycode_normal(5, 3);
map[SDL_SCANCODE_ESCAPE] = keycode_function(0);
map[SDL_SCANCODE_F1] = keycode_function(1);
map[SDL_SCANCODE_F2] = keycode_function(2);
map[SDL_SCANCODE_F3] = keycode_function(3);
map[SDL_SCANCODE_F4] = keycode_function(4);
map[SDL_SCANCODE_F5] = keycode_function(5);
map[SDL_SCANCODE_F6] = keycode_function(6);
map[SDL_SCANCODE_F7] = keycode_function(7);
map[SDL_SCANCODE_F8] = keycode_function(8);
map[SDL_SCANCODE_F9] = keycode_function(9);
map[SDL_SCANCODE_F10] = keycode_function(10);
map[SDL_SCANCODE_F11] = keycode_function(11);
map[SDL_SCANCODE_F12] = keycode_function(12);
map[SDL_SCANCODE_INSERT] = keycode_function(13);
map[SDL_SCANCODE_PRINTSCREEN] = keycode_function(14);
map[SDL_SCANCODE_DELETE] = keycode_function(15);
map[SDL_SCANCODE_HOME] = keycode_function(16);
map[SDL_SCANCODE_END] = keycode_function(17);
map[SDL_SCANCODE_PAGEUP] = keycode_function(18);
map[SDL_SCANCODE_PAGEDOWN] = keycode_function(19);
map[SDL_SCANCODE_SCROLLLOCK] = keycode_function(20);
map[SDL_SCANCODE_NUMLOCKCLEAR] = keycode_numpad(0, 0);
map[SDL_SCANCODE_KP_DIVIDE] = keycode_numpad(0, 1);
map[SDL_SCANCODE_KP_MULTIPLY] = keycode_numpad(0, 2);
map[SDL_SCANCODE_KP_MINUS] = keycode_numpad(0, 3);
map[SDL_SCANCODE_KP_7] = keycode_numpad(1, 0);
map[SDL_SCANCODE_KP_8] = keycode_numpad(1, 1);
map[SDL_SCANCODE_KP_9] = keycode_numpad(1, 2);
map[SDL_SCANCODE_KP_PLUS] = keycode_numpad(1, 3);
map[SDL_SCANCODE_KP_4] = keycode_numpad(2, 0);
map[SDL_SCANCODE_KP_5] = keycode_numpad(2, 1);
map[SDL_SCANCODE_KP_6] = keycode_numpad(2, 2);
map[SDL_SCANCODE_KP_1] = keycode_numpad(3, 0);
map[SDL_SCANCODE_KP_2] = keycode_numpad(3, 1);
map[SDL_SCANCODE_KP_3] = keycode_numpad(3, 2);
map[SDL_SCANCODE_KP_ENTER] = keycode_numpad(3, 3);
map[SDL_SCANCODE_KP_0] = keycode_numpad(4, 0);
map[SDL_SCANCODE_KP_COMMA] = keycode_numpad(4, 1);
};

View File

@@ -1,703 +0,0 @@
#include "../Events.h"
#include "../Keymap.h"
#include "../Platform.h"
#include <BAN/Atomic.h>
#include <BAN/HashMap.h>
#include <SDL3/SDL.h>
#include <pthread.h>
#include <sys/eventfd.h>
#include <unistd.h>
BAN::HashMap<uint32_t, struct SDLWindow*> s_window_map;
struct SDLWindow final : public PlatformWindow
{
~SDLWindow()
{
if (texture != nullptr)
SDL_DestroyTexture(texture);
if (renderer != nullptr)
SDL_DestroyRenderer(renderer);
if (window != nullptr)
{
s_window_map.remove(SDL_GetWindowID(window));
SDL_DestroyWindow(window);
}
}
WINDOW wid;
uint32_t width;
uint32_t height;
SDL_Window* window { nullptr };
SDL_Renderer* renderer { nullptr };
SDL_Texture* texture { nullptr };
};
struct SDLCursor final : public PlatformCursor
{
~SDLCursor()
{
if (cursor != nullptr)
SDL_DestroyCursor(cursor);
}
SDL_Cursor* cursor { nullptr };
};
static int s_eventfd { -1 };
static SDL_Cursor* s_default_cursor { nullptr };
static void* sdl3_thread(void*)
{
for (;;)
{
const uint64_t value { 1 };
write(s_eventfd, &value, sizeof(value));
usleep(16'666);
}
return nullptr;
}
static void sdl3_initialize_keymap();
static bool sdl3_initialize(uint32_t* display_w, uint32_t* display_h)
{
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
{
dwarnln("Could not initialize SDL: {}", SDL_GetError());
return false;
}
*display_w = *display_h = 0;
const SDL_DisplayID* display_ids = SDL_GetDisplays(nullptr);
for (int i = 0; display_ids[i]; i++)
{
SDL_Rect rect;
SDL_GetDisplayBounds(display_ids[i], &rect);
*display_w = BAN::Math::max<uint32_t>(*display_w, rect.x + rect.w);
*display_h = BAN::Math::max<uint32_t>(*display_h, rect.y + rect.h);
}
sdl3_initialize_keymap();
s_default_cursor = SDL_GetCursor();
s_eventfd = eventfd(0, 0);
if (s_eventfd == -1)
{
dwarnln("Could not create eventfd: {}", strerror(errno));
return false;
}
register_event_fd(s_eventfd, nullptr);
pthread_t thread;
pthread_create(&thread, nullptr, sdl3_thread, nullptr);
return true;
}
static BAN::ErrorOr<BAN::UniqPtr<PlatformWindow>> sdl3_create_window(PlatformWindow* parent, WindowType type, WINDOW wid, int32_t x, int32_t y, uint32_t width, uint32_t height)
{
auto window = TRY(BAN::UniqPtr<SDLWindow>::create());
window->wid = wid;
window->width = width;
window->height = height;
int flags;
switch (type)
{
case WindowType::Normal:
case WindowType::Utility:
flags = SDL_WINDOW_RESIZABLE;
break;
case WindowType::Popup:
flags = SDL_WINDOW_BORDERLESS;
break;
}
if (parent == nullptr || type != WindowType::Popup)
{
if (type != WindowType::Normal)
flags |= SDL_WINDOW_UTILITY;
window->window = SDL_CreateWindow("", width, height, flags);
}
else
{
auto& sdl_parent = *static_cast<SDLWindow*>(parent);
int parent_x, parent_y;
SDL_GetWindowPosition(sdl_parent.window, &parent_x, &parent_y);
window->window = SDL_CreatePopupWindow(sdl_parent.window, x - parent_x, y - parent_y, width, height, flags | SDL_WINDOW_POPUP_MENU);
}
if (window->window == nullptr)
{
dwarnln("Could not create SDL window: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
window->renderer = SDL_CreateRenderer(window->window, nullptr);
if (window->renderer == nullptr)
{
dwarnln("Could not create SDL renderer: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
window->texture = SDL_CreateTexture(window->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);
if (window->texture == nullptr)
{
dwarnln("Could not create SDL texture: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
TRY(s_window_map.insert(SDL_GetWindowID(window->window), window.ptr()));
return BAN::UniqPtr<PlatformWindow>(BAN::move(window));
}
static void sdl3_request_resize(PlatformWindow* window, uint32_t width, uint32_t height)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
SDL_SetWindowSize(sdl_window.window, width, height);
}
static void sdl3_request_reposition(PlatformWindow* window, int32_t x, int32_t y)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
SDL_SetWindowPosition(sdl_window.window, x, y);
}
static void sdl3_poll_events(void*)
{
uint64_t dummy;
read(s_eventfd, &dummy, sizeof(dummy));
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
if (auto it = s_window_map.find(event.window.windowID); it != s_window_map.end())
on_window_close_event(it->value->wid);
break;
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
if (auto it = s_window_map.find(event.window.windowID); it != s_window_map.end())
{
auto& window = *it->value;
window.width = event.window.data1;
window.height = event.window.data2;
SDL_DestroyTexture(window.texture);
window.texture = SDL_CreateTexture(window.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, window.width, window.height);
ASSERT(window.texture);
on_window_resize_event(window.wid, window.width, window.height);
}
break;
case SDL_EVENT_WINDOW_MOVED:
if (auto it = s_window_map.find(event.motion.windowID); it != s_window_map.end())
on_window_move_event(it->value->wid, event.window.data1, event.window.data2);
break;
case SDL_EVENT_WINDOW_FOCUS_GAINED:
case SDL_EVENT_WINDOW_FOCUS_LOST:
if (auto it = s_window_map.find(event.motion.windowID); it != s_window_map.end())
on_window_focus_event(it->value->wid, (event.type == SDL_EVENT_WINDOW_FOCUS_GAINED));
break;
case SDL_EVENT_WINDOW_ENTER_FULLSCREEN:
case SDL_EVENT_WINDOW_LEAVE_FULLSCREEN:
if (auto it = s_window_map.find(event.motion.windowID); it != s_window_map.end())
on_window_fullscreen_event(it->value->wid, (event.type == SDL_EVENT_WINDOW_ENTER_FULLSCREEN));
break;
case SDL_EVENT_WINDOW_MOUSE_LEAVE:
if (auto it = s_window_map.find(event.motion.windowID); it != s_window_map.end())
on_window_leave_event(it->value->wid);
break;
case SDL_EVENT_MOUSE_MOTION:
if (auto it = s_window_map.find(event.motion.windowID); it != s_window_map.end())
on_mouse_move_event(it->value->wid, event.motion.x, event.motion.y);
break;
case SDL_EVENT_MOUSE_BUTTON_UP:
case SDL_EVENT_MOUSE_BUTTON_DOWN:
{
uint8_t xbutton { 0 };
switch (event.button.button)
{
case SDL_BUTTON_LEFT: xbutton = 1; break;
case SDL_BUTTON_MIDDLE: xbutton = 2; break;
case SDL_BUTTON_RIGHT: xbutton = 3; break;
case SDL_BUTTON_X1: xbutton = 8; break;
case SDL_BUTTON_X2: xbutton = 9; break;
}
auto it = s_window_map.find(event.window.windowID);
if (xbutton && it != s_window_map.end())
on_mouse_button_event(it->value->wid, xbutton, (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN));
break;
}
case SDL_EVENT_MOUSE_WHEEL:
{
uint8_t xbutton { 0 };
if (event.wheel.y > 0)
xbutton = 4;
if (event.wheel.y < 0)
xbutton = 5;
auto it = s_window_map.find(event.window.windowID);
if (xbutton && it != s_window_map.end())
{
on_mouse_button_event(it->value->wid, xbutton, true);
on_mouse_button_event(it->value->wid, xbutton, false);
}
break;
}
case SDL_EVENT_KEY_UP:
case SDL_EVENT_KEY_DOWN:
{
const uint8_t xmod =
((event.key.mod & SDL_KMOD_SHIFT) ? (1 << 0) : 0) |
((event.key.mod & SDL_KMOD_CAPS) ? (1 << 1) : 0) |
((event.key.mod & SDL_KMOD_CTRL) ? (1 << 2) : 0) |
((event.key.mod & SDL_KMOD_ALT) ? (1 << 3) : 0) |
((event.key.mod & SDL_KMOD_NUM) ? (1 << 4) : 0) |
((event.key.mod & SDL_KMOD_LEVEL5) ? (1 << 5) : 0) |
((event.key.mod & SDL_KMOD_GUI) ? (1 << 6) : 0) |
((event.key.mod & SDL_KMOD_MODE) ? (1 << 7) : 0);
auto it = s_window_map.find(event.window.windowID);
if (it != s_window_map.end())
on_key_event(it->value->wid, event.key.scancode, xmod, (event.type == SDL_EVENT_KEY_DOWN));
break;
}
case SDL_EVENT_KEYMAP_CHANGED:
sdl3_initialize_keymap();
on_keymap_changed();
break;
}
}
}
static void sdl3_invalidate(PlatformWindow* window, const uint32_t* src_pixels, uint32_t x, uint32_t y, uint32_t width, uint32_t height)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
ASSERT(x < sdl_window.width && width <= sdl_window.width - x);
ASSERT(y < sdl_window.height && height <= sdl_window.height - y);
const SDL_Rect rect {
.x = static_cast<int>(x),
.y = static_cast<int>(y),
.w = static_cast<int>(width),
.h = static_cast<int>(height),
};
void* dst_pixels;
int dst_pitch;
if (!SDL_LockTexture(sdl_window.texture, &rect, &dst_pixels, &dst_pitch))
{
dwarnln("Could not lock texture: {}", SDL_GetError());
return;
}
for (int32_t y_off = 0; y_off < rect.h; y_off++)
{
memcpy(
static_cast<uint8_t*>(dst_pixels) + y_off * dst_pitch,
&src_pixels[(rect.y + y_off) * sdl_window.width + rect.x],
rect.w * sizeof(uint32_t)
);
}
SDL_UnlockTexture(sdl_window.texture);
SDL_RenderClear(sdl_window.renderer);
SDL_RenderTexture(sdl_window.renderer, sdl_window.texture, NULL, NULL);
SDL_RenderPresent(sdl_window.renderer);
}
static void sdl3_request_fullscreen(PlatformWindow* window, bool fullscreen)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
SDL_SetWindowFullscreen(sdl_window.window, fullscreen);
}
static void sdl3_warp_pointer(int32_t x, int32_t y, bool relative)
{
if (relative)
{
float cx, cy;
SDL_GetGlobalMouseState(&cx, &cy);
x += cx;
x += cy;
}
SDL_WarpMouseGlobal(x, y);
}
static void sdl3_query_pointer(int32_t* x, int32_t* y)
{
float cx, cy;
SDL_GetGlobalMouseState(&cx, &cy);
*x = cx;
*y = cy;
}
static void sdl3_set_pointer_grab(PlatformWindow* window, bool grabbed)
{
auto& sdl_window = *static_cast<SDLWindow*>(window);
SDL_SetWindowMouseGrab(sdl_window.window, grabbed);
}
static BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> sdl3_create_system_cursor(SystemCursorType type)
{
static constexpr SDL_SystemCursor cursor_type_map[] {
[static_cast<size_t>(SystemCursorType::Pointer)] = SDL_SYSTEM_CURSOR_DEFAULT,
[static_cast<size_t>(SystemCursorType::Text)] = SDL_SYSTEM_CURSOR_TEXT,
[static_cast<size_t>(SystemCursorType::Wait)] = SDL_SYSTEM_CURSOR_WAIT,
[static_cast<size_t>(SystemCursorType::Hand)] = SDL_SYSTEM_CURSOR_POINTER,
[static_cast<size_t>(SystemCursorType::Help)] = SDL_SYSTEM_CURSOR_DEFAULT, // :(
[static_cast<size_t>(SystemCursorType::Move)] = SDL_SYSTEM_CURSOR_MOVE,
[static_cast<size_t>(SystemCursorType::Forbidden)] = SDL_SYSTEM_CURSOR_NOT_ALLOWED,
[static_cast<size_t>(SystemCursorType::ResizeN)] = SDL_SYSTEM_CURSOR_N_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeE)] = SDL_SYSTEM_CURSOR_E_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeS)] = SDL_SYSTEM_CURSOR_S_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeW)] = SDL_SYSTEM_CURSOR_W_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeNW)] = SDL_SYSTEM_CURSOR_NW_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeNE)] = SDL_SYSTEM_CURSOR_NE_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeSW)] = SDL_SYSTEM_CURSOR_SW_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeSE)] = SDL_SYSTEM_CURSOR_SE_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeVertical)] = SDL_SYSTEM_CURSOR_NS_RESIZE,
[static_cast<size_t>(SystemCursorType::ResizeHorizontal)] = SDL_SYSTEM_CURSOR_EW_RESIZE,
};
auto cursor = TRY(BAN::UniqPtr<SDLCursor>::create());
cursor->cursor = SDL_CreateSystemCursor(cursor_type_map[static_cast<size_t>(type)]);
if (cursor->cursor == nullptr)
{
dwarnln("Could not create SDL system cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
return BAN::UniqPtr<PlatformCursor>(BAN::move(cursor));
}
static BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> sdl3_create_bitmap_cursor(const uint32_t* pixels, uint32_t width, uint32_t height, int32_t origin_x, int32_t origin_y)
{
auto cursor = TRY(BAN::UniqPtr<SDLCursor>::create());
SDL_Surface* surface = SDL_CreateSurfaceFrom(width, height, SDL_PIXELFORMAT_ARGB8888, const_cast<uint32_t*>(pixels), width * 4);
if (surface == nullptr)
{
dwarnln("Could not create SDL surface for cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
origin_x = BAN::Math::clamp<int32_t>(origin_x, 0, width - 1);
origin_y = BAN::Math::clamp<int32_t>(origin_y, 0, height - 1);
cursor->cursor = SDL_CreateColorCursor(surface, origin_x, origin_y);
SDL_DestroySurface(surface);
if (cursor->cursor == nullptr)
{
dwarnln("Could not create SDL color cursor: {}", SDL_GetError());
return BAN::Error::from_errno(EFAULT);
}
return BAN::UniqPtr<PlatformCursor>(BAN::move(cursor));
}
static void sdl3_set_cursor(PlatformWindow*, PlatformCursor* cursor)
{
if (cursor == nullptr)
SDL_SetCursor(s_default_cursor);
else
{
auto& sdl_cursor = *static_cast<SDLCursor*>(cursor);
SDL_SetCursor(sdl_cursor.cursor);
}
}
PlatformOps g_platform_ops = {
.initialize = sdl3_initialize,
.poll_events = sdl3_poll_events,
.create_window = sdl3_create_window,
.invalidate = sdl3_invalidate,
.request_resize = sdl3_request_resize,
.request_reposition = sdl3_request_reposition,
.request_fullscreen = sdl3_request_fullscreen,
.warp_pointer = sdl3_warp_pointer,
.query_pointer = sdl3_query_pointer,
.set_pointer_grab = sdl3_set_pointer_grab,
.create_system_cursor = sdl3_create_system_cursor,
.create_bitmap_cursor = sdl3_create_bitmap_cursor,
.set_cursor = sdl3_set_cursor,
};
static uint32_t sdl3_keycode_to_x_keysym(SDL_Keycode keycode);
static void sdl3_initialize_keymap()
{
static constexpr SDL_Keymod modifier_map[] {
SDL_KMOD_NONE,
SDL_KMOD_SHIFT,
SDL_KMOD_MODE,
SDL_KMOD_MODE | SDL_KMOD_SHIFT,
};
memset(g_keymap, 0, sizeof(g_keymap));
memset(g_modifier_map, 0, sizeof(g_modifier_map));
for (size_t scancode = 0; scancode < g_keymap_size; scancode++)
for (size_t layer = 0; layer < g_keymap_layers; layer++)
if (const auto sdl_key = SDL_GetKeyFromScancode(static_cast<SDL_Scancode>(scancode), modifier_map[layer], false); sdl_key != SDLK_UNKNOWN)
g_keymap[scancode][layer] = sdl3_keycode_to_x_keysym(sdl_key);
const auto get_scancode = [](SDL_Keycode keycode) -> uint8_t {
const auto scancode = SDL_GetScancodeFromKey(keycode, nullptr);;
if (scancode != SDL_SCANCODE_UNKNOWN && scancode < g_keymap_size)
return scancode + g_keymap_min_keycode;
return 0;
};
g_modifier_map[0][0] = get_scancode(SDLK_LSHIFT);
g_modifier_map[0][1] = get_scancode(SDLK_RSHIFT);
g_modifier_map[1][0] = get_scancode(SDLK_CAPSLOCK);
g_modifier_map[2][0] = get_scancode(SDLK_LCTRL);
g_modifier_map[2][1] = get_scancode(SDLK_RCTRL);
g_modifier_map[3][0] = get_scancode(SDLK_LALT);
g_modifier_map[3][1] = get_scancode(SDLK_RALT);
g_modifier_map[4][0] = get_scancode(SDLK_NUMLOCKCLEAR);
g_modifier_map[5][0] = get_scancode(SDLK_LEVEL5_SHIFT);
g_modifier_map[6][0] = get_scancode(SDLK_LGUI);
g_modifier_map[6][1] = get_scancode(SDLK_RGUI);
g_modifier_map[7][0] = get_scancode(SDLK_MODE);
}
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <wctype.h>
static uint32_t sdl3_keycode_to_x_keysym(SDL_Keycode keycode)
{
if (iswprint(keycode))
{
if ((keycode >= 0x20 && keycode <= 0x7E) || (keycode >= 0xA0 && keycode <= 0xFF))
return keycode;
return 0x01000000 | keycode;
}
switch (keycode)
{
case SDLK_RETURN: return XK_Return;
case SDLK_ESCAPE: return XK_Escape;
case SDLK_BACKSPACE: return XK_BackSpace;
case SDLK_TAB: return XK_Tab;
case SDLK_DELETE: return XK_Delete;
case SDLK_CAPSLOCK: return XK_Caps_Lock;
case SDLK_F1: return XK_F1;
case SDLK_F2: return XK_F2;
case SDLK_F3: return XK_F3;
case SDLK_F4: return XK_F4;
case SDLK_F5: return XK_F5;
case SDLK_F6: return XK_F6;
case SDLK_F7: return XK_F7;
case SDLK_F8: return XK_F8;
case SDLK_F9: return XK_F9;
case SDLK_F10: return XK_F10;
case SDLK_F11: return XK_F11;
case SDLK_F12: return XK_F12;
case SDLK_PRINTSCREEN: return XK_Print;
case SDLK_SCROLLLOCK: return XK_Scroll_Lock;
case SDLK_PAUSE: return XK_Pause;
case SDLK_INSERT: return XK_Insert;
case SDLK_HOME: return XK_Home;
case SDLK_PAGEUP: return XK_Page_Up;
case SDLK_END: return XK_End;
case SDLK_PAGEDOWN: return XK_Page_Down;
case SDLK_RIGHT: return XK_Right;
case SDLK_LEFT: return XK_Left;
case SDLK_DOWN: return XK_Down;
case SDLK_UP: return XK_Up;
case SDLK_NUMLOCKCLEAR: return XK_Num_Lock;
case SDLK_KP_DIVIDE: return XK_KP_Divide;
case SDLK_KP_MULTIPLY: return XK_KP_Multiply;
case SDLK_KP_MINUS: return XK_KP_Subtract;
case SDLK_KP_PLUS: return XK_KP_Add;
case SDLK_KP_ENTER: return XK_KP_Enter;
case SDLK_KP_1: return XK_KP_1;
case SDLK_KP_2: return XK_KP_2;
case SDLK_KP_3: return XK_KP_3;
case SDLK_KP_4: return XK_KP_4;
case SDLK_KP_5: return XK_KP_5;
case SDLK_KP_6: return XK_KP_6;
case SDLK_KP_7: return XK_KP_7;
case SDLK_KP_8: return XK_KP_8;
case SDLK_KP_9: return XK_KP_9;
case SDLK_KP_0: return XK_KP_0;
case SDLK_KP_PERIOD: return XK_KP_Decimal;
case SDLK_APPLICATION: return XF86XK_ApplicationLeft;
case SDLK_POWER: return XF86XK_PowerOff;
case SDLK_KP_EQUALS: return XK_KP_Equal;
case SDLK_F13: return XK_F13;
case SDLK_F14: return XK_F14;
case SDLK_F15: return XK_F15;
case SDLK_F16: return XK_F16;
case SDLK_F17: return XK_F17;
case SDLK_F18: return XK_F18;
case SDLK_F19: return XK_F19;
case SDLK_F20: return XK_F20;
case SDLK_F21: return XK_F21;
case SDLK_F22: return XK_F22;
case SDLK_F23: return XK_F23;
case SDLK_F24: return XK_F24;
case SDLK_EXECUTE: return XK_Execute;
case SDLK_HELP: return XK_Help;
case SDLK_MENU: return XK_Menu;
case SDLK_SELECT: return XK_Select;
case SDLK_STOP: return XF86XK_Stop;
case SDLK_AGAIN: return XK_Redo;
case SDLK_UNDO: return XK_Undo;
case SDLK_CUT: return XF86XK_Cut;
case SDLK_COPY: return XF86XK_Copy;
case SDLK_PASTE: return XF86XK_Paste;
case SDLK_FIND: return XK_Find;
case SDLK_MUTE: return XF86XK_AudioMute;
case SDLK_VOLUMEUP: return XF86XK_AudioRaiseVolume;
case SDLK_VOLUMEDOWN: return XF86XK_AudioLowerVolume;
case SDLK_KP_COMMA: return XK_KP_Separator;
//case SDLK_KP_EQUALSAS400: return ;
//case SDLK_ALTERASE: return ;
case SDLK_SYSREQ: return XK_Sys_Req;
case SDLK_CANCEL: return XK_Cancel;
case SDLK_CLEAR: return XK_Clear;
case SDLK_PRIOR: return XK_Prior;
case SDLK_RETURN2: return XK_Return;
//case SDLK_SEPARATOR: return ;
//case SDLK_OUT: return ;
//case SDLK_OPER: return ;
//case SDLK_CLEARAGAIN: return ;
//case SDLK_CRSEL: return ;
//case SDLK_EXSEL: return ;
//case SDLK_KP_00: return ;
//case SDLK_KP_000: return ;
//case SDLK_THOUSANDSSEPARATOR: return ;
//case SDLK_DECIMALSEPARATOR: return ;
//case SDLK_CURRENCYUNIT: return ;
//case SDLK_CURRENCYSUBUNIT: return ;
//case SDLK_KP_LEFTPAREN: return ;
//case SDLK_KP_RIGHTPAREN: return ;
//case SDLK_KP_LEFTBRACE: return ;
//case SDLK_KP_RIGHTBRACE: return ;
case SDLK_KP_TAB: return XK_KP_Tab;
//case SDLK_KP_BACKSPACE: return ;
//case SDLK_KP_A: return ;
//case SDLK_KP_B: return ;
//case SDLK_KP_C: return ;
//case SDLK_KP_D: return ;
//case SDLK_KP_E: return ;
//case SDLK_KP_F: return ;
//case SDLK_KP_XOR: return ;
//case SDLK_KP_POWER: return ;
//case SDLK_KP_PERCENT: return ;
//case SDLK_KP_LESS: return ;
//case SDLK_KP_GREATER: return ;
//case SDLK_KP_AMPERSAND: return ;
//case SDLK_KP_DBLAMPERSAND: return ;
//case SDLK_KP_VERTICALBAR: return ;
//case SDLK_KP_DBLVERTICALBAR: return ;
//case SDLK_KP_COLON: return ;
//case SDLK_KP_HASH: return ;
//case SDLK_KP_SPACE: return ;
//case SDLK_KP_AT: return ;
//case SDLK_KP_EXCLAM: return ;
//case SDLK_KP_MEMSTORE: return ;
//case SDLK_KP_MEMRECALL: return ;
//case SDLK_KP_MEMCLEAR: return ;
//case SDLK_KP_MEMADD: return ;
//case SDLK_KP_MEMSUBTRACT: return ;
//case SDLK_KP_MEMMULTIPLY: return ;
//case SDLK_KP_MEMDIVIDE: return ;
//case SDLK_KP_PLUSMINUS: return ;
//case SDLK_KP_CLEAR: return ;
//case SDLK_KP_CLEARENTRY: return ;
//case SDLK_KP_BINARY: return ;
//case SDLK_KP_OCTAL: return ;
//case SDLK_KP_DECIMAL: return ;
//case SDLK_KP_HEXADECIMAL: return ;
case SDLK_LCTRL: return XK_Control_L;
case SDLK_LSHIFT: return XK_Shift_L;
case SDLK_LALT: return XK_Alt_L;
case SDLK_LGUI: return XK_Super_L;
case SDLK_RCTRL: return XK_Control_R;
case SDLK_RSHIFT: return XK_Shift_R;
case SDLK_RALT: return XK_Alt_R;
case SDLK_RGUI: return XK_Super_R;
case SDLK_MODE: return XK_Mode_switch;
case SDLK_SLEEP: return XF86XK_Sleep;
case SDLK_WAKE: return XF86XK_WakeUp;
//case SDLK_CHANNEL_INCREMENT: return XF86XK_ChannelUp;
//case SDLK_CHANNEL_DECREMENT: return XF86XK_ChannelDown;
case SDLK_MEDIA_PLAY: return XF86XK_AudioPlay;
case SDLK_MEDIA_PAUSE: return XF86XK_AudioPause;
case SDLK_MEDIA_RECORD: return XF86XK_AudioRecord;
case SDLK_MEDIA_FAST_FORWARD: return XF86XK_AudioForward;
case SDLK_MEDIA_REWIND: return XF86XK_AudioRewind;
case SDLK_MEDIA_NEXT_TRACK: return XF86XK_AudioNext;
case SDLK_MEDIA_PREVIOUS_TRACK: return XF86XK_AudioPrev;
case SDLK_MEDIA_STOP: return XF86XK_AudioStop;
case SDLK_MEDIA_EJECT: return XF86XK_Eject;
//case SDLK_MEDIA_PLAY_PAUSE: return XF86XK_MediaPlayPause;
case SDLK_MEDIA_SELECT: return XF86XK_AudioMedia;
case SDLK_AC_NEW: return XF86XK_New;
case SDLK_AC_OPEN: return XF86XK_Open;
case SDLK_AC_CLOSE: return XF86XK_Close;
//case SDLK_AC_EXIT: return XF86XK_Exit;
case SDLK_AC_SAVE: return XF86XK_Save;
case SDLK_AC_PRINT: return XK_Print;
//case SDLK_AC_PROPERTIES: return ;
case SDLK_AC_SEARCH: return XF86XK_Search;
case SDLK_AC_HOME: return XF86XK_HomePage; // ?
case SDLK_AC_BACK: return XF86XK_Back;
case SDLK_AC_FORWARD: return XF86XK_Forward;
case SDLK_AC_STOP: return XF86XK_Stop;
case SDLK_AC_REFRESH: return XF86XK_Refresh;
case SDLK_AC_BOOKMARKS: return XF86XK_Book; // ?
//case SDLK_SOFTLEFT: return ;
//case SDLK_SOFTRIGHT: return ;
//case SDLK_CALL: return ;
//case SDLK_ENDCALL: return ;
case SDLK_LEFT_TAB: return XK_ISO_Left_Tab;
case SDLK_LEVEL5_SHIFT: return XK_ISO_Level5_Shift;
case SDLK_MULTI_KEY_COMPOSE: return XK_Multi_key;
case SDLK_LMETA: return XK_Meta_L;
case SDLK_RMETA: return XK_Meta_R;
case SDLK_LHYPER: return XK_Hyper_L;
case SDLK_RHYPER: return XK_Hyper_R;
}
return 0;
}

View File

@@ -1,5 +1,4 @@
#include "../Events.h"
#include "../Keymap.h"
#include "../Platform.h"
#include <BAN/Vector.h>
@@ -26,8 +25,6 @@ struct BananCursor final : public PlatformCursor
int32_t origin_y;
};
static BAN::ErrorOr<void> bananos_initialize_keymap();
static bool bananos_initialize(uint32_t* display_w, uint32_t* display_h)
{
auto attributes = LibGUI::Window::default_attributes;
@@ -43,12 +40,6 @@ static bool bananos_initialize(uint32_t* display_w, uint32_t* display_h)
*display_w = dummy_or_error.value()->width();
*display_h = dummy_or_error.value()->height();
if (auto ret = bananos_initialize_keymap(); ret.is_error())
{
dwarnln("Could not initialize keymap: {}", ret.error());
return false;
}
return true;
}
@@ -112,11 +103,7 @@ static BAN::ErrorOr<BAN::UniqPtr<PlatformWindow>> bananos_create_window(Platform
(event.shift() ? (1 << 0) : 0) |
(event.caps_lock() ? (1 << 1) : 0) |
(event.ctrl() ? (1 << 2) : 0) |
(event.alt() ? (1 << 3) : 0) |
(event.num_lock() ? (1 << 4) : 0) |
// level5 shift
// super
(event.ralt() ? (1 << 7) : 0); // FIXME: altgr
(event.alt() ? (1 << 3) : 0);
on_key_event(wid, event.scancode, xmod, event.pressed());
});
@@ -147,10 +134,10 @@ static void bananos_invalidate(PlatformWindow* window, const uint32_t* pixels, u
banan_window.window->invalidate(x, y, width, height);
}
static void bananos_request_fullscreen(PlatformWindow* window, bool fullscreen)
static BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> bananos_create_system_cursor(SystemCursorType type)
{
auto& banan_window = *static_cast<BananWindow*>(window);
banan_window.window->set_fullscreen(fullscreen);
(void)type;
return BAN::Error::from_errno(ENOTSUP);
}
static BAN::ErrorOr<BAN::UniqPtr<PlatformCursor>> bananos_create_bitmap_cursor(const uint32_t* pixels, uint32_t width, uint32_t height, int32_t origin_x, int32_t origin_y)
@@ -182,164 +169,20 @@ static void bananos_set_cursor(PlatformWindow* window, PlatformCursor* cursor)
}
}
static void bananos_request_fullscreen(PlatformWindow* window, bool fullscreen)
{
auto& banan_window = *static_cast<BananWindow*>(window);
banan_window.window->set_fullscreen(fullscreen);
}
PlatformOps g_platform_ops = {
.initialize = bananos_initialize,
.poll_events = bananos_poll_events,
.create_window = bananos_create_window,
.invalidate = bananos_invalidate,
.request_resize = bananos_request_resize,
.request_reposition = nullptr,
.request_fullscreen = bananos_request_fullscreen,
.warp_pointer = nullptr,
.query_pointer = nullptr,
.set_pointer_grab = nullptr,
.create_system_cursor = nullptr,
.create_system_cursor = bananos_create_system_cursor,
.create_bitmap_cursor = bananos_create_bitmap_cursor,
.set_cursor = bananos_set_cursor,
};
#include <LibInput/KeyboardLayout.h>
#include <LibInput/KeyEvent.h>
static uint32_t bananos_key_to_x_keysym(LibInput::Key, bool upper);
static BAN::ErrorOr<void> bananos_initialize_keymap()
{
// FIXME: get this from somewhere (gui command? enviroment? tmp file?)
const auto keymap_path = "./us.keymap"_sv;
TRY(LibInput::KeyboardLayout::initialize());
auto& keyboard_layout = LibInput::KeyboardLayout::get();
TRY(keyboard_layout.load_from_file(keymap_path));
const BAN::Span<const LibInput::Key> banan_keymaps[] {
keyboard_layout.keymap_normal(),
keyboard_layout.keymap_shift(),
keyboard_layout.keymap_altgr(),
keyboard_layout.keymap_altgr(), // add shift+altgr map?
};
for (size_t scancode = 0; scancode < g_keymap_size; scancode++)
for (size_t layer = 0; layer < g_keymap_layers; layer++)
if (const auto banan_key = banan_keymaps[layer][scancode]; banan_key != LibInput::Key::None)
g_keymap[scancode][layer] = bananos_key_to_x_keysym(banan_key, layer % 2);
using LibInput::keycode_normal;
using LibInput::keycode_numpad;
g_modifier_map[0][0] = keycode_normal(3, 0) + g_keymap_min_keycode; // lshift
g_modifier_map[0][1] = keycode_normal(3, 12) + g_keymap_min_keycode; // rshift
g_modifier_map[1][0] = keycode_normal(2, 0) + g_keymap_min_keycode; // caps lock
g_modifier_map[2][0] = keycode_normal(4, 0) + g_keymap_min_keycode; // lctrl
g_modifier_map[2][1] = keycode_normal(4, 6) + g_keymap_min_keycode; // rctrl
g_modifier_map[3][0] = keycode_normal(4, 2) + g_keymap_min_keycode; // lalt
g_modifier_map[3][1] = keycode_normal(4, 5) + g_keymap_min_keycode; // ralt
g_modifier_map[4][0] = keycode_numpad(0, 0) + g_keymap_min_keycode; // num lock
//g_modifier_map[5][0] = level5 shift;
g_modifier_map[6][0] = keycode_normal(4, 1) + g_keymap_min_keycode; // lsuper
g_modifier_map[6][1] = keycode_normal(4, 4) + g_keymap_min_keycode; // rsuper
g_modifier_map[7][0] = keycode_normal(4, 5) + g_keymap_min_keycode; // FIXME: altgr
return {};
}
#include <BAN/UTF8.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#include <wctype.h>
static uint32_t bananos_key_to_x_keysym(LibInput::Key key, bool upper)
{
using namespace LibInput;
if (const char* utf8 = key_to_utf8(key, upper ? KeyEvent::LShift : 0))
{
const uint32_t codepoint = BAN::UTF8::to_codepoint(utf8);
if (codepoint != BAN::UTF8::invalid && iswprint(codepoint))
{
if ((codepoint >= 0x20 && codepoint <= 0x7E) || (codepoint >= 0xA0 && codepoint <= 0xFF))
return codepoint;
return 0x01000000 | codepoint;
}
}
switch (key)
{
case Key::F1: return XK_F1;
case Key::F2: return XK_F2;
case Key::F3: return XK_F3;
case Key::F4: return XK_F4;
case Key::F5: return XK_F5;
case Key::F6: return XK_F6;
case Key::F7: return XK_F7;
case Key::F8: return XK_F8;
case Key::F9: return XK_F9;
case Key::F10: return XK_F10;
case Key::F11: return XK_F11;
case Key::F12: return XK_F12;
case Key::Insert: return XK_Insert;
case Key::PrintScreen: return XK_Print;
case Key::Delete: return XK_Delete;
case Key::Home: return XK_Home;
case Key::End: return XK_End;
case Key::PageUp: return XK_Page_Up;
case Key::PageDown: return XK_Page_Down;
case Key::Enter: return XK_Return;
case Key::Backspace: return XK_BackSpace;
case Key::Escape: return XK_Escape;
case Key::Tab: return XK_Tab;
case Key::CapsLock: return XK_Caps_Lock;
case Key::LeftShift: return XK_Shift_L;
case Key::LeftCtrl: return XK_Control_L;
case Key::Super: return XK_Super_L;
case Key::LeftAlt: return XK_Alt_L;
case Key::RightAlt: return XK_Alt_R;
case Key::RightCtrl: return XK_Control_R;
case Key::RightShift: return XK_Shift_R;
case Key::ArrowUp: return XK_Up;
case Key::ArrowDown: return XK_Down;
case Key::ArrowLeft: return XK_Left;
case Key::ArrowRight: return XK_Right;
case Key::NumLock: return XK_Num_Lock;
case Key::ScrollLock: return XK_Scroll_Lock;
case Key::Numpad0: return XK_KP_0;
case Key::Numpad1: return XK_KP_1;
case Key::Numpad2: return XK_KP_2;
case Key::Numpad3: return XK_KP_3;
case Key::Numpad4: return XK_KP_4;
case Key::Numpad5: return XK_KP_5;
case Key::Numpad6: return XK_KP_6;
case Key::Numpad7: return XK_KP_7;
case Key::Numpad8: return XK_KP_8;
case Key::Numpad9: return XK_KP_9;
case Key::NumpadPlus: return XK_KP_Add;
case Key::NumpadMinus: return XK_KP_Subtract;
case Key::NumpadMultiply: return XK_KP_Multiply;
case Key::NumpadDivide: return XK_KP_Divide;
case Key::NumpadEnter: return XK_KP_Enter;
case Key::NumpadDecimal: return XK_KP_Decimal;
case Key::VolumeMute: return XF86XK_AudioMute;
case Key::VolumeUp: return XF86XK_AudioRaiseVolume;
case Key::VolumeDown: return XF86XK_AudioLowerVolume;
case Key::Calculator: return XF86XK_Calculator;
case Key::MediaPlayPause: return XF86XK_AudioPlay;
case Key::MediaStop: return XF86XK_AudioStop;
case Key::MediaPrevious: return XF86XK_AudioPrev;
case Key::MediaNext: return XF86XK_AudioNext;
default: break;
}
static_assert(static_cast<size_t>(Key::Count) == 145, "update keymap");
return 0;
}

View File

@@ -1,12 +1,12 @@
#include "Base.h"
#include "Definitions.h"
#include "Keymap.h"
#include <X11/X.h>
#include <X11/Xatom.h>
#include <locale.h>
#include <poll.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -92,14 +92,13 @@ BAN::HashMap<BAN::String, ATOM> g_atoms_name_to_id;
BAN::HashMap<ATOM, BAN::String> g_atoms_id_to_name;
ATOM g_atom_value = XA_LAST_PREDEFINED + 1;
BAN::HashMap<int, Pollable> g_pollables;
int g_epoll_fd;
BAN::HashMap<int, EpollThingy> g_epoll_thingies;
int g_server_grabber_fd = -1;
int main()
{
setlocale(LC_ALL, "");
for (int sig = 1; sig < NSIG; sig++)
if (sig != SIGWINCH)
signal(sig, exit);
@@ -154,6 +153,22 @@ int main()
return 1;
}
g_epoll_fd = epoll_create1(0);
if (g_epoll_fd == -1)
{
perror("xbanan: epoll_create1");
return 1;
}
{
epoll_event event { .events = EPOLLIN, .data = { .ptr = nullptr } };
if (epoll_ctl(g_epoll_fd, EPOLL_CTL_ADD, server_sock, &event) == -1)
{
perror("xbanan: epoll_ctl");
return 1;
}
}
#define APPEND_ATOM(name) do { \
MUST(g_atoms_id_to_name.insert(name, #name##_sv.substring(3))); \
MUST(g_atoms_name_to_id.insert(#name##_sv.substring(3), name)); \
@@ -244,6 +259,8 @@ int main()
APPEND_ATOM_CUSTOM(_NET_WM_WINDOW_TYPE_UTILITY);
#undef APPEND_ATOM_CUSTOM
MUST(initialize_keymap());
uint32_t display_w, display_h;
if (!g_platform_ops.initialize(&display_w, &display_h))
return 1;
@@ -257,9 +274,9 @@ int main()
const auto close_client =
[](int client_fd)
{
auto& pollable = g_pollables[client_fd];
ASSERT(pollable.type == Pollable::Type::Client);
auto& client_info = pollable.value.get<Client>();
auto& epoll_thingy = g_epoll_thingies[client_fd];
ASSERT(epoll_thingy.type == EpollThingy::Type::Client);
auto& client_info = epoll_thingy.value.get<Client>();
dprintln("client {} disconnected", client_fd);
@@ -273,18 +290,6 @@ int main()
window.event_masks.remove(&client_info);
}
for (auto it = client_info.objects.begin(); it != client_info.objects.end();)
{
auto obj_it = g_objects.find(*it);
if (obj_it == g_objects.end() || obj_it->value->type != Object::Type::Window)
it++;
else
{
(void)destroy_window(client_info, *it);
it = client_info.objects.begin();
}
}
for (auto id : client_info.objects)
{
auto it = g_objects.find(id);
@@ -299,23 +304,42 @@ int main()
case Object::Type::Pixmap:
case Object::Type::GraphicsContext:
case Object::Type::Font:
break;
case Object::Type::Window:
ASSERT_NOT_REACHED();
break;
case Object::Type::Extension:
{
auto& extension = object.object.get<Object::Extension>();
extension.destructor(extension);
break;
}
}
g_objects.remove(it);
}
g_pollables.remove(client_fd);
epoll_ctl(g_epoll_fd, EPOLL_CTL_DEL, client_fd, nullptr);
g_epoll_thingies.remove(client_fd);
close(client_fd);
if (g_server_grabber_fd == client_fd)
if (client_fd == g_server_grabber_fd)
{
g_server_grabber_fd = -1;
for (const auto& [_, thingy] : g_epoll_thingies)
{
if (thingy.type != EpollThingy::Type::Client)
continue;
auto& other_client = thingy.value.get<Client>();
uint32_t events = EPOLLIN;
if (other_client.has_epollout)
events |= EPOLLOUT;
epoll_event event { .events = events, .data = { .fd = other_client.fd } };
epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, other_client.fd, &event);
}
}
};
Client dummy_client {};
@@ -342,37 +366,12 @@ int main()
for (;;)
{
BAN::Vector<pollfd> pollfds;
MUST(pollfds.reserve(g_pollables.size() + 1));
MUST(pollfds.push_back({
.fd = server_sock,
.events = POLLIN,
.revents = 0,
}));
for (auto& [fd, pollable] : g_pollables)
epoll_event events[16];
const int event_count = epoll_wait(g_epoll_fd, events, 16, -1);
for (int i = 0; i < event_count; i++)
{
short events = 0;
if (g_server_grabber_fd == -1 || g_server_grabber_fd == fd)
events |= POLLIN;
if (pollable.type == Pollable::Type::Client && !pollable.value.get<Client>().output_buffer.empty())
events |= POLLOUT;
if (events == 0)
continue;
MUST(pollfds.push_back(pollfd {
.fd = fd,
.events = events,
.revents = 0,
}));
}
const int event_count = poll(pollfds.data(), pollfds.size(), -1);
for (const auto& pollfd : pollfds)
{
if (pollfd.revents == 0)
continue;
if (pollfd.fd == server_sock)
if (events[i].data.ptr == nullptr)
{
int client_sock = accept(server_sock, nullptr, nullptr);
if (client_sock == -1)
@@ -381,50 +380,52 @@ int main()
continue;
}
BAN::Optional<uint32_t> client_pid;
#ifdef SO_PEERCRED
ucred client_cred;
socklen_t client_cred_len = sizeof(client_cred);
if (getsockopt(client_sock, SOL_SOCKET, SO_PEERCRED, &client_cred, &client_cred_len) == 0)
client_pid = client_cred.pid;
#endif
MUST(g_pollables.insert(client_sock, {
.type = Pollable::Type::Client,
MUST(g_epoll_thingies.insert(client_sock, {
.type = EpollThingy::Type::Client,
.value = Client {
.fd = client_sock,
.state = Client::State::ConnectionSetup,
.pid = client_pid,
}
}));
uint32_t events = 0;
if (g_server_grabber_fd == -1)
events |= EPOLLIN;
epoll_event event = { .events = events, .data = { .fd = client_sock } };
if (epoll_ctl(g_epoll_fd, EPOLL_CTL_ADD, client_sock, &event) == -1)
{
perror("xbanan: epoll_ctl");
close(client_sock);
continue;
}
dprintln("client {} connected", client_sock);
continue;
}
auto it = g_pollables.find(pollfd.fd);
if (it == g_pollables.end())
auto it = g_epoll_thingies.find(events[i].data.fd);
if (it == g_epoll_thingies.end())
continue;
auto& pollable = it->value;
auto& epoll_thingy = it->value;
if (pollable.type == Pollable::Type::Event)
if (epoll_thingy.type == EpollThingy::Type::Event)
{
g_platform_ops.poll_events(pollable.value.get<void*>());
g_platform_ops.poll_events(epoll_thingy.value.get<void*>());
continue;
}
ASSERT(pollable.type == Pollable::Type::Client);
ASSERT(epoll_thingy.type == EpollThingy::Type::Client);
auto& client_info = pollable.value.get<Client>();
auto& client_info = epoll_thingy.value.get<Client>();
if (pollfd.revents & POLLHUP)
if (events[i].events & EPOLLHUP)
{
close_client(client_info.fd);
continue;
}
if (pollfd.revents & POLLOUT)
if (events[i].events & EPOLLOUT)
{
const ssize_t nsend = send(
client_info.fd,
@@ -451,11 +452,28 @@ int main()
);
MUST(client_info.output_buffer.resize(client_info.output_buffer.size() - nsend));
if (client_info.output_buffer.empty())
{
uint32_t events = 0;
if (g_server_grabber_fd == -1 || g_server_grabber_fd == client_info.fd)
events |= EPOLLIN;
epoll_event event { .events = events, .data = { .fd = client_info.fd } };
if (epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, client_info.fd, &event) == -1)
{
perror("xbanan: epoll_ctl");
close_client(client_info.fd);
continue;
}
client_info.has_epollout = false;
}
send_done:
(void)0;
}
if (!(pollfd.revents & POLLIN))
if (!(events[i].events & EPOLLIN))
continue;
if (g_server_grabber_fd != -1 && g_server_grabber_fd != client_info.fd)
@@ -567,5 +585,30 @@ int main()
}
}
}
iterator_invalidated:
for (auto& [_, thingy] : g_epoll_thingies)
{
if (thingy.type != EpollThingy::Type::Client)
continue;
auto& client_info = thingy.value.get<Client>();
if (client_info.output_buffer.empty() || client_info.has_epollout)
continue;
uint32_t events = EPOLLOUT;
if (g_server_grabber_fd == -1 || g_server_grabber_fd == client_info.fd)
events |= EPOLLIN;
epoll_event event { .events = events, .data = { .fd = client_info.fd } };
if (epoll_ctl(g_epoll_fd, EPOLL_CTL_MOD, client_info.fd, &event) == -1)
{
perror("xbanan: epoll_ctl");
close_client(client_info.fd);
goto iterator_invalidated;
}
client_info.has_epollout = true;
}
}
}