kakoune

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

json_ui.cc (11191B)


      1 #include "json_ui.hh"
      2 
      3 #include "display_buffer.hh"
      4 #include "event_manager.hh"
      5 #include "exception.hh"
      6 #include "file.hh"
      7 #include "json.hh"
      8 #include "keys.hh"
      9 #include "ranges.hh"
     10 #include "string_utils.hh"
     11 #include "format.hh"
     12 
     13 #include <cstdio>
     14 #include <utility>
     15 
     16 #include <unistd.h>
     17 
     18 namespace Kakoune
     19 {
     20 
     21 struct invalid_rpc_request : runtime_error {
     22     invalid_rpc_request(const String& message)
     23         : runtime_error(format("invalid json rpc request ({})", message)) {}
     24 };
     25 
     26 String to_json(Color color)
     27 {
     28     if (color.color == Kakoune::Color::RGB)
     29     {
     30         char buffer[10];
     31         format_to(buffer, R"("#{:02}{:02}{:02}")", hex(color.r), hex(color.g), hex(color.b));
     32         return buffer;
     33     }
     34     return to_json(to_string(color));
     35 }
     36 
     37 String to_json(Attribute attributes)
     38 {
     39     struct Attr { Attribute attr; StringView name; }
     40     attrs[] {
     41         { Attribute::Underline, "underline" },
     42         { Attribute::CurlyUnderline, "curly_underline" },
     43         { Attribute::DoubleUnderline, "double_underline" },
     44         { Attribute::Reverse, "reverse" },
     45         { Attribute::Blink, "blink" },
     46         { Attribute::Bold, "bold" },
     47         { Attribute::Dim, "dim" },
     48         { Attribute::Italic, "italic" },
     49         { Attribute::FinalFg, "final_fg" },
     50         { Attribute::FinalBg, "final_bg" },
     51         { Attribute::FinalAttr, "final_attr" },
     52         { Attribute::Strikethrough, "strikethrough" },
     53     };
     54 
     55     return "[" + join(attrs |
     56                       filter([=](const Attr& a) { return attributes & a.attr; }) |
     57                       transform([](const Attr& a) { return to_json(a.name); }),
     58                       ',', false) + "]";
     59 }
     60 
     61 String to_json(Face face)
     62 {
     63     return format(R"(\{ "fg": {}, "bg": {}, "underline": {}, "attributes": {} })",
     64                   to_json(face.fg), to_json(face.bg), to_json(face.underline), to_json(face.attributes));
     65 }
     66 
     67 String to_json(const DisplayAtom& atom)
     68 {
     69     return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content()));
     70 }
     71 
     72 String to_json(const DisplayLine& line)
     73 {
     74     return to_json(line.atoms());
     75 }
     76 
     77 String to_json(ColumnCount column)
     78 {
     79     return format("{}", column);
     80 }
     81 
     82 String to_json(DisplayCoord coord)
     83 {
     84     return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column);
     85 }
     86 
     87 String to_json(MenuStyle style)
     88 {
     89     switch (style)
     90     {
     91         case MenuStyle::Prompt: return R"("prompt")";
     92         case MenuStyle::Search: return R"("search")";
     93         case MenuStyle::Inline: return R"("inline")";
     94     }
     95     return "";
     96 }
     97 
     98 String to_json(InfoStyle style)
     99 {
    100     switch (style)
    101     {
    102         case InfoStyle::Prompt: return R"("prompt")";
    103         case InfoStyle::Inline: return R"("inline")";
    104         case InfoStyle::InlineAbove: return R"("inlineAbove")";
    105         case InfoStyle::InlineBelow: return R"("inlineBelow")";
    106         case InfoStyle::MenuDoc: return R"("menuDoc")";
    107         case InfoStyle::Modal: return R"("modal")";
    108     }
    109     return "";
    110 }
    111 
    112 String to_json(StatusStyle style)
    113 {
    114     switch (style)
    115     {
    116         case StatusStyle::Status: return R"("status")";
    117         case StatusStyle::Command: return R"("command")";
    118         case StatusStyle::Search: return R"("search")";
    119         case StatusStyle::Prompt: return R"("prompt")";
    120     }
    121     return "";
    122 }
    123 
    124 String concat()
    125 {
    126     return "";
    127 }
    128 
    129 template<typename First, typename... Args>
    130 String concat(First&& first, Args&&... args)
    131 {
    132     if (sizeof...(Args) != 0)
    133         return to_json(first) + ", " + concat(args...);
    134     return to_json(first);
    135 }
    136 
    137 template<typename... Args>
    138 void rpc_call(StringView method, Args&&... args)
    139 {
    140     auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})",
    141                     method, concat(std::forward<Args>(args)...), "\n");
    142 
    143     write(1, q);
    144 }
    145 
    146 JsonUI::JsonUI()
    147     : m_stdin_watcher{0, FdEvents::Read, EventMode::Urgent,
    148                       [this](FDWatcher&, FdEvents, EventMode mode) {
    149         parse_requests(mode);
    150       }}, m_dimensions{24, 80}
    151 {
    152     set_signal_handler(SIGINT, SIG_DFL);
    153 }
    154 
    155 void JsonUI::draw(const DisplayBuffer& display_buffer, DisplayCoord cursor_pos,
    156                   const Face& default_face, const Face& padding_face,
    157                   ColumnCount widget_columns)
    158 {
    159     rpc_call("draw", display_buffer.lines(), cursor_pos, default_face, padding_face,
    160              widget_columns);
    161 }
    162 
    163 void JsonUI::draw_status(const DisplayLine& prompt,
    164                          const DisplayLine& content,
    165                          const ColumnCount cursor_pos,
    166                          const DisplayLine& mode_line,
    167                          const Face& default_face,
    168                          StatusStyle style)
    169 {
    170     rpc_call("draw_status", prompt, content, cursor_pos, mode_line, default_face, style);
    171 }
    172 
    173 
    174 void JsonUI::menu_show(ConstArrayView<DisplayLine> items,
    175                        DisplayCoord anchor, Face fg, Face bg,
    176                        MenuStyle style)
    177 {
    178     rpc_call("menu_show", items, anchor, fg, bg, style);
    179 }
    180 
    181 void JsonUI::menu_select(int selected)
    182 {
    183     rpc_call("menu_select", selected);
    184 }
    185 
    186 void JsonUI::menu_hide()
    187 {
    188     rpc_call("menu_hide");
    189 }
    190 
    191 void JsonUI::info_show(const DisplayLine& title, const DisplayLineList& content,
    192                        DisplayCoord anchor, Face face,
    193                        InfoStyle style)
    194 {
    195     rpc_call("info_show", title, content, anchor, face, style);
    196 }
    197 
    198 void JsonUI::info_hide()
    199 {
    200     rpc_call("info_hide");
    201 }
    202 
    203 void JsonUI::refresh(bool force)
    204 {
    205     rpc_call("refresh", force);
    206 }
    207 
    208 void JsonUI::set_ui_options(const Options& options)
    209 {
    210     rpc_call("set_ui_options", options);
    211 }
    212 
    213 DisplayCoord JsonUI::dimensions()
    214 {
    215     return m_dimensions;
    216 }
    217 
    218 void JsonUI::set_on_key(OnKeyCallback callback)
    219 {
    220     m_on_key = std::move(callback);
    221 }
    222 
    223 void JsonUI::set_on_paste(OnPasteCallback callback)
    224 {
    225     m_on_paste = std::move(callback);
    226 }
    227 
    228 void JsonUI::eval_json(const Value& json)
    229 {
    230     if (not json.is_a<JsonObject>())
    231         throw invalid_rpc_request("request is not an object");
    232 
    233     const JsonObject& object = json.as<JsonObject>();
    234     auto json_it = object.find("jsonrpc"_sv);
    235     if (json_it == object.end() or
    236         not json_it->value.is_a<String>() or
    237         json_it->value.as<String>() != "2.0")
    238         throw invalid_rpc_request("only protocol '2.0' is supported");
    239     else if (not json_it->value.is_a<String>())
    240         throw invalid_rpc_request("'jsonrpc' is not a string");
    241 
    242     auto method_it = object.find("method"_sv);
    243     if (method_it == object.end())
    244         throw invalid_rpc_request("method missing");
    245     else if (not method_it->value.is_a<String>())
    246         throw invalid_rpc_request("'method' is not a string");
    247     StringView method = method_it->value.as<String>();
    248 
    249     auto params_it = object.find("params"_sv);
    250     if (params_it == object.end())
    251         throw invalid_rpc_request("params missing");
    252     else if (not params_it->value.is_a<JsonArray>())
    253         throw invalid_rpc_request("'params' is not an array");
    254     const JsonArray& params = params_it->value.as<JsonArray>();
    255 
    256     if (method == "keys")
    257     {
    258         for (auto& key_val : params)
    259         {
    260             if (not key_val.is_a<String>())
    261                 throw invalid_rpc_request("'keys' is not an array of strings");
    262 
    263             for (auto& key : parse_keys(key_val.as<String>()))
    264                 m_on_key(key);
    265         }
    266     }
    267     else if (method == "paste")
    268     {
    269         if (params.size() != 1 or not params[0].is_a<String>())
    270             throw invalid_rpc_request("paste requires a string parameter");
    271         if (m_on_paste)
    272             m_on_paste(params[0].as<String>());
    273     }
    274     else if (method == "mouse_move")
    275     {
    276         if (params.size() != 2)
    277             throw invalid_rpc_request("mouse coordinates not specified");
    278 
    279         if (not params[0].is_a<int>() or not params[1].is_a<int>())
    280             throw invalid_rpc_request("mouse coordinates are not integers");
    281 
    282         m_on_key({Key::Modifiers::MousePos, encode_coord({params[0].as<int>(), params[1].as<int>()})});
    283     }
    284     else if (method == "mouse_press" or method == "mouse_release")
    285     {
    286         if (params.size() != 3)
    287             throw invalid_rpc_request("mouse button/coordinates not specified");
    288 
    289         if (not params[0].is_a<String>())
    290             throw invalid_rpc_request("mouse button is not a string");
    291         if (not params[1].is_a<int>() or not params[2].is_a<int>())
    292             throw invalid_rpc_request("mouse coordinates are not integers");
    293 
    294         auto event = method == "mouse_press" ? Key::Modifiers::MousePress : Key::Modifiers::MouseRelease;
    295         auto button = str_to_button(params[0].as<String>());
    296 
    297         m_on_key({event | Key::to_modifier(button), encode_coord({params[1].as<int>(), params[2].as<int>()})});
    298     }
    299     else if (method == "scroll")
    300     {
    301         if (params.size() != 3)
    302             throw invalid_rpc_request("scroll needs an amount and coordinates");
    303         else if (not params[0].is_a<int>() or not params[1].is_a<int>() or not params[2].is_a<int>())
    304             throw invalid_rpc_request("scroll parameters are not integers");
    305         m_on_key({Key::Modifiers::Scroll | (Key::Modifiers)(params[0].as<int>() << 16),
    306                   encode_coord({params[1].as<int>(), params[2].as<int>()})});
    307     }
    308     else if (method == "menu_select")
    309     {
    310         if (params.size() != 1)
    311             throw invalid_rpc_request("menu_select needs the item index");
    312         else if (not params[0].is_a<int>())
    313             throw invalid_rpc_request("menu index is not an integer");
    314 
    315         m_on_key({Key::Modifiers::MenuSelect, (Codepoint)params[0].as<int>()});
    316     }
    317     else if (method == "resize")
    318     {
    319         if (params.size() != 2)
    320             throw runtime_error("resize expects 2 parameters");
    321         else if (not params[0].is_a<int>() or
    322                  not params[1].is_a<int>())
    323             throw invalid_rpc_request("width and height are not integers");
    324 
    325         DisplayCoord dim{params[0].as<int>(), params[1].as<int>()};
    326         m_dimensions = dim;
    327         m_on_key(resize(dim));
    328     }
    329     else
    330         throw invalid_rpc_request(format("unknown method: {}", method));
    331 }
    332 
    333 void JsonUI::parse_requests(EventMode mode)
    334 {
    335     constexpr size_t bufsize = 1024;
    336     char buf[bufsize];
    337     while (fd_readable(0))
    338     {
    339         ssize_t size = ::read(0, buf, bufsize);
    340         if (size == -1 or size == 0)
    341         {
    342             m_stdin_watcher.close_fd();
    343             break;
    344         }
    345 
    346         m_requests += StringView{buf, buf + size};
    347     }
    348 
    349     if (not m_on_key)
    350         return;
    351 
    352     while (not m_requests.empty())
    353     {
    354         const char* pos = nullptr;
    355         try
    356         {
    357             auto [json, new_pos] = parse_json(m_requests);
    358             pos = new_pos;
    359             if (json)
    360                 eval_json(json);
    361         }
    362         catch (runtime_error& error)
    363         {
    364             write(2, format("error while handling requests '{}': '{}'\n",
    365                             m_requests, error.what()));
    366             // try to salvage request by dropping its first line
    367             pos = std::min(m_requests.end(), find(m_requests, '\n')+1);
    368         }
    369         if (not pos)
    370             break; // unterminated request ?
    371 
    372         m_requests = String{pos, m_requests.end()};
    373     }
    374 }
    375 
    376 }