summaryrefslogtreecommitdiff
path: root/src/tooltip.c
blob: e900e4011c1c7969a98d5e1af8e48897f5796409 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#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;
	}
}