client.cc (19421B)
1 #include "client.hh" 2 3 #include "clock.hh" 4 #include "context.hh" 5 #include "buffer_utils.hh" 6 #include "debug.hh" 7 #include "file.hh" 8 #include "remote.hh" 9 #include "option.hh" 10 #include "option_types.hh" 11 #include "client_manager.hh" 12 #include "event_manager.hh" 13 #include "hook_manager.hh" 14 #include "keymap_manager.hh" 15 #include "option_manager.hh" 16 #include "shell_manager.hh" 17 #include "face_registry.hh" 18 #include "command_manager.hh" 19 #include "user_interface.hh" 20 #include "window.hh" 21 #include "hash_map.hh" 22 23 #include <csignal> 24 #include <unistd.h> 25 26 #include <utility> 27 28 namespace Kakoune 29 { 30 31 Client::Client(UniquePtr<UserInterface>&& ui, 32 UniquePtr<Window>&& window, 33 SelectionList selections, int pid, 34 EnvVarMap env_vars, 35 String name, 36 OnExitCallback on_exit) 37 : m_ui{std::move(ui)}, m_window{std::move(window)}, 38 m_pid{pid}, 39 m_on_exit{std::move(on_exit)}, 40 m_env_vars(std::move(env_vars)), 41 m_input_handler{std::move(selections), Context::Flags::None, 42 std::move(name)} 43 { 44 m_window->set_client(this); 45 46 context().set_client(*this); 47 context().set_window(*m_window); 48 49 m_window->set_dimensions(m_ui->dimensions()); 50 m_window->options().register_watcher(*this); 51 52 m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); 53 m_ui->set_on_key([this](Key key) { 54 kak_assert(key != Key::Invalid); 55 if (key == ctrl('c')) 56 { 57 auto prev_handler = set_signal_handler(SIGINT, SIG_IGN); 58 killpg(getpgrp(), SIGINT); 59 set_signal_handler(SIGINT, prev_handler); 60 } 61 else if (key == ctrl('g')) 62 { 63 m_pending_keys.clear(); 64 print_status({}, {"operation cancelled", context().faces()["Error"]}, -1, StatusStyle::Status); 65 throw cancel{}; 66 } 67 else if (key.modifiers & Key::Modifiers::Resize) 68 { 69 m_window->set_dimensions(key.coord()); 70 force_redraw(true); 71 } 72 else 73 m_pending_keys.push_back(key); 74 }); 75 m_ui->set_on_paste([this](StringView content) { 76 context().input_handler().paste(content); 77 }); 78 79 m_window->hooks().run_hook(Hook::WinDisplay, m_window->buffer().name(), context()); 80 81 force_redraw(); 82 } 83 84 Client::~Client() 85 { 86 m_window->options().unregister_watcher(*this); 87 m_window->set_client(nullptr); 88 // Do not move the selections here, as we need them to be valid 89 // in order to correctly destroy the input handler 90 ClientManager::instance().add_free_window(std::move(m_window), 91 context().selections()); 92 } 93 94 bool Client::is_ui_ok() const 95 { 96 return m_ui->is_ok(); 97 } 98 99 bool Client::process_pending_inputs() 100 { 101 const bool debug_keys = (bool)(context().options()["debug"].get<DebugFlags>() & DebugFlags::Keys); 102 m_window->run_resize_hook_ifn(); 103 // steal keys as we might receive new keys while handling them. 104 Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys); 105 for (auto& key : keys) 106 { 107 try 108 { 109 if (debug_keys) 110 write_to_debug_buffer(format("Client '{}' got key '{}'", context().name(), key)); 111 112 if (key == Key::FocusIn) 113 context().hooks().run_hook(Hook::FocusIn, context().name(), context()); 114 else if (key == Key::FocusOut) 115 context().hooks().run_hook(Hook::FocusOut, context().name(), context()); 116 else 117 { 118 context().ensure_cursor_visible = true; 119 m_input_handler.handle_key(key, /*synthesized=*/false); 120 } 121 122 context().hooks().run_hook(Hook::RawKey, to_string(key), context()); 123 } 124 catch (Kakoune::runtime_error& error) 125 { 126 write_to_debug_buffer(format("Error: {}", error.what())); 127 context().print_status({}, {error.what().str(), context().faces()["Error"]}, -1, StatusStyle::Status); 128 context().hooks().run_hook(Hook::RuntimeError, error.what(), context()); 129 } 130 } 131 return not keys.empty(); 132 } 133 134 void Client::print_status(DisplayLine prompt, DisplayLine content, ColumnCount cursor_pos, StatusStyle style) 135 { 136 m_status_prompt = std::move(prompt); 137 m_status_content = std::move(content); 138 m_status_cursor_pos = cursor_pos; 139 m_status_style = style; 140 m_ui_pending |= StatusLine; 141 m_pending_clear &= ~PendingClear::StatusLine; 142 } 143 144 145 DisplayCoord Client::dimensions() const 146 { 147 return m_ui->dimensions(); 148 } 149 150 String generate_context_info(const Context& context) 151 { 152 String s = ""; 153 if (context.buffer().is_modified()) 154 s += "[+]"; 155 if (context.client().input_handler().is_recording()) 156 s += format("[recording ({})]", context.client().input_handler().recording_reg()); 157 if (context.hooks_disabled()) 158 s += "[no-hooks]"; 159 if (not(context.buffer().flags() & (Buffer::Flags::File | Buffer::Flags::Debug))) 160 s += "[scratch]"; 161 if (context.buffer().flags() & Buffer::Flags::New) 162 s += "[new file]"; 163 if (context.buffer().flags() & Buffer::Flags::Fifo) 164 s += "[fifo]"; 165 if (context.buffer().flags() & Buffer::Flags::Debug) 166 s += "[debug]"; 167 if (context.buffer().flags() & Buffer::Flags::ReadOnly) 168 s += "[readonly]"; 169 return s; 170 } 171 172 DisplayLine Client::generate_mode_line() const 173 { 174 DisplayLine modeline; 175 try 176 { 177 auto [mode_info_line, normal_params] = context().client().input_handler().mode_info(); 178 const String& modelinefmt = context().options()["modelinefmt"].get<String>(); 179 HashMap<String, DisplayLine> atoms{{ "mode_info", mode_info_line}, 180 { "context_info", {generate_context_info(context()), 181 context().faces()["Information"]}}}; 182 ShellContext shell_context{{}, { 183 {"register", normal_params ? StringView{normal_params->reg}.str() : ""}, 184 {"count", normal_params ? String{to_string(normal_params->count)} : ""}, 185 }}; 186 auto expanded = expand(modelinefmt, context(), shell_context, 187 [](String s) { return escape(s, '{', '\\'); }); 188 modeline = parse_display_line(expanded, context().faces(), atoms); 189 } 190 catch (runtime_error& err) 191 { 192 write_to_debug_buffer(format("Error while parsing modelinefmt: {}", err.what())); 193 modeline.push_back({ "modelinefmt error, see *debug* buffer", context().faces()["Error"] }); 194 } 195 196 return modeline; 197 } 198 199 void Client::change_buffer(Buffer& buffer, Optional<FunctionRef<void()>> set_selections) 200 { 201 if (m_buffer_reload_dialog_opened) 202 close_buffer_reload_dialog(); 203 204 if (context().buffer().flags() & Buffer::Flags::Locked) 205 throw runtime_error("Changing buffer is not allowed while current buffer is locked"); 206 207 buffer.flags() |= Buffer::Flags::Locked; 208 OnScopeEnd unlock{[&] { buffer.flags() &= ~Buffer::Flags::Locked; }}; 209 210 auto& client_manager = ClientManager::instance(); 211 WindowAndSelections ws = client_manager.get_free_window(buffer); 212 213 m_window->options().unregister_watcher(*this); 214 m_window->set_client(nullptr); 215 client_manager.add_free_window(std::move(m_window), 216 context().selections()); 217 218 m_window = std::move(ws.window); 219 m_window->set_client(this); 220 m_window->options().register_watcher(*this); 221 222 if (set_selections) 223 (*set_selections)(); 224 else 225 { 226 ScopedSelectionEdition selection_edition{context()}; 227 context().selections_write_only() = std::move(ws.selections); 228 } 229 230 context().set_window(*m_window); 231 232 m_window->set_dimensions(m_ui->dimensions()); 233 m_ui->set_ui_options(m_window->options()["ui_options"].get<UserInterface::Options>()); 234 235 m_window->hooks().run_hook(Hook::WinDisplay, buffer.name(), context()); 236 force_redraw(true); 237 } 238 239 static bool is_inline(InfoStyle style) 240 { 241 return style == InfoStyle::Inline or 242 style == InfoStyle::InlineAbove or 243 style == InfoStyle::InlineBelow; 244 } 245 246 void Client::redraw_ifn() 247 { 248 Window& window = context().window(); 249 if (window.needs_redraw(context())) 250 m_ui_pending |= Draw; 251 252 const auto& faces = context().faces(); 253 254 if (m_ui_pending & Draw) 255 { 256 auto& display_buffer = window.update_display_buffer(context()); 257 auto cursor_pos = window.display_coord(context().selections().main().cursor()).value_or(DisplayCoord{}); 258 m_ui->draw(display_buffer, cursor_pos, faces["Default"], faces["BufferPadding"], 259 window.last_display_setup().widget_columns); 260 } 261 262 const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and 263 not m_menu.items.empty() and m_menu.style == MenuStyle::Inline; 264 if ((m_ui_pending & MenuShow) or update_menu_anchor) 265 { 266 auto anchor = m_menu.style == MenuStyle::Inline ? 267 window.display_coord(m_menu.anchor) : DisplayCoord{}; 268 if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor) 269 m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide; 270 m_menu.ui_anchor = anchor; 271 } 272 273 if (m_ui_pending & MenuShow and m_menu.ui_anchor) 274 m_ui->menu_show(m_menu.items, *m_menu.ui_anchor, 275 faces["MenuForeground"], faces["MenuBackground"], 276 m_menu.style); 277 if (m_ui_pending & MenuSelect and m_menu.ui_anchor) 278 m_ui->menu_select(m_menu.selected); 279 if (m_ui_pending & MenuHide) 280 m_ui->menu_hide(); 281 282 const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and 283 not m_info.content.empty() and is_inline(m_info.style); 284 if ((m_ui_pending & InfoShow) or update_info_anchor) 285 { 286 auto anchor = is_inline(m_info.style) ? 287 window.display_coord(m_info.anchor) : DisplayCoord{}; 288 if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor) 289 m_ui_pending |= anchor ? InfoShow : InfoHide; 290 m_info.ui_anchor = anchor; 291 } 292 293 if (m_ui_pending & InfoShow and m_info.ui_anchor) 294 m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor, 295 faces[(is_inline(m_info.style) or m_info.style == InfoStyle::MenuDoc) 296 ? "InlineInformation" : "Information"], m_info.style); 297 if (m_ui_pending & InfoHide) 298 m_ui->info_hide(); 299 300 // This needs to be done *after* update_display_buffer as ithe mode line may rely on it to 301 // compute whether selections are visible. 302 DisplayLine mode_line = generate_mode_line(); 303 if (mode_line.atoms() != m_mode_line.atoms()) 304 { 305 m_ui_pending |= StatusLine; 306 m_mode_line = std::move(mode_line); 307 } 308 if (m_ui_pending & StatusLine) 309 m_ui->draw_status(m_status_prompt, m_status_content, m_status_cursor_pos, m_mode_line, faces["StatusLine"], m_status_style); 310 311 if (m_ui_pending != 0) 312 m_ui->refresh(m_ui_pending & Refresh); 313 314 m_ui_pending = 0; 315 } 316 317 void Client::force_redraw(bool full) 318 { 319 if (full) 320 m_ui_pending |= Refresh | Draw | StatusLine | 321 (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) | 322 (m_info.content.empty() ? InfoHide : InfoShow); 323 else 324 m_ui_pending |= Draw; 325 } 326 327 void Client::reload_buffer() 328 { 329 Buffer& buffer = context().buffer(); 330 try 331 { 332 reload_file_buffer(buffer); 333 context().print_status({ format("'{}' reloaded", buffer.display_name()), 334 context().faces()["Information"] }); 335 336 m_window->hooks().run_hook(Hook::BufReload, buffer.name(), context()); 337 } 338 catch (runtime_error& error) 339 { 340 context().print_status({ format("error while reloading buffer: '{}'", error.what()), 341 context().faces()["Error"] }); 342 buffer.set_fs_status(get_fs_status(buffer.filename())); 343 } 344 } 345 346 void Client::on_buffer_reload_key(Key key) 347 { 348 auto& buffer = context().buffer(); 349 350 auto set_autoreload = [this](Autoreload autoreload) { 351 auto* option = &context().options()["autoreload"]; 352 // Do not touch global autoreload, set it at least at buffer level 353 if (&option->manager() == &GlobalScope::instance().options()) 354 option = &context().buffer().options().get_local_option("autoreload"); 355 option->set(autoreload); 356 }; 357 358 if (key == 'y' or key == 'Y' or key == Key::Return) 359 { 360 reload_buffer(); 361 if (key == 'Y') 362 set_autoreload(Autoreload::Yes); 363 } 364 else if (key == 'n' or key == 'N' or key == Key::Escape) 365 { 366 // reread timestamp in case the file was modified again 367 buffer.set_fs_status(get_fs_status(buffer.filename())); 368 print_status({}, { format("'{}' kept", buffer.display_name()), 369 context().faces()["Information"] }, -1, StatusStyle::Status); 370 if (key == 'N') 371 set_autoreload(Autoreload::No); 372 } 373 else 374 { 375 print_status({}, { format("'{}' is not a valid choice", key), 376 context().faces()["Error"] }, -1, StatusStyle::Status); 377 m_input_handler.on_next_key("buffer-reload", KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); 378 return; 379 } 380 381 for (auto& client : ClientManager::instance()) 382 { 383 if (&client->context().buffer() == &buffer and 384 client->m_buffer_reload_dialog_opened) 385 client->close_buffer_reload_dialog(); 386 } 387 } 388 389 void Client::close_buffer_reload_dialog() 390 { 391 kak_assert(m_buffer_reload_dialog_opened); 392 // Reset first as this might check for reloading. 393 m_input_handler.reset_normal_mode(); 394 m_buffer_reload_dialog_opened = false; 395 info_hide(true); 396 } 397 398 void Client::check_if_buffer_needs_reloading() 399 { 400 if (m_buffer_reload_dialog_opened) 401 return; 402 403 Buffer& buffer = context().buffer(); 404 auto reload = context().options()["autoreload"].get<Autoreload>(); 405 if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No) 406 return; 407 408 try 409 { 410 const String& filename = buffer.filename(); 411 const timespec ts = get_fs_timestamp(filename); 412 const auto status = buffer.fs_status(); 413 414 if (ts == InvalidTime or ts == status.timestamp) 415 return; 416 417 if (MappedFile fd{filename}; 418 fd.st.st_size == status.file_size and murmur3(fd.data, fd.st.st_size) == status.hash) 419 return; 420 421 if (reload == Autoreload::Ask) 422 { 423 info_show(format("reload '{}' ?", buffer.display_name()), 424 format("'{}' was modified externally\n" 425 " y, <ret>: reload | n, <esc>: keep\n" 426 " Y: always reload | N: always keep\n", 427 buffer.display_name()), {}, InfoStyle::Modal); 428 429 m_buffer_reload_dialog_opened = true; 430 m_input_handler.on_next_key("buffer-reload", KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); }); 431 } 432 else 433 reload_buffer(); 434 } 435 catch (Kakoune::runtime_error& error) 436 { 437 write_to_debug_buffer(format("Error while checking if buffer {} changed: {}", buffer.filename(), error.what())); 438 } 439 } 440 441 StringView Client::get_env_var(StringView name) const 442 { 443 auto it = m_env_vars.find(name); 444 if (it == m_env_vars.end()) 445 return {}; 446 return it->value; 447 } 448 449 void Client::on_option_changed(const Option& option) 450 { 451 if (option.name() == "ui_options") 452 m_ui->set_ui_options(option.get<UserInterface::Options>()); 453 m_ui_pending |= Draw; // a highlighter might depend on the option, so we need to redraw 454 } 455 456 void Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style) 457 { 458 m_menu = Menu{ std::move(choices), anchor, {}, style, -1 }; 459 m_ui_pending |= MenuShow; 460 m_ui_pending &= ~MenuHide; 461 } 462 463 void Client::menu_select(int selected) 464 { 465 m_menu.selected = selected; 466 m_ui_pending |= MenuSelect; 467 m_ui_pending &= ~MenuHide; 468 } 469 470 void Client::menu_hide() 471 { 472 m_menu = Menu{}; 473 m_ui_pending |= MenuHide; 474 m_ui_pending &= ~(MenuShow | MenuSelect); 475 } 476 477 void Client::info_show(DisplayLine title, DisplayLineList content, BufferCoord anchor, InfoStyle style) 478 { 479 if (m_info.style == InfoStyle::Modal) // We already have a modal info opened, do not touch it. 480 return; 481 482 m_info = Info{ std::move(title), std::move(content), anchor, {}, style }; 483 m_ui_pending |= InfoShow; 484 m_ui_pending &= ~InfoHide; 485 m_pending_clear &= ~PendingClear::Info; 486 } 487 488 void Client::info_show(StringView title, StringView content, BufferCoord anchor, InfoStyle style) 489 { 490 if (not content.empty() and content.back() == '\n') 491 content = content.substr(0, content.length() - 1); 492 info_show(title.empty() ? DisplayLine{} : DisplayLine{title.str(), Face{}}, 493 content | split<StringView>('\n') 494 | transform([](StringView s) { return DisplayLine{replace(s, '\t', ' '), Face{}}; }) 495 | gather<DisplayLineList>(), 496 anchor, style); 497 } 498 499 void Client::info_hide(bool even_modal) 500 { 501 if (not even_modal and m_info.style == InfoStyle::Modal) 502 return; 503 504 m_info = Info{}; 505 m_ui_pending |= InfoHide; 506 m_ui_pending &= ~InfoShow; 507 } 508 509 void Client::schedule_clear() 510 { 511 if (not (m_ui_pending & InfoShow)) 512 m_pending_clear |= PendingClear::Info; 513 if (not (m_ui_pending & StatusLine)) 514 m_pending_clear |= PendingClear::StatusLine; 515 } 516 517 void Client::clear_pending() 518 { 519 if (m_pending_clear & PendingClear::StatusLine) 520 print_status({}, {}, -1, StatusStyle::Status); 521 if (m_pending_clear & PendingClear::Info) 522 info_hide(); 523 m_pending_clear = PendingClear::None; 524 } 525 526 constexpr std::chrono::seconds wait_timeout{1}; 527 528 BusyIndicator::BusyIndicator(const Context& context, 529 Function<DisplayLine(std::chrono::seconds)> status_message, 530 TimePoint wait_time) 531 : m_context(context), 532 m_timer{wait_time + wait_timeout, 533 [this, status_message = std::move(status_message), wait_time](Timer& timer) { 534 if (not m_context.has_client()) 535 return; 536 using namespace std::chrono; 537 const auto now = Clock::now(); 538 timer.set_next_date(now + wait_timeout); 539 540 auto& client = m_context.client(); 541 if (not m_previous_status) 542 m_previous_status.emplace(client.m_status_prompt, client.m_status_content, client.m_status_cursor_pos, client.m_status_style); 543 544 client.print_status({}, status_message(duration_cast<seconds>(now - wait_time)), -1, StatusStyle::Status); 545 client.redraw_ifn(); 546 }, EventMode::Urgent} {} 547 548 BusyIndicator::~BusyIndicator() 549 { 550 if (m_previous_status and std::uncaught_exceptions() == 0) // restore the status line 551 { 552 auto& [prompt, content, cursor_pos, style] = *m_previous_status; 553 m_context.print_status(std::move(prompt), std::move(content), std::move(cursor_pos), style); 554 m_context.client().redraw_ifn(); 555 } 556 } 557 558 }