kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

client_manager.cc (7673B)


      1 #include "client_manager.hh"
      2 
      3 #include "buffer_manager.hh"
      4 #include "command_manager.hh"
      5 #include "hook_manager.hh"
      6 #include "face_registry.hh"
      7 #include "file.hh"
      8 #include "ranges.hh"
      9 #include "window.hh"
     10 
     11 namespace Kakoune
     12 {
     13 
     14 ClientManager::ClientManager() = default;
     15 ClientManager::~ClientManager()
     16 {
     17     clear(true);
     18 }
     19 
     20 void ClientManager::clear(bool disconnect_clients)
     21 {
     22     if (disconnect_clients)
     23     {
     24         while (not m_clients.empty())
     25             remove_client(*m_clients.front(), true, 0);
     26     }
     27     else
     28         m_clients.clear();
     29     m_client_trash.clear();
     30 
     31     for (auto& window : m_free_windows)
     32         window.window->run_hook_in_own_context(Hook::WinClose,
     33                                                window.window->buffer().name());
     34     m_free_windows.clear();
     35     m_window_trash.clear();
     36 }
     37 
     38 String ClientManager::generate_name() const
     39 {
     40     for (int i = 0; true; ++i)
     41     {
     42         String name = format("client{}", i);
     43         if (not client_name_exists(name))
     44             return name;
     45     }
     46 }
     47 
     48 Client* ClientManager::create_client(UniquePtr<UserInterface>&& ui, int pid,
     49                                      String name, EnvVarMap env_vars, StringView init_cmds,
     50                                      StringView init_buffer, Optional<BufferCoord> init_coord,
     51                                      Client::OnExitCallback on_exit)
     52 {
     53     Buffer* buffer = nullptr;
     54     if (not init_buffer.empty())
     55         buffer = BufferManager::instance().get_buffer_ifp(init_buffer);
     56     if (buffer == nullptr)
     57         buffer = &BufferManager::instance().get_first_buffer();
     58 
     59     buffer->flags() |= Buffer::Flags::Locked;
     60     OnScopeEnd unlock{[&] { buffer->flags() &= ~Buffer::Flags::Locked; }};
     61 
     62     WindowAndSelections ws = get_free_window(*buffer);
     63     Client* client = new Client{std::move(ui), std::move(ws.window),
     64                                 std::move(ws.selections), pid,
     65                                 std::move(env_vars),
     66                                 name.empty() ? generate_name() : std::move(name),
     67                                 std::move(on_exit)};
     68     m_clients.emplace_back(client);
     69 
     70     auto& context = client->context();
     71     if (context.buffer().name() == "*scratch*")
     72         context.print_status({"This *scratch* buffer won't be automatically saved",
     73                               context.faces()["Information"]});
     74 
     75     if (init_coord)
     76     {
     77         context.selections_write_only() = SelectionList(*buffer, context.buffer().clamp(*init_coord));
     78         context.window().center_line(init_coord->line);
     79     }
     80 
     81     unlock.trigger();
     82 
     83     try
     84     {
     85         context.hooks().run_hook(Hook::ClientCreate, context.name(), context);
     86         CommandManager::instance().execute(init_cmds, context);
     87     }
     88     catch (Kakoune::runtime_error& error)
     89     {
     90         context.print_status({error.what().str(), context.faces()["Error"]});
     91         context.hooks().run_hook(Hook::RuntimeError, error.what(), context);
     92     }
     93 
     94     // Do not return the client if it already got moved to the trash
     95     return contains(m_clients, client) ? client : nullptr;
     96 }
     97 
     98 bool ClientManager::process_pending_inputs()
     99 {
    100     bool processed_some_input = false;
    101     while (true)
    102     {
    103         bool had_input = false;
    104         // Use index based iteration as a m_clients might get mutated during
    105         // client input processing, which would break iterator based iteration.
    106         // (its fine to skip a client if that happens as had_input will be true
    107         // if a client triggers client removal)
    108         for (int i = 0; i < m_clients.size(); )
    109         {
    110             if (not m_clients[i]->is_ui_ok())
    111             {
    112                 remove_client(*m_clients[i], false, -1);
    113                 continue;
    114             }
    115             had_input = m_clients[i]->process_pending_inputs() or had_input;
    116             processed_some_input |= had_input;
    117             ++i;
    118         }
    119 
    120         if (not had_input)
    121             break;
    122     }
    123     return processed_some_input;
    124 }
    125 
    126 bool ClientManager::has_pending_inputs() const
    127 {
    128     return any_of(m_clients, [](auto&& c) { return c->has_pending_inputs(); });
    129 }
    130 
    131 void ClientManager::remove_client(Client& client, bool graceful, int status)
    132 {
    133     auto it = find(m_clients, &client);
    134     if (it == m_clients.end())
    135     {
    136         kak_assert(contains(m_client_trash, &client));
    137         return;
    138     }
    139 
    140     m_client_trash.push_back(std::move(*it));
    141     m_clients.erase(it);
    142 
    143     auto& context = client.context();
    144     context.hooks().run_hook(Hook::ClientClose, context.name(), context);
    145 
    146     client.exit(status);
    147 
    148     if (not graceful and m_clients.empty())
    149         BufferManager::instance().backup_modified_buffers();
    150 }
    151 
    152 WindowAndSelections ClientManager::get_free_window(Buffer& buffer)
    153 {
    154     kak_assert(contains(BufferManager::instance(), &buffer));
    155     auto it = find_if(m_free_windows | reverse(),
    156                       [&](const WindowAndSelections& ws)
    157                       { return &ws.window->buffer() == &buffer; });
    158 
    159     if (it == m_free_windows.rend())
    160         return { make_unique_ptr<Window>(buffer), { buffer, Selection{} } };
    161 
    162     WindowAndSelections res = std::move(*it);
    163     m_free_windows.erase(it.base()-1);
    164     res.selections.update();
    165     return res;
    166 }
    167 
    168 void ClientManager::add_free_window(UniquePtr<Window>&& window, SelectionList selections)
    169 {
    170     if (not contains(BufferManager::instance(), &window->buffer()))
    171     {
    172         m_window_trash.push_back(std::move(window));
    173         return;
    174     }
    175 
    176     window->clear_display_buffer();
    177     m_free_windows.push_back({std::move(window), std::move(selections)});
    178 }
    179 
    180 void ClientManager::ensure_no_client_uses_buffer(Buffer& buffer)
    181 {
    182     for (auto& client : m_clients)
    183         client->context().forget_buffer(buffer);
    184 
    185     Vector<UniquePtr<Window>> removed_windows;
    186     m_free_windows.erase(remove_if(m_free_windows,
    187                                    [&buffer, &removed_windows](WindowAndSelections& ws) {
    188                                        if (&ws.window->buffer() != &buffer)
    189                                            return false;
    190                                        removed_windows.push_back(std::move(ws.window));
    191                                        return true;
    192                                    }),
    193                          m_free_windows.end());
    194 
    195     for (auto&& removed_window : removed_windows)
    196     {
    197         removed_window->run_hook_in_own_context(Hook::WinClose,
    198                                                 removed_window->buffer().name());
    199         m_window_trash.push_back(std::move(removed_window));
    200     }
    201 }
    202 
    203 void ClientManager::clear_window_trash()
    204 {
    205     m_window_trash.clear();
    206 }
    207 
    208 void ClientManager::clear_client_trash()
    209 {
    210     m_client_trash.clear();
    211 }
    212 
    213 bool ClientManager::client_name_exists(StringView name) const
    214 {
    215     return const_cast<ClientManager*>(this)->get_client_ifp(name) != nullptr;
    216 }
    217 
    218 Client* ClientManager::get_client_ifp(StringView name)
    219 {
    220     for (auto& client : m_clients)
    221     {
    222         if (client->context().name() == name)
    223             return client.get();
    224     }
    225     return nullptr;
    226 }
    227 
    228 Client& ClientManager::get_client(StringView name)
    229 {
    230     if (Client* client = get_client_ifp(name))
    231         return *client;
    232     throw runtime_error(format("no such client: '{}'", name));
    233 }
    234 
    235 void ClientManager::redraw_clients() const
    236 {
    237     for (auto& client : m_clients)
    238         client->redraw_ifn();
    239 }
    240 
    241 CandidateList ClientManager::complete_client_name(StringView prefix,
    242                                                   ByteCount cursor_pos) const
    243 {
    244     auto c = m_clients | transform([](const UniquePtr<Client>& c) -> const String&
    245                                    { return c->context().name(); });
    246     return complete(prefix, cursor_pos, c);
    247 }
    248 
    249 }