~kiwec/ke

ref: 842396976984e3cbd83251296dd90a46b9d53b3c ke/src/Editor.cc -rw-r--r-- 2.2 KiB
84239697 — Wolf Clément Downgrade to C++17, avoid stdlib 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
91
92
93
94
95
96
#include <stdlib.h>
#include <termbox.h>
#include "Conversion.h"
#include "Editor.h"
#include "Prompt.h"
#include "Gutter.h"
#include "StatusBar.h"

void Editor::draw() {
	tb_clear();

	// Draw buffer (file text)
	m_buf->draw(Canvas{ 0, 0, tb_width(), tb_height() - m_status.height() });

	tb_set_cursor(Gutter::width(*m_buf) + m_buf->get_visible_x(), m_buf->get_visible_y());
	m_status.draw(*m_buf);

	tb_present();
}

bool Editor::handle_key(tb_event* ev) {
	switch(ev->key) {
	case TB_KEY_CTRL_G:
		m_status.prompt = std::make_unique<Prompt>(L"Go to line : ", [&buf = *m_buf](auto answer) {
			int line = -1;

			try {
				line = std::stoi(answer);
			} catch(std::exception& e) {
				// TODO show error
			}

			if(line > 0) {
				buf.move_to(line);
			}
		});
		return true;
	case TB_KEY_CTRL_F:
		m_status.prompt = std::make_unique<Prompt>(L"Find : ", [&buf = *m_buf](auto answer) {
			if(answer == L"") return;
			auto result = buf.m_text.search(answer);
			buf.move_to(result.first, result.second);
			// TODO show no matches
		});
		return true;
	case TB_KEY_CTRL_Q:
#ifdef _DEBUG
		// Debug : dump text
		tb_shutdown();
		wprintf(&m_buf->m_text[0]);
#endif

		exit(0);
		return true;
	case TB_KEY_CTRL_O:
		m_status.prompt = std::make_unique<Prompt>(L"Open file : ", [this](auto answer) {
			if(answer == L"") return; // TODO show error
			auto str = Convert::from_wide_string(answer);
			open(str.get());
		});
		return true;
	case TB_KEY_CTRL_S:
		// Ctrl-Alt-S
		if(ev->mod == TB_MOD_ALT || m_buf->filename == "") {
			m_status.prompt = std::make_unique<Prompt>(L"Save as : ", [&buf = *m_buf](auto answer) {
				if(answer == L"") return; // TODO show error
				auto str = Convert::from_wide_string(answer);
				buf.filename = str.get();
				buf.save();
			});

			auto wstr = Convert::to_wide_string(m_buf->filename.c_str());
			m_status.prompt->set_answer(wstr.get());
		} else {
			m_buf->save();
		}
		return true;
	}

	return false;
}

bool Editor::handle_mouse(tb_event* ev) {
	switch(ev->key) {
	case TB_KEY_MOUSE_LEFT:
		m_buf->screen_to(ev->x - Gutter::width(*m_buf) - 1, ev->y);
		return true;
	}

	return false;
}

void Editor::open(std::string filename) {
	m_buf = std::make_shared<Buffer>(filename);
}