summaryrefslogtreecommitdiff
path: root/main.c
blob: 41a9a984ce45b9ece0c4370fceb0ded086d99ef7 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// @TODO:
// - text size (text-size, :increase-text-size, :decrease-text-size)
// - put stuff in UserData on windows
#include "base.h"
no_warn_start
#if _WIN32
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif
no_warn_end
#include <GL/gl.h>
#include <locale.h>
#include <wctype.h>
#if _WIN32
#include <shellapi.h>
#endif

#define TED_PATH_MAX 256

#include "command.h"
#include "util.c"
#include "filesystem.c"
#include "colors.c"
typedef struct {
	float cursor_blink_time_on, cursor_blink_time_off;
	u32 colors[COLOR_COUNT];
	u8 tab_width;
	u8 cursor_width;
	u8 undo_save_time;
} Settings;
#include "time.c"
#include "unicode.h"
#define MATH_GL
#include "math.c"
#include "text.h"
#include "string32.c"
#include "arr.c"
#include "buffer.c"
#include "ted-base.c"
#include "command.c"
#include "config.c"

static void die(char const *fmt, ...) {
	char buf[256] = {0};
	
	va_list args;
	va_start(args, fmt);
	vsnprintf(buf, sizeof buf - 1, fmt, args);
	va_end(args);

	// show a message box, and if that fails, print it
	if (SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", buf, NULL) < 0) {
		debug_println("%s\n", buf);
	}

	exit(EXIT_FAILURE);
}

// should the working directory be searched for files? set to true if the executable isn't "installed"
static bool ted_search_cwd = false;
#if _WIN32
// @TODO
#else
static char const *const ted_global_data_dir = "/usr/share/ted";
#endif

// Check the various places a file could be, and return the full path.
static Status ted_get_file(char const *name, char *out, size_t outsz) {
#if _WIN32
	#error "@TODO(windows)"
#else
	if (ted_search_cwd && fs_file_exists(name)) {
		// check in current working directory
		str_cpy(out, outsz, name);
		return true;
	}

	char *home = getenv("HOME");
	if (home) {
		str_printf(out, outsz, "%s/.local/share/ted/%s", home, name);
		if (!fs_file_exists(out)) {
			str_printf(out, outsz, "%s/%s", ted_global_data_dir, name);
			if (!fs_file_exists(out))
				return false;
		}
	}
	return true;
#endif
}

#if _WIN32
INT WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    PSTR lpCmdLine, INT nCmdShow) {
	int argc = 0;
    LPWSTR* wide_argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    char** argv = malloc(argc * sizeof *argv);
	if (!argv) {
		die("Out of memory.");
	}
    for (int i = 0; i < argc; i++) {
        LPWSTR wide_arg = wide_args[i];
        int len = wcslen(wide_arg);
        argv[i] = malloc(len + 1);
		if (!argv[i]) die("Out of memory.");
        for (int j = 0; j <= len; j++)
            argv[i][j] = (char)wide_arg[j];
    }
    LocalFree(wide_args);
#else
int main(int argc, char **argv) {
#endif
	setlocale(LC_ALL, ""); // allow unicode

	{ // check if this is the installed version of ted (as opposed to just running it from the directory with the source)
		char executable_path[TED_PATH_MAX] = {0};
	#if _WIN32
		// @TODO(windows): GetModuleFileNameW
	#else
		ssize_t len = readlink("/proc/self/exe", executable_path, sizeof executable_path - 1);
		executable_path[len] = '\0';
		ted_search_cwd = !str_is_prefix(executable_path, "/usr");
	#endif
	}

	Ted *ted = calloc(1, sizeof *ted);
	if (!ted) {
		die("Not enough memory available to run ted.");
	}

	Settings *settings = &ted->settings;

	{
		// read global configuration file first to establish defaults
		char global_config_filename[TED_PATH_MAX];
		strbuf_printf(global_config_filename, "%s/ted.cfg", ted_global_data_dir);
		if (fs_file_exists(global_config_filename))
			config_read(ted, global_config_filename);
	}
	{
		// read local configuration file
		char config_filename[TED_PATH_MAX];
		if (ted_get_file("ted.cfg", config_filename, sizeof config_filename))
			config_read(ted, config_filename);
		else
			ted_seterr(ted, "Couldn't find config file (ted.cfg), not even the backup one that should have come with ted.");
	}
	if (ted_haserr(ted)) {
		die("Error reading config: %s", ted_geterr(ted));
	}

	SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1"); // if this program is sent a SIGTERM/SIGINT, don't turn it into a quit event
	if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
		die("%s", SDL_GetError());

	SDL_Window *window = SDL_CreateWindow("ted", SDL_WINDOWPOS_UNDEFINED, 
		SDL_WINDOWPOS_UNDEFINED, 1280, 720, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
	if (!window)
		die("%s", SDL_GetError());
		
	{ // set icon
		char icon_filename[TED_PATH_MAX];
		if (ted_get_file("assets/icon.bmp", icon_filename, sizeof icon_filename)) {
			SDL_Surface *icon = SDL_LoadBMP(icon_filename);
			SDL_SetWindowIcon(window, icon);
			SDL_FreeSurface(icon);
		} // if we can't find the icon file, it's no big deal
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GLContext *glctx = SDL_GL_CreateContext(window);
	if (!glctx) {
		die("%s", SDL_GetError());
	}

	SDL_GL_SetSwapInterval(1); // vsync

	Font *font = NULL;
	{
		char font_filename[TED_PATH_MAX];
		if (ted_get_file("assets/font.ttf", font_filename, sizeof font_filename)) {
			font = text_font_load(font_filename, 16);
			if (!font) {
				die("Couldn't load font: %s", text_get_err());
			}
		} else {
			die("Couldn't find font file. There is probably a problem with your ted installation.");
		}
	}
	
	TextBuffer text_buffer;
	TextBuffer *buffer = &text_buffer;
	buffer_create(buffer, font, settings);
	ted->active_buffer = buffer;

	char const *starting_filename = "Untitled";
	
	switch (argc) {
	case 0: case 1: break;
	case 2:
		starting_filename = argv[1];
		break;
	default:	
		die("Usage: %s [filename]", argv[0]);
		break;
	}

	if (fs_file_exists(starting_filename)) {
		buffer_load_file(buffer, starting_filename);
		if (buffer_haserr(buffer))
			die("Error loading file: %s", buffer_geterr(buffer));
	} else {
		buffer_new_file(buffer, starting_filename);
		if (buffer_haserr(buffer))
			die("Error creating file: %s", buffer_geterr(buffer));
	}


	Uint32 time_at_last_frame = SDL_GetTicks();

	bool quit = false;
	while (!quit) {
	#if DEBUG
		//printf("\033[H\033[2J");
	#endif

		SDL_Event event;
		Uint8 const *keyboard_state = SDL_GetKeyboardState(NULL);
		bool ctrl_down = keyboard_state[SDL_SCANCODE_LCTRL] || keyboard_state[SDL_SCANCODE_RCTRL];
		bool shift_down = keyboard_state[SDL_SCANCODE_LSHIFT] || keyboard_state[SDL_SCANCODE_RSHIFT];
		bool alt_down = keyboard_state[SDL_SCANCODE_LALT] || keyboard_state[SDL_SCANCODE_RALT];
		u32 key_modifier = (u32)ctrl_down << KEY_MODIFIER_CTRL_BIT
			| (u32)shift_down << KEY_MODIFIER_SHIFT_BIT
			| (u32)alt_down << KEY_MODIFIER_ALT_BIT;

		while (SDL_PollEvent(&event)) {
			// @TODO: make a function to handle text buffer events
			switch (event.type) {
			case SDL_QUIT:
				quit = true;
				break;
			case SDL_MOUSEWHEEL: {
				// scroll with mouse wheel
				Sint32 dx = event.wheel.x, dy = -event.wheel.y;
				double scroll_speed = 2.5;
				buffer_scroll(buffer, dx * scroll_speed, dy * scroll_speed);
			} break;
			case SDL_MOUSEBUTTONDOWN:
				switch (event.button.button) {
				case SDL_BUTTON_LEFT: {
					BufferPos pos = {0};
					if (buffer_pixels_to_pos(buffer, V2((float)event.button.x, (float)event.button.y), &pos)) {
						if (key_modifier == KEY_MODIFIER_SHIFT) {
							buffer_select_to_pos(buffer, pos);
						} else if (key_modifier == 0) {
							buffer_cursor_move_to_pos(buffer, pos);
							switch ((event.button.clicks - 1) % 3) {
							case 0: break; // single-click
							case 1: // double-click: select word
								buffer_select_word(buffer);
								break;
							case 2: // triple-click: select line
								buffer_select_line(buffer);
								break;
							}
						}
					}
				} break;
				}
				break;
			case SDL_MOUSEMOTION:
				if (event.motion.state == SDL_BUTTON_LMASK) {
					BufferPos pos = {0};
					if (buffer_pixels_to_pos(buffer, V2((float)event.button.x, (float)event.button.y), &pos)) {
						buffer_select_to_pos(buffer, pos);
					}
				}
				break;
			case SDL_KEYDOWN: {
				SDL_Scancode scancode = event.key.keysym.scancode;
				SDL_Keymod modifier = event.key.keysym.mod;
				u32 key_combo = (u32)scancode << 3 |
					(u32)((modifier & (KMOD_LCTRL|KMOD_RCTRL)) != 0) << KEY_MODIFIER_CTRL_BIT |
					(u32)((modifier & (KMOD_LSHIFT|KMOD_RSHIFT)) != 0) << KEY_MODIFIER_SHIFT_BIT |
					(u32)((modifier & (KMOD_LALT|KMOD_RALT)) != 0) << KEY_MODIFIER_ALT_BIT;
				if (key_combo < KEY_COMBO_COUNT) {
					KeyAction *action = &ted->key_actions[key_combo];
					if (action->command) {
						command_execute(ted, action->command, action->argument);
					} else switch (event.key.keysym.sym) {
						case SDLK_RETURN:
							buffer_insert_char_at_cursor(buffer, U'\n');
							break;
						case SDLK_TAB:
							buffer_insert_char_at_cursor(buffer, U'\t');
							break;
					}
				}
			} break;
			case SDL_TEXTINPUT: {
				char *text = event.text.text;
				buffer_insert_utf8_at_cursor(buffer, text);
			} break;
			}
		}

		double frame_dt;
		{
			Uint32 time_this_frame = SDL_GetTicks();
			frame_dt = 0.001 * (time_this_frame - time_at_last_frame);
			time_at_last_frame = time_this_frame;
		}

		if (key_modifier == KEY_MODIFIER_ALT) {
			// alt + arrow keys to scroll
			double scroll_speed = 20.0;
			double scroll_amount_x = scroll_speed * frame_dt * 1.5; // characters are taller than they are wide
			double scroll_amount_y = scroll_speed * frame_dt;
			if (keyboard_state[SDL_SCANCODE_UP])
				buffer_scroll(buffer, 0, -scroll_amount_y);
			if (keyboard_state[SDL_SCANCODE_DOWN])
				buffer_scroll(buffer, 0, +scroll_amount_y);
			if (keyboard_state[SDL_SCANCODE_LEFT])
				buffer_scroll(buffer, -scroll_amount_x, 0);
			if (keyboard_state[SDL_SCANCODE_RIGHT])
				buffer_scroll(buffer, +scroll_amount_x, 0);
		}
			

		int window_width = 0, window_height = 0;
		SDL_GetWindowSize(window, &window_width, &window_height);
		float window_widthf = (float)window_width, window_heightf = (float)window_height;

		// set up GL
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glViewport(0, 0, window_width, window_height);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		// pixel coordinates; down is positive y
		glOrtho(0, window_width, window_height, 0, -1, +1);
		{ // clear (background)
			float bg_color[4];
			rgba_u32_to_floats(settings->colors[COLOR_BG], bg_color);
			glClearColor(bg_color[0], bg_color[1], bg_color[2], bg_color[3]);
		}
		glClear(GL_COLOR_BUFFER_BIT);

		{
			float x1 = 50, y1 = 50, x2 = window_widthf-50, y2 = window_heightf-50;
			buffer_render(buffer, x1, y1, x2, y2);
			if (text_has_err()) {
				debug_println("Text error: %s\n", text_get_err());
				break;
			}
		}

	#if DEBUG
		//buffer_print_debug(buffer);
		buffer_check_valid(buffer);
		//buffer_print_undo_history(buffer);
	#endif

		SDL_GL_SwapWindow(window);
	}

	SDL_GL_DeleteContext(glctx);
	SDL_DestroyWindow(window);
	SDL_Quit();
	buffer_free(buffer);
	text_font_free(font);
	free(ted);
#if _WIN32
	for (int i = 0; i < argc; ++i)
		free(argv[i]);
	free(argv);
#endif

	return 0;
}