Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
filter
!/src/search
search
!/src/kbinput
kbinput
!/src/kbinput
!/src/tools
tools
60 changes: 60 additions & 0 deletions src/kbinput/keyboard_lib.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include "../../include/keyboard/keyboard.h"
#include "../common/display.hpp"
#include "keyboard.hpp"

#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream> // optional (only if you keep error logs)

static char* dup_cstr(const std::string& s) {
char* out = static_cast<char*>(std::malloc(s.size() + 1));
if (!out) return nullptr;
std::memcpy(out, s.c_str(), s.size() + 1);
return out;
}

// C ABI function callable from Onion (C)
extern "C" const char* launch_keyboard(const char* initial_value, const char* title) {
Display* display = nullptr;
Keyboard* kb = nullptr;
char* ret = nullptr;

try {
display = new Display();
// defensively handle nullptr inputs
const char* init = initial_value ? initial_value : "";
const char* lab = title ? title : "";

kb = new Keyboard(display, init, lab);
display->lib_mode = true;

int quit = 0;
std::string result;

auto input_handler = [&kb](SDLKey key, Uint8 type, int repeating) {
return kb->handleKeyPress(key, type, repeating);
};
auto frame_handler = [display, input_handler]() {
return display->onInputEvent(input_handler);
};

while (!quit) quit = display->requestFrame(frame_handler);

if (!kb->cancelled) result = kb->getValue();

ret = dup_cstr(result); // empty string if cancelled
}
catch (const std::exception& e) {
optional: std::cerr << "launch_keyboard error: " << e.what() << '\n';
}

// Destroy in safe order (kb may reference display)
delete kb;
delete display;
return ret;
}

extern "C" void keyboard_free(const char* p) {
std::free(const_cast<char*>(p));
}