summaryrefslogtreecommitdiff
path: root/examples/dte/window.c
blob: 6b0c5cbb2b500ab655cd6fe76238df4f6695f0c9 (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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include "window.h"
#include "editor.h"
#include "error.h"
#include "file-history.h"
#include "load-save.h"
#include "lock.h"
#include "move.h"
#include "util/path.h"
#include "util/str-util.h"
#include "util/strtonum.h"
#include "util/xmalloc.h"

Window *new_window(EditorState *e)
{
    Window *window = xnew0(Window, 1);
    window->editor = e;
    return window;
}

View *window_add_buffer(Window *window, Buffer *buffer)
{
    // We rely on this being 0, for implicit initialization of
    // View::selection and View::select_mode
    static_assert(SELECT_NONE == 0);

    View *view = xnew(View, 1);
    *view = (View) {
        .buffer = buffer,
        .window = window,
        .cursor = {
            .blk = BLOCK(buffer->blocks.next),
            .head = &buffer->blocks,
        }
    };

    ptr_array_append(&buffer->views, view);
    ptr_array_append(&window->views, view);
    window->update_tabbar = true;
    return view;
}

View *window_open_empty_buffer(Window *window)
{
    EditorState *e = window->editor;
    return window_add_buffer(window, open_empty_buffer(&e->buffers, &e->options));
}

View *window_open_buffer (
    Window *window,
    const char *filename,
    bool must_exist,
    const Encoding *encoding
) {
    if (unlikely(filename[0] == '\0')) {
        error_msg("Empty filename not allowed");
        return NULL;
    }

    EditorState *e = window->editor;
    bool dir_missing = false;
    char *absolute = path_absolute(filename);
    if (absolute) {
        // Already open?
        Buffer *buffer = find_buffer(&e->buffers, absolute);
        if (buffer) {
            if (!streq(absolute, buffer->abs_filename)) {
                const char *bufname = buffer_filename(buffer);
                char *s = short_filename(absolute, &e->home_dir);
                info_msg("%s and %s are the same file", s, bufname);
                free(s);
            }
            free(absolute);
            return window_get_view(window, buffer);
        }
    } else {
        // Let load_buffer() create error message
        dir_missing = (errno == ENOENT);
    }

    /*
    /proc/$PID/fd/ contains symbolic links to files that have been opened
    by process $PID. Some of the files may have been deleted but can still
    be opened using the symbolic link but not by using the absolute path.

    # create file
    mkdir /tmp/x
    echo foo > /tmp/x/file

    # in another shell: keep the file open
    tail -f /tmp/x/file

    # make the absolute path unavailable
    rm /tmp/x/file
    rmdir /tmp/x

    # this should still succeed
    dte /proc/$(pidof tail)/fd/3
    */

    Buffer *buffer = buffer_new(&e->buffers, &e->options, encoding);
    if (!load_buffer(buffer, filename, &e->options, must_exist)) {
        remove_and_free_buffer(&e->buffers, buffer);
        free(absolute);
        return NULL;
    }
    if (unlikely(buffer->file.mode == 0 && dir_missing)) {
        // New file in non-existing directory; this is usually a mistake
        error_msg("Error opening %s: Directory does not exist", filename);
        remove_and_free_buffer(&e->buffers, buffer);
        free(absolute);
        return NULL;
    }

    if (absolute) {
        buffer->abs_filename = absolute;
    } else {
        // FIXME: obviously wrong
        buffer->abs_filename = xstrdup(filename);
    }
    update_short_filename(buffer, &e->home_dir);

    if (e->options.lock_files) {
        if (!lock_file(buffer->abs_filename)) {
            buffer->readonly = true;
        } else {
            buffer->locked = true;
        }
    }

    if (buffer->file.mode != 0 && !buffer->readonly && access(filename, W_OK)) {
        error_msg("No write permission to %s, marking read-only", filename);
        buffer->readonly = true;
    }

    return window_add_buffer(window, buffer);
}

View *window_get_view(Window *window, Buffer *buffer)
{
    View *view = window_find_view(window, buffer);
    if (!view) {
        // Open the buffer in other window to this window
        view = window_add_buffer(window, buffer);
        view->cursor = ((View*)buffer->views.ptrs[0])->cursor;
    }
    return view;
}

View *window_find_view(Window *window, Buffer *buffer)
{
    for (size_t i = 0, n = buffer->views.count; i < n; i++) {
        View *view = buffer->views.ptrs[i];
        if (view->window == window) {
            return view;
        }
    }
    // Buffer isn't open in this window
    return NULL;
}

View *window_find_unclosable_view(Window *window)
{
    // Check active view first
    if (window->view && !view_can_close(window->view)) {
        return window->view;
    }
    for (size_t i = 0, n = window->views.count; i < n; i++) {
        View *view = window->views.ptrs[i];
        if (!view_can_close(view)) {
            return view;
        }
    }
    return NULL;
}

static void window_remove_views(Window *window)
{
    while (window->views.count > 0) {
        View *view = window->views.ptrs[window->views.count - 1];
        remove_view(view);
    }
}

// NOTE: window->frame isn't removed
void window_free(Window *window)
{
    window_remove_views(window);
    free(window->views.ptrs);
    window->frame = NULL;
    free(window);
}

// Remove view from view->window and view->buffer->views and free it
size_t remove_view(View *view)
{
    Window *window = view->window;
    EditorState *e = window->editor;
    if (view == window->prev_view) {
        window->prev_view = NULL;
    }
    if (view == e->view) {
        e->view = NULL;
        e->buffer = NULL;
    }

    size_t idx = ptr_array_idx(&window->views, view);
    BUG_ON(idx >= window->views.count);
    ptr_array_remove_idx(&window->views, idx);
    window->update_tabbar = true;

    Buffer *buffer = view->buffer;
    ptr_array_remove(&buffer->views, view);
    if (buffer->views.count == 0) {
        if (buffer->options.file_history && buffer->abs_filename) {
            FileHistory *hist = &e->file_history;
            file_history_add(hist, view->cy + 1, view->cx_char + 1, buffer->abs_filename);
        }
        remove_and_free_buffer(&e->buffers, buffer);
    }

    free(view);
    return idx;
}

void window_close_current_view(Window *window)
{
    size_t idx = remove_view(window->view);
    if (window->prev_view) {
        window->view = window->prev_view;
        window->prev_view = NULL;
        return;
    }
    if (window->views.count == 0) {
        window_open_empty_buffer(window);
    }
    if (window->views.count == idx) {
        idx--;
    }
    window->view = window->views.ptrs[idx];
}

static void restore_cursor_from_history(const FileHistory *hist, View *view)
{
    unsigned long row, col;
    if (file_history_find(hist, view->buffer->abs_filename, &row, &col)) {
        move_to_filepos(view, row, col);
    }
}

void set_view(View *view)
{
    EditorState *e = view->window->editor;
    if (e->view == view) {
        return;
    }

    // Forget previous view when changing view using any other command but open
    if (e->window) {
        e->window->prev_view = NULL;
    }

    e->view = view;
    e->buffer = view->buffer;
    e->window = view->window;
    e->window->view = view;

    if (!view->buffer->setup) {
        buffer_setup(e, view->buffer);
        if (view->buffer->options.file_history && view->buffer->abs_filename) {
            restore_cursor_from_history(&e->file_history, view);
        }
    }

    // view.cursor can be invalid if same buffer was modified from another view
    if (view->restore_cursor) {
        view->cursor.blk = BLOCK(view->buffer->blocks.next);
        block_iter_goto_offset(&view->cursor, view->saved_cursor_offset);
        view->restore_cursor = false;
        view->saved_cursor_offset = 0;
    }

    // Save cursor states of views sharing same buffer
    for (size_t i = 0, n = view->buffer->views.count; i < n; i++) {
        View *other = view->buffer->views.ptrs[i];
        if (other != view) {
            other->saved_cursor_offset = block_iter_get_offset(&other->cursor);
            other->restore_cursor = true;
        }
    }
}

View *window_open_new_file(Window *window)
{
    View *prev = window->view;
    View *view = window_open_empty_buffer(window);
    set_view(view);
    window->prev_view = prev;
    return view;
}

static bool buffer_is_empty_and_untouched(const Buffer *b)
{
    return !b->abs_filename && b->change_head.nr_prev == 0 && !b->display_filename;
}

// If window contains only one untouched buffer it'll be closed after
// opening another file. This is done because closing the last buffer
// causes an empty buffer to be opened (windows must contain at least
// one buffer).
static bool is_useless_empty_view(const View *v)
{
    return v && v->window->views.count == 1 && buffer_is_empty_and_untouched(v->buffer);
}

View *window_open_file(Window *window, const char *filename, const Encoding *encoding)
{
    View *prev = window->view;
    bool useless = is_useless_empty_view(prev);
    View *view = window_open_buffer(window, filename, false, encoding);
    if (view) {
        set_view(view);
        if (useless) {
            remove_view(prev);
        } else {
            window->prev_view = prev;
        }
    }
    return view;
}

// Open multiple files in window and return the first opened View
View *window_open_files(Window *window, char **filenames, const Encoding *encoding)
{
    View *empty = window->view;
    bool useless = is_useless_empty_view(empty);
    View *first = NULL;

    for (size_t i = 0; filenames[i]; i++) {
        View *view = window_open_buffer(window, filenames[i], false, encoding);
        if (view && !first) {
            set_view(view);
            first = view;
        }
    }

    if (useless && window->view != empty) {
        remove_view(empty);
    }

    return first;
}

void mark_buffer_tabbars_changed(Buffer *buffer)
{
    for (size_t i = 0, n = buffer->views.count; i < n; i++) {
        View *view = buffer->views.ptrs[i];
        view->window->update_tabbar = true;
    }
}

static int line_numbers_width(const Window *window, const GlobalOptions *options)
{
    if (!options->show_line_numbers || !window->view) {
        return 0;
    }
    size_t width = size_str_width(window->view->buffer->nl) + 1;
    return MAX(width, LINE_NUMBERS_MIN_WIDTH);
}

static int edit_x_offset(const Window *window, const GlobalOptions *options)
{
    return line_numbers_width(window, options);
}

static int edit_y_offset(const GlobalOptions *options)
{
    return options->tab_bar ? 1 : 0;
}

static void set_edit_size(Window *window, const GlobalOptions *options)
{
    int xo = edit_x_offset(window, options);
    int yo = edit_y_offset(options);

    window->edit_w = window->w - xo;
    window->edit_h = window->h - yo - 1; // statusline
    window->edit_x = window->x + xo;
}

void calculate_line_numbers(Window *window)
{
    const GlobalOptions *options = &window->editor->options;
    int w = line_numbers_width(window, options);
    if (w != window->line_numbers.width) {
        window->line_numbers.width = w;
        window->line_numbers.first = 0;
        window->line_numbers.last = 0;
        mark_all_lines_changed(window->view->buffer);
    }
    set_edit_size(window, options);
}

void set_window_coordinates(Window *window, int x, int y)
{
    const GlobalOptions *options = &window->editor->options;
    window->x = x;
    window->y = y;
    window->edit_x = x + edit_x_offset(window, options);
    window->edit_y = y + edit_y_offset(options);
}

void set_window_size(Window *window, int w, int h)
{
    window->w = w;
    window->h = h;
    calculate_line_numbers(window);
}

int window_get_scroll_margin(const Window *window, unsigned int scroll_margin)
{
    int max = (window->edit_h - 1) / 2;
    BUG_ON(max < 0);
    return MIN(max, scroll_margin);
}

void frame_for_each_window(const Frame *frame, void (*func)(Window*, void*), void *data)
{
    if (frame->window) {
        func(frame->window, data);
        return;
    }
    for (size_t i = 0, n = frame->frames.count; i < n; i++) {
        frame_for_each_window(frame->frames.ptrs[i], func, data);
    }
}

typedef struct {
    const Window *const target; // Window to search for (set at init.)
    Window *first; // Window passed in first callback invocation
    Window *last; // Window passed in last callback invocation
    Window *prev; // Window immediately before target (if any)
    Window *next; // Window immediately after target (if any)
    bool found; // Set to true when target is found
} WindowCallbackData;

static void find_prev_and_next(Window *window, void *ud)
{
    WindowCallbackData *data = ud;
    data->last = window;
    if (data->found) {
        if (!data->next) {
            data->next = window;
        }
        return;
    }
    if (!data->first) {
        data->first = window;
    }
    if (window == data->target) {
        data->found = true;
        return;
    }
    data->prev = window;
}

Window *prev_window(Window *window)
{
    WindowCallbackData data = {.target = window};
    frame_for_each_window(window->editor->root_frame, find_prev_and_next, &data);
    BUG_ON(!data.found);
    return data.prev ? data.prev : data.last;
}

Window *next_window(Window *window)
{
    WindowCallbackData data = {.target = window};
    frame_for_each_window(window->editor->root_frame, find_prev_and_next, &data);
    BUG_ON(!data.found);
    return data.next ? data.next : data.first;
}

void window_close(Window *window)
{
    EditorState *e = window->editor;
    if (!window->frame->parent) {
        // Don't close last window
        window_remove_views(window);
        set_view(window_open_empty_buffer(window));
        return;
    }

    WindowCallbackData data = {.target = window};
    frame_for_each_window(e->root_frame, find_prev_and_next, &data);
    BUG_ON(!data.found);
    Window *next_or_prev = data.next ? data.next : data.prev;
    BUG_ON(!next_or_prev);

    remove_frame(e, window->frame);
    e->window = NULL;
    set_view(next_or_prev->view);

    mark_everything_changed(e);
    debug_frame(e->root_frame);
}