~kiwec/ke

ref: 4e0a6570b5c10ffd1830ab776619aa0a2f95ddfb ke/src/Prompt.cc -rw-r--r-- 1.7 KiB
4e0a6570 — Wolf Clément Change file style 3 years ago
                                                                                
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <sstream>
#include <wchar.h>
#include "Editor.h"
#include "Line.h"
#include "Prompt.h"

void Prompt::draw(int rwidth) {
	if(!m_prompting) return;

	const int16_t fg = 0;
	const int16_t bg = 234;

	// Background
	for(int i = 0; i < tb_width() - rwidth; i++) {
		tb_change_cell(i, tb_height() - 1, ' ', fg, bg);
	}

	// Prompt
	Canvas::print(m_prompt, 1, tb_height() - 1, fg, bg);
	m_answer.get_line(1).print(wcslen(m_prompt) + 1, tb_height() - 1, bg);
}

uint Prompt::get_visible_x() {
	return 1 + wcslen(m_prompt) + m_answer.get_line(1).width();
}

bool Prompt::handle_key(tb_event* ev) {
	if(!m_prompting) return false;

	// Close prompt
	switch(ev->key) {
	case TB_KEY_ENTER:
		m_callback(m_answer.get_line(1).begin());
	case TB_KEY_CTRL_C:
	case TB_KEY_ESC:
		m_prompting = false;
		return true;
	}
	
	// Handle input
	if(ev->ch) {
		m_answer.insert((wchar_t*)&ev->ch, 1, m_answer.size());
		m_pos++;
		tb_set_cursor(get_visible_x(), tb_height() - 1);
		return true;
	}

	// Handle special keys
	switch(ev->key) {
	case TB_KEY_SPACE:
		m_answer.insert(L" ", 1, m_answer.size());
		m_pos++;
		break;
	case TB_KEY_BACKSPACE:
		if(m_pos > 0) {
			m_answer.erase(m_pos - 1, 1);
			m_pos--;
		}
		break;
	case TB_KEY_DELETE:
		if(m_pos < m_answer.size()) {
			m_answer.erase(m_pos, 1);
			m_pos--;
		}
		break;
	case TB_KEY_ARROW_LEFT:
		if(m_pos == 0) break;
		m_pos--;
		break;
	case TB_KEY_ARROW_RIGHT:
		if(m_pos == m_answer.size()) break;
		m_pos++;
		break;
	case TB_KEY_END:
		m_pos = m_answer.size();
		break;
	case TB_KEY_HOME:
		m_pos = 0;
		break;
	default:
		return false;
	}

	tb_set_cursor(get_visible_x(), tb_height() - 1);
	return true;
}

bool Prompt::handle_mouse(tb_event* ev) {
	return false;
}