Initial commit: X11 C code editor

This commit is contained in:
user committed 2026-11-30 22:12:00 +03:00
commit 8eae6763f6
21 files changed
+36389

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
editor
*.o
*.bak
*.tar.gz
+34
View File
@@ -0,0 +1,34 @@
code_editor/
├── editor.h
├── main.c
├── file_io.c
├── clipboard.c
├── history_search.c
├── render/
│ ├── render.h
│ ├── render_main.c (основной цикл отрисовки, строки, курсор)
│ ├── render_syntax.c (подсветка синтаксиса C)
│ └── render_ui.c (подсветка поиска/выделения, скроллбары, статус/чекбокс)
└── input/
├── input.h
├── utf8.c (работа с UTF-8 символами)
├── text_ops.c (вставка, удаление, работа с выделением)
├── keyboard.c (горячие клавиши, поиск, ввод)
└── mouse.c (клики, выделение мышью, скроллбары)
=================================================================================================
Compilation:
gcc -Wall -Wextra main.c file_io.c clipboard.c history_search.c menu.c tabs.c file_dialog.c \
render/render_main.c render/render_syntax.c render/render_ui.c \
input/utf8.c input/text_ops.c input/keyboard.c input/mouse.c \
-o editor $(pkg-config --cflags --libs x11 xft)
Run:
./editor main.c editor.h tabs.c
+59
View File
@@ -0,0 +1,59 @@
# X11 C Code Editor (UTF-8)
Минималистичный многовкладочный редактор кода на языке C с использованием чистых библиотек **X11 (Xlib)** и **Xft** (сглаженные шрифты, двойная буферизация через `Pixmap`).
## Сборка и запуск
```bash
gcc -Wall -Wextra main.c file_io.c clipboard.c history_search.c menu.c tabs.c file_dialog.c \
render/render_main.c render/render_syntax.c render/render_ui.c \
input/utf8.c input/text_ops.c input/keyboard.c input/mouse.c \
-o editor \$(pkg-config --cflags --libs x11 xft)
# Запуск (можно передать несколько файлов для открытия во вкладках)
./editor main.c editor.h
```
## Архитектура проекта
* **`editor.h`** — глобальные константы (`MAX_LINES=4096`, `MAX_LEN=1024`, `MAX_TABS=16`, размеры панелей `MENUBAR_H`, `TABBAR_H`, `GUTTER_W`, `STATUS_H`, `SCROLLBAR_W`), структуры `Editor`, `EditorTab`, `UndoStep`, `SymbolItem`, `NavPoint`, `DirEntry` и прототипы всех модулей.
* **`main.c`** — инициализация X11/XIM/XIC/Xft, палитры цветов, неблокирующий цикл событий (`XPending` + `select` с таймаутом 500 мс для мигания курсора).
* **`tabs.c`** — управление вкладками (`tabs_init`, `tabs_new`, `tabs_open_file`, `tabs_switch`, `tabs_next`, `tabs_request_close`, `tabs_request_quit`), сохранение/восстановление независимых буферов, курсоров, истории Undo/Redo и стека навигации для каждой вкладки, а также модальный диалог подтверждения закрытия несохранённых файлов (`confirm_*`).
* **`file_io.c`** — загрузка и сохранение файлов (`editor_load`, `editor_save`), управление флагом изменений `dirty`, синхронизация с заголовком окна (`*filename`) и точкой сохранения в истории (`saved_undo_level`).
* **`file_dialog.c`** — модальный всплывающий файловый менеджер (`fbrowser_*`): навигация по директориям (`..`, `[DIR]`), сортировка, фильтр ввода с клавиатуры, двойной клик мышью, прокрутка.
* **`menu.c`** — верхняя панель меню (`File`, `Edit`, `Navigation`), выпадающие списки, парсер объявлений C-функций (`menu_refresh_symbols`), подменю «Список функций», переход по `Ctrl + клик` и стек навигации `Назад` / `Вперед`.
* **`history_search.c`** — стек отмены/повтора (`Undo`/`Redo` до 128 шагов) с отслеживанием возврата к сохранённому состоянию, поиск подстроки вперёд и назад (`search_find_next`, `search_find_prev`).
* **`clipboard.c`** — работа с системным буфером обмена X11 (`CLIPBOARD`, `UTF8_STRING`).
* **`render/`**:
* `render_main.c` — главный конвейер отрисовки в `backbuf` и копирование на экран (`XCopyArea`).
* `render_syntax.c` — подсветка синтаксиса C (ключевые слова, типы, числа, строки, директивы `#`, однострочные `//` и многострочные `/* */` комментарии).
* `render_ui.c` — отрисовка скроллбаров с кнопками-стрелками (`▲`, `▼`, `◄`, `►`, эффект наведения и нажатия), кнопки сворачивания статус-бара на уровне горизонтального скроллбара и панели поиска.
* **`input/`**:
* `utf8.c` — посимвольная навигация и подсчёт ширины многобайтовых символов UTF-8.
* `text_ops.c` — выделение текста, удаление выделения, автопрокрутка к курсору, автоотступ при `Enter` (включая `+4` пробела после `{`), блочный отступ `Tab` / `Shift+Tab`.
* `keyboard.c` — обработка нажатий клавиш, горячих клавиш и режимов ввода.
* `mouse.c` — клики и выделение мышью, перетаскивание ползунков, смена системного курсора на руку (`XC_hand2`) при наведении на кнопки UI, вкладки и ссылки на функции.
## Реализованный функционал и горячие клавиши
* **Вкладки и файлы**:
* `Ctrl + N` или кнопка `+` — новая вкладка
* `Ctrl + O` или `File → Open...` — всплывающий файловый менеджер
* `Ctrl + S` или `File → Save` — сохранить текущий файл
* `Ctrl + W` или кнопка `×` — закрыть вкладку (с подтверждением, если есть несохранённые изменения)
* `Ctrl + Tab` / `Ctrl + Shift + Tab` — переключение между вкладками
* `Ctrl + Q` или `File → Quit` — выход (с проверкой всех вкладок на несохранённые изменения)
* **Редактирование и буфер обмена**:
* `Ctrl + Z` / `Ctrl + Y` (или `Ctrl + Shift + Z`) — отмена и повтор действий
* `Ctrl + C` / `Ctrl + X` / `Ctrl + V` / `Ctrl + A` — копировать, вырезать, вставить, выделить всё
* `Tab` / `Shift + Tab` — отступ / уменьшение отступа (для строки или выделенного блока)
* Автоотступ при нажатии `Enter`
* **Поиск и навигация**:
* `Ctrl + F` — панель поиска в статус-баре (`Enter` — далее, `Shift + Enter` — назад, чекбокс `All` — подсветка всех совпадений, `Esc` — закрыть)
* `F3` / `Shift + F3` — следующее / предыдущее совпадение
* `Ctrl + наведение и клик` по имени функции — переход к её определению
* `Alt + Left` / `Alt + Right` — навигация назад и вперёд по истории переходов
* **Интерфейс**:
* Сворачиваемый статус-бар (кнопка со стрелкой в левом нижнем углу на уровне горизонтального скроллбара)
* Скроллбары с кнопками пошаговой прокрутки (на 1 строку / 1 символ)
* Индикация несохранённых изменений (`*` и красный цвет имени файла на вкладке)
+115
View File
@@ -0,0 +1,115 @@
#include "editor.h"
#include <X11/Xatom.h>
#include <stdlib.h>
#include <string.h>
void clipboard_init(Editor *ed) {
ed->atom_clipboard = XInternAtom(ed->dpy, "CLIPBOARD", False);
ed->atom_utf8 = XInternAtom(ed->dpy, "UTF8_STRING", False);
ed->atom_targets = XInternAtom(ed->dpy, "TARGETS", False);
ed->atom_prop = XInternAtom(ed->dpy, "X11_EDITOR_CLIP", False);
ed->clip_data = NULL;
}
void clipboard_copy(Editor *ed) {
if (!ed->has_sel) return;
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
if (sy == ey && sx == ex) return;
size_t total_size = 1;
for (int y = sy; y <= ey; y++) {
int line_len = (int)strlen(ed->lines[y]);
int a = (y == sy) ? sx : 0;
int b = (y == ey) ? ex : line_len;
if (b > a) total_size += (size_t)(b - a);
if (y < ey) total_size += 1;
}
char *buf = malloc(total_size);
if (!buf) return;
size_t pos = 0;
for (int y = sy; y <= ey; y++) {
int line_len = (int)strlen(ed->lines[y]);
int a = (y == sy) ? sx : 0;
int b = (y == ey) ? ex : line_len;
if (b > a) {
memcpy(buf + pos, &ed->lines[y][a], (size_t)(b - a));
pos += (size_t)(b - a);
}
if (y < ey) {
buf[pos++] = '\n';
}
}
buf[pos] = '\0';
free(ed->clip_data);
ed->clip_data = buf;
XSetSelectionOwner(ed->dpy, ed->atom_clipboard, ed->win, CurrentTime);
XSetSelectionOwner(ed->dpy, XA_PRIMARY, ed->win, CurrentTime);
XFlush(ed->dpy);
}
void clipboard_request_paste(Editor *ed) {
XConvertSelection(ed->dpy, ed->atom_clipboard, ed->atom_utf8,
ed->atom_prop, ed->win, CurrentTime);
XFlush(ed->dpy);
}
void clipboard_handle_selection_request(Editor *ed, XSelectionRequestEvent *req) {
XSelectionEvent resp;
memset(&resp, 0, sizeof(resp));
resp.type = SelectionNotify;
resp.requestor = req->requestor;
resp.selection = req->selection;
resp.target = req->target;
resp.time = req->time;
resp.property = None;
if (ed->clip_data && req->property != None) {
if (req->target == ed->atom_targets) {
Atom targets[2];
targets[0] = ed->atom_utf8;
targets[1] = XA_STRING;
XChangeProperty(ed->dpy, req->requestor, req->property, XA_ATOM, 32,
PropModeReplace, (unsigned char *)targets, 2);
resp.property = req->property;
} else if (req->target == ed->atom_utf8 || req->target == XA_STRING) {
XChangeProperty(ed->dpy, req->requestor, req->property, req->target, 8,
PropModeReplace, (unsigned char *)ed->clip_data,
(int)strlen(ed->clip_data));
resp.property = req->property;
}
}
XSendEvent(ed->dpy, req->requestor, False, 0, (XEvent *)&resp);
XFlush(ed->dpy);
}
void clipboard_handle_selection_notify(Editor *ed, XSelectionEvent *sev) {
if (sev->property == None) return;
Atom actual_type;
int actual_format;
unsigned long nitems, bytes_after;
unsigned char *data = NULL;
if (XGetWindowProperty(ed->dpy, ed->win, sev->property, 0, 1024 * 1024, True,
AnyPropertyType, &actual_type, &actual_format,
&nitems, &bytes_after, &data) == Success && data) {
if (nitems > 0) {
char *text = malloc(nitems + 1);
if (text) {
memcpy(text, data, nitems);
text[nitems] = '\0';
if (ed->has_sel) editor_delete_selection(ed);
editor_insert_text(ed, text);
free(text);
}
}
XFree(data);
}
}
+286
View File
@@ -0,0 +1,286 @@
#ifndef EDITOR_H
#define EDITOR_H
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/cursorfont.h>
#include <X11/Xft/Xft.h>
#define MAX_LINES 4096
#define MAX_LEN 1024
#define FNAME_LEN 256
#define STATUS_LEN 512
#define SEARCH_LEN 256
#define MAX_UNDO 128
#define MAX_SYMBOLS 512
#define SYM_NAME_LEN 64
#define MAX_NAV_HISTORY 64
#define MAX_TABS 16
#define MAX_DIR_ENTRIES 1024
#define MENUBAR_H 26
#define TABBAR_H 26
#define TOP_UI_H (MENUBAR_H + TABBAR_H)
#define GUTTER_W 52
#define STATUS_H 24
#define SCROLLBAR_W 14
typedef struct {
char (*lines)[MAX_LEN];
int num_lines;
int cx, cy;
} UndoStep;
typedef struct {
char name[SYM_NAME_LEN];
int line;
} SymbolItem;
typedef struct {
int cx, cy;
} NavPoint;
typedef struct {
char name[FNAME_LEN];
int is_dir;
} DirEntry;
typedef struct {
char (*lines)[MAX_LEN];
int num_lines;
int cx, cy;
int scroll_x, scroll_y;
int has_sel, sel_ax, sel_ay;
UndoStep undo_stack[MAX_UNDO];
int undo_count;
UndoStep redo_stack[MAX_UNDO];
int redo_count;
NavPoint nav_back[MAX_NAV_HISTORY];
int nav_back_count;
NavPoint nav_fwd[MAX_NAV_HISTORY];
int nav_fwd_count;
int dirty;
int saved_undo_level;
char filename[FNAME_LEN];
} EditorTab;
typedef struct {
Display *dpy;
int screen;
Window win;
Cursor cursor_hand;
int cursor_is_hand;
int hover_btn;
int pressed_btn;
GC gc;
Pixmap backbuf;
int win_w, win_h;
int running;
XIM xim;
XIC xic;
XftFont *font;
XftDraw *xft_draw;
int char_w;
int line_h;
unsigned long col_bg;
unsigned long col_gutter;
unsigned long col_curline;
unsigned long col_sel;
unsigned long col_match_all;
unsigned long col_match_cur;
unsigned long col_fg;
unsigned long col_status;
unsigned long col_sb_track;
unsigned long col_sb_thumb;
XftColor xft_fg;
XftColor xft_lineno;
XftColor xft_kw;
XftColor xft_type;
XftColor xft_num;
XftColor xft_str;
XftColor xft_com;
XftColor xft_mcom;
XftColor xft_prep;
XftColor xft_link;
/* Вкладки документов */
EditorTab tabs[MAX_TABS];
int num_tabs;
int active_tab;
int hover_tab;
int hover_tab_close;
/* Активный документ (рабочий буфер) */
char lines[MAX_LINES][MAX_LEN];
int num_lines;
int cx, cy;
int scroll_x, scroll_y;
/* Главное меню и Navigation -> Список функций */
int menu_open;
int menu_sub_open;
int menu_hover_item;
int menu_hover_sym;
int menu_sym_scroll;
SymbolItem symbols[MAX_SYMBOLS];
int num_symbols;
/* Подсветка функции по Ctrl + наведение */
int hover_sym_line;
int hover_sym_sx;
int hover_sym_ex;
int hover_sym_target;
/* Стек навигации (Назад / Вперед) */
NavPoint nav_back[MAX_NAV_HISTORY];
int nav_back_count;
NavPoint nav_fwd[MAX_NAV_HISTORY];
int nav_fwd_count;
/* Выделение текста */
int has_sel;
int sel_ax, sel_ay;
int drag_select;
/* Буфер обмена X11 */
Atom atom_clipboard;
Atom atom_utf8;
Atom atom_targets;
Atom atom_prop;
char *clip_data;
/* История Undo/Redo */
UndoStep undo_stack[MAX_UNDO];
int undo_count;
UndoStep redo_stack[MAX_UNDO];
int redo_count;
/* Поиск по тексту */
int search_mode;
int search_highlight_all;
char search_query[SEARCH_LEN];
int chk_x1, chk_x2;
/* Всплывающий файловый менеджер */
int fbrowser_open;
char fb_cwd[FNAME_LEN * 2];
char fb_filter[64];
DirEntry fb_entries[MAX_DIR_ENTRIES];
int fb_count;
int fb_selected;
int fb_scroll;
int fb_hover_btn; /* 0: Открыть, 1: Отмена, 2: Вверх (..) */
int fb_last_click_idx;
Time fb_last_click_time;
/* Диалог подтверждения закрытия (0: нет, 1: закрыть вкладку, 2: выход) */
int confirm_mode;
int confirm_target_tab;
int confirm_hover_btn;
/* Сворачивание статус-бара */
int status_collapsed;
/* Состояние файла и мигание курсора */
int dirty;
int saved_undo_level;
int cursor_visible;
int drag_vscroll;
int drag_hscroll;
int drag_offset;
char filename[FNAME_LEN];
char status_msg[STATUS_LEN];
} Editor;
static inline int editor_status_h(const Editor *ed) {
return ed->status_collapsed ? 0 : STATUS_H;
}
/* UTF-8 утилиты (input/utf8.c) */
int utf8_char_count(const char *s, int max_bytes);
int utf8_byte_offset(const char *s, int char_idx);
int utf8_prev_char_pos(const char *s, int byte_pos);
int utf8_next_char_pos(const char *s, int byte_pos);
/* Выделение и вставка (input/text_ops.c) */
void editor_ensure_cursor_visible(Editor *ed);
void editor_get_sel_bounds(const Editor *ed, int *sy, int *sx, int *ey, int *ex);
void editor_delete_selection(Editor *ed);
void editor_insert_text(Editor *ed, const char *text);
/* file_io.c */
void editor_set_dirty(Editor *ed, int dirty);
void editor_load(Editor *ed, const char *fname);
void editor_save(Editor *ed);
void editor_open_system_dialog(Editor *ed);
int editor_max_line_len(const Editor *ed);
/* tabs.c */
void tabs_init(Editor *ed, int argc, char *argv[]);
void tabs_new(Editor *ed, const char *fname);
void tabs_open_file(Editor *ed, const char *fname);
void tabs_switch(Editor *ed, int idx);
void tabs_next(Editor *ed, int prev);
void tabs_request_close(Editor *ed, int idx);
void tabs_request_quit(Editor *ed);
void tabs_close_force(Editor *ed, int idx);
void tabs_free_all(Editor *ed);
void tabs_render(Editor *ed);
int tabs_handle_click(Editor *ed, int mx, int my, int button);
int tabs_handle_motion(Editor *ed, int mx, int my);
void confirm_render(Editor *ed);
int confirm_handle_click(Editor *ed, int mx, int my);
int confirm_handle_motion(Editor *ed, int mx, int my);
void confirm_handle_key(Editor *ed, KeySym ks);
/* file_dialog.c */
void fbrowser_show(Editor *ed);
void fbrowser_render(Editor *ed);
int fbrowser_handle_click(Editor *ed, int mx, int my, int button, Time time);
int fbrowser_handle_motion(Editor *ed, int mx, int my);
void fbrowser_handle_key(Editor *ed, KeySym ks, int ctrl, const char *buf, int n);
/* render/render_main.c */
void editor_render(Editor *ed);
/* input/keyboard.c & input/mouse.c */
void editor_handle_key(Editor *ed, XKeyEvent *kev);
void editor_handle_button_press(Editor *ed, XButtonEvent *bev);
void editor_handle_motion(Editor *ed, XMotionEvent *mev);
void editor_handle_button_release(Editor *ed, XButtonEvent *bev);
int mouse_update_cursor(Editor *ed, int mx, int my, unsigned int state);
/* clipboard.c */
void clipboard_init(Editor *ed);
void clipboard_copy(Editor *ed);
void clipboard_request_paste(Editor *ed);
void clipboard_handle_selection_request(Editor *ed, XSelectionRequestEvent *req);
void clipboard_handle_selection_notify(Editor *ed, XSelectionEvent *sev);
/* history_search.c */
void history_push_undo(Editor *ed);
void history_undo(Editor *ed);
void history_redo(Editor *ed);
void history_free_all(Editor *ed);
void search_find_next(Editor *ed, int from_cur_pos);
void search_find_prev(Editor *ed);
/* menu.c */
void menu_init(Editor *ed);
void menu_refresh_symbols(Editor *ed);
int menu_goto_symbol_at_cursor(Editor *ed);
int menu_update_hover_symbol(Editor *ed, int mx, int my, unsigned int state);
void nav_go_back(Editor *ed);
void nav_go_forward(Editor *ed);
void menu_render(Editor *ed);
int menu_handle_click(Editor *ed, int mx, int my, int button);
int menu_handle_motion(Editor *ed, int mx, int my);
#endif
+395
View File
@@ -0,0 +1,395 @@
#include "editor.h"
#include <ctype.h>
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#define FB_W 560
#define FB_H 400
#define FB_ROW_H 24
#define FB_VIS_ROWS 11
static int cmp_entries(const void *a, const void *b) {
const DirEntry *ea = (const DirEntry *)a;
const DirEntry *eb = (const DirEntry *)b;
if (strcmp(ea->name, "..") == 0) return -1;
if (strcmp(eb->name, "..") == 0) return 1;
if (ea->is_dir != eb->is_dir) return eb->is_dir - ea->is_dir;
return strcasecmp(ea->name, eb->name);
}
static int str_contains_icase(const char *haystack, const char *needle) {
if (!needle || !*needle) return 1;
size_t nlen = strlen(needle);
for (const char *p = haystack; *p; p++) {
size_t i = 0;
while (i < nlen && p[i] &&
tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) {
i++;
}
if (i == nlen) return 1;
}
return 0;
}
static void fbrowser_reload_dir(Editor *ed) {
ed->fb_count = 0;
ed->fb_selected = 0;
ed->fb_scroll = 0;
DIR *dir = opendir(ed->fb_cwd);
if (!dir) return;
/* Всегда добавляем выход на уровень вверх '..' */
strcpy(ed->fb_entries[ed->fb_count].name, "..");
ed->fb_entries[ed->fb_count].is_dir = 1;
ed->fb_count++;
struct dirent *ent;
while ((ent = readdir(dir)) != NULL && ed->fb_count < MAX_DIR_ENTRIES) {
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
if (!str_contains_icase(ent->d_name, ed->fb_filter)) continue;
char full[FNAME_LEN * 3];
snprintf(full, sizeof(full), "%s/%s", ed->fb_cwd, ent->d_name);
struct stat st;
int is_d = (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) ? 1 : 0;
snprintf(ed->fb_entries[ed->fb_count].name, FNAME_LEN, "%s", ent->d_name);
ed->fb_entries[ed->fb_count].is_dir = is_d;
ed->fb_count++;
}
closedir(dir);
if (ed->fb_count > 1) {
qsort(&ed->fb_entries[1], (size_t)(ed->fb_count - 1), sizeof(DirEntry), cmp_entries);
}
}
static void fbrowser_ensure_visible(Editor *ed) {
if (ed->fb_selected < 0) ed->fb_selected = 0;
if (ed->fb_selected >= ed->fb_count) ed->fb_selected = ed->fb_count - 1;
if (ed->fb_selected < ed->fb_scroll) ed->fb_scroll = ed->fb_selected;
if (ed->fb_selected >= ed->fb_scroll + FB_VIS_ROWS) {
ed->fb_scroll = ed->fb_selected - FB_VIS_ROWS + 1;
}
if (ed->fb_scroll < 0) ed->fb_scroll = 0;
}
static void fbrowser_change_dir(Editor *ed, const char *sub) {
char next_path[FNAME_LEN * 3];
if (strcmp(sub, "..") == 0) {
snprintf(next_path, sizeof(next_path), "%s/..", ed->fb_cwd);
} else {
snprintf(next_path, sizeof(next_path), "%s/%s", ed->fb_cwd, sub);
}
char resolved[PATH_MAX];
if (realpath(next_path, resolved)) {
snprintf(ed->fb_cwd, sizeof(ed->fb_cwd), "%.511s", resolved);
*ed->fb_filter = '\0';
fbrowser_reload_dir(ed);
}
}
static void fbrowser_activate_selected(Editor *ed) {
if (ed->fb_selected < 0 || ed->fb_selected >= ed->fb_count) return;
DirEntry *item = &ed->fb_entries[ed->fb_selected];
if (item->is_dir) {
fbrowser_change_dir(ed, item->name);
} else {
char full_path[FNAME_LEN * 3];
char cwd_now[PATH_MAX];
if (getcwd(cwd_now, sizeof(cwd_now)) && strcmp(cwd_now, ed->fb_cwd) == 0) {
snprintf(full_path, sizeof(full_path), "%s", item->name);
} else {
snprintf(full_path, sizeof(full_path), "%s/%s", ed->fb_cwd, item->name);
}
ed->fbrowser_open = 0;
tabs_open_file(ed, full_path);
}
}
void fbrowser_show(Editor *ed) {
ed->fbrowser_open = 1;
ed->fb_hover_btn = -1;
ed->fb_last_click_idx = -1;
ed->fb_filter[0] = '\0';
if (ed->fb_cwd[0] == '\0') {
if (!getcwd(ed->fb_cwd, sizeof(ed->fb_cwd))) {
strcpy(ed->fb_cwd, ".");
}
}
fbrowser_reload_dir(ed);
}
void fbrowser_render(Editor *ed) {
if (!ed->fbrowser_open) return;
int dx = (ed->win_w - FB_W) / 2;
int dy = (ed->win_h - FB_H) / 2;
/* Основное окно и рамка */
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx, dy, FB_W, FB_H);
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, dx, dy, FB_W - 1, FB_H - 1);
/* Шапка окна */
XSetForeground(ed->dpy, ed->gc, ed->col_status);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx + 1, dy + 1, FB_W - 2, 26);
const char *title = "Открыть файл (Enter: Открыть | Backspace: Вверх | Esc: Закрыть)";
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 10, dy + 18,
(const FcChar8 *)title, (int)strlen(title));
/* Полоса текущего пути + кнопка "Вверх" */
int path_y = dy + 32;
int up_x = dx + 10, up_w = 34, up_h = 22;
XSetForeground(ed->dpy, ed->gc, (ed->fb_hover_btn == 2) ? ed->col_match_cur : ed->col_status);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, up_x, path_y, up_w, up_h);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, up_x, path_y, up_w - 1, up_h - 1);
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, up_x + 9, path_y + 16,
(const FcChar8 *)"..", 2);
int pbox_x = up_x + up_w + 6;
int pbox_w = FB_W - 20 - up_w - 6;
XSetForeground(ed->dpy, ed->gc, ed->col_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, pbox_x, path_y, pbox_w, up_h);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, pbox_x, path_y, pbox_w - 1, up_h - 1);
char path_disp[FNAME_LEN * 2];
int max_pchars = (pbox_w - 12) / ed->char_w;
int clen = (int)strlen(ed->fb_cwd);
if (clen > max_pchars && max_pchars > 3) {
snprintf(path_disp, sizeof(path_disp), "...%.508s", &ed->fb_cwd[clen - max_pchars + 3]);
} else {
snprintf(path_disp, sizeof(path_disp), "%.511s", ed->fb_cwd);
}
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, pbox_x + 6, path_y + 16,
(const FcChar8 *)path_disp, (int)strlen(path_disp));
/* Список файлов и папок */
int list_x = dx + 10;
int list_y = dy + 60;
int list_w = FB_W - 20;
int list_h = FB_VIS_ROWS * FB_ROW_H;
XSetForeground(ed->dpy, ed->gc, ed->col_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, list_x, list_y, list_w, list_h);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, list_x, list_y, list_w - 1, list_h - 1);
int max_name_chars = (list_w - 80) / ed->char_w;
if (max_name_chars < 1) max_name_chars = 1;
for (int i = 0; i < FB_VIS_ROWS; i++) {
int idx = ed->fb_scroll + i;
if (idx >= ed->fb_count) break;
int ry = list_y + i * FB_ROW_H;
int base_y = ry + (FB_ROW_H + ed->font->ascent - ed->font->descent) / 2;
if (idx == ed->fb_selected) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_cur);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, list_x + 1, ry + 1, list_w - 14, FB_ROW_H - 1);
} else if (i % 2 == 1) {
XSetForeground(ed->dpy, ed->gc, ed->col_curline);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, list_x + 1, ry + 1, list_w - 14, FB_ROW_H - 1);
}
DirEntry *ent = &ed->fb_entries[idx];
if (ent->is_dir) {
XftDrawStringUtf8(ed->xft_draw, &ed->xft_kw, ed->font, list_x + 8, base_y,
(const FcChar8 *)"[DIR]", 5);
} else {
XftDrawStringUtf8(ed->xft_draw, &ed->xft_lineno, ed->font, list_x + 8, base_y,
(const FcChar8 *)" ", 5);
}
char nbuf[FNAME_LEN];
snprintf(nbuf, sizeof(nbuf), "%s", ent->name);
if ((int)strlen(nbuf) > max_name_chars) nbuf[max_name_chars] = '\0';
XftColor *ncol = ent->is_dir ? &ed->xft_link : &ed->xft_fg;
XftDrawStringUtf8(ed->xft_draw, ncol, ed->font, list_x + 56, base_y,
(const FcChar8 *)nbuf, (int)strlen(nbuf));
}
/* Полоса прокрутки списка */
if (ed->fb_count > FB_VIS_ROWS) {
int sb_x = list_x + list_w - 11;
XSetForeground(ed->dpy, ed->gc, ed->col_sb_track);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, sb_x, list_y + 1, 10, list_h - 2);
int th = ((list_h - 2) * FB_VIS_ROWS) / ed->fb_count;
if (th < 16) th = 16;
int max_sc = ed->fb_count - FB_VIS_ROWS;
int ty = list_y + 1 + (ed->fb_scroll * (list_h - 2 - th)) / max_sc;
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, sb_x + 1, ty, 8, th);
}
/* Нижняя панель: фильтр и кнопки [Открыть] / [Отмена] */
int bot_y = dy + FB_H - 38;
char flt[128];
snprintf(flt, sizeof(flt), "Фильтр: %s_", ed->fb_filter);
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 12, bot_y + 19,
(const FcChar8 *)flt, (int)strlen(flt));
const char *btns[2] = {"Открыть", "Отмена"};
int bw = 104, bh = 26, gap = 10;
int bx0 = dx + FB_W - 10 - (bw * 2 + gap);
for (int i = 0; i < 2; i++) {
int bx = bx0 + i * (bw + gap);
unsigned long bbg = (ed->fb_hover_btn == i) ? ed->col_match_cur : ed->col_status;
XSetForeground(ed->dpy, ed->gc, bbg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, bx, bot_y, bw, bh);
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, bx, bot_y, bw - 1, bh - 1);
int tlen = (int)strlen(btns[i]);
int tcols = utf8_char_count(btns[i], tlen);
int tx = bx + (bw - tcols * ed->char_w) / 2;
int ty = bot_y + (bh + ed->font->ascent - ed->font->descent) / 2;
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, tx, ty,
(const FcChar8 *)btns[i], tlen);
}
}
int fbrowser_handle_motion(Editor *ed, int mx, int my) {
if (!ed->fbrowser_open) return 0;
int old = ed->fb_hover_btn;
ed->fb_hover_btn = -1;
int dx = (ed->win_w - FB_W) / 2;
int dy = (ed->win_h - FB_H) / 2;
/* Кнопка '..' */
int up_x = dx + 10, up_y = dy + 32, up_w = 34, up_h = 22;
if (mx >= up_x && mx < up_x + up_w && my >= up_y && my < up_y + up_h) {
ed->fb_hover_btn = 2;
return (old != ed->fb_hover_btn);
}
/* Кнопки [Открыть] / [Отмена] */
int bot_y = dy + FB_H - 38;
int bw = 104, bh = 26, gap = 10;
int bx0 = dx + FB_W - 10 - (bw * 2 + gap);
if (my >= bot_y && my < bot_y + bh) {
for (int i = 0; i < 2; i++) {
int bx = bx0 + i * (bw + gap);
if (mx >= bx && mx < bx + bw) {
ed->fb_hover_btn = i;
break;
}
}
}
return (old != ed->fb_hover_btn);
}
int fbrowser_handle_click(Editor *ed, int mx, int my, int button, Time time) {
if (!ed->fbrowser_open) return 0;
int dx = (ed->win_w - FB_W) / 2;
int dy = (ed->win_h - FB_H) / 2;
int list_x = dx + 10;
int list_y = dy + 60;
int list_w = FB_W - 20;
int list_h = FB_VIS_ROWS * FB_ROW_H;
/* Прокрутка списка колесиком */
if (button == Button4) {
ed->fb_scroll -= 2;
if (ed->fb_scroll < 0) ed->fb_scroll = 0;
return 1;
}
if (button == Button5) {
int max_sc = ed->fb_count - FB_VIS_ROWS;
if (max_sc < 0) max_sc = 0;
ed->fb_scroll += 2;
if (ed->fb_scroll > max_sc) ed->fb_scroll = max_sc;
return 1;
}
if (button != Button1) return 1;
fbrowser_handle_motion(ed, mx, my);
if (ed->fb_hover_btn == 2) {
fbrowser_change_dir(ed, "..");
return 1;
}
if (ed->fb_hover_btn == 0) {
fbrowser_activate_selected(ed);
return 1;
}
if (ed->fb_hover_btn == 1) {
ed->fbrowser_open = 0;
return 1;
}
/* Клик по строке списка */
if (mx >= list_x && mx < list_x + list_w && my >= list_y && my < list_y + list_h) {
int idx = ed->fb_scroll + (my - list_y) / FB_ROW_H;
if (idx >= 0 && idx < ed->fb_count) {
int is_double = (idx == ed->fb_last_click_idx && (time - ed->fb_last_click_time) < 400);
ed->fb_selected = idx;
ed->fb_last_click_idx = idx;
ed->fb_last_click_time = time;
if (is_double) {
fbrowser_activate_selected(ed);
}
}
}
return 1;
}
void fbrowser_handle_key(Editor *ed, KeySym ks, int ctrl, const char *buf, int n) {
if (!ed->fbrowser_open) return;
if (ks == XK_Escape || (ctrl && (ks == XK_o || ks == XK_O))) {
ed->fbrowser_open = 0;
return;
}
if (ks == XK_Return || ks == XK_KP_Enter) {
fbrowser_activate_selected(ed);
return;
}
if (ks == XK_Up) {
if (ed->fb_selected > 0) ed->fb_selected--;
fbrowser_ensure_visible(ed);
return;
}
if (ks == XK_Down) {
if (ed->fb_selected < ed->fb_count - 1) ed->fb_selected++;
fbrowser_ensure_visible(ed);
return;
}
if (ks == XK_Prior) {
ed->fb_selected -= FB_VIS_ROWS;
fbrowser_ensure_visible(ed);
return;
}
if (ks == XK_Next) {
ed->fb_selected += FB_VIS_ROWS;
fbrowser_ensure_visible(ed);
return;
}
if (ks == XK_BackSpace) {
int flen = (int)strlen(ed->fb_filter);
if (flen > 0) {
int prev = utf8_prev_char_pos(ed->fb_filter, flen);
ed->fb_filter[prev] = '\0';
fbrowser_reload_dir(ed);
} else {
fbrowser_change_dir(ed, "..");
}
return;
}
if (n > 0 && !ctrl && (unsigned char)(*buf) >= 32 && (unsigned char)(*buf) != 127) {
int flen = (int)strlen(ed->fb_filter);
if (flen + n < (int)sizeof(ed->fb_filter) - 1) {
memcpy(&ed->fb_filter[flen], buf, (size_t)n);
ed->fb_filter[flen + n] = '\0';
fbrowser_reload_dir(ed);
}
}
}
+113
View File
@@ -0,0 +1,113 @@
#include "editor.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void editor_set_dirty(Editor *ed, int dirty) {
ed->dirty = dirty;
if (!dirty) {
ed->saved_undo_level = ed->undo_count;
}
if (ed->active_tab >= 0 && ed->active_tab < ed->num_tabs) {
ed->tabs[ed->active_tab].dirty = dirty;
ed->tabs[ed->active_tab].saved_undo_level = ed->saved_undo_level;
snprintf(ed->tabs[ed->active_tab].filename, sizeof(ed->tabs[ed->active_tab].filename), "%s", ed->filename);
}
if (ed->dpy && ed->win) {
char title[FNAME_LEN + 64];
snprintf(title, sizeof(title), "%s%s - X11 C Code Editor",
ed->dirty ? "*" : "", ed->filename);
XStoreName(ed->dpy, ed->win, title);
}
}
void editor_save(Editor *ed) {
FILE *fp = fopen(ed->filename, "w");
if (!fp) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Save error: %s", ed->filename);
return;
}
for (int i = 0; i < ed->num_lines; i++) {
fprintf(fp, "%s\n", ed->lines[i]);
}
fclose(fp);
editor_set_dirty(ed, 0);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Saved: %s (%d lines)", ed->filename, ed->num_lines);
}
void editor_load(Editor *ed, const char *fname) {
snprintf(ed->filename, sizeof(ed->filename), "%s", fname);
FILE *fp = fopen(fname, "r");
if (!fp) {
ed->num_lines = 1;
**ed->lines = '\0';
editor_set_dirty(ed, 0);
snprintf(ed->status_msg, sizeof(ed->status_msg), "New file: %s", fname);
return;
}
ed->num_lines = 0;
while (ed->num_lines < MAX_LINES && fgets(ed->lines[ed->num_lines], MAX_LEN, fp)) {
size_t len = strlen(ed->lines[ed->num_lines]);
while (len > 0 && (ed->lines[ed->num_lines][len - 1] == '\n' || ed->lines[ed->num_lines][len - 1] == '\r')) {
ed->lines[ed->num_lines][--len] = '\0';
}
ed->num_lines++;
}
fclose(fp);
if (ed->num_lines == 0) {
ed->num_lines = 1;
**ed->lines = '\0';
}
editor_set_dirty(ed, 0);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Loaded: %s (%d lines)", fname, ed->num_lines);
}
int editor_max_line_len(const Editor *ed) {
int max_c = 0;
for (int i = 0; i < ed->num_lines; i++) {
int c = utf8_char_count(ed->lines[i], (int)strlen(ed->lines[i]));
if (c > max_c) max_c = c;
}
return max_c;
}
void editor_open_system_dialog(Editor *ed) {
int has_zenity = (system("command -v zenity >/dev/null 2>&1") == 0);
int has_kdialog = !has_zenity && (system("command -v kdialog >/dev/null 2>&1") == 0);
if (!has_zenity && !has_kdialog) {
ed->status_collapsed = 0;
snprintf(ed->status_msg, sizeof(ed->status_msg),
"zenity/kdialog не установлены. Используйте File -> Open... (Ctrl+O)");
return;
}
const char *cmd = has_zenity
? "zenity --file-selection --title='Open File' 2>/dev/null"
: "kdialog --getopenfilename . 2>/dev/null";
FILE *fp = popen(cmd, "r");
if (!fp) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Ошибка запуска системного диалога");
return;
}
char path[FNAME_LEN * 2] = {0};
char *res = fgets(path, sizeof(path), fp);
pclose(fp);
if (res) {
size_t len = strlen(path);
while (len > 0 && (path[len - 1] == '\n' || path[len - 1] == '\r')) {
path[--len] = '\0';
}
if (len > 0) {
tabs_open_file(ed, path);
return;
}
}
snprintf(ed->status_msg, sizeof(ed->status_msg), "Открытие файла отменено");
}
+191
View File
@@ -0,0 +1,191 @@
#include "editor.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void free_step(UndoStep *step) {
free(step->lines);
step->lines = NULL;
step->num_lines = 0;
}
static int save_state_to_step(const Editor *ed, UndoStep *step) {
size_t bytes = (size_t)ed->num_lines * MAX_LEN;
step->lines = malloc(bytes);
if (!step->lines) return 0;
memcpy(step->lines, ed->lines, bytes);
step->num_lines = ed->num_lines;
step->cx = ed->cx;
step->cy = ed->cy;
return 1;
}
static void restore_state_from_step(Editor *ed, const UndoStep *step) {
if (!step->lines) return;
memcpy(ed->lines, step->lines, (size_t)step->num_lines * MAX_LEN);
ed->num_lines = step->num_lines;
ed->cx = step->cx;
ed->cy = step->cy;
ed->has_sel = 0;
editor_ensure_cursor_visible(ed);
}
void history_push_undo(Editor *ed) {
for (int i = 0; i < ed->redo_count; i++) {
free_step(&ed->redo_stack[i]);
}
ed->redo_count = 0;
if (ed->undo_count < ed->saved_undo_level) {
ed->saved_undo_level = -1;
}
if (ed->undo_count >= MAX_UNDO) {
free_step(ed->undo_stack);
memmove(ed->undo_stack, ed->undo_stack + 1, (MAX_UNDO - 1) * sizeof(UndoStep));
ed->undo_count = MAX_UNDO - 1;
if (ed->saved_undo_level > 0) ed->saved_undo_level--;
else ed->saved_undo_level = -1;
}
if (save_state_to_step(ed, &ed->undo_stack[ed->undo_count])) {
ed->undo_count++;
}
editor_set_dirty(ed, 1);
}
void history_undo(Editor *ed) {
if (ed->undo_count <= 0) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Nothing to undo");
return;
}
if (ed->redo_count >= MAX_UNDO) {
free_step(ed->redo_stack);
memmove(ed->redo_stack, ed->redo_stack + 1, (MAX_UNDO - 1) * sizeof(UndoStep));
ed->redo_count = MAX_UNDO - 1;
}
if (save_state_to_step(ed, &ed->redo_stack[ed->redo_count])) {
ed->redo_count++;
}
ed->undo_count--;
restore_state_from_step(ed, &ed->undo_stack[ed->undo_count]);
free_step(&ed->undo_stack[ed->undo_count]);
editor_set_dirty(ed, ed->undo_count != ed->saved_undo_level);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Undo");
}
void history_redo(Editor *ed) {
if (ed->redo_count <= 0) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Nothing to redo");
return;
}
if (ed->undo_count >= MAX_UNDO) {
free_step(ed->undo_stack);
memmove(ed->undo_stack, ed->undo_stack + 1, (MAX_UNDO - 1) * sizeof(UndoStep));
ed->undo_count = MAX_UNDO - 1;
}
if (save_state_to_step(ed, &ed->undo_stack[ed->undo_count])) {
ed->undo_count++;
}
ed->redo_count--;
restore_state_from_step(ed, &ed->redo_stack[ed->redo_count]);
free_step(&ed->redo_stack[ed->redo_count]);
editor_set_dirty(ed, ed->undo_count != ed->saved_undo_level);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Redo");
}
void history_free_all(Editor *ed) {
for (int i = 0; i < ed->undo_count; i++) free_step(&ed->undo_stack[i]);
for (int i = 0; i < ed->redo_count; i++) free_step(&ed->redo_stack[i]);
ed->undo_count = 0;
ed->redo_count = 0;
}
void search_find_next(Editor *ed, int from_cur_pos) {
int qlen = (int)strlen(ed->search_query);
if (qlen == 0) {
ed->has_sel = 0;
return;
}
int start_y = ed->cy;
int start_x = ed->cx;
if (ed->has_sel) {
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
start_y = sy;
start_x = from_cur_pos ? sx : (sx + 1);
} else if (!from_cur_pos) {
start_x = ed->cx + 1;
}
for (int pass = 0; pass < 2; pass++) {
int y_begin = (pass == 0) ? start_y : 0;
int y_end = (pass == 0) ? ed->num_lines : (start_y + 1);
for (int y = y_begin; y < y_end; y++) {
int line_len = (int)strlen(ed->lines[y]);
int x_begin = (pass == 0 && y == start_y) ? start_x : 0;
if (x_begin > line_len) continue;
const char *found = strstr(&ed->lines[y][x_begin], ed->search_query);
if (found) {
int pos = (int)(found - ed->lines[y]);
ed->has_sel = 1;
ed->sel_ay = y;
ed->sel_ax = pos;
ed->cy = y;
ed->cx = pos + qlen;
editor_ensure_cursor_visible(ed);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Found at Ln %d", y + 1);
return;
}
}
}
snprintf(ed->status_msg, sizeof(ed->status_msg), "Not found: %s", ed->search_query);
}
void search_find_prev(Editor *ed) {
int qlen = (int)strlen(ed->search_query);
if (qlen == 0) return;
int limit_y = ed->cy;
int limit_x = ed->cx;
if (ed->has_sel) {
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
limit_y = sy;
limit_x = sx;
}
for (int pass = 0; pass < 2; pass++) {
int y_begin = (pass == 0) ? limit_y : (ed->num_lines - 1);
int y_end = (pass == 0) ? 0 : limit_y;
for (int y = y_begin; y >= y_end; y--) {
int line_len = (int)strlen(ed->lines[y]);
int max_x = (pass == 0 && y == limit_y) ? (limit_x - 1) : (line_len - qlen);
if (max_x > line_len - qlen) max_x = line_len - qlen;
for (int x = max_x; x >= 0; x--) {
if (strncmp(&ed->lines[y][x], ed->search_query, (size_t)qlen) == 0) {
ed->has_sel = 1;
ed->sel_ay = y;
ed->sel_ax = x;
ed->cy = y;
ed->cx = x + qlen;
editor_ensure_cursor_visible(ed);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Found at Ln %d", y + 1);
return;
}
}
}
}
snprintf(ed->status_msg, sizeof(ed->status_msg), "Not found: %s", ed->search_query);
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef INPUT_H
#define INPUT_H
#include "../editor.h"
void input_insert_bytes(Editor *ed, const char *bytes, int count);
void input_insert_newline(Editor *ed);
void input_indent_selection(Editor *ed, int unindent);
#endif
+276
View File
@@ -0,0 +1,276 @@
#include "input.h"
#include <string.h>
#define KEY_BUF_LEN 64
static void update_selection_on_nav(Editor *ed, int shift, int old_x, int old_y) {
if (shift) {
if (!ed->has_sel) {
ed->has_sel = 1;
ed->sel_ax = old_x;
ed->sel_ay = old_y;
} else if (ed->sel_ax == ed->cx && ed->sel_ay == ed->cy) {
ed->has_sel = 0;
}
} else {
ed->has_sel = 0;
}
}
static void handle_search_key(Editor *ed, KeySym ks, int ctrl, int shift, const char *buf, int n) {
if (ks == XK_Escape || (ctrl && (ks == XK_f || ks == XK_F || ks == XK_Cyrillic_a || ks == XK_Cyrillic_A))) {
ed->search_mode = 0;
return;
}
if (ks == XK_Return || ks == XK_KP_Enter || ks == XK_F3) {
if (shift) search_find_prev(ed);
else search_find_next(ed, 0);
return;
}
if (ks == XK_BackSpace) {
int qlen = (int)strlen(ed->search_query);
if (qlen > 0) {
int prev = utf8_prev_char_pos(ed->search_query, qlen);
ed->search_query[prev] = '\0';
search_find_next(ed, 1);
}
return;
}
if (n > 0 && !ctrl && (unsigned char)(*buf) >= 32 && (unsigned char)(*buf) != 127) {
int qlen = (int)strlen(ed->search_query);
if (qlen + n < SEARCH_LEN - 1) {
memcpy(&ed->search_query[qlen], buf, (size_t)n);
ed->search_query[qlen + n] = '\0';
search_find_next(ed, 1);
}
}
}
static int handle_ctrl_shortcuts(Editor *ed, KeySym ks, int shift) {
if (ks == XK_Tab || ks == XK_ISO_Left_Tab) {
tabs_next(ed, shift || ks == XK_ISO_Left_Tab);
return 1;
}
if (ks == XK_n || ks == XK_N || ks == XK_Cyrillic_te || ks == XK_Cyrillic_TE) {
tabs_new(ed, NULL);
return 1;
}
if (ks == XK_o || ks == XK_O || ks == XK_Cyrillic_shcha || ks == XK_Cyrillic_SHCHA) {
if (shift) editor_open_system_dialog(ed);
else fbrowser_show(ed);
return 1;
}
if (ks == XK_w || ks == XK_W || ks == XK_Cyrillic_tse || ks == XK_Cyrillic_TSE) {
tabs_request_close(ed, ed->active_tab);
return 1;
}
if (ks == XK_q || ks == XK_Q || ks == XK_Cyrillic_shorti || ks == XK_Cyrillic_SHORTI) {
tabs_request_quit(ed);
return 1;
}
if (ks == XK_s || ks == XK_S || ks == XK_Cyrillic_yeru || ks == XK_Cyrillic_YERU) {
editor_save(ed);
return 1;
}
if (ks == XK_f || ks == XK_F || ks == XK_Cyrillic_a || ks == XK_Cyrillic_A) {
ed->status_collapsed = 0;
ed->search_mode = 1;
if (ed->has_sel) {
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
if (sy == ey && ex > sx) {
int clen = ex - sx;
if (clen >= SEARCH_LEN) clen = SEARCH_LEN - 1;
memcpy(ed->search_query, &ed->lines[sy][sx], (size_t)clen);
ed->search_query[clen] = '\0';
}
}
return 1;
}
if (ks == XK_z || ks == XK_Z || ks == XK_Cyrillic_ya || ks == XK_Cyrillic_YA) {
if (shift) history_redo(ed);
else history_undo(ed);
return 1;
}
if (ks == XK_y || ks == XK_Y || ks == XK_Cyrillic_en || ks == XK_Cyrillic_EN) {
history_redo(ed);
return 1;
}
if (ks == XK_a || ks == XK_A || ks == XK_Cyrillic_ef || ks == XK_Cyrillic_EF) {
ed->has_sel = 1;
ed->sel_ax = 0;
ed->sel_ay = 0;
ed->cy = ed->num_lines - 1;
ed->cx = (int)strlen(ed->lines[ed->cy]);
return 1;
}
if (ks == XK_c || ks == XK_C || ks == XK_Cyrillic_es || ks == XK_Cyrillic_ES) {
clipboard_copy(ed);
return 1;
}
if (ks == XK_x || ks == XK_X || ks == XK_Cyrillic_che || ks == XK_Cyrillic_CHE) {
if (ed->has_sel) {
clipboard_copy(ed);
history_push_undo(ed);
editor_delete_selection(ed);
editor_ensure_cursor_visible(ed);
}
return 1;
}
if (ks == XK_v || ks == XK_V || ks == XK_Cyrillic_em || ks == XK_Cyrillic_EM) {
clipboard_request_paste(ed);
return 1;
}
return 0;
}
void editor_handle_key(Editor *ed, XKeyEvent *kev) {
char buf[KEY_BUF_LEN];
memset(buf, 0, sizeof(buf));
KeySym ks = NoSymbol;
Status status;
int n = ed->xic ? Xutf8LookupString(ed->xic, kev, buf, sizeof(buf) - 1, &ks, &status)
: XLookupString(kev, buf, sizeof(buf) - 1, &ks, NULL);
int ctrl = (kev->state & ControlMask);
int shift = (kev->state & ShiftMask);
int alt = (kev->state & Mod1Mask);
if (ed->confirm_mode != 0) {
confirm_handle_key(ed, ks);
return;
}
if (ed->fbrowser_open) {
fbrowser_handle_key(ed, ks, ctrl, buf, n);
return;
}
if (ed->menu_open >= 0) {
if (ks == XK_Escape) menu_init(ed);
return;
}
if (ed->search_mode) {
handle_search_key(ed, ks, ctrl, shift, buf, n);
return;
}
if (ctrl && handle_ctrl_shortcuts(ed, ks, shift)) return;
if (alt) {
if (ks == XK_Left) {
nav_go_back(ed);
return;
}
if (ks == XK_Right) {
nav_go_forward(ed);
return;
}
}
if (ks == XK_F3) {
if (shift) search_find_prev(ed);
else search_find_next(ed, 0);
return;
}
int old_x = ed->cx, old_y = ed->cy;
if (ks == XK_Up) {
if (ed->cy > 0) {
int col = utf8_char_count(ed->lines[ed->cy], ed->cx);
ed->cy--;
ed->cx = utf8_byte_offset(ed->lines[ed->cy], col);
}
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_Down) {
if (ed->cy < ed->num_lines - 1) {
int col = utf8_char_count(ed->lines[ed->cy], ed->cx);
ed->cy++;
ed->cx = utf8_byte_offset(ed->lines[ed->cy], col);
}
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_Left) {
if (ed->cx > 0) ed->cx = utf8_prev_char_pos(ed->lines[ed->cy], ed->cx);
else if (ed->cy > 0) {
ed->cy--;
ed->cx = (int)strlen(ed->lines[ed->cy]);
}
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_Right) {
int len = (int)strlen(ed->lines[ed->cy]);
if (ed->cx < len) ed->cx = utf8_next_char_pos(ed->lines[ed->cy], ed->cx);
else if (ed->cy < ed->num_lines - 1) {
ed->cy++;
ed->cx = 0;
}
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_Home) {
ed->cx = 0;
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_End) {
ed->cx = (int)strlen(ed->lines[ed->cy]);
update_selection_on_nav(ed, shift, old_x, old_y);
} else if (ks == XK_Return || ks == XK_KP_Enter) {
history_push_undo(ed);
if (ed->has_sel) editor_delete_selection(ed);
input_insert_newline(ed);
} else if (ks == XK_BackSpace) {
if (ed->has_sel) {
history_push_undo(ed);
editor_delete_selection(ed);
} else {
int len = (int)strlen(ed->lines[ed->cy]);
if (ed->cx > 0) {
history_push_undo(ed);
int prev = utf8_prev_char_pos(ed->lines[ed->cy], ed->cx);
memmove(&ed->lines[ed->cy][prev], &ed->lines[ed->cy][ed->cx], (size_t)(len - ed->cx + 1));
ed->cx = prev;
} else if (ed->cy > 0) {
int prev_len = (int)strlen(ed->lines[ed->cy - 1]);
if (prev_len + len < MAX_LEN - 1) {
history_push_undo(ed);
strcat(ed->lines[ed->cy - 1], ed->lines[ed->cy]);
for (int i = ed->cy; i < ed->num_lines - 1; i++) strcpy(ed->lines[i], ed->lines[i + 1]);
ed->num_lines--;
ed->cy--;
ed->cx = prev_len;
}
}
}
} else if (ks == XK_Delete) {
if (ed->has_sel) {
history_push_undo(ed);
editor_delete_selection(ed);
} else {
int len = (int)strlen(ed->lines[ed->cy]);
if (ed->cx < len) {
history_push_undo(ed);
int next = utf8_next_char_pos(ed->lines[ed->cy], ed->cx);
memmove(&ed->lines[ed->cy][ed->cx], &ed->lines[ed->cy][next], (size_t)(len - next + 1));
} else if (ed->cy < ed->num_lines - 1) {
int next_len = (int)strlen(ed->lines[ed->cy + 1]);
if (len + next_len < MAX_LEN - 1) {
history_push_undo(ed);
strcat(ed->lines[ed->cy], ed->lines[ed->cy + 1]);
for (int i = ed->cy + 1; i < ed->num_lines - 1; i++) strcpy(ed->lines[i], ed->lines[i + 1]);
ed->num_lines--;
}
}
}
} else if (ks == XK_Tab || ks == XK_ISO_Left_Tab) {
int unindent = (shift || ks == XK_ISO_Left_Tab);
history_push_undo(ed);
if (ed->has_sel || unindent) {
input_indent_selection(ed, unindent);
} else {
input_insert_bytes(ed, " ", 4);
}
} else if (n > 0 && !ctrl && (unsigned char)(*buf) >= 32 && (unsigned char)(*buf) != 127) {
history_push_undo(ed);
if (ed->has_sel) editor_delete_selection(ed);
input_insert_bytes(ed, buf, n);
}
editor_ensure_cursor_visible(ed);
}
+276
View File
@@ -0,0 +1,276 @@
#include "input.h"
/* Возвращает: 0 - нет, 1 - статус-бар, 2 - вверх, 3 - вниз, 4 - влево, 5 - вправо */
static int get_hovered_ui_button(const Editor *ed, int mx, int my) {
if (ed->menu_open >= 0 || ed->confirm_mode != 0 || ed->fbrowser_open) return 0;
int st_h = editor_status_h(ed);
int v_track_x = ed->win_w - SCROLLBAR_W;
int v_full_y = TOP_UI_H;
int v_full_h = ed->win_h - TOP_UI_H - st_h - SCROLLBAR_W;
int h_track_y = ed->win_h - st_h - SCROLLBAR_W;
int h_full_x = GUTTER_W;
int h_full_w = ed->win_w - GUTTER_W - SCROLLBAR_W;
if (mx >= 0 && mx < GUTTER_W && my >= h_track_y && my < h_track_y + SCROLLBAR_W) {
return 1;
}
if (v_full_h >= SCROLLBAR_W * 2 && mx >= v_track_x && mx < ed->win_w) {
if (my >= v_full_y && my < v_full_y + SCROLLBAR_W) return 2;
if (my >= v_full_y + v_full_h - SCROLLBAR_W && my < v_full_y + v_full_h) return 3;
}
if (h_full_w >= SCROLLBAR_W * 2 && my >= h_track_y && my < h_track_y + SCROLLBAR_W) {
if (mx >= h_full_x && mx < h_full_x + SCROLLBAR_W) return 4;
if (mx >= v_track_x - SCROLLBAR_W && mx < v_track_x) return 5;
}
return 0;
}
int mouse_update_cursor(Editor *ed, int mx, int my, unsigned int state) {
(void)state;
int old_btn = ed->hover_btn;
ed->hover_btn = get_hovered_ui_button(ed, mx, my);
int want_hand = (ed->hover_sym_line >= 0) || (ed->hover_btn > 0) ||
(ed->hover_tab != -1) ||
(ed->confirm_mode != 0 && ed->confirm_hover_btn >= 0) ||
(ed->fbrowser_open && ed->fb_hover_btn >= 0);
if (want_hand && !ed->cursor_is_hand) {
XDefineCursor(ed->dpy, ed->win, ed->cursor_hand);
ed->cursor_is_hand = 1;
} else if (!want_hand && ed->cursor_is_hand) {
XUndefineCursor(ed->dpy, ed->win);
ed->cursor_is_hand = 0;
}
return (old_btn != ed->hover_btn);
}
static void set_cursor_from_mouse(Editor *ed, int mx, int my) {
int target_y = ed->scroll_y + ((my - TOP_UI_H) / ed->line_h);
if (target_y >= ed->num_lines) target_y = ed->num_lines - 1;
if (target_y < 0) target_y = 0;
ed->cy = target_y;
int target_col = ed->scroll_x + ((mx - GUTTER_W - 8 + ed->char_w / 2) / ed->char_w);
if (target_col < 0) target_col = 0;
ed->cx = utf8_byte_offset(ed->lines[ed->cy], target_col);
}
static void update_vscroll_from_mouse(Editor *ed, int my) {
int v_full_h = ed->win_h - TOP_UI_H - editor_status_h(ed) - SCROLLBAR_W;
int visible_lines = v_full_h / ed->line_h;
int max_sy = ed->num_lines - visible_lines;
if (max_sy <= 0) return;
int v_track_y = TOP_UI_H + SCROLLBAR_W;
int v_track_h = v_full_h - SCROLLBAR_W * 2;
if (v_track_h <= 0) return;
int thumb_h = (v_track_h * visible_lines) / ed->num_lines;
if (thumb_h < 16) thumb_h = 16;
int usable = v_track_h - thumb_h;
if (usable <= 0) return;
int pos = (my - v_track_y) - ed->drag_offset;
if (pos < 0) pos = 0;
if (pos > usable) pos = usable;
ed->scroll_y = (pos * max_sy) / usable;
}
static void update_hscroll_from_mouse(Editor *ed, int mx) {
int h_full_w = ed->win_w - GUTTER_W - SCROLLBAR_W;
int visible_cols = (h_full_w - 8) / ed->char_w;
int max_cols = editor_max_line_len(ed);
int max_sx = max_cols - visible_cols;
if (max_sx <= 0) return;
int h_track_x = GUTTER_W + SCROLLBAR_W;
int h_track_w = h_full_w - SCROLLBAR_W * 2;
if (h_track_w <= 0) return;
int thumb_w = (h_track_w * visible_cols) / max_cols;
if (thumb_w < 16) thumb_w = 16;
int usable = h_track_w - thumb_w;
if (usable <= 0) return;
int pos = (mx - h_track_x) - ed->drag_offset;
if (pos < 0) pos = 0;
if (pos > usable) pos = usable;
ed->scroll_x = (pos * max_sx) / usable;
}
void editor_handle_button_press(Editor *ed, XButtonEvent *bev) {
int mx = bev->x, my = bev->y;
if (ed->confirm_mode != 0) {
if (bev->button == Button1) confirm_handle_click(ed, mx, my);
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
if (ed->fbrowser_open) {
fbrowser_handle_click(ed, mx, my, bev->button, bev->time);
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
if (menu_handle_click(ed, mx, my, bev->button)) {
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
if (tabs_handle_click(ed, mx, my, bev->button)) {
tabs_handle_motion(ed, mx, my);
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
int st_h = editor_status_h(ed);
int status_y = ed->win_h - st_h;
int h_track_y = ed->win_h - st_h - SCROLLBAR_W;
if (bev->button == Button1 && mx >= 0 && mx < GUTTER_W &&
my >= h_track_y && my < h_track_y + SCROLLBAR_W) {
ed->pressed_btn = 1;
ed->status_collapsed = !ed->status_collapsed;
editor_ensure_cursor_visible(ed);
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
if (bev->button == Button1 && !ed->status_collapsed && my >= status_y) {
if (ed->search_mode && mx >= ed->chk_x1 && mx <= ed->chk_x2) {
ed->search_highlight_all = !ed->search_highlight_all;
}
return;
}
int v_track_x = ed->win_w - SCROLLBAR_W;
int v_full_y = TOP_UI_H;
int v_full_h = ed->win_h - TOP_UI_H - st_h - SCROLLBAR_W;
int h_full_x = GUTTER_W;
int h_full_w = ed->win_w - GUTTER_W - SCROLLBAR_W;
int visible_lines = (v_full_h > 0) ? (v_full_h / ed->line_h) : 1;
int visible_cols = (h_full_w > 8) ? ((h_full_w - 8) / ed->char_w) : 1;
int max_sy = ed->num_lines - visible_lines;
if (max_sy < 0) max_sy = 0;
int max_sx = editor_max_line_len(ed) - visible_cols;
if (max_sx < 0) max_sx = 0;
if (bev->button == Button4) {
ed->scroll_y -= 3;
if (ed->scroll_y < 0) ed->scroll_y = 0;
return;
}
if (bev->button == Button5) {
ed->scroll_y += 3;
if (ed->scroll_y > max_sy) ed->scroll_y = max_sy;
return;
}
if (bev->button != Button1) return;
if (mx >= v_track_x && my >= v_full_y && my < v_full_y + v_full_h) {
if (my < v_full_y + SCROLLBAR_W) {
ed->pressed_btn = 2;
if (ed->scroll_y > 0) ed->scroll_y--;
return;
}
if (my >= v_full_y + v_full_h - SCROLLBAR_W) {
ed->pressed_btn = 3;
if (ed->scroll_y < max_sy) ed->scroll_y++;
return;
}
if (max_sy > 0) {
int v_track_y = v_full_y + SCROLLBAR_W;
int v_track_h = v_full_h - SCROLLBAR_W * 2;
int thumb_h = (v_track_h * visible_lines) / ed->num_lines;
if (thumb_h < 16) thumb_h = 16;
int thumb_y = v_track_y + (ed->scroll_y * (v_track_h - thumb_h)) / max_sy;
ed->drag_vscroll = 1;
if (my >= thumb_y && my <= thumb_y + thumb_h) ed->drag_offset = my - thumb_y;
else {
ed->drag_offset = thumb_h / 2;
update_vscroll_from_mouse(ed, my);
}
}
} else if (my >= h_track_y && my < h_track_y + SCROLLBAR_W && mx >= h_full_x && mx < v_track_x) {
if (mx < h_full_x + SCROLLBAR_W) {
ed->pressed_btn = 4;
if (ed->scroll_x > 0) ed->scroll_x--;
return;
}
if (mx >= v_track_x - SCROLLBAR_W) {
ed->pressed_btn = 5;
if (ed->scroll_x < max_sx) ed->scroll_x++;
return;
}
if (max_sx > 0) {
int h_track_x = h_full_x + SCROLLBAR_W;
int h_track_w = h_full_w - SCROLLBAR_W * 2;
int max_cols = editor_max_line_len(ed);
int thumb_w = (h_track_w * visible_cols) / max_cols;
if (thumb_w < 16) thumb_w = 16;
int thumb_x = h_track_x + (ed->scroll_x * (h_track_w - thumb_w)) / max_sx;
ed->drag_hscroll = 1;
if (mx >= thumb_x && mx <= thumb_x + thumb_w) ed->drag_offset = mx - thumb_x;
else {
ed->drag_offset = thumb_w / 2;
update_hscroll_from_mouse(ed, mx);
}
}
} else if (mx >= GUTTER_W && mx < v_track_x && my >= TOP_UI_H && my < h_track_y) {
int ctrl = (bev->state & ControlMask);
int shift = (bev->state & ShiftMask);
if (ctrl) {
set_cursor_from_mouse(ed, mx, my);
ed->has_sel = 0;
ed->hover_sym_line = -1;
menu_goto_symbol_at_cursor(ed);
mouse_update_cursor(ed, mx, my, bev->state);
return;
}
if (shift) {
if (!ed->has_sel) {
ed->sel_ax = ed->cx;
ed->sel_ay = ed->cy;
}
set_cursor_from_mouse(ed, mx, my);
ed->has_sel = (ed->cx != ed->sel_ax || ed->cy != ed->sel_ay);
} else {
set_cursor_from_mouse(ed, mx, my);
ed->has_sel = 0;
ed->sel_ax = ed->cx;
ed->sel_ay = ed->cy;
}
ed->drag_select = 1;
}
}
void editor_handle_motion(Editor *ed, XMotionEvent *mev) {
if (ed->drag_vscroll) update_vscroll_from_mouse(ed, mev->y);
else if (ed->drag_hscroll) update_hscroll_from_mouse(ed, mev->x);
else if (ed->drag_select) {
set_cursor_from_mouse(ed, mev->x, mev->y);
ed->has_sel = (ed->cx != ed->sel_ax || ed->cy != ed->sel_ay);
}
}
void editor_handle_button_release(Editor *ed, XButtonEvent *bev) {
if (bev->button == Button1) {
ed->drag_vscroll = 0;
ed->drag_hscroll = 0;
ed->drag_select = 0;
ed->pressed_btn = 0;
}
}
+180
View File
@@ -0,0 +1,180 @@
#include "input.h"
#include <string.h>
void editor_get_sel_bounds(const Editor *ed, int *sy, int *sx, int *ey, int *ex) {
if (ed->sel_ay < ed->cy || (ed->sel_ay == ed->cy && ed->sel_ax <= ed->cx)) {
*sy = ed->sel_ay; *sx = ed->sel_ax;
*ey = ed->cy; *ex = ed->cx;
} else {
*sy = ed->cy; *sx = ed->cx;
*ey = ed->sel_ay; *ex = ed->sel_ax;
}
}
void editor_delete_selection(Editor *ed) {
if (!ed->has_sel) return;
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
ed->has_sel = 0;
if (sy == ey && sx == ex) return;
if (sy == ey) {
int len = (int)strlen(ed->lines[sy]);
memmove(&ed->lines[sy][sx], &ed->lines[sy][ex], (size_t)(len - ex + 1));
} else {
int tail_len = (int)strlen(&ed->lines[ey][ex]);
if (sx + tail_len < MAX_LEN - 1) {
memcpy(&ed->lines[sy][sx], &ed->lines[ey][ex], (size_t)(tail_len + 1));
} else {
ed->lines[sy][sx] = '\0';
}
int removed = ey - sy;
for (int i = sy + 1; i < ed->num_lines - removed; i++) {
strcpy(ed->lines[i], ed->lines[i + removed]);
}
ed->num_lines -= removed;
}
ed->cy = sy;
ed->cx = sx;
}
void editor_ensure_cursor_visible(Editor *ed) {
int visible_lines = (ed->win_h - TOP_UI_H - editor_status_h(ed) - SCROLLBAR_W) / ed->line_h;
int visible_cols = (ed->win_w - GUTTER_W - SCROLLBAR_W - 8) / ed->char_w;
if (visible_lines < 1) visible_lines = 1;
if (visible_cols < 1) visible_cols = 1;
int cur_col = utf8_char_count(ed->lines[ed->cy], ed->cx);
if (ed->cy < ed->scroll_y) ed->scroll_y = ed->cy;
if (ed->cy >= ed->scroll_y + visible_lines) ed->scroll_y = ed->cy - visible_lines + 1;
if (cur_col < ed->scroll_x) ed->scroll_x = cur_col;
if (cur_col >= ed->scroll_x + visible_cols) ed->scroll_x = cur_col - visible_cols + 1;
}
void input_insert_bytes(Editor *ed, const char *bytes, int count) {
int len = (int)strlen(ed->lines[ed->cy]);
if (len + count < MAX_LEN - 1) {
memmove(&ed->lines[ed->cy][ed->cx + count], &ed->lines[ed->cy][ed->cx], (size_t)(len - ed->cx + 1));
memcpy(&ed->lines[ed->cy][ed->cx], bytes, (size_t)count);
ed->cx += count;
}
}
static void insert_raw_newline(Editor *ed) {
if (ed->num_lines < MAX_LINES) {
for (int i = ed->num_lines; i > ed->cy + 1; i--) {
strcpy(ed->lines[i], ed->lines[i - 1]);
}
strcpy(ed->lines[ed->cy + 1], &ed->lines[ed->cy][ed->cx]);
ed->lines[ed->cy][ed->cx] = '\0';
ed->num_lines++;
ed->cy++;
ed->cx = 0;
}
}
void input_insert_newline(Editor *ed) {
if (ed->num_lines >= MAX_LINES) return;
const char *cur_line = ed->lines[ed->cy];
/* Подсчитываем отступ текущей строки (в пробелах) до позиции курсора */
int indent_spaces = 0;
for (int i = 0; i < ed->cx && cur_line[i] != '\0'; i++) {
if (cur_line[i] == ' ') indent_spaces++;
else if (cur_line[i] == '\t') indent_spaces += 4;
else break;
}
/* Если перед курсором стоит открывающая фигурная скобка '{', добавляем +4 пробела */
int check = ed->cx - 1;
while (check >= 0 && (cur_line[check] == ' ' || cur_line[check] == '\t')) {
check--;
}
if (check >= 0 && cur_line[check] == '{') {
indent_spaces += 4;
}
insert_raw_newline(ed);
/* Вставляем вычисленный отступ в начало новой строки */
int tail_len = (int)strlen(ed->lines[ed->cy]);
if (indent_spaces > MAX_LEN - 1 - tail_len) {
indent_spaces = MAX_LEN - 1 - tail_len;
}
if (indent_spaces > 0) {
memmove(&ed->lines[ed->cy][indent_spaces], ed->lines[ed->cy], (size_t)(tail_len + 1));
memset(ed->lines[ed->cy], ' ', (size_t)indent_spaces);
ed->cx = indent_spaces;
}
}
void editor_insert_text(Editor *ed, const char *text) {
history_push_undo(ed);
if (ed->has_sel) editor_delete_selection(ed);
int i = 0;
while (text[i] != '\0') {
if (text[i] == '\r') {
i++;
continue;
}
if (text[i] == '\n') {
insert_raw_newline(ed);
i++;
} else if (text[i] == '\t') {
input_insert_bytes(ed, " ", 4);
i++;
} else if ((unsigned char)text[i] >= 32 && (unsigned char)text[i] != 127) {
int next = utf8_next_char_pos(text, i);
input_insert_bytes(ed, &text[i], next - i);
i = next;
} else {
i++;
}
}
editor_ensure_cursor_visible(ed);
}
void input_indent_selection(Editor *ed, int unindent) {
int sy = ed->cy, ey = ed->cy;
int sx = ed->cx, ex = ed->cx;
if (ed->has_sel) {
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
if (ey > sy && ex == 0) {
ey--;
}
}
for (int y = sy; y <= ey; y++) {
int len = (int)strlen(ed->lines[y]);
if (!unindent) {
if (len + 4 < MAX_LEN - 1) {
memmove(&ed->lines[y][4], ed->lines[y], (size_t)(len + 1));
memcpy(ed->lines[y], " ", 4);
if (y == ed->cy) ed->cx += 4;
if (ed->has_sel && y == ed->sel_ay) ed->sel_ax += 4;
}
} else {
int rem = 0;
if (ed->lines[y][0] == '\t') {
rem = 1;
} else {
while (rem < 4 && ed->lines[y][rem] == ' ') rem++;
}
if (rem > 0) {
memmove(ed->lines[y], &ed->lines[y][rem], (size_t)(len - rem + 1));
if (y == ed->cy) {
ed->cx = (ed->cx > rem) ? (ed->cx - rem) : 0;
}
if (ed->has_sel && y == ed->sel_ay) {
ed->sel_ax = (ed->sel_ax > rem) ? (ed->sel_ax - rem) : 0;
}
}
}
}
}
+35
View File
@@ -0,0 +1,35 @@
#include "input.h"
#include <string.h>
int utf8_char_count(const char *s, int max_bytes) {
int count = 0;
for (int i = 0; i < max_bytes && s[i] != '\0'; i++) {
if (((unsigned char)s[i] & 0xC0) != 0x80) count++;
}
return count;
}
int utf8_byte_offset(const char *s, int char_idx) {
int i = 0, count = 0;
while (s[i] != '\0' && count < char_idx) {
if (((unsigned char)s[i] & 0xC0) != 0x80) count++;
if (count <= char_idx) i++;
}
while (s[i] != '\0' && ((unsigned char)s[i] & 0xC0) == 0x80) i++;
return i;
}
int utf8_prev_char_pos(const char *s, int byte_pos) {
if (byte_pos <= 0) return 0;
int pos = byte_pos - 1;
while (pos > 0 && ((unsigned char)s[pos] & 0xC0) == 0x80) pos--;
return pos;
}
int utf8_next_char_pos(const char *s, int byte_pos) {
int len = (int)strlen(s);
if (byte_pos >= len) return len;
int pos = byte_pos + 1;
while (pos < len && ((unsigned char)s[pos] & 0xC0) == 0x80) pos++;
return pos;
}
+223
View File
@@ -0,0 +1,223 @@
#include "editor.h"
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
static unsigned long alloc_color(Display *dpy, Colormap cmap, const char *hex) {
XColor col;
if (XParseColor(dpy, cmap, hex, &col) && XAllocColor(dpy, cmap, &col)) {
return col.pixel;
}
return BlackPixel(dpy, DefaultScreen(dpy));
}
static void init_theme(Editor *ed, Visual *vis, Colormap cmap) {
ed->col_bg = alloc_color(ed->dpy, cmap, "#ffffff");
ed->col_gutter = alloc_color(ed->dpy, cmap, "#e6e9ef");
ed->col_curline = alloc_color(ed->dpy, cmap, "#eff1f5");
ed->col_sel = alloc_color(ed->dpy, cmap, "#ccd0da");
ed->col_match_all = alloc_color(ed->dpy, cmap, "#fff3a8");
ed->col_match_cur = alloc_color(ed->dpy, cmap, "#99c8ff");
ed->col_fg = alloc_color(ed->dpy, cmap, "#1e1e2e");
ed->col_status = alloc_color(ed->dpy, cmap, "#dce0e8");
ed->col_sb_track = alloc_color(ed->dpy, cmap, "#e6e9ef");
ed->col_sb_thumb = alloc_color(ed->dpy, cmap, "#bcc0cc");
XftColorAllocName(ed->dpy, vis, cmap, "#1e1e2e", &ed->xft_fg);
XftColorAllocName(ed->dpy, vis, cmap, "#8c8fa1", &ed->xft_lineno);
XftColorAllocName(ed->dpy, vis, cmap, "#8839ef", &ed->xft_kw);
XftColorAllocName(ed->dpy, vis, cmap, "#40a02b", &ed->xft_str);
XftColorAllocName(ed->dpy, vis, cmap, "#7c7f93", &ed->xft_com);
XftColorAllocName(ed->dpy, vis, cmap, "#f527bb", &ed->xft_mcom);
XftColorAllocName(ed->dpy, vis, cmap, "#fe640b", &ed->xft_prep);
XftColorAllocName(ed->dpy, vis, cmap, "#179299", &ed->xft_type);
XftColorAllocName(ed->dpy, vis, cmap, "#d20f39", &ed->xft_num);
XftColorAllocName(ed->dpy, vis, cmap, "#0969da", &ed->xft_link);
}
int main(int argc, char *argv[]) {
setlocale(LC_ALL, "");
Editor ed = {0};
ed.win_w = 960;
ed.win_h = 640;
ed.running = 1;
ed.hover_sym_line = -1;
ed.cursor_visible = 1;
ed.dpy = XOpenDisplay(NULL);
if (!ed.dpy) {
fprintf(stderr, "Failed to open X Display\n");
return 1;
}
ed.screen = DefaultScreen(ed.dpy);
Visual *vis = DefaultVisual(ed.dpy, ed.screen);
Colormap cmap = DefaultColormap(ed.dpy, ed.screen);
init_theme(&ed, vis, cmap);
clipboard_init(&ed);
menu_init(&ed);
ed.win = XCreateSimpleWindow(ed.dpy, RootWindow(ed.dpy, ed.screen),
100, 100, ed.win_w, ed.win_h, 1,
ed.col_fg, ed.col_bg);
ed.cursor_hand = XCreateFontCursor(ed.dpy, XC_hand2);
XSelectInput(ed.dpy, ed.win,
ExposureMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
Atom wm_delete = XInternAtom(ed.dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(ed.dpy, ed.win, &wm_delete, 1);
XSetLocaleModifiers("");
ed.xim = XOpenIM(ed.dpy, NULL, NULL, NULL);
if (ed.xim) {
ed.xic = XCreateIC(ed.xim,
XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, ed.win,
XNFocusWindow, ed.win,
NULL);
}
ed.gc = XCreateGC(ed.dpy, ed.win, 0, NULL);
ed.font = XftFontOpenName(ed.dpy, ed.screen, "monospace-12");
if (!ed.font) {
fprintf(stderr, "Failed to load Xft font\n");
return 1;
}
XGlyphInfo ext;
XftTextExtentsUtf8(ed.dpy, ed.font, (const FcChar8 *)"M", 1, &ext);
ed.char_w = (ext.xOff > 0) ? ext.xOff : 8;
ed.line_h = ed.font->ascent + ed.font->descent + 0;
ed.backbuf = XCreatePixmap(ed.dpy, ed.win, ed.win_w, ed.win_h, DefaultDepth(ed.dpy, ed.screen));
ed.xft_draw = XftDrawCreate(ed.dpy, ed.backbuf, vis, cmap);
tabs_init(&ed, argc, argv);
XMapWindow(ed.dpy, ed.win);
int x11_fd = ConnectionNumber(ed.dpy);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 500000;
while (ed.running) {
if (!XPending(ed.dpy)) {
fd_set in_fds;
FD_ZERO(&in_fds);
FD_SET(x11_fd, &in_fds);
XFlush(ed.dpy);
int ready = select(x11_fd + 1, &in_fds, NULL, NULL, &tv);
if (ready == 0) {
ed.cursor_visible = !ed.cursor_visible;
editor_render(&ed);
tv.tv_sec = 0;
tv.tv_usec = 500000;
continue;
}
}
while (XPending(ed.dpy) && ed.running) {
XEvent ev;
XNextEvent(ed.dpy, &ev);
if (XFilterEvent(&ev, None)) continue;
if (ev.type == Expose && ev.xexpose.count == 0) {
editor_render(&ed);
} else if (ev.type == ConfigureNotify) {
if (ev.xconfigure.width != ed.win_w || ev.xconfigure.height != ed.win_h) {
ed.win_w = ev.xconfigure.width;
ed.win_h = ev.xconfigure.height;
XFreePixmap(ed.dpy, ed.backbuf);
ed.backbuf = XCreatePixmap(ed.dpy, ed.win, ed.win_w, ed.win_h, DefaultDepth(ed.dpy, ed.screen));
XftDrawChange(ed.xft_draw, ed.backbuf);
editor_render(&ed);
}
} else if (ev.type == KeyPress) {
ed.cursor_visible = 1;
tv.tv_sec = 0;
tv.tv_usec = 500000;
editor_handle_key(&ed, &ev.xkey);
if (ed.running) {
KeySym ks = XLookupKeysym(&ev.xkey, 0);
if (ks == XK_Control_L || ks == XK_Control_R) {
menu_update_hover_symbol(&ed, ev.xkey.x, ev.xkey.y, ev.xkey.state | ControlMask);
mouse_update_cursor(&ed, ev.xkey.x, ev.xkey.y, ev.xkey.state | ControlMask);
}
editor_render(&ed);
}
} else if (ev.type == KeyRelease) {
KeySym ks = XLookupKeysym(&ev.xkey, 0);
if (ks == XK_Control_L || ks == XK_Control_R) {
int sym_chg = menu_update_hover_symbol(&ed, ev.xkey.x, ev.xkey.y, ev.xkey.state & ~ControlMask);
int btn_chg = mouse_update_cursor(&ed, ev.xkey.x, ev.xkey.y, ev.xkey.state & ~ControlMask);
if (sym_chg || btn_chg) {
editor_render(&ed);
}
}
} else if (ev.type == ButtonPress) {
ed.cursor_visible = 1;
tv.tv_sec = 0;
tv.tv_usec = 500000;
editor_handle_button_press(&ed, &ev.xbutton);
editor_render(&ed);
} else if (ev.type == MotionNotify) {
int fb_hover = fbrowser_handle_motion(&ed, ev.xmotion.x, ev.xmotion.y);
int dlg_hover = confirm_handle_motion(&ed, ev.xmotion.x, ev.xmotion.y);
int menu_hover = menu_handle_motion(&ed, ev.xmotion.x, ev.xmotion.y);
int tab_hover = tabs_handle_motion(&ed, ev.xmotion.x, ev.xmotion.y);
int sym_hover = menu_update_hover_symbol(&ed, ev.xmotion.x, ev.xmotion.y, ev.xmotion.state);
int btn_hover = mouse_update_cursor(&ed, ev.xmotion.x, ev.xmotion.y, ev.xmotion.state);
editor_handle_motion(&ed, &ev.xmotion);
if (fb_hover || dlg_hover || menu_hover || tab_hover || sym_hover || btn_hover ||
ed.drag_vscroll || ed.drag_hscroll || ed.drag_select) {
editor_render(&ed);
}
} else if (ev.type == ButtonRelease) {
editor_handle_button_release(&ed, &ev.xbutton);
editor_render(&ed);
} else if (ev.type == SelectionRequest) {
clipboard_handle_selection_request(&ed, &ev.xselectionrequest);
} else if (ev.type == SelectionNotify) {
clipboard_handle_selection_notify(&ed, &ev.xselection);
editor_render(&ed);
} else if (ev.type == ClientMessage) {
if ((Atom)(*ev.xclient.data.l) == wm_delete) {
tabs_request_quit(&ed);
editor_render(&ed);
}
}
}
}
history_free_all(&ed);
tabs_free_all(&ed);
free(ed.clip_data);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_fg);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_lineno);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_kw);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_str);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_com);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_mcom);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_prep);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_type);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_num);
XftColorFree(ed.dpy, vis, cmap, &ed.xft_link);
XftDrawDestroy(ed.xft_draw);
XftFontClose(ed.dpy, ed.font);
if (ed.xic) XDestroyIC(ed.xic);
if (ed.xim) XCloseIM(ed.xim);
XFreeCursor(ed.dpy, ed.cursor_hand);
XFreePixmap(ed.dpy, ed.backbuf);
XFreeGC(ed.dpy, ed.gc);
XDestroyWindow(ed.dpy, ed.win);
XCloseDisplay(ed.dpy);
return 0;
}
+539
View File
@@ -0,0 +1,539 @@
#include "editor.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define DROP_W 245
#define SUB_W 240
#define ITEM_H 24
#define HDR_BUF_LEN 64
static const char *top_titles[] = {"File", "Edit", "Navigation"};
static const int top_x[] = {8, 64, 120};
static const int top_w[] = {52, 52, 100};
void menu_init(Editor *ed) {
ed->menu_open = -1;
ed->menu_sub_open = 0;
ed->menu_hover_item = -1;
ed->menu_hover_sym = -1;
ed->menu_sym_scroll = 0;
}
static void nav_push_back(Editor *ed, int cx, int cy) {
ed->nav_fwd_count = 0;
if (ed->nav_back_count > 0 &&
ed->nav_back[ed->nav_back_count - 1].cy == cy &&
ed->nav_back[ed->nav_back_count - 1].cx == cx) {
return;
}
if (ed->nav_back_count >= MAX_NAV_HISTORY) {
memmove(ed->nav_back, ed->nav_back + 1, (MAX_NAV_HISTORY - 1) * sizeof(NavPoint));
ed->nav_back_count = MAX_NAV_HISTORY - 1;
}
ed->nav_back[ed->nav_back_count].cx = cx;
ed->nav_back[ed->nav_back_count].cy = cy;
ed->nav_back_count++;
}
void nav_go_back(Editor *ed) {
if (ed->nav_back_count <= 0) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Нет точек для возврата назад");
return;
}
if (ed->nav_fwd_count >= MAX_NAV_HISTORY) {
memmove(ed->nav_fwd, ed->nav_fwd + 1, (MAX_NAV_HISTORY - 1) * sizeof(NavPoint));
ed->nav_fwd_count = MAX_NAV_HISTORY - 1;
}
ed->nav_fwd[ed->nav_fwd_count].cx = ed->cx;
ed->nav_fwd[ed->nav_fwd_count].cy = ed->cy;
ed->nav_fwd_count++;
ed->nav_back_count--;
ed->cx = ed->nav_back[ed->nav_back_count].cx;
ed->cy = ed->nav_back[ed->nav_back_count].cy;
if (ed->cy >= ed->num_lines) ed->cy = ed->num_lines - 1;
int len = (int)strlen(ed->lines[ed->cy]);
if (ed->cx > len) ed->cx = len;
ed->has_sel = 0;
editor_ensure_cursor_visible(ed);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Назад: Ln %d", ed->cy + 1);
}
void nav_go_forward(Editor *ed) {
if (ed->nav_fwd_count <= 0) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Нет точек для перехода вперед");
return;
}
if (ed->nav_back_count >= MAX_NAV_HISTORY) {
memmove(ed->nav_back, ed->nav_back + 1, (MAX_NAV_HISTORY - 1) * sizeof(NavPoint));
ed->nav_back_count = MAX_NAV_HISTORY - 1;
}
ed->nav_back[ed->nav_back_count].cx = ed->cx;
ed->nav_back[ed->nav_back_count].cy = ed->cy;
ed->nav_back_count++;
ed->nav_fwd_count--;
ed->cx = ed->nav_fwd[ed->nav_fwd_count].cx;
ed->cy = ed->nav_fwd[ed->nav_fwd_count].cy;
if (ed->cy >= ed->num_lines) ed->cy = ed->num_lines - 1;
int len = (int)strlen(ed->lines[ed->cy]);
if (ed->cx > len) ed->cx = len;
ed->has_sel = 0;
editor_ensure_cursor_visible(ed);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Вперед: Ln %d", ed->cy + 1);
}
static void jump_to_line_with_history(Editor *ed, int target_line, const char *sym_name) {
if (target_line != ed->cy) {
nav_push_back(ed, ed->cx, ed->cy);
}
ed->cy = target_line;
ed->cx = 0;
ed->has_sel = 0;
ed->scroll_x = 0;
ed->scroll_y = (ed->cy > 3) ? (ed->cy - 3) : 0;
if (sym_name) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Jumped to %s (Ln %d)", sym_name, ed->cy + 1);
}
}
static int is_c_control_word(const char *w, int len) {
const char *ctrl[] = {"if", "else", "for", "while", "switch", "return", "sizeof", "typedef", NULL};
for (int i = 0; ctrl[i]; i++) {
if ((int)strlen(ctrl[i]) == len && strncmp(ctrl[i], w, (size_t)len) == 0) return 1;
}
return 0;
}
void menu_refresh_symbols(Editor *ed) {
ed->num_symbols = 0;
int brace_depth = 0;
int in_comment = 0;
for (int y = 0; y < ed->num_lines; y++) {
const char *line = ed->lines[y];
int len = (int)strlen(line);
int i = 0;
int first_non_space = 0;
while (first_non_space < len && isspace((unsigned char)line[first_non_space])) first_non_space++;
int is_preproc = (!in_comment && first_non_space < len && line[first_non_space] == '#');
if (!in_comment && !is_preproc && brace_depth == 0 && ed->num_symbols < MAX_SYMBOLS) {
const char *paren = strchr(line, '(');
if (paren && strchr(line, ';') == NULL && strchr(line, '=') == NULL) {
int p_idx = (int)(paren - line) - 1;
while (p_idx >= 0 && isspace((unsigned char)line[p_idx])) p_idx--;
int name_end = p_idx + 1;
while (p_idx >= 0 && (isalnum((unsigned char)line[p_idx]) || line[p_idx] == '_')) p_idx--;
int name_start = p_idx + 1;
int name_len = name_end - name_start;
if (name_len > 0 && !isdigit((unsigned char)line[name_start]) &&
!is_c_control_word(&line[name_start], name_len)) {
int before = name_start - 1;
while (before >= 0 && (isspace((unsigned char)line[before]) || line[before] == '*')) before--;
if (before >= 0) {
int copy_len = (name_len < SYM_NAME_LEN - 1) ? name_len : (SYM_NAME_LEN - 1);
memcpy(ed->symbols[ed->num_symbols].name, &line[name_start], (size_t)copy_len);
ed->symbols[ed->num_symbols].name[copy_len] = '\0';
ed->symbols[ed->num_symbols].line = y;
ed->num_symbols++;
}
}
}
}
while (i < len) {
if (in_comment) {
if (line[i] == '*' && i + 1 < len && line[i + 1] == '/') {
in_comment = 0;
i += 2;
} else {
i++;
}
} else if (line[i] == '/' && i + 1 < len && line[i + 1] == '/') {
break;
} else if (line[i] == '/' && i + 1 < len && line[i + 1] == '*') {
in_comment = 1;
i += 2;
} else if (line[i] == '"' || line[i] == '\'') {
char q = line[i++];
while (i < len && line[i] != q) {
if (line[i] == '\\' && i + 1 < len) i++;
i++;
}
if (i < len) i++;
} else {
if (line[i] == '{') brace_depth++;
else if (line[i] == '}' && brace_depth > 0) brace_depth--;
i++;
}
}
}
}
int menu_goto_symbol_at_cursor(Editor *ed) {
const char *line = ed->lines[ed->cy];
int len = (int)strlen(line);
int pos = ed->cx;
if (pos > 0 && (pos == len || (!isalnum((unsigned char)line[pos]) && line[pos] != '_'))) {
if (isalnum((unsigned char)line[pos - 1]) || line[pos - 1] == '_') {
pos--;
}
}
if (pos >= len || (!isalnum((unsigned char)line[pos]) && line[pos] != '_')) {
return 0;
}
int start = pos;
while (start > 0 && (isalnum((unsigned char)line[start - 1]) || line[start - 1] == '_')) {
start--;
}
int end = pos;
while (end < len && (isalnum((unsigned char)line[end]) || line[end] == '_')) {
end++;
}
int wlen = end - start;
if (wlen <= 0 || wlen >= SYM_NAME_LEN) return 0;
char word[SYM_NAME_LEN];
memcpy(word, &line[start], (size_t)wlen);
word[wlen] = '\0';
menu_refresh_symbols(ed);
for (int i = 0; i < ed->num_symbols; i++) {
if (strcmp(ed->symbols[i].name, word) == 0) {
jump_to_line_with_history(ed, ed->symbols[i].line, word);
return 1;
}
}
snprintf(ed->status_msg, sizeof(ed->status_msg), "Definition not found: %s", word);
return 0;
}
int menu_update_hover_symbol(Editor *ed, int mx, int my, unsigned int state) {
int old_line = ed->hover_sym_line;
int old_sx = ed->hover_sym_sx;
int old_ex = ed->hover_sym_ex;
ed->hover_sym_line = -1;
ed->hover_sym_sx = 0;
ed->hover_sym_ex = 0;
ed->hover_sym_target = -1;
int v_track_x = ed->win_w - SCROLLBAR_W;
int h_track_y = ed->win_h - editor_status_h(ed) - SCROLLBAR_W;
if ((state & ControlMask) && ed->menu_open < 0 && ed->confirm_mode == 0 && !ed->fbrowser_open &&
mx >= GUTTER_W && mx < v_track_x && my >= TOP_UI_H && my < h_track_y) {
int y = ed->scroll_y + ((my - TOP_UI_H) / ed->line_h);
if (y >= 0 && y < ed->num_lines) {
int col = ed->scroll_x + ((mx - GUTTER_W - 8) / ed->char_w);
if (col >= 0) {
const char *line = ed->lines[y];
int len = (int)strlen(line);
int pos = utf8_byte_offset(line, col);
if (pos < len && (isalnum((unsigned char)line[pos]) || line[pos] == '_')) {
int start = pos;
while (start > 0 && (isalnum((unsigned char)line[start - 1]) || line[start - 1] == '_')) {
start--;
}
int end = pos;
while (end < len && (isalnum((unsigned char)line[end]) || line[end] == '_')) {
end++;
}
int wlen = end - start;
if (wlen > 0 && wlen < SYM_NAME_LEN) {
char word[SYM_NAME_LEN];
memcpy(word, &line[start], (size_t)wlen);
word[wlen] = '\0';
menu_refresh_symbols(ed);
for (int i = 0; i < ed->num_symbols; i++) {
if (strcmp(ed->symbols[i].name, word) == 0 && ed->symbols[i].line != y) {
ed->hover_sym_line = y;
ed->hover_sym_sx = start;
ed->hover_sym_ex = end;
ed->hover_sym_target = ed->symbols[i].line;
break;
}
}
}
}
}
}
}
return (old_line != ed->hover_sym_line || old_sx != ed->hover_sym_sx || old_ex != ed->hover_sym_ex);
}
static void draw_dropdown_box(Editor *ed, int x, int y, int w, int h) {
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, x, y, w, h);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, x, y, w - 1, h - 1);
}
static void render_symbols_submenu(Editor *ed, int sub_x, int sub_y) {
int st_h = editor_status_h(ed);
int max_vis = (ed->win_h - sub_y - st_h - 8) / ITEM_H;
if (max_vis < 1) max_vis = 1;
int count = ed->num_symbols;
int vis_count = (count == 0) ? 1 : ((count < max_vis) ? count : max_vis);
int sub_h = vis_count * ITEM_H + 4;
draw_dropdown_box(ed, sub_x, sub_y, SUB_W, sub_h);
if (count == 0) {
int base = sub_y + 2 + (ITEM_H + ed->font->ascent - ed->font->descent) / 2;
const char *empty_msg = "(Нет функций)";
XftDrawStringUtf8(ed->xft_draw, &ed->xft_lineno, ed->font, sub_x + 10, base,
(const FcChar8 *)empty_msg, (int)strlen(empty_msg));
return;
}
if (ed->menu_sym_scroll > count - vis_count) ed->menu_sym_scroll = count - vis_count;
if (ed->menu_sym_scroll < 0) ed->menu_sym_scroll = 0;
int active_sym = -1;
for (int i = 0; i < count; i++) {
if (ed->symbols[i].line <= ed->cy) active_sym = i;
else break;
}
int max_chars = (SUB_W - 36) / ed->char_w;
if (max_chars < 1) max_chars = 1;
for (int i = 0; i < vis_count; i++) {
int idx = ed->menu_sym_scroll + i;
int iy = sub_y + 2 + i * ITEM_H;
int base = iy + (ITEM_H + ed->font->ascent - ed->font->descent) / 2;
if (idx == ed->menu_hover_sym) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_cur);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, sub_x + 2, iy, SUB_W - 4, ITEM_H);
} else if (idx == active_sym) {
XSetForeground(ed->dpy, ed->gc, ed->col_sel);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, sub_x + 2, iy, SUB_W - 4, ITEM_H);
}
const char *fn_icon = "ƒ";
XftDrawStringUtf8(ed->xft_draw, &ed->xft_kw, ed->font, sub_x + 8, base,
(const FcChar8 *)fn_icon, (int)strlen(fn_icon));
int nlen = (int)strlen(ed->symbols[idx].name);
if (nlen > max_chars) nlen = max_chars;
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, sub_x + 24, base,
(const FcChar8 *)ed->symbols[idx].name, nlen);
}
}
void menu_render(Editor *ed) {
XSetForeground(ed->dpy, ed->gc, ed->col_status);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, 0, ed->win_w, MENUBAR_H);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, 0, MENUBAR_H - 1, ed->win_w, MENUBAR_H - 1);
int base_top = (MENUBAR_H + ed->font->ascent - ed->font->descent) / 2;
for (int i = 0; i < 3; i++) {
if (ed->menu_open == i) {
XSetForeground(ed->dpy, ed->gc, ed->col_sel);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, top_x[i], 2, top_w[i], MENUBAR_H - 3);
}
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, top_x[i] + 8, base_top,
(const FcChar8 *)top_titles[i], (int)strlen(top_titles[i]));
}
if (ed->menu_open < 0) return;
int dx = top_x[ed->menu_open];
int dy = MENUBAR_H;
if (ed->menu_open == 0) {
const char *file_items[6];
file_items[0] = "New Tab Ctrl+N";
file_items[1] = "Open... Ctrl+O";
file_items[2] = "Open>>> Ctrl+Shift+O";
file_items[3] = "Save Ctrl+S";
file_items[4] = "Close Tab Ctrl+W";
file_items[5] = "Quit Ctrl+Q";
draw_dropdown_box(ed, dx, dy, DROP_W, 6 * ITEM_H + 4);
for (int i = 0; i < 6; i++) {
int iy = dy + 2 + i * ITEM_H;
if (ed->menu_hover_item == i) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_cur);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx + 2, iy, DROP_W - 4, ITEM_H);
}
int base = iy + (ITEM_H + ed->font->ascent - ed->font->descent) / 2;
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 10, base,
(const FcChar8 *)file_items[i], (int)strlen(file_items[i]));
}
} else if (ed->menu_open == 1) {
const char *edit_items[3];
edit_items[0] = "Undo Ctrl+Z";
edit_items[1] = "Redo Ctrl+Y";
edit_items[2] = "Find Ctrl+F";
draw_dropdown_box(ed, dx, dy, DROP_W, 3 * ITEM_H + 4);
for (int i = 0; i < 3; i++) {
int iy = dy + 2 + i * ITEM_H;
if (ed->menu_hover_item == i) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_cur);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx + 2, iy, DROP_W - 4, ITEM_H);
}
int base = iy + (ITEM_H + ed->font->ascent - ed->font->descent) / 2;
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 10, base,
(const FcChar8 *)edit_items[i], (int)strlen(edit_items[i]));
}
} else if (ed->menu_open == 2) {
char lbl0[HDR_BUF_LEN];
snprintf(lbl0, sizeof(lbl0), "Список функций (%d) ▶", ed->num_symbols);
const char *nav_items[3];
nav_items[0] = lbl0;
nav_items[1] = "Назад Alt+Left";
nav_items[2] = "Вперед Alt+Right";
int nav_w = DROP_W + 10;
draw_dropdown_box(ed, dx, dy, nav_w, 3 * ITEM_H + 4);
for (int i = 0; i < 3; i++) {
int iy = dy + 2 + i * ITEM_H;
int is_active = (ed->menu_hover_item == i) || (i == 0 && ed->menu_sub_open);
if (is_active) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_cur);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx + 2, iy, nav_w - 4, ITEM_H);
}
XftColor *col = &ed->xft_fg;
if ((i == 1 && ed->nav_back_count == 0) || (i == 2 && ed->nav_fwd_count == 0)) {
col = &ed->xft_lineno;
}
int base = iy + (ITEM_H + ed->font->ascent - ed->font->descent) / 2;
XftDrawStringUtf8(ed->xft_draw, col, ed->font, dx + 10, base,
(const FcChar8 *)nav_items[i], (int)strlen(nav_items[i]));
}
if (ed->menu_sub_open) {
render_symbols_submenu(ed, dx + nav_w, dy);
}
}
}
int menu_handle_motion(Editor *ed, int mx, int my) {
if (ed->menu_open < 0) return 0;
if (my >= 0 && my < MENUBAR_H) {
for (int i = 0; i < 3; i++) {
if (mx >= top_x[i] && mx < top_x[i] + top_w[i]) {
if (ed->menu_open != i) {
ed->menu_open = i;
ed->menu_sub_open = (i == 2);
ed->menu_hover_item = -1;
ed->menu_hover_sym = -1;
if (i == 2) menu_refresh_symbols(ed);
}
return 1;
}
}
}
int dx = top_x[ed->menu_open];
int dy = MENUBAR_H;
int dw = (ed->menu_open == 2) ? (DROP_W + 10) : DROP_W;
int item_cnt = (ed->menu_open == 0) ? 6 : 3;
if (mx >= dx && mx < dx + dw && my >= dy + 2 && my < dy + 2 + item_cnt * ITEM_H) {
ed->menu_hover_item = (my - (dy + 2)) / ITEM_H;
ed->menu_hover_sym = -1;
if (ed->menu_open == 2) {
if (ed->menu_hover_item == 0 && !ed->menu_sub_open) {
menu_refresh_symbols(ed);
ed->menu_sub_open = 1;
} else if (ed->menu_hover_item != 0) {
ed->menu_sub_open = 0;
}
}
return 1;
}
if (ed->menu_open == 2 && ed->menu_sub_open) {
int sub_x = dx + dw;
int max_vis = (ed->win_h - dy - editor_status_h(ed) - 8) / ITEM_H;
if (max_vis < 1) max_vis = 1;
int vis_count = (ed->num_symbols < max_vis) ? ed->num_symbols : max_vis;
if (mx >= sub_x && mx < sub_x + SUB_W && my >= dy + 2 && my < dy + 2 + vis_count * ITEM_H) {
ed->menu_hover_sym = ed->menu_sym_scroll + ((my - (dy + 2)) / ITEM_H);
return 1;
}
}
ed->menu_hover_item = -1;
ed->menu_hover_sym = -1;
return 1;
}
int menu_handle_click(Editor *ed, int mx, int my, int button) {
if (my >= 0 && my < MENUBAR_H) {
if (button != Button1) return 1;
for (int i = 0; i < 3; i++) {
if (mx >= top_x[i] && mx < top_x[i] + top_w[i]) {
if (ed->menu_open == i) {
menu_init(ed);
} else {
ed->menu_open = i;
ed->menu_sub_open = (i == 2);
ed->menu_hover_item = -1;
ed->menu_hover_sym = -1;
if (i == 2) menu_refresh_symbols(ed);
}
return 1;
}
}
menu_init(ed);
return 1;
}
if (ed->menu_open < 0) return 0;
int dx = top_x[ed->menu_open];
int dy = MENUBAR_H;
int dw = (ed->menu_open == 2) ? (DROP_W + 10) : DROP_W;
if (ed->menu_open == 2 && ed->menu_sub_open) {
int sub_x = dx + dw;
int max_vis = (ed->win_h - dy - editor_status_h(ed) - 8) / ITEM_H;
if (max_vis < 1) max_vis = 1;
int vis_count = (ed->num_symbols < max_vis) ? ed->num_symbols : max_vis;
int sub_h = (vis_count > 0 ? vis_count : 1) * ITEM_H + 4;
if (mx >= sub_x && mx < sub_x + SUB_W && my >= dy && my < dy + sub_h) {
if (button == Button4) {
ed->menu_sym_scroll -= 2;
if (ed->menu_sym_scroll < 0) ed->menu_sym_scroll = 0;
return 1;
}
if (button == Button5) {
ed->menu_sym_scroll += 2;
return 1;
}
if (button == Button1 && ed->num_symbols > 0) {
int idx = ed->menu_sym_scroll + ((my - (dy + 2)) / ITEM_H);
if (idx >= 0 && idx < ed->num_symbols) {
jump_to_line_with_history(ed, ed->symbols[idx].line, ed->symbols[idx].name);
menu_init(ed);
}
}
return 1;
}
}
int item_cnt = (ed->menu_open == 0) ? 6 : 3;
if (button == Button1 && mx >= dx && mx < dx + dw && my >= dy + 2 && my < dy + 2 + item_cnt * ITEM_H) {
int item = (my - (dy + 2)) / ITEM_H;
int open_m = ed->menu_open;
if (open_m == 2 && item == 0) {
menu_refresh_symbols(ed);
ed->menu_sub_open = !ed->menu_sub_open;
return 1;
}
menu_init(ed);
if (open_m == 0) {
if (item == 0) tabs_new(ed, NULL);
else if (item == 1) fbrowser_show(ed);
else if (item == 2) editor_open_system_dialog(ed);
else if (item == 3) editor_save(ed);
else if (item == 4) tabs_request_close(ed, ed->active_tab);
else if (item == 5) tabs_request_quit(ed);
} else if (open_m == 1) {
if (item == 0) history_undo(ed);
else if (item == 1) history_redo(ed);
else if (item == 2) {
ed->status_collapsed = 0;
ed->search_mode = 1;
}
} else if (open_m == 2) {
if (item == 1) nav_go_back(ed);
else if (item == 2) nav_go_forward(ed);
}
return 1;
}
menu_init(ed);
return 1;
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef RENDER_H
#define RENDER_H
#include "../editor.h"
int render_calc_comment_state(const Editor *ed, int target_line);
void render_syntax_line(Editor *ed, const char *line, int scroll_x, int x, int y, int max_chars, int *in_comment);
void render_search_highlights(Editor *ed, int line_idx, int top_y, int visible_cols);
void render_selection_bg(Editor *ed, int line_idx, int top_y, int visible_cols);
void render_scrollbars(Editor *ed, int visible_lines, int visible_cols);
void render_status_bar(Editor *ed, int cur_col);
void render_hover_symbol_link(Editor *ed, int line_idx, int top_y, int baseline_y, int visible_cols);
#endif
+69
View File
@@ -0,0 +1,69 @@
#include "render.h"
#include <stdio.h>
#include <string.h>
#define NUM_BUF_LEN 16
void editor_render(Editor *ed) {
int top_offset = TOP_UI_H;
int st_h = editor_status_h(ed);
int text_x = GUTTER_W + 8;
int view_h = ed->win_h - top_offset - st_h - SCROLLBAR_W;
int view_w = ed->win_w - text_x - SCROLLBAR_W;
int visible_lines = (view_h > 0) ? (view_h / ed->line_h) : 1;
int visible_cols = (view_w > 0) ? (view_w / ed->char_w) : 1;
XSetForeground(ed->dpy, ed->gc, ed->col_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, 0, ed->win_w, ed->win_h);
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, top_offset, GUTTER_W, ed->win_h - top_offset - st_h);
int in_comment = render_calc_comment_state(ed, ed->scroll_y);
for (int i = 0; i < visible_lines; i++) {
int line_idx = ed->scroll_y + i;
if (line_idx >= ed->num_lines) break;
int top_y = top_offset + i * ed->line_h;
int baseline_y = top_y + ed->font->ascent + 2;
if (line_idx == ed->cy && !ed->has_sel) {
XSetForeground(ed->dpy, ed->gc, ed->col_curline);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, GUTTER_W, top_y,
ed->win_w - GUTTER_W - SCROLLBAR_W, ed->line_h);
}
render_search_highlights(ed, line_idx, top_y, visible_cols);
render_selection_bg(ed, line_idx, top_y, visible_cols);
char num_buf[NUM_BUF_LEN];
snprintf(num_buf, sizeof(num_buf), "%4d", line_idx + 1);
XftColor *num_col = (line_idx == ed->cy) ? &ed->xft_fg : &ed->xft_lineno;
XftDrawStringUtf8(ed->xft_draw, num_col, ed->font, 6, baseline_y,
(const FcChar8 *)num_buf, (int)strlen(num_buf));
render_syntax_line(ed, ed->lines[line_idx], ed->scroll_x, text_x, baseline_y, visible_cols + 1, &in_comment);
render_hover_symbol_link(ed, line_idx, top_y, baseline_y, visible_cols);
}
int cur_col = utf8_char_count(ed->lines[ed->cy], ed->cx);
if (ed->cursor_visible && ed->cy >= ed->scroll_y && ed->cy < ed->scroll_y + visible_lines &&
cur_col >= ed->scroll_x && cur_col <= ed->scroll_x + visible_cols) {
int cur_y = top_offset + (ed->cy - ed->scroll_y) * ed->line_h;
int cur_x = text_x + (cur_col - ed->scroll_x) * ed->char_w;
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, cur_x, cur_y + 2, 2, ed->line_h - 4);
}
render_scrollbars(ed, visible_lines, visible_cols);
render_status_bar(ed, cur_col);
tabs_render(ed);
menu_render(ed);
fbrowser_render(ed);
confirm_render(ed);
XCopyArea(ed->dpy, ed->backbuf, ed->win, ed->gc, 0, 0, ed->win_w, ed->win_h, 0, 0);
}
+185
View File
@@ -0,0 +1,185 @@
#include "render.h"
#include <ctype.h>
#include <string.h>
static const char *c_keywords[] = {
"auto", "break", "case", "char", "const", "continue", "default", "do",
"double", "else", "enum", "extern", "float", "for", "goto", "if",
"inline", "int", "long", "register", "restrict", "return", "short",
"signed", "sizeof", "static", "struct", "switch", "typedef", "union",
"unsigned", "void", "volatile", "while", NULL
};
static const char *c_types[] = {
"bool", "size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t",
"int8_t", "int16_t", "int32_t", "int64_t",
"uint8_t", "uint16_t", "uint32_t", "uint64_t",
"FILE", "DIR", "time_t", "clock_t", "off_t", "pid_t", "uid_t", "gid_t",
NULL
};
static const char *c_constants[] = {
"NULL", "true", "false", "EOF", "errno",
"STDIN_FILENO", "STDOUT_FILENO", "STDERR_FILENO",
"EXIT_SUCCESS", "EXIT_FAILURE", NULL
};
static int in_word_list(const char *word, int len, const char **list) {
for (int i = 0; list[i]; i++) {
if ((int)strlen(list[i]) == len && strncmp(list[i], word, len) == 0) {
return 1;
}
}
return 0;
}
int render_calc_comment_state(const Editor *ed, int target_line) {
int in_comment = 0;
for (int y = 0; y < target_line && y < ed->num_lines; y++) {
const char *line = ed->lines[y];
int len = (int)strlen(line);
int i = 0;
while (i < len) {
if (in_comment) {
if (line[i] == '*' && i + 1 < len && line[i + 1] == '/') {
in_comment = 0;
i += 2;
} else {
i++;
}
} else {
if (line[i] == '/' && i + 1 < len && line[i + 1] == '/') {
break;
} else if (line[i] == '/' && i + 1 < len && line[i + 1] == '*') {
in_comment = 1;
i += 2;
} else if (line[i] == '"' || line[i] == '\'') {
char quote = line[i++];
while (i < len && line[i] != quote) {
if (line[i] == '\\' && i + 1 < len) i++;
i++;
}
if (i < len) i++;
} else {
i++;
}
}
}
}
return in_comment;
}
void render_syntax_line(Editor *ed, const char *line, int scroll_x, int x, int y, int max_chars, int *in_comment) {
int len = (int)strlen(line);
int start_byte = utf8_byte_offset(line, scroll_x);
int end_byte = utf8_byte_offset(line, scroll_x + max_chars);
int first_non_space = 0;
while (first_non_space < len && isspace((unsigned char)line[first_non_space])) {
first_non_space++;
}
if (!(*in_comment) && first_non_space < len && line[first_non_space] == '#') {
if (start_byte < len) {
XftDrawStringUtf8(ed->xft_draw, &ed->xft_prep, ed->font, x, y,
(const FcChar8 *)(line + start_byte), end_byte - start_byte);
}
return;
}
int i = 0;
while (i < len) {
int tok_start = i;
int tok_end = i;
XftColor *color = &ed->xft_fg;
if (*in_comment) {
color = &ed->xft_mcom;
while (tok_end < len) {
if (line[tok_end] == '*' && tok_end + 1 < len && line[tok_end + 1] == '/') {
tok_end += 2;
*in_comment = 0;
break;
}
tok_end++;
}
} else if (line[i] == '/' && i + 1 < len && line[i + 1] == '/') {
color = &ed->xft_com;
tok_end = len;
} else if (line[i] == '/' && i + 1 < len && line[i + 1] == '*') {
color = &ed->xft_mcom;
tok_end += 2;
*in_comment = 1;
while (tok_end < len) {
if (line[tok_end] == '*' && tok_end + 1 < len && line[tok_end + 1] == '/') {
tok_end += 2;
*in_comment = 0;
break;
}
tok_end++;
}
} else if (line[i] == '"' || line[i] == '\'') {
char quote = line[i];
tok_end++;
while (tok_end < len && line[tok_end] != quote) {
if (line[tok_end] == '\\' && tok_end + 1 < len) tok_end++;
tok_end++;
}
if (tok_end < len) tok_end++;
color = &ed->xft_str;
} else if (isdigit((unsigned char)line[i])) {
color = &ed->xft_num;
if (line[i] == '0' && i + 1 < len && (line[i + 1] == 'x' || line[i + 1] == 'X')) {
tok_end += 2;
while (tok_end < len && (isxdigit((unsigned char)line[tok_end]) || line[tok_end] == '_')) {
tok_end++;
}
} else if (line[i] == '0' && i + 1 < len && (line[i + 1] == 'b' || line[i + 1] == 'B')) {
tok_end += 2;
while (tok_end < len && (line[tok_end] == '0' || line[tok_end] == '1' || line[tok_end] == '_')) {
tok_end++;
}
} else {
while (tok_end < len && (isdigit((unsigned char)line[tok_end]) || line[tok_end] == '.' || line[tok_end] == '_')) {
tok_end++;
}
if (tok_end < len && (line[tok_end] == 'e' || line[tok_end] == 'E')) {
tok_end++;
if (tok_end < len && (line[tok_end] == '+' || line[tok_end] == '-')) tok_end++;
while (tok_end < len && isdigit((unsigned char)line[tok_end])) tok_end++;
}
}
while (tok_end < len && strchr("uUlLfF", line[tok_end])) {
tok_end++;
}
} else if (isalpha((unsigned char)line[i]) || line[i] == '_') {
while (tok_end < len && (isalnum((unsigned char)line[tok_end]) || line[tok_end] == '_')) {
tok_end++;
}
int wlen = tok_end - tok_start;
if (in_word_list(&line[tok_start], wlen, c_keywords)) {
color = &ed->xft_kw;
} else if (in_word_list(&line[tok_start], wlen, c_types)) {
color = &ed->xft_type;
} else if (in_word_list(&line[tok_start], wlen, c_constants)) {
color = &ed->xft_num;
} else {
color = &ed->xft_fg;
}
} else {
tok_end = utf8_next_char_pos(line, i);
}
if (start_byte < len) {
int vis_start = (tok_start > start_byte) ? tok_start : start_byte;
int vis_end = (tok_end < end_byte) ? tok_end : end_byte;
if (vis_start < vis_end) {
int col_offset = utf8_char_count(line + start_byte, vis_start - start_byte);
XftDrawStringUtf8(ed->xft_draw, color, ed->font,
x + col_offset * ed->char_w, y,
(const FcChar8 *)&line[vis_start], vis_end - vis_start);
}
}
i = tok_end;
}
}
+251
View File
@@ -0,0 +1,251 @@
#include "render.h"
#include <stdio.h>
#include <string.h>
#define BAR_BUF_LEN 512
void render_search_highlights(Editor *ed, int line_idx, int top_y, int visible_cols) {
if (!ed->search_mode || !ed->search_highlight_all) return;
int qlen = (int)strlen(ed->search_query);
if (qlen == 0) return;
const char *line = ed->lines[line_idx];
const char *p = line;
while ((p = strstr(p, ed->search_query)) != NULL) {
int b_start = (int)(p - line);
int b_end = b_start + qlen;
int c_start = utf8_char_count(line, b_start);
int c_end = utf8_char_count(line, b_end);
if (c_end > ed->scroll_x && c_start < ed->scroll_x + visible_cols + 1) {
int vis_s = (c_start < ed->scroll_x) ? ed->scroll_x : c_start;
int vis_e = (c_end > ed->scroll_x + visible_cols + 1) ? (ed->scroll_x + visible_cols + 1) : c_end;
int x1 = GUTTER_W + 8 + (vis_s - ed->scroll_x) * ed->char_w;
int w = (vis_e - vis_s) * ed->char_w;
if (w > 0) {
XSetForeground(ed->dpy, ed->gc, ed->col_match_all);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, x1, top_y, w, ed->line_h);
}
}
p += qlen;
}
}
void render_selection_bg(Editor *ed, int line_idx, int top_y, int visible_cols) {
if (!ed->has_sel) return;
int sy, sx, ey, ex;
editor_get_sel_bounds(ed, &sy, &sx, &ey, &ex);
if (line_idx < sy || line_idx > ey) return;
const char *line = ed->lines[line_idx];
int line_len = (int)strlen(line);
int b_start = (line_idx == sy) ? sx : 0;
int b_end = (line_idx == ey) ? ex : line_len;
int c_start = utf8_char_count(line, b_start);
int c_end = utf8_char_count(line, b_end);
if (line_idx < ey) c_end += 1;
if (c_end <= ed->scroll_x || c_start >= ed->scroll_x + visible_cols + 1) return;
if (c_start < ed->scroll_x) c_start = ed->scroll_x;
if (c_end > ed->scroll_x + visible_cols + 1) c_end = ed->scroll_x + visible_cols + 1;
int x1 = GUTTER_W + 8 + (c_start - ed->scroll_x) * ed->char_w;
int w = (c_end - c_start) * ed->char_w;
if (w > 0) {
unsigned long bg = (ed->search_mode && ed->search_highlight_all) ? ed->col_match_cur : ed->col_sel;
XSetForeground(ed->dpy, ed->gc, bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, x1, top_y, w, ed->line_h);
}
}
void render_hover_symbol_link(Editor *ed, int line_idx, int top_y, int baseline_y, int visible_cols) {
if (ed->hover_sym_line != line_idx) return;
const char *line = ed->lines[line_idx];
int vis_b_start = (ed->hover_sym_sx > utf8_byte_offset(line, ed->scroll_x))
? ed->hover_sym_sx : utf8_byte_offset(line, ed->scroll_x);
int vis_b_end = (ed->hover_sym_ex < utf8_byte_offset(line, ed->scroll_x + visible_cols + 1))
? ed->hover_sym_ex : utf8_byte_offset(line, ed->scroll_x + visible_cols + 1);
if (vis_b_start >= vis_b_end) return;
int c_start = utf8_char_count(line, vis_b_start);
int c_end = utf8_char_count(line, vis_b_end);
int x1 = GUTTER_W + 8 + (c_start - ed->scroll_x) * ed->char_w;
int w = (c_end - c_start) * ed->char_w;
if (w > 0) {
unsigned long line_bg = (line_idx == ed->cy && !ed->has_sel) ? ed->col_curline : ed->col_bg;
XSetForeground(ed->dpy, ed->gc, line_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, x1, top_y, w, ed->line_h);
XftDrawStringUtf8(ed->xft_draw, &ed->xft_link, ed->font, x1, baseline_y,
(const FcChar8 *)&line[vis_b_start], vis_b_end - vis_b_start);
XSetForeground(ed->dpy, ed->gc, ed->xft_link.pixel);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, x1, baseline_y + 1, x1 + w - 1, baseline_y + 1);
}
}
/* dir: 0 = вверх, 1 = вниз, 2 = влево, 3 = вправо */
static void draw_sb_arrow_btn(Editor *ed, int x, int y, int dir, int hovered, int pressed) {
unsigned long bg = pressed ? ed->col_sel : (hovered ? ed->col_bg : ed->col_status);
XSetForeground(ed->dpy, ed->gc, bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, x, y, SCROLLBAR_W, SCROLLBAR_W);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, x, y, SCROLLBAR_W - 1, SCROLLBAR_W - 1);
int shift = pressed ? 1 : 0;
int cx = x + SCROLLBAR_W / 2 + shift;
int cy = y + SCROLLBAR_W / 2 + shift;
XPoint p0, p1, p2;
if (dir == 0) {
p0 = (XPoint){(short)(cx - 3), (short)(cy + 2)};
p1 = (XPoint){(short)(cx + 3), (short)(cy + 2)};
p2 = (XPoint){(short)cx, (short)(cy - 2)};
} else if (dir == 1) {
p0 = (XPoint){(short)(cx - 3), (short)(cy - 2)};
p1 = (XPoint){(short)(cx + 3), (short)(cy - 2)};
p2 = (XPoint){(short)cx, (short)(cy + 2)};
} else if (dir == 2) {
p0 = (XPoint){(short)(cx + 2), (short)(cy - 3)};
p1 = (XPoint){(short)(cx + 2), (short)(cy + 3)};
p2 = (XPoint){(short)(cx - 2), (short)cy};
} else {
p0 = (XPoint){(short)(cx - 2), (short)(cy - 3)};
p1 = (XPoint){(short)(cx - 2), (short)(cy + 3)};
p2 = (XPoint){(short)(cx + 2), (short)cy};
}
XPoint tri[3] = {p0, p1, p2};
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XFillPolygon(ed->dpy, ed->backbuf, ed->gc, tri, 3, Convex, CoordModeOrigin);
}
void render_scrollbars(Editor *ed, int visible_lines, int visible_cols) {
int st_h = editor_status_h(ed);
int v_track_x = ed->win_w - SCROLLBAR_W;
int v_full_y = TOP_UI_H;
int v_full_h = ed->win_h - TOP_UI_H - st_h - SCROLLBAR_W;
if (v_full_h >= SCROLLBAR_W * 2) {
draw_sb_arrow_btn(ed, v_track_x, v_full_y, 0, ed->hover_btn == 2, ed->pressed_btn == 2);
draw_sb_arrow_btn(ed, v_track_x, v_full_y + v_full_h - SCROLLBAR_W, 1, ed->hover_btn == 3, ed->pressed_btn == 3);
int v_track_y = v_full_y + SCROLLBAR_W;
int v_track_h = v_full_h - SCROLLBAR_W * 2;
XSetForeground(ed->dpy, ed->gc, ed->col_sb_track);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, v_track_x, v_track_y, SCROLLBAR_W, v_track_h);
if (ed->num_lines > visible_lines && v_track_h > 0) {
int thumb_h = (v_track_h * visible_lines) / ed->num_lines;
if (thumb_h < 16) thumb_h = 16;
if (thumb_h > v_track_h) thumb_h = v_track_h;
int max_sy = ed->num_lines - visible_lines;
int thumb_y = v_track_y + ((max_sy > 0) ? (ed->scroll_y * (v_track_h - thumb_h)) / max_sy : 0);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, v_track_x + 2, thumb_y, SCROLLBAR_W - 4, thumb_h);
}
}
int h_full_x = GUTTER_W;
int h_track_y = ed->win_h - st_h - SCROLLBAR_W;
int h_full_w = ed->win_w - GUTTER_W - SCROLLBAR_W;
if (h_full_w >= SCROLLBAR_W * 2) {
draw_sb_arrow_btn(ed, h_full_x, h_track_y, 2, ed->hover_btn == 4, ed->pressed_btn == 4);
draw_sb_arrow_btn(ed, h_full_x + h_full_w - SCROLLBAR_W, h_track_y, 3, ed->hover_btn == 5, ed->pressed_btn == 5);
int h_track_x = h_full_x + SCROLLBAR_W;
int h_track_w = h_full_w - SCROLLBAR_W * 2;
XSetForeground(ed->dpy, ed->gc, ed->col_sb_track);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, h_track_x, h_track_y, h_track_w, SCROLLBAR_W);
int max_cols = editor_max_line_len(ed);
if (max_cols > visible_cols && h_track_w > 0) {
int thumb_w = (h_track_w * visible_cols) / max_cols;
if (thumb_w < 16) thumb_w = 16;
if (thumb_w > h_track_w) thumb_w = h_track_w;
int max_sx = max_cols - visible_cols;
int thumb_x = h_track_x + ((max_sx > 0) ? (ed->scroll_x * (h_track_w - thumb_w)) / max_sx : 0);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, thumb_x, h_track_y + 2, thumb_w, SCROLLBAR_W - 4);
}
}
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, v_track_x, h_track_y, SCROLLBAR_W, SCROLLBAR_W);
int st_pressed = (ed->pressed_btn == 1);
unsigned long st_bg = st_pressed ? ed->col_sel : ((ed->hover_btn == 1) ? ed->col_bg : ed->col_gutter);
XSetForeground(ed->dpy, ed->gc, st_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, h_track_y, GUTTER_W, SCROLLBAR_W);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, 0, h_track_y, GUTTER_W - 1, h_track_y);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, GUTTER_W - 1, h_track_y, GUTTER_W - 1, h_track_y + SCROLLBAR_W);
int shift = st_pressed ? 1 : 0;
int cx = GUTTER_W / 2 + shift;
int cy = h_track_y + SCROLLBAR_W / 2 + shift;
XPoint p0, p1, p2;
if (!ed->status_collapsed) {
p0 = (XPoint){(short)(cx - 4), (short)(cy - 2)};
p1 = (XPoint){(short)(cx + 4), (short)(cy - 2)};
p2 = (XPoint){(short)cx, (short)(cy + 3)};
} else {
p0 = (XPoint){(short)(cx - 4), (short)(cy + 2)};
p1 = (XPoint){(short)(cx + 4), (short)(cy + 2)};
p2 = (XPoint){(short)cx, (short)(cy - 3)};
}
XPoint tri[3] = {p0, p1, p2};
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XFillPolygon(ed->dpy, ed->backbuf, ed->gc, tri, 3, Convex, CoordModeOrigin);
}
void render_status_bar(Editor *ed, int cur_col) {
if (ed->status_collapsed) return;
int st_h = editor_status_h(ed);
int status_y = ed->win_h - st_h;
XSetForeground(ed->dpy, ed->gc, ed->col_status);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, status_y, ed->win_w, st_h);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, 0, status_y, ed->win_w, status_y);
int baseline = status_y + ed->font->ascent + 4;
char bar[BAR_BUF_LEN];
if (ed->search_mode) {
snprintf(bar, sizeof(bar), " Find: %s_ ", ed->search_query);
int bar_len = (int)strlen(bar);
int bar_cols = utf8_char_count(bar, bar_len);
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, 6, baseline,
(const FcChar8 *)bar, bar_len);
int box_x = 6 + bar_cols * ed->char_w;
int box_y = status_y + (st_h - 14) / 2;
XSetForeground(ed->dpy, ed->gc, ed->col_bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, box_x, box_y, 14, 14);
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, box_x, box_y, 14, 14);
if (ed->search_highlight_all) {
XDrawLine(ed->dpy, ed->backbuf, ed->gc, box_x + 3, box_y + 7, box_x + 6, box_y + 11);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, box_x + 6, box_y + 11, box_x + 11, box_y + 3);
}
const char *lbl = " All | Enter: Next | Shift+Enter: Prev | Esc: Close";
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, box_x + 18, baseline,
(const FcChar8 *)lbl, (int)strlen(lbl));
ed->chk_x1 = box_x;
ed->chk_x2 = box_x + 18 + 4 * ed->char_w;
} else {
snprintf(bar, sizeof(bar), " %.200s | Ln %d, Col %d | Ctrl+O: Open | Ctrl+N/W: Tabs",
ed->status_msg, ed->cy + 1, cur_col + 1);
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, 6, baseline,
(const FcChar8 *)bar, (int)strlen(bar));
}
}
+480
View File
@@ -0,0 +1,480 @@
#include "editor.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAB_MIN_W 110
#define TAB_MAX_W 210
#define TAB_NEW_BTN_W 28
static const char *base_filename(const char *path) {
const char *slash = strrchr(path, '/');
return slash ? (slash + 1) : path;
}
static void free_tab_storage(EditorTab *t) {
free(t->lines);
t->lines = NULL;
for (int i = 0; i < t->undo_count; i++) {
free(t->undo_stack[i].lines);
t->undo_stack[i].lines = NULL;
}
for (int i = 0; i < t->redo_count; i++) {
free(t->redo_stack[i].lines);
t->redo_stack[i].lines = NULL;
}
t->undo_count = 0;
t->redo_count = 0;
}
static void save_active_to_tab(Editor *ed) {
if (ed->active_tab < 0 || ed->active_tab >= ed->num_tabs) return;
EditorTab *t = &ed->tabs[ed->active_tab];
if (!t->lines) {
t->lines = malloc((size_t)MAX_LINES * MAX_LEN);
}
if (t->lines) {
memcpy(t->lines, ed->lines, (size_t)ed->num_lines * MAX_LEN);
}
t->num_lines = ed->num_lines;
t->cx = ed->cx;
t->cy = ed->cy;
t->scroll_x = ed->scroll_x;
t->scroll_y = ed->scroll_y;
t->has_sel = ed->has_sel;
t->sel_ax = ed->sel_ax;
t->sel_ay = ed->sel_ay;
memcpy(t->undo_stack, ed->undo_stack, sizeof(ed->undo_stack));
t->undo_count = ed->undo_count;
memset(ed->undo_stack, 0, sizeof(ed->undo_stack));
ed->undo_count = 0;
memcpy(t->redo_stack, ed->redo_stack, sizeof(ed->redo_stack));
t->redo_count = ed->redo_count;
memset(ed->redo_stack, 0, sizeof(ed->redo_stack));
ed->redo_count = 0;
memcpy(t->nav_back, ed->nav_back, sizeof(ed->nav_back));
t->nav_back_count = ed->nav_back_count;
memcpy(t->nav_fwd, ed->nav_fwd, sizeof(ed->nav_fwd));
t->nav_fwd_count = ed->nav_fwd_count;
t->dirty = ed->dirty;
t->saved_undo_level = ed->saved_undo_level;
snprintf(t->filename, sizeof(t->filename), "%s", ed->filename);
}
static void load_tab_to_active(Editor *ed, int idx) {
EditorTab *t = &ed->tabs[idx];
ed->active_tab = idx;
if (t->lines) {
memcpy(ed->lines, t->lines, (size_t)t->num_lines * MAX_LEN);
} else {
**ed->lines = '\0';
}
ed->num_lines = (t->num_lines > 0) ? t->num_lines : 1;
ed->cx = t->cx;
ed->cy = t->cy;
ed->scroll_x = t->scroll_x;
ed->scroll_y = t->scroll_y;
ed->has_sel = t->has_sel;
ed->sel_ax = t->sel_ax;
ed->sel_ay = t->sel_ay;
memcpy(ed->undo_stack, t->undo_stack, sizeof(ed->undo_stack));
ed->undo_count = t->undo_count;
memset(t->undo_stack, 0, sizeof(t->undo_stack));
t->undo_count = 0;
memcpy(ed->redo_stack, t->redo_stack, sizeof(ed->redo_stack));
ed->redo_count = t->redo_count;
memset(t->redo_stack, 0, sizeof(t->redo_stack));
t->redo_count = 0;
memcpy(ed->nav_back, t->nav_back, sizeof(ed->nav_back));
ed->nav_back_count = t->nav_back_count;
memcpy(ed->nav_fwd, t->nav_fwd, sizeof(ed->nav_fwd));
ed->nav_fwd_count = t->nav_fwd_count;
snprintf(ed->filename, sizeof(ed->filename), "%s", t->filename);
ed->saved_undo_level = t->saved_undo_level;
editor_set_dirty(ed, t->dirty);
ed->hover_sym_line = -1;
}
static int calc_tab_width(const Editor *ed) {
if (ed->num_tabs <= 0) return TAB_MAX_W;
int avail = ed->win_w - TAB_NEW_BTN_W - 8;
int w = avail / ed->num_tabs;
if (w > TAB_MAX_W) w = TAB_MAX_W;
if (w < TAB_MIN_W) w = TAB_MIN_W;
return w;
}
void tabs_new(Editor *ed, const char *fname) {
if (ed->num_tabs >= MAX_TABS) {
snprintf(ed->status_msg, sizeof(ed->status_msg), "Максимум %d вкладок", MAX_TABS);
return;
}
if (ed->num_tabs > 0) {
save_active_to_tab(ed);
}
int idx = ed->num_tabs++;
memset(&ed->tabs[idx], 0, sizeof(EditorTab));
ed->active_tab = idx;
ed->cx = 0;
ed->cy = 0;
ed->scroll_x = 0;
ed->scroll_y = 0;
ed->has_sel = 0;
ed->undo_count = 0;
ed->redo_count = 0;
ed->nav_back_count = 0;
ed->nav_fwd_count = 0;
ed->saved_undo_level = 0;
if (fname && *fname != '\0') {
editor_load(ed, fname);
} else {
char def_name[FNAME_LEN];
snprintf(def_name, sizeof(def_name), "untitled_%d.c", idx + 1);
snprintf(ed->filename, sizeof(ed->filename), "%s", def_name);
ed->num_lines = 1;
**ed->lines = '\0';
editor_set_dirty(ed, 0);
snprintf(ed->status_msg, sizeof(ed->status_msg), "New tab: %s", def_name);
}
save_active_to_tab(ed);
load_tab_to_active(ed, idx);
}
void tabs_open_file(Editor *ed, const char *fname) {
if (!fname || *fname == '\0') return;
for (int i = 0; i < ed->num_tabs; i++) {
const char *tab_name = (i == ed->active_tab) ? ed->filename : ed->tabs[i].filename;
if (strcmp(tab_name, fname) == 0) {
tabs_switch(ed, i);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Switched to open tab: %s", fname);
return;
}
}
tabs_new(ed, fname);
}
void tabs_switch(Editor *ed, int idx) {
if (idx < 0 || idx >= ed->num_tabs || idx == ed->active_tab) return;
save_active_to_tab(ed);
load_tab_to_active(ed, idx);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Tab: %s", ed->filename);
}
void tabs_next(Editor *ed, int prev) {
if (ed->num_tabs <= 1) return;
int next = ed->active_tab + (prev ? -1 : 1);
if (next < 0) next = ed->num_tabs - 1;
if (next >= ed->num_tabs) next = 0;
tabs_switch(ed, next);
}
void tabs_close_force(Editor *ed, int idx) {
if (idx < 0 || idx >= ed->num_tabs) return;
if (ed->num_tabs == 1) {
history_free_all(ed);
free_tab_storage(ed->tabs);
ed->num_tabs = 0;
ed->active_tab = -1;
tabs_new(ed, NULL);
return;
}
save_active_to_tab(ed);
free_tab_storage(&ed->tabs[idx]);
for (int i = idx; i < ed->num_tabs - 1; i++) {
ed->tabs[i] = ed->tabs[i + 1];
}
memset(&ed->tabs[ed->num_tabs - 1], 0, sizeof(EditorTab));
ed->num_tabs--;
int next_idx = ed->active_tab;
if (idx < ed->active_tab) next_idx--;
if (next_idx >= ed->num_tabs) next_idx = ed->num_tabs - 1;
if (next_idx < 0) next_idx = 0;
ed->active_tab = -1;
load_tab_to_active(ed, next_idx);
snprintf(ed->status_msg, sizeof(ed->status_msg), "Closed tab");
}
void tabs_request_close(Editor *ed, int idx) {
if (idx < 0 || idx >= ed->num_tabs) return;
int is_dirty = (idx == ed->active_tab) ? ed->dirty : ed->tabs[idx].dirty;
if (is_dirty) {
ed->confirm_mode = 1;
ed->confirm_target_tab = idx;
ed->confirm_hover_btn = 0;
} else {
tabs_close_force(ed, idx);
}
}
void tabs_request_quit(Editor *ed) {
for (int i = 0; i < ed->num_tabs; i++) {
int is_dirty = (i == ed->active_tab) ? ed->dirty : ed->tabs[i].dirty;
if (is_dirty) {
ed->confirm_mode = 2;
ed->confirm_target_tab = i;
ed->confirm_hover_btn = 0;
return;
}
}
ed->running = 0;
}
void tabs_init(Editor *ed, int argc, char *argv[]) {
ed->num_tabs = 0;
ed->active_tab = -1;
ed->hover_tab = -1;
ed->hover_tab_close = -1;
if (argc > 1) {
for (int i = 1; i < argc && ed->num_tabs < MAX_TABS; i++) {
tabs_new(ed, argv[i]);
}
tabs_switch(ed, 0);
} else {
tabs_new(ed, "main.c");
}
}
void tabs_free_all(Editor *ed) {
for (int i = 0; i < ed->num_tabs; i++) {
free_tab_storage(&ed->tabs[i]);
}
ed->num_tabs = 0;
}
void tabs_render(Editor *ed) {
int y0 = MENUBAR_H;
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, 0, y0, ed->win_w, TABBAR_H);
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, 0, y0 + TABBAR_H - 1, ed->win_w, y0 + TABBAR_H - 1);
int tw = calc_tab_width(ed);
int base_y = y0 + (TABBAR_H + ed->font->ascent - ed->font->descent) / 2;
for (int i = 0; i < ed->num_tabs; i++) {
int tx = i * tw;
if (tx >= ed->win_w - TAB_NEW_BTN_W) break;
int is_active = (i == ed->active_tab);
int is_dirty = is_active ? ed->dirty : ed->tabs[i].dirty;
const char *full_name = is_active ? ed->filename : ed->tabs[i].filename;
const char *short_name = base_filename(full_name);
unsigned long bg = is_active ? ed->col_bg : ((ed->hover_tab == i) ? ed->col_curline : ed->col_gutter);
XSetForeground(ed->dpy, ed->gc, bg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, tx, y0, tw, is_active ? TABBAR_H : (TABBAR_H - 1));
XSetForeground(ed->dpy, ed->gc, ed->col_sb_thumb);
XDrawLine(ed->dpy, ed->backbuf, ed->gc, tx + tw - 1, y0, tx + tw - 1, y0 + TABBAR_H - 1);
if (is_active) {
XSetForeground(ed->dpy, ed->gc, ed->xft_link.pixel);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, tx, y0, tw - 1, 2);
}
char label[FNAME_LEN + 8];
snprintf(label, sizeof(label), "%s%s", is_dirty ? "*" : "", short_name);
int max_chars = (tw - 26) / ed->char_w;
if (max_chars < 1) max_chars = 1;
int slen = (int)strlen(label);
if (slen > max_chars) {
label[max_chars] = '\0';
slen = max_chars;
}
XftColor *tcol = is_dirty ? &ed->xft_num : (is_active ? &ed->xft_fg : &ed->xft_lineno);
XftDrawStringUtf8(ed->xft_draw, tcol, ed->font, tx + 8, base_y,
(const FcChar8 *)label, slen);
int cx = tx + tw - 18;
int cy = y0 + (TABBAR_H - 14) / 2;
if (ed->hover_tab_close == i) {
XSetForeground(ed->dpy, ed->gc, ed->col_sel);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, cx, cy, 14, 14);
}
XftColor *xcol = (ed->hover_tab_close == i) ? &ed->xft_num : &ed->xft_lineno;
XftDrawStringUtf8(ed->xft_draw, xcol, ed->font, cx + 3, base_y,
(const FcChar8 *)"×", 2);
}
int plus_x = ed->num_tabs * tw;
if (plus_x + TAB_NEW_BTN_W <= ed->win_w) {
if (ed->hover_tab == -2) {
XSetForeground(ed->dpy, ed->gc, ed->col_curline);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, plus_x + 2, y0 + 2, TAB_NEW_BTN_W - 4, TABBAR_H - 5);
}
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, plus_x + 9, base_y,
(const FcChar8 *)"+", 1);
}
}
int tabs_handle_motion(Editor *ed, int mx, int my) {
int old_ht = ed->hover_tab;
int old_hc = ed->hover_tab_close;
ed->hover_tab = -1;
ed->hover_tab_close = -1;
if (ed->menu_open < 0 && ed->confirm_mode == 0 && my >= MENUBAR_H && my < TOP_UI_H) {
int tw = calc_tab_width(ed);
int idx = mx / tw;
if (idx >= 0 && idx < ed->num_tabs && (idx * tw) < ed->win_w - TAB_NEW_BTN_W) {
ed->hover_tab = idx;
int cx = idx * tw + tw - 18;
if (mx >= cx && mx < cx + 14) {
ed->hover_tab_close = idx;
}
} else {
int plus_x = ed->num_tabs * tw;
if (mx >= plus_x && mx < plus_x + TAB_NEW_BTN_W) {
ed->hover_tab = -2;
}
}
}
return (old_ht != ed->hover_tab || old_hc != ed->hover_tab_close);
}
int tabs_handle_click(Editor *ed, int mx, int my, int button) {
if (my < MENUBAR_H || my >= TOP_UI_H) return 0;
if (ed->menu_open >= 0) return 0;
int tw = calc_tab_width(ed);
int idx = mx / tw;
if (idx >= 0 && idx < ed->num_tabs && (idx * tw) < ed->win_w - TAB_NEW_BTN_W) {
int cx = idx * tw + tw - 18;
if (button == Button2 || (button == Button1 && mx >= cx && mx < cx + 14)) {
tabs_request_close(ed, idx);
} else if (button == Button1) {
tabs_switch(ed, idx);
}
return 1;
}
int plus_x = ed->num_tabs * tw;
if (button == Button1 && mx >= plus_x && mx < plus_x + TAB_NEW_BTN_W) {
tabs_new(ed, NULL);
return 1;
}
return 1;
}
/* --- Модальный диалог подтверждения закрытия / выхода --- */
#define DLG_W 440
#define DLG_H 128
static void confirm_apply_choice(Editor *ed, int choice) {
int mode = ed->confirm_mode;
int target = ed->confirm_target_tab;
ed->confirm_mode = 0;
if (choice == 2) return; /* Отмена */
if (mode == 1) {
if (choice == 0) {
int prev = ed->active_tab;
tabs_switch(ed, target);
editor_save(ed);
if (prev != target) tabs_switch(ed, prev);
}
tabs_close_force(ed, target);
} else if (mode == 2) {
if (choice == 0) {
for (int i = 0; i < ed->num_tabs; i++) {
int d = (i == ed->active_tab) ? ed->dirty : ed->tabs[i].dirty;
if (d) {
tabs_switch(ed, i);
editor_save(ed);
}
}
}
ed->running = 0;
}
}
void confirm_render(Editor *ed) {
if (ed->confirm_mode == 0) return;
int dx = (ed->win_w - DLG_W) / 2;
int dy = (ed->win_h - DLG_H) / 2;
XSetForeground(ed->dpy, ed->gc, ed->col_gutter);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx, dy, DLG_W, DLG_H);
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, dx, dy, DLG_W - 1, DLG_H - 1);
XSetForeground(ed->dpy, ed->gc, ed->col_status);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, dx + 1, dy + 1, DLG_W - 2, 26);
const char *hdr = (ed->confirm_mode == 1) ? "Несохранённые изменения во вкладке" : "Несохранённые изменения";
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 12, dy + 18,
(const FcChar8 *)hdr, (int)strlen(hdr));
char msg[STATUS_LEN];
if (ed->confirm_mode == 1) {
const char *fn = (ed->confirm_target_tab == ed->active_tab)
? ed->filename : ed->tabs[ed->confirm_target_tab].filename;
snprintf(msg, sizeof(msg), "Сохранить изменения в «%s»?", base_filename(fn));
} else {
snprintf(msg, sizeof(msg), "Сохранить изменения перед выходом?");
}
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, dx + 14, dy + 54,
(const FcChar8 *)msg, (int)strlen(msg));
const char *btns[] = {"Сохранить (S)", "Не сохранять (N)", "Отмена (Esc)"};
int bw = 132, bh = 28, gap = 10;
int start_x = dx + (DLG_W - (bw * 3 + gap * 2)) / 2;
int by = dy + DLG_H - bh - 14;
for (int i = 0; i < 3; i++) {
int bx = start_x + i * (bw + gap);
unsigned long bbg = (ed->confirm_hover_btn == i) ? ed->col_match_cur : ed->col_status;
XSetForeground(ed->dpy, ed->gc, bbg);
XFillRectangle(ed->dpy, ed->backbuf, ed->gc, bx, by, bw, bh);
XSetForeground(ed->dpy, ed->gc, ed->col_fg);
XDrawRectangle(ed->dpy, ed->backbuf, ed->gc, bx, by, bw - 1, bh - 1);
int tlen = (int)strlen(btns[i]);
int tcols = utf8_char_count(btns[i], tlen);
int tx = bx + (bw - tcols * ed->char_w) / 2;
int ty = by + (bh + ed->font->ascent - ed->font->descent) / 2;
XftDrawStringUtf8(ed->xft_draw, &ed->xft_fg, ed->font, tx, ty,
(const FcChar8 *)btns[i], tlen);
}
}
int confirm_handle_motion(Editor *ed, int mx, int my) {
if (ed->confirm_mode == 0) return 0;
int old = ed->confirm_hover_btn;
ed->confirm_hover_btn = -1;
int dx = (ed->win_w - DLG_W) / 2;
int dy = (ed->win_h - DLG_H) / 2;
int bw = 132, bh = 28, gap = 10;
int start_x = dx + (DLG_W - (bw * 3 + gap * 2)) / 2;
int by = dy + DLG_H - bh - 14;
if (my >= by && my < by + bh) {
for (int i = 0; i < 3; i++) {
int bx = start_x + i * (bw + gap);
if (mx >= bx && mx < bx + bw) {
ed->confirm_hover_btn = i;
break;
}
}
}
return (old != ed->confirm_hover_btn);
}
int confirm_handle_click(Editor *ed, int mx, int my) {
if (ed->confirm_mode == 0) return 0;
confirm_handle_motion(ed, mx, my);
if (ed->confirm_hover_btn >= 0) {
confirm_apply_choice(ed, ed->confirm_hover_btn);
}
return 1;
}
void confirm_handle_key(Editor *ed, KeySym ks) {
if (ed->confirm_mode == 0) return;
if (ks == XK_Escape || ks == XK_c || ks == XK_C) confirm_apply_choice(ed, 2);
else if (ks == XK_s || ks == XK_S || ks == XK_Return || ks == XK_KP_Enter) confirm_apply_choice(ed, 0);
else if (ks == XK_n || ks == XK_N) confirm_apply_choice(ed, 1);
else if (ks == XK_Left) ed->confirm_hover_btn = (ed->confirm_hover_btn + 2) % 3;
else if (ks == XK_Right || ks == XK_Tab) ed->confirm_hover_btn = (ed->confirm_hover_btn + 1) % 3;
}