Skip to content

Instantly share code, notes, and snippets.

@martincohen
Created January 14, 2016 01:59
Show Gist options
  • Save martincohen/4b667f33f178fc9a4968 to your computer and use it in GitHub Desktop.
Save martincohen/4b667f33f178fc9a4968 to your computer and use it in GitHub Desktop.
typedef struct UITextEditor
{
int text_capacity;
int text_length;
char *text;
int cursor;
}
UITextEditor;
void
ui_text_editor_init(UITextEditor *editor)
{
memset(editor, 0, sizeof(UITextEditor));
editor->text_capacity = 256;
editor->text = calloc(editor->text_capacity, 1);
}
void
_ui_text_editor_ensure_capacity(UITextEditor *editor, size_t length, bool copy)
{
length++;
if (length >= editor->text_capacity) {
editor->text_capacity = editor->text_capacity * 2;
char *_text = realloc(editor->text, editor->text_capacity);
if (copy) {
memcpy(_text, editor->text, editor->text_length);
_text[editor->text_length] = 0;
}
free(editor->text);
editor->text = _text;
}
}
void
ui_text_editor_insert(UITextEditor *editor, const char *string)
{
size_t length = strlen(string);
if (length == 0) {
return;
}
_ui_text_editor_ensure_capacity(editor, editor->text_length + length, true);
if (editor->cursor != editor->text_length)
{
memmove(editor->text + editor->cursor + length,
editor->text + editor->cursor,
editor->text_length - editor->cursor);
}
memmove(editor->text + editor->cursor,
string,
length);
editor->cursor += length;
editor->text_length += length;
editor->text[editor->text_length] = 0;
}
void
ui_text_editor_remove(UITextEditor *editor, int from, int length)
{
if (length <= 0) {
printf("ui_text_editor_remove: length <= 0\n");
return;
}
if (from < 0) {
printf("ui_text_editor_remove: from < 0\n");
return;
}
if (from >= editor->text_length) {
printf("ui_text_editor_remove: from >= editor->text_length\n");
return;
}
int to = from + length;
if (to > editor->text_length) {
printf("ui_text_editor_remove: from + length > editor->text_length\n");
return;
}
if (to != editor->text_length)
{
memmove(editor->text + from,
editor->text + to,
editor->text_length - to);
}
editor->text_length -= length;
editor->cursor = from;
editor->text[editor->text_length] = 0;
}
bool
ui_text_editor_event(UITextEditor *editor, SDL_Event *event)
{
switch (event->type)
{
case SDL_TEXTINPUT:
ui_text_editor_insert(editor, event->text.text);
return true;
case SDL_KEYDOWN:
switch (event->key.keysym.sym)
{
case SDLK_RIGHT:
editor->cursor = MIN(editor->text_length, editor->cursor + 1);
return true;
case SDLK_LEFT:
editor->cursor = MAX(0, editor->cursor - 1);
return true;
case SDLK_BACKSPACE:
ui_text_editor_remove(editor, editor->cursor - 1, 1);
return true;
case SDLK_DELETE:
ui_text_editor_remove(editor, editor->cursor, 1);
return true;
}
break;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment