#include #include #include "panic.h" #include "font.h" #include "hash.h" #include "main.h" #include "tooltip.h" #define PADDING 4 void set_tooltip_text(tooltip *t, const char *text) { if (!t->window) { t->window = must(SDL_CreatePopupWindow(window, 0, 0, 0, 0, SDL_WINDOW_TOOLTIP | SDL_WINDOW_BORDERLESS )); t->renderer = must(SDL_CreateRenderer(t->window, NULL)); } uint64_t hash = fnv(text, text ? strlen(text) : 0); if (hash == t->hash) { return; } t->hash = hash; if (t->texture) { SDL_DestroyTexture(t->texture); t->texture = NULL; } if (!text) return; SDL_Color color = {0xff, 0xff, 0xff, 0xff}; SDL_Surface *s = must(TTF_RenderText_Blended_Wrapped( font, text, 0, color, 0 )); t->texture = must(SDL_CreateTextureFromSurface(t->renderer, s)); SDL_DestroySurface(s); float tw, th; SDL_GetTextureSize(t->texture, &tw, &th); SDL_SetWindowSize(t->window, tw + PADDING*2, th + PADDING*2); SDL_SyncWindow(t->window); } void show_tooltip(tooltip *t, int x, int y) { if (!(SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)) { hide_tooltip(t); return; } if (!t->texture) { hide_tooltip(t); return; } float tw, th; SDL_GetTextureSize(t->texture, &tw, &th); SDL_SetWindowPosition(t->window, x + PADDING, y - th - PADDING*3); if (t->hidden) { SDL_ShowWindow(t->window); SDL_SyncWindow(t->window); t->hidden = false; } SDL_SetRenderDrawColor(t->renderer, 0, 0, 0x20, 0xff); SDL_RenderClear(t->renderer); SDL_SetRenderDrawColor(t->renderer, 0, 0, 0, 0xff); SDL_FRect dst = {PADDING, PADDING, tw, th}; SDL_RenderTexture(t->renderer, t->texture, NULL, &dst); SDL_FRect border_rect = {0, 0, tw + PADDING*2, th + PADDING*2}; SDL_SetRenderDrawColor(t->renderer, 0x50, 0x50, 0x50, 0xff); SDL_RenderRect(t->renderer, &border_rect); must(SDL_RenderPresent(t->renderer)); } void hide_tooltip(tooltip *t) { if (t->window && !t->hidden) { SDL_HideWindow(t->window); t->hidden = true; } }