#include "../../include/mgl/window/window.h" #include "../../include/mgl/window/event.h" #include "../../include/mgl/mgl.h" #include "../../include/mgl/system/utf8.h" #include #include #include #include #include #include #include #include /* TODO: Handle XIM better. Set XIM position to text position on screen (for text input) and reset input when selecting a new text input, etc */ /* Should be in range [2,] */ #define MAX_STACKED_EVENTS 32 typedef struct { mgl_event stack[MAX_STACKED_EVENTS]; int start; int end; int size; } x11_events_circular_buffer; static void x11_events_circular_buffer_init(x11_events_circular_buffer *self) { self->start = 0; self->end = 0; self->size = 0; } static bool x11_events_circular_buffer_append(x11_events_circular_buffer *self, const mgl_event *event) { if(self->size == MAX_STACKED_EVENTS) return false; self->stack[self->end] = *event; self->end = (self->end + 1) % MAX_STACKED_EVENTS; ++self->size; return true; } static bool x11_events_circular_buffer_pop(x11_events_circular_buffer *self, mgl_event *event) { if(self->size == 0) return false; *event = self->stack[self->start]; self->start = (self->start + 1) % MAX_STACKED_EVENTS; --self->size; return true; } typedef struct { GLXContext glx_context; XIM xim; XIC xic; Atom clipboard_atom; Atom targets_atom; Atom text_atom; Atom utf8_string_atom; Atom target_property_atom; Atom incr_atom; Cursor default_cursor; Cursor invisible_cursor; unsigned int prev_keycode_pressed; bool key_was_released; Colormap color_map; /* Used to stack text event on top of key press/release events and other text events. For example pressing a key should give the user both key press and text events and for IM with multiple characters entered (such as chinese), we want to trigger an event for all of them. */ x11_events_circular_buffer events; bool key_pressed[__MGL_NUM_KEYS__]; bool mouse_button_pressed[__MGL_NUM_MOUSE_BUTTONS__]; } x11_context; static void x11_context_deinit(x11_context *self); static int x11_context_init(x11_context *self) { mgl_context *context = mgl_get_context(); self->glx_context = NULL; self->xim = NULL; self->xic = NULL; self->clipboard_atom = XInternAtom(context->connection, "CLIPBOARD", False); self->targets_atom = XInternAtom(context->connection, "TARGETS", False); self->text_atom = XInternAtom(context->connection, "TEXT", False); self->utf8_string_atom = XInternAtom(context->connection, "UTF8_STRING", True); self->target_property_atom = XInternAtom(context->connection, "MGL_CLIPBOARD_TARGET_PROPERTY", False); self->incr_atom = XInternAtom(context->connection, "INCR", False); self->default_cursor = None; self->invisible_cursor = None; self->prev_keycode_pressed = 0; self->key_was_released = false; self->color_map = None; self->default_cursor = XCreateFontCursor(context->connection, XC_arrow); if(!self->default_cursor) { x11_context_deinit(self); return -1; } const char data[1] = {0}; Pixmap blank_bitmap = XCreateBitmapFromData(context->connection, DefaultRootWindow(context->connection), data, 1, 1); if(!blank_bitmap) return -1; XColor dummy; self->invisible_cursor = XCreatePixmapCursor(context->connection, blank_bitmap, blank_bitmap, &dummy, &dummy, 0, 0); XFreePixmap(context->connection, blank_bitmap); if(!self->invisible_cursor) { x11_context_deinit(self); return -1; } x11_events_circular_buffer_init(&self->events); for(size_t i = 0; i < __MGL_NUM_KEYS__; ++i) { self->key_pressed[i] = false; } for(size_t i = 0; i < __MGL_NUM_MOUSE_BUTTONS__; ++i) { self->mouse_button_pressed[i] = false; } return 0; } void x11_context_deinit(x11_context *self) { mgl_context *context = mgl_get_context(); if(self->color_map) { XFreeColormap(context->connection, self->color_map); self->color_map = None; } if(self->invisible_cursor) { XFreeCursor(context->connection, self->invisible_cursor); self->invisible_cursor = None; } if(self->default_cursor) { XFreeCursor(context->connection, self->default_cursor); self->default_cursor = None; } if(self->xic) { XDestroyIC(self->xic); self->xic = NULL; } if(self->xim) { XCloseIM(self->xim); self->xim = NULL; } if(self->glx_context) { context->gl.glXDestroyContext(context->connection, self->glx_context); self->glx_context = NULL; } } static bool x11_context_append_event(x11_context *self, const mgl_event *event) { return x11_events_circular_buffer_append(&self->events, event); } static bool x11_context_pop_event(x11_context *self, mgl_event *event) { return x11_events_circular_buffer_pop(&self->events, event); } /* Returns true if the state changed */ static bool x11_context_update_key_state(x11_context *self, mgl_key key, bool key_pressed) { if(self->key_pressed[key] != key_pressed) { self->key_pressed[key] = key_pressed; return true; } else { return false; } } /* Returns true if the state changed */ static bool x11_context_update_mouse_button_state(x11_context *self, mgl_mouse_button button, bool button_pressed) { if(self->mouse_button_pressed[button] != button_pressed) { self->mouse_button_pressed[button] = button_pressed; return true; } else { return false; } } static bool x11_context_is_key_pressed(const x11_context *self, mgl_key key) { return self->key_pressed[key]; } static bool x11_context_is_mouse_button_pressed(const x11_context *self, mgl_mouse_button button) { return self->mouse_button_pressed[button]; } /* TODO: Use gl OML present for other platforms than nvidia? nvidia doesn't support present yet */ /* TODO: check for glx swap control extension string (GLX_EXT_swap_control, etc) */ static void set_vertical_sync_enabled(Window window, int enabled) { int result = 0; mgl_context *context = mgl_get_context(); if(context->gl.glXSwapIntervalEXT) { context->gl.glXSwapIntervalEXT(context->connection, window, enabled ? 1 : 0); } else if(context->gl.glXSwapIntervalMESA) { result = context->gl.glXSwapIntervalMESA(enabled ? 1 : 0); } else if(context->gl.glXSwapIntervalSGI) { result = context->gl.glXSwapIntervalSGI(enabled ? 1 : 0); } else { static int warned = 0; if (!warned) { warned = 1; fprintf(stderr, "Warning: setting vertical sync not supported\n"); } } if(result != 0) fprintf(stderr, "Warning: setting vertical sync failed\n"); } static void mgl_window_on_resize(mgl_window *self, int width, int height) { self->size.x = width; self->size.y = height; mgl_view view; view.position = (mgl_vec2i){ 0, 0 }; view.size = self->size; mgl_window_set_view(self, &view); } static int mgl_window_init(mgl_window *self, const char *title, const mgl_window_create_params *params, Window existing_window) { self->window = 0; self->context = NULL; self->open = false; self->focused = false; self->key_repeat_enabled = true; self->frame_time_limit = 0.0; mgl_clock_init(&self->frame_timer); self->clipboard_string = NULL; self->clipboard_size = 0; mgl_vec2i window_size = params ? params->size : (mgl_vec2i){ 0, 0 }; if(window_size.x <= 0 || window_size.y <= 0) { window_size.x = 1; window_size.y = 1; } self->size = window_size; self->context = malloc(sizeof(x11_context)); if(!self->context) { fprintf(stderr, "Failed to allocate x11 context\n"); return -1; } x11_context *x11_context = self->context; if(x11_context_init(x11_context) != 0) { fprintf(stderr, "x11_context_init failed\n"); mgl_window_deinit(self); return -1; } mgl_context *context = mgl_get_context(); Window parent_window = params ? params->parent_window : None; if(parent_window == 0) parent_window = DefaultRootWindow(context->connection); x11_context->glx_context = context->gl.glXCreateContext(context->connection, context->visual_info, NULL, 1); if(!x11_context->glx_context) { fprintf(stderr, "glXCreateContext failed\n"); mgl_window_deinit(self); return -1; } x11_context->color_map = XCreateColormap(context->connection, DefaultRootWindow(context->connection), ((XVisualInfo*)context->visual_info)->visual, AllocNone); if(!x11_context->color_map) { fprintf(stderr, "XCreateColormap failed\n"); mgl_window_deinit(self); return -1; } XSetWindowAttributes window_attr; window_attr.colormap = x11_context->color_map; window_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | ButtonMotionMask | StructureNotifyMask | EnterWindowMask | LeaveWindowMask | VisibilityChangeMask | PropertyChangeMask | FocusChangeMask; if(existing_window) { if(!XChangeWindowAttributes(context->connection, existing_window, CWColormap | CWEventMask, &window_attr)) { fprintf(stderr, "XChangeWindowAttributes failed\n"); mgl_window_deinit(self); return -1; } self->window = existing_window; } else { self->window = XCreateWindow(context->connection, parent_window, params->position.x, params->position.y, window_size.x, window_size.y, 0, ((XVisualInfo*)context->visual_info)->depth, InputOutput, ((XVisualInfo*)context->visual_info)->visual, CWColormap | CWEventMask, &window_attr); if(!self->window) { fprintf(stderr, "XCreateWindow failed\n"); mgl_window_deinit(self); return -1; } XStoreName(context->connection, self->window, title); XMapWindow(context->connection, self->window); } if(params) mgl_window_set_size_limits(self, params->min_size, params->max_size); /* TODO: Call XGetWMProtocols and add wm_delete_window_atom on top, to not overwrite existing wm protocol atoms */ Atom wm_protocol_atoms[2] = { context->wm_delete_window_atom, context->net_wm_ping_atom }; XSetWMProtocols(context->connection, self->window, wm_protocol_atoms, 2); XFlush(context->connection); /* TODO: Check for failure? */ context->gl.glXMakeCurrent(context->connection, self->window, x11_context->glx_context); set_vertical_sync_enabled(self->window, 1); context->gl.glEnable(GL_TEXTURE_2D); context->gl.glEnable(GL_BLEND); context->gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); context->gl.glEnableClientState(GL_VERTEX_ARRAY); context->gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY); context->gl.glEnableClientState(GL_COLOR_ARRAY); context->gl.glPixelStorei(GL_UNPACK_ALIGNMENT, 1); Window dummy_w; int dummy_i; unsigned int dummy_u; XQueryPointer(context->connection, self->window, &dummy_w, &dummy_w, &dummy_i, &dummy_i, &self->cursor_position.x, &self->cursor_position.y, &dummy_u); mgl_window_on_resize(self, self->size.x, self->size.y); x11_context->xim = XOpenIM(context->connection, NULL, NULL, NULL); if(!x11_context->xim) { fprintf(stderr, "XOpenIM failed\n"); mgl_window_deinit(self); return -1; } x11_context->xic = XCreateIC(x11_context->xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, self->window, NULL); if(!x11_context->xic) { fprintf(stderr, "XCreateIC failed\n"); mgl_window_deinit(self); return -1; } XSetICFocus(x11_context->xic); self->open = true; self->focused = false; /* TODO: Check if we need to call XGetInputFocus for this, or just wait for focus event */ return 0; } int mgl_window_create(mgl_window *self, const char *title, const mgl_window_create_params *params) { return mgl_window_init(self, title, params, None); } /* TODO: Test this */ int mgl_window_init_from_existing_window(mgl_window *self, mgl_window_handle existing_window) { return mgl_window_init(self, "", NULL, existing_window); } void mgl_window_deinit(mgl_window *self) { mgl_context *context = mgl_get_context(); x11_context *x11_context = self->context; if(x11_context) { x11_context_deinit(x11_context); free(x11_context); self->context = NULL; } if(self->clipboard_string) { free(self->clipboard_string); self->clipboard_string = NULL; } self->clipboard_size = 0; if(self->window) { XDestroyWindow(context->connection, self->window); self->window = 0; } self->open = false; } static mgl_key x11_keysym_to_mgl_key(KeySym key_sym) { if(key_sym >= XK_A && key_sym <= XK_Z) return MGL_KEY_A + (key_sym - XK_A); /* TODO: Check if this ever happens */ if(key_sym >= XK_a && key_sym <= XK_z) return MGL_KEY_A + (key_sym - XK_a); if(key_sym >= XK_0 && key_sym <= XK_9) return MGL_KEY_NUM0 + (key_sym - XK_0); if(key_sym >= XK_KP_0 && key_sym <= XK_KP_9) return MGL_KEY_NUMPAD0 + (key_sym - XK_KP_0); /* TODO: Fill in the rest */ switch(key_sym) { case XK_space: return MGL_KEY_SPACE; case XK_BackSpace: return MGL_KEY_BACKSPACE; case XK_Tab: return MGL_KEY_TAB; case XK_Return: return MGL_KEY_ENTER; case XK_Escape: return MGL_KEY_ESCAPE; case XK_Control_L: return MGL_KEY_LCONTROL; case XK_Shift_L: return MGL_KEY_LSHIFT; case XK_Alt_L: return MGL_KEY_LALT; case XK_Super_L: return MGL_KEY_LSYSTEM; case XK_Control_R: return MGL_KEY_RCONTROL; case XK_Shift_R: return MGL_KEY_RSHIFT; case XK_Alt_R: return MGL_KEY_RALT; case XK_Super_R: return MGL_KEY_RSYSTEM; case XK_Delete: return MGL_KEY_DELETE; case XK_Home: return MGL_KEY_HOME; case XK_Left: return MGL_KEY_LEFT; case XK_Up: return MGL_KEY_UP; case XK_Right: return MGL_KEY_RIGHT; case XK_Down: return MGL_KEY_DOWN; case XK_Page_Up: return MGL_KEY_PAGEUP; case XK_Page_Down: return MGL_KEY_PAGEDOWN; case XK_End: return MGL_KEY_END; case XK_F1: return MGL_KEY_F1; case XK_F2: return MGL_KEY_F2; case XK_F3: return MGL_KEY_F3; case XK_F4: return MGL_KEY_F4; case XK_F5: return MGL_KEY_F5; case XK_F6: return MGL_KEY_F6; case XK_F7: return MGL_KEY_F7; case XK_F8: return MGL_KEY_F8; case XK_F9: return MGL_KEY_F9; case XK_F10: return MGL_KEY_F10; case XK_F11: return MGL_KEY_F11; case XK_F12: return MGL_KEY_F12; case XK_F13: return MGL_KEY_F13; case XK_F14: return MGL_KEY_F14; case XK_F15: return MGL_KEY_F15; } return MGL_KEY_UNKNOWN; } static mgl_mouse_button x11_button_to_mgl_button(unsigned int button) { switch(button) { case Button1: return MGL_BUTTON_LEFT; case Button2: return MGL_BUTTON_MIDDLE; case Button3: return MGL_BUTTON_RIGHT; case 8: return MGL_BUTTON_XBUTTON1; case 9: return MGL_BUTTON_XBUTTON2; } return MGL_BUTTON_UNKNOWN; } static void mgl_window_handle_key_event(mgl_window *self, XKeyEvent *xkey, mgl_event *event, mgl_context *context, bool pressed) { event->key.code = x11_keysym_to_mgl_key(XKeycodeToKeysym(context->connection, xkey->keycode, 0)); event->key.alt = ((xkey->state & Mod1Mask) != 0); event->key.control = ((xkey->state & ControlMask) != 0); event->key.shift = ((xkey->state & ShiftMask) != 0); event->key.system = ((xkey->state & Mod4Mask) != 0); x11_context_update_key_state(self->context, event->key.code, pressed); } static void mgl_window_handle_text_event(mgl_window *self, XEvent *xev) { /* Ignore silent keys */ if(XFilterEvent(xev, None)) return; x11_context *x11_context = self->context; char buf[128]; Status status; KeySym ksym; const size_t input_str_len = Xutf8LookupString(x11_context->xic, &xev->xkey, buf, sizeof(buf), &ksym, &status); /* TODO: Handle XBufferOverflow */ if(status == XBufferOverflow || input_str_len == 0) return; /* TODO: Set XIC location on screen with XSetICValues */ for(size_t i = 0; i < input_str_len;) { const unsigned char *cp = (const unsigned char*)&buf[i]; uint32_t codepoint; size_t clen; if(!mgl_utf8_decode(cp, input_str_len - i, &codepoint, &clen)) { codepoint = *cp; clen = 1; } mgl_event text_event; text_event.type = MGL_EVENT_TEXT_ENTERED; text_event.text.codepoint = codepoint; text_event.text.size = clen; memcpy(text_event.text.str, &buf[i], clen); text_event.text.str[clen] = '\0'; /* Text may contain multiple codepoints so they need to separated into multiple events */ if(!x11_context_append_event(x11_context, &text_event)) break; i += clen; } } static void mgl_window_on_receive_event(mgl_window *self, XEvent *xev, mgl_event *event, mgl_context *context) { switch(xev->type) { case KeyPress: { x11_context *x11_context = self->context; if(!self->key_repeat_enabled && xev->xkey.keycode == x11_context->prev_keycode_pressed && !x11_context->key_was_released) { event->type = MGL_EVENT_UNKNOWN; return; } x11_context->prev_keycode_pressed = xev->xkey.keycode; x11_context->key_was_released = false; event->type = MGL_EVENT_KEY_PRESSED; mgl_window_handle_key_event(self, &xev->xkey, event, context, true); mgl_window_handle_text_event(self, xev); return; } case KeyRelease: { x11_context *x11_context = self->context; if(xev->xkey.keycode == x11_context->prev_keycode_pressed) x11_context->key_was_released = true; event->type = MGL_EVENT_KEY_RELEASED; mgl_window_handle_key_event(self, &xev->xkey, event, context, false); return; } case ButtonPress: { if(xev->xbutton.button == Button4) { /* Mouse scroll up */ event->type = MGL_EVENT_MOUSE_WHEEL_SCROLLED; event->mouse_wheel_scroll.delta = 1; event->mouse_wheel_scroll.x = xev->xbutton.x; event->mouse_wheel_scroll.y = xev->xbutton.y; } else if(xev->xbutton.button == Button5) { /* Mouse scroll down */ event->type = MGL_EVENT_MOUSE_WHEEL_SCROLLED; event->mouse_wheel_scroll.delta = -1; event->mouse_wheel_scroll.x = xev->xbutton.x; event->mouse_wheel_scroll.y = xev->xbutton.y; } else { event->type = MGL_EVENT_MOUSE_BUTTON_PRESSED; event->mouse_button.button = x11_button_to_mgl_button(xev->xbutton.button); event->mouse_button.x = xev->xbutton.x; event->mouse_button.y = xev->xbutton.y; x11_context_update_mouse_button_state(self->context, event->mouse_button.button, true); } return; } case ButtonRelease: { event->type = MGL_EVENT_MOUSE_BUTTON_RELEASED; event->mouse_button.button = x11_button_to_mgl_button(xev->xbutton.button); event->mouse_button.x = xev->xbutton.x; event->mouse_button.y = xev->xbutton.y; x11_context_update_mouse_button_state(self->context, event->mouse_button.button, false); return; } case FocusIn: { event->type = MGL_EVENT_GAINED_FOCUS; self->focused = true; return; } case FocusOut: { event->type = MGL_EVENT_LOST_FOCUS; self->focused = false; return; } case ConfigureNotify: { while(XCheckTypedWindowEvent(context->connection, self->window, ConfigureNotify, xev)) {} if(xev->xconfigure.width != self->size.x || xev->xconfigure.height != self->size.x) { mgl_window_on_resize(self, xev->xconfigure.width, xev->xconfigure.height); event->type = MGL_EVENT_RESIZED; event->size.width = self->size.x; event->size.height = self->size.y; return; } event->type = MGL_EVENT_UNKNOWN; return; } case MotionNotify: { while(XCheckTypedWindowEvent(context->connection, self->window, MotionNotify, xev)) {} self->cursor_position.x = xev->xmotion.x; self->cursor_position.y = xev->xmotion.y; event->type = MGL_EVENT_MOUSE_MOVED; event->mouse_move.x = self->cursor_position.x; event->mouse_move.y = self->cursor_position.y; return; } case SelectionClear: { event->type = MGL_EVENT_UNKNOWN; return; } case SelectionRequest: { x11_context *x11_context = self->context; XSelectionEvent selection_event; selection_event.type = SelectionNotify; selection_event.requestor = xev->xselectionrequest.requestor; selection_event.selection = xev->xselectionrequest.selection; selection_event.property = xev->xselectionrequest.property; selection_event.time = xev->xselectionrequest.time; selection_event.target = xev->xselectionrequest.target; if(selection_event.selection == x11_context->clipboard_atom) { /* TODO: Support ascii text separately by unsetting the 8th bit in the clipboard string? */ if(selection_event.target == x11_context->targets_atom) { /* A client requested for our valid conversion targets */ int num_targets = 3; Atom targets[4]; targets[0] = x11_context->targets_atom; targets[1] = x11_context->text_atom; targets[2] = XA_STRING; if(x11_context->utf8_string_atom) { targets[3] = x11_context->utf8_string_atom; num_targets = 4; } XChangeProperty(context->connection, selection_event.requestor, selection_event.property, XA_ATOM, 32, PropModeReplace, (unsigned char*)targets, num_targets); selection_event.target = x11_context->targets_atom; XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event); } else if(selection_event.target == XA_STRING || (!x11_context->utf8_string_atom && selection_event.target == x11_context->text_atom)) { /* A client requested ascii clipboard */ XChangeProperty(context->connection, selection_event.requestor, selection_event.property, XA_STRING, 8, PropModeReplace, self->clipboard_string, self->clipboard_size); selection_event.target = XA_STRING; XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event); } else if(x11_context->utf8_string_atom && (selection_event.target == x11_context->utf8_string_atom || selection_event.target == x11_context->text_atom)) { /* A client requested utf8 clipboard */ XChangeProperty(context->connection, selection_event.requestor, selection_event.property, x11_context->utf8_string_atom, 8, PropModeReplace, self->clipboard_string, self->clipboard_size); selection_event.target = x11_context->utf8_string_atom; XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event); } } selection_event.property = None; XSendEvent(context->connection, selection_event.requestor, True, NoEventMask, (XEvent*)&selection_event); event->type = MGL_EVENT_UNKNOWN; return; } case ClientMessage: { if(xev->xclient.format == 32 && (unsigned long)xev->xclient.data.l[0] == context->wm_delete_window_atom) { event->type = MGL_EVENT_CLOSED; self->open = false; return; } else if(xev->xclient.format == 32 && (unsigned long)xev->xclient.data.l[0] == context->net_wm_ping_atom) { xev->xclient.window = DefaultRootWindow(context->connection); XSendEvent(context->connection, DefaultRootWindow(context->connection), False, SubstructureNotifyMask | SubstructureRedirectMask, xev); } event->type = MGL_EVENT_UNKNOWN; return; } default: { event->type = MGL_EVENT_UNKNOWN; return; } } } void mgl_window_clear(mgl_window *self, mgl_color color) { mgl_context *context = mgl_get_context(); context->gl.glClear(GL_COLOR_BUFFER_BIT); context->gl.glClearColor((float)color.r / 255.0f, (float)color.g / 255.0f, (float)color.b / 255.0f, (float)color.a / 255.0f); } bool mgl_window_poll_event(mgl_window *self, mgl_event *event) { mgl_context *context = mgl_get_context(); Display *display = context->connection; x11_context *x11_context = self->context; if(x11_context_pop_event(x11_context, event)) return true; if(XPending(display)) { XEvent xev; /* TODO: Move to window struct */ XNextEvent(display, &xev); mgl_window_on_receive_event(self, &xev, event, context); return true; } else { return false; } } void mgl_window_display(mgl_window *self) { mgl_context *context = mgl_get_context(); context->gl.glXSwapBuffers(context->connection, self->window); if(self->frame_time_limit > 0.000001) { double time_left_to_sleep = self->frame_time_limit - mgl_clock_get_elapsed_time_seconds(&self->frame_timer); if(time_left_to_sleep > 0.000001) usleep(time_left_to_sleep * 1000000.0); mgl_clock_restart(&self->frame_timer); } } void mgl_window_set_view(mgl_window *self, mgl_view *new_view) { mgl_context *context = mgl_get_context(); self->view = *new_view; context->gl.glViewport(new_view->position.x, self->size.y - new_view->size.y - new_view->position.y, new_view->size.x, new_view->size.y); context->gl.glMatrixMode(GL_PROJECTION); context->gl.glLoadIdentity(); context->gl.glOrtho(0.0, new_view->size.x, new_view->size.y, 0.0, 0.0, 1.0); context->gl.glMatrixMode(GL_MODELVIEW); } void mgl_window_get_view(mgl_window *self, mgl_view *view) { *view = self->view; } bool mgl_window_is_open(const mgl_window *self) { return self->open; } bool mgl_window_has_focus(const mgl_window *self) { return self->focused; } bool mgl_window_is_key_pressed(const mgl_window *self, mgl_key key) { if(key < 0 || key >= __MGL_NUM_KEYS__) return false; return x11_context_is_key_pressed(self->context, key); } bool mgl_window_is_mouse_button_pressed(const mgl_window *self, mgl_mouse_button button) { if(button < 0 || button >= __MGL_NUM_MOUSE_BUTTONS__) return false; return x11_context_is_mouse_button_pressed(self->context, button); } void mgl_window_close(mgl_window *self) { mgl_context *context = mgl_get_context(); XDestroyWindow(context->connection, self->window); XSync(context->connection, False); self->window = None; self->open = false; } void mgl_window_set_title(mgl_window *self, const char *title) { mgl_context *context = mgl_get_context(); XStoreName(context->connection, self->window, title); } void mgl_window_set_cursor_visible(mgl_window *self, bool visible) { mgl_context *context = mgl_get_context(); x11_context *x11_context = self->context; XDefineCursor(context->connection, self->window, visible ? x11_context->default_cursor : x11_context->invisible_cursor); } void mgl_window_set_framerate_limit(mgl_window *self, int fps) { if(fps <= 0) self->frame_time_limit = 0.0; else self->frame_time_limit = 1.0 / fps; } void mgl_window_set_position(mgl_window *self, mgl_vec2i position) { XMoveWindow(mgl_get_context()->connection, self->window, position.x, position.y); } void mgl_window_set_size(mgl_window *self, mgl_vec2i size) { XResizeWindow(mgl_get_context()->connection, self->window, size.x, size.y); } void mgl_window_set_size_limits(mgl_window *self, mgl_vec2i minimum, mgl_vec2i maximum) { XSizeHints *size_hints = XAllocSizeHints(); if(size_hints) { size_hints->width = self->size.x; size_hints->min_width = minimum.x; size_hints->max_width = maximum.x; size_hints->height = self->size.y; size_hints->min_height = minimum.y; size_hints->max_height = maximum.y; size_hints->flags = PSize; if(size_hints->min_width || size_hints->min_height) size_hints->flags |= PMinSize; if(size_hints->max_width || size_hints->max_height) size_hints->flags |= PMaxSize; mgl_context *context = mgl_get_context(); XSetWMNormalHints(context->connection, self->window, size_hints); XFree(size_hints); XSync(context->connection, False); } else { fprintf(stderr, "Warning: failed to set window size hints\n"); } } void mgl_window_set_clipboard(mgl_window *self, const char *str, size_t size) { mgl_context *context = mgl_get_context(); x11_context *x11_context = self->context; if(self->clipboard_string) { free(self->clipboard_string); self->clipboard_string = NULL; self->clipboard_size = 0; } XSetSelectionOwner(context->connection, x11_context->clipboard_atom, self->window, CurrentTime); /* Check if setting the selection owner was successful */ if(XGetSelectionOwner(context->connection, x11_context->clipboard_atom) != self->window) { fprintf(stderr, "Error: mgl_window_set_clipboard failed\n"); return; } self->clipboard_string = malloc(size + 1); if(!self->clipboard_string) { fprintf(stderr, "Error: failed to allocate string for clipboard\n"); return; } memcpy(self->clipboard_string, str, size); self->clipboard_string[size] = '\0'; self->clipboard_size = size; } /* TODO: Right now the returned str is free'd with free, but shouldn't it be free'd with free? */ bool mgl_window_get_clipboard(mgl_window *self, char **str, size_t *size) { mgl_context *context = mgl_get_context(); x11_context *x11_context = self->context; *str = NULL; *size = 0; Window selection_owner = XGetSelectionOwner(context->connection, x11_context->clipboard_atom); if(!selection_owner) { char *empty_str = malloc(1); if(!empty_str) return false; empty_str[0] = '\0'; return true; } /* Return data immediately if we are the owner of the clipboard, because we can't process other events in the below event loop */ if(selection_owner == self->window) { if(!self->clipboard_string) { char *empty_str = malloc(1); if(!empty_str) return false; empty_str[0] = '\0'; return true; } char *data = malloc(self->clipboard_size + 1); if(!data) return false; memcpy(data, self->clipboard_string, self->clipboard_size); data[self->clipboard_size] = '\0'; *str = data; *size = self->clipboard_size; return true; } XEvent xev; while(XCheckTypedWindowEvent(context->connection, self->window, SelectionNotify, &xev)) {} XConvertSelection(context->connection, x11_context->clipboard_atom, x11_context->utf8_string_atom ? x11_context->utf8_string_atom : XA_STRING, x11_context->target_property_atom, self->window, CurrentTime); mgl_clock timeout_timer; mgl_clock_init(&timeout_timer); const double timeout_seconds = 1.0; while(mgl_clock_get_elapsed_time_seconds(&timeout_timer) < timeout_seconds) { while(XCheckTypedWindowEvent(context->connection, self->window, SelectionNotify, &xev)) { if(!xev.xselection.property || xev.xselection.selection != x11_context->clipboard_atom) continue; Atom type; int format; unsigned long items; unsigned long remaining_bytes; unsigned char *data = NULL; if(XGetWindowProperty(context->connection, self->window, x11_context->target_property_atom, 0, INT32_MAX, False, AnyPropertyType, &type, &format, &items, &remaining_bytes, &data) == Success) { bool got_clipboard = false; if(type != x11_context->incr_atom) { if(type == x11_context->utf8_string_atom && format == 8) { *str = (char*)data; *size = items; got_clipboard = true; } else if(type == XA_STRING && format == 8) { *str = (char*)data; *size = items; got_clipboard = true; } } XDeleteProperty(context->connection, self->window, x11_context->target_property_atom); if(got_clipboard) return true; } } } /* Timed out waiting for clipboard */ return false; } void mgl_window_set_key_repeat_enabled(mgl_window *self, bool enabled) { self->key_repeat_enabled = enabled; }