bettola/client/src/ui/ui_window.cpp

105 lines
3.2 KiB
C++

#include "ui_window.h"
#include <SDL3/SDL_events.h>
#include "gfx/shape_renderer.h"
#include "gfx/txt_renderer.h"
UIWindow::UIWindow(const char* title, int x, int y, int width, int height) {
_title = title;
_x = x;
_y = y;
_width = width;
_height = height;
_content = nullptr;
_is_dragging = false;
_is_hovered = false;
_is_focused = false; /* Not focused by default? */
}
void UIWindow::set_content(Terminal* term) {
_content = term;
}
void UIWindow::set_focused(bool focused) {
_is_focused = focused;
}
Terminal* UIWindow::get_content(void) {
return _content;
}
bool UIWindow::is_point_inside(int x, int y) {
return (x >= _x && x <= _x + _width &&
y >= _y && y <= _y + _height);
}
void UIWindow::render(ShapeRenderer* shape_renderer, TextRenderer* txt_renderer,
int screen_height, bool show_cursor) {
int title_bar_height = 30;
/* Define colours. */
float frame_color[] = { 0.2f, 0.2f, 0.25f };
float title_bar_color[] = { 0.15f, 0.15f, 0.2f };
float focused_title_bar_color[] = { 0.3f, 0.3f, 0.4f };
float title_text_color[] = { 0.9f, 0.9f, 0.9f };
/* Convert top-left coords to bottom-left for OpenGL. */
int y_gl = screen_height - _y - _height;
/* Draw main window frame/background. */
shape_renderer->draw_rect(_x, y_gl, _width, _height, frame_color);
/* Draw title bar. */
if(_is_focused) {
shape_renderer->draw_rect(_x, y_gl+_height-title_bar_height, _width, title_bar_height,
focused_title_bar_color);
} else {
shape_renderer->draw_rect(_x, y_gl+_height-title_bar_height, _width, title_bar_height,
title_bar_color);
}
/* Draw title text. */
txt_renderer->render_text(_title.c_str(), _x+5, y_gl+_height-title_bar_height+8,
1.0f, title_text_color);
if(_content) {
int content_y_gl = y_gl;
int content_height_gl = _height - title_bar_height;
_content->render(txt_renderer, _x, content_y_gl, _width, content_height_gl, show_cursor);
}
}
void UIWindow::handle_event(SDL_Event* event) {
int title_bar_height = 30;
if(event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
int mouse_x = event->button.x;
int mouse_y = event->button.y;
/* Is click within title bar? */
if(mouse_x >= _x && mouse_x <= _x + _width &&
mouse_y >= _y && mouse_y <= _y + title_bar_height) {
_is_dragging = true;
_drag_offset_x = mouse_x - _x;
_drag_offset_y = mouse_y - _y;
}
} else if(event->type == SDL_EVENT_MOUSE_BUTTON_UP) {
_is_dragging = false;
} else if(event->type == SDL_EVENT_MOUSE_MOTION) {
if(_is_dragging) {
_x = event->motion.x - _drag_offset_x;
_y = event->motion.y - _drag_offset_y;
}
/* Check if mouse hovered over window. */
_is_hovered = is_point_inside(event->motion.x, event->motion.y);
} else if(event->type == SDL_EVENT_MOUSE_WHEEL) {
/* Only scroll window if mouse is hovering. */
if(_is_hovered && _content) {
/* SDL's wheel motion is negative scroll up on the y. */
int content_height_gl = _height - title_bar_height;
_content->scroll(-event->wheel.y, content_height_gl);
}
}
}