robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Barrett Ruthfix(messages): `inputlist()` offers the mouse when it cannot be used (#41280)fc3f71fb7d

master
12.3 KiB429 linesraw
1// dialog.c: user prompts and console dialogs (yes/no, number, confirm()).
2
3#include <stdbool.h>
4#include <stdint.h>
5#include <string.h>
6
7#include "nvim/ascii_defs.h"
8#include "nvim/dialog.h"
9#include "nvim/ex_getln.h"
10#include "nvim/gettext_defs.h"
11#include "nvim/globals.h"
12#include "nvim/highlight_defs.h"
13#include "nvim/input.h"
14#include "nvim/keycodes.h"
15#include "nvim/math.h"
16#include "nvim/mbyte.h"
17#include "nvim/memory.h"
18#include "nvim/message.h"
19#include "nvim/mouse.h"
20#include "nvim/option_vars.h"
21#include "nvim/os/input.h"
22#include "nvim/state_defs.h"
23#include "nvim/ui.h"
24#include "nvim/vim_defs.h"
25
26#include "dialog.c.generated.h"  // IWYU pragma: export
27
28// Magic chars used in confirm dialog strings
29enum {
30  DLG_BUTTON_SEP = '\n',
31  DLG_HOTKEY_CHAR = '&',
32};
33
34char *confirm_msg = NULL;      // ":confirm" message
35char *confirm_buttons = NULL;  // ":confirm" buttons sent to cmdline as prompt
36
37/// Ask for a reply from the user, a 'y' or a 'n', with prompt "str" (which
38/// should have been translated already).
39///
40/// No other characters are accepted, the message is repeated until a valid
41/// reply is entered or <C-c> is hit.
42///
43/// @param[in]  str  Prompt: question to ask user. Is always followed by " (y/n)?".
44///
45/// @return 'y' or 'n'. Last is also what will be returned in case of interrupt.
46int ask_yesno(const char *const str)
47{
48  const int save_State = State;
49
50  no_wait_return++;
51  snprintf(IObuff, IOSIZE, _("%s (y/n)?"), str);
52  char *prompt = xstrdup(IObuff);
53
54  int r = ' ';
55  while (r != 'y' && r != 'n') {
56    // same highlighting as for wait_return()
57    r = prompt_for_input(prompt, HLF_R, true, NULL);
58    if (r == Ctrl_C || r == ESC) {
59      r = 'n';
60      if (!ui_has(kUIMessages)) {
61        msg_putchar(r);
62      }
63    }
64  }
65
66  need_wait_return = msg_scrolled;
67  no_wait_return--;
68  State = save_State;
69  setmouse();
70  xfree(prompt);
71
72  return r;
73}
74
75/// Ask the user for input through a cmdline prompt.
76///
77/// @param one_key Return from cmdline after one key press.
78/// @param mouse_used When not NULL, allow using the mouse to press a number.
79int prompt_for_input(char *prompt, int hl_id, bool one_key, bool *mouse_used)
80{
81  int ret = one_key ? ESC : 0;
82  char *kmsg = keep_msg ? xstrdup(keep_msg) : NULL;
83
84  if (prompt == NULL) {
85    if (mouse_used != NULL && ui_mouse_has(kMouseCommand)) {
86      prompt = _("Type number and <Enter> or click with the mouse (q or empty cancels): ");
87    } else {
88      prompt = _("Type number and <Enter> (q or empty cancels): ");
89    }
90  }
91
92  cmdline_row = msg_row;
93  ui_flush();
94
95  no_mapping++;  // don't map prompt input
96  allow_keys++;  // allow special keys
97  char *resp = getcmdline_prompt(-1, prompt, hl_id, EXPAND_NOTHING, NULL,
98                                 CALLBACK_NONE, one_key, mouse_used);
99  allow_keys--;
100  no_mapping--;
101
102  if (resp) {
103    ret = one_key ? (int)(*resp) : atoi(resp);
104    xfree(resp);
105  }
106
107  if (kmsg != NULL) {
108    set_keep_msg(kmsg, keep_msg_hl_id);
109    xfree(kmsg);
110  }
111
112  return ret;
113}
114
115/// Used for "confirm()" function, and the :confirm command prefix.
116/// Versions which haven't got flexible dialogs yet, and console
117/// versions, get this generic handler which uses the command line.
118///
119/// type  = one of:
120///         VIM_QUESTION, VIM_INFO, VIM_WARNING, VIM_ERROR or VIM_GENERIC
121/// title = title string (can be NULL for default)
122/// (neither used in console dialogs at the moment)
123///
124/// Format of the "buttons" string:
125/// "Button1Name\nButton2Name\nButton3Name"
126/// The first button should normally be the default/accept
127/// The second button should be the 'Cancel' button
128/// Other buttons- use your imagination!
129/// A '&' in a button name becomes a shortcut, so each '&' should be before a
130/// different letter.
131///
132/// @param textfiel  IObuff for inputdialog(), NULL otherwise
133/// @param ex_cmd  when true pressing : accepts default and starts Ex command
134/// @returns 0 if cancelled, otherwise the nth button (1-indexed).
135int do_dialog(int type, const char *title, const char *message, const char *buttons, int dfltbutton,
136              const char *textfield, int ex_cmd)
137{
138  int retval = 0;
139  int i;
140
141  if (silent_mode) {  // No dialogs in silent mode ("ex -s")
142    return dfltbutton;  // return default option
143  }
144
145  int save_msg_silent = msg_silent;
146  int oldState = State;
147
148  msg_silent = 0;  // If dialog prompts for input, user needs to see it! #8788
149
150  // Since we wait for a keypress, don't make the
151  // user press RETURN as well afterwards.
152  no_wait_return++;
153  char *hotkeys = msg_show_console_dialog(message, buttons, dfltbutton);
154
155  while (true) {
156    // Without a UI Nvim waits for input forever.
157    if (!ui_active() && !input_available()) {
158      retval = dfltbutton;
159      break;
160    }
161
162    // Get a typed character directly from the user.
163    int c = prompt_for_input(confirm_buttons, HLF_M, true, NULL);
164    switch (c) {
165    case CAR:                 // User accepts default option
166    case NUL:
167      retval = dfltbutton;
168      break;
169    case Ctrl_C:              // User aborts/cancels
170    case ESC:
171      retval = 0;
172      break;
173    default:                  // Could be a hotkey?
174      if (c < 0) {            // special keys are ignored here
175        msg_didout = msg_didany = false;
176        continue;
177      }
178      if (c == ':' && ex_cmd) {
179        retval = dfltbutton;
180        ins_typebuf(":", REMAP_YES, 0, false, false);
181        break;
182      }
183
184      // Make the character lowercase, as chars in "hotkeys" are.
185      c = mb_tolower(c);
186      retval = 1;
187      for (i = 0; hotkeys[i]; i++) {
188        if (utf_ptr2char(hotkeys + i) == c) {
189          break;
190        }
191        i += utfc_ptr2len(hotkeys + i) - 1;
192        retval++;
193      }
194      if (hotkeys[i]) {
195        break;
196      }
197      // No hotkey match, so keep waiting
198      msg_didout = msg_didany = false;
199      continue;
200    }
201    break;
202  }
203
204  xfree(hotkeys);
205  xfree(confirm_msg);
206  confirm_msg = NULL;
207
208  msg_silent = save_msg_silent;
209  State = oldState;
210  setmouse();
211  no_wait_return--;
212  msg_end_prompt();
213
214  return retval;
215}
216
217/// Copy one character from "*from" to "*to", taking care of multi-byte
218/// characters.  Return the length of the character in bytes.
219///
220/// @param lowercase  make character lower case
221static int copy_char(const char *from, char *to, bool lowercase)
222  FUNC_ATTR_NONNULL_ALL
223{
224  if (lowercase) {
225    int c = mb_tolower(utf_ptr2char(from));
226    return utf_char2bytes(c, to);
227  }
228  int len = utfc_ptr2len(from);
229  memmove(to, from, (size_t)len);
230  return len;
231}
232
233#define HAS_HOTKEY_LEN 30
234#define HOTK_LEN MB_MAXBYTES
235
236/// Allocates memory for dialog string & for storing hotkeys
237///
238/// Finds the size of memory required for the confirm_msg & for storing hotkeys
239/// and then allocates the memory for them.
240/// has_hotkey array is also filled-up.
241///
242/// @param message Message which will be part of the confirm_msg
243/// @param buttons String containing button names
244/// @param[out] has_hotkey An element in this array is set to true if
245///                        corresponding button has a hotkey
246///
247/// @return Pointer to memory allocated for storing hotkeys
248static char *console_dialog_alloc(const char *message, const char *buttons, bool has_hotkey[])
249{
250  int lenhotkey = HOTK_LEN;  // count first button
251  has_hotkey[0] = false;
252
253  // Compute the size of memory to allocate.
254  int msg_len = 0;
255  int button_len = 0;
256  int idx = 0;
257  const char *r = buttons;
258  while (*r) {
259    if (*r == DLG_BUTTON_SEP) {
260      button_len += 3;                  // '\n' -> ', '; 'x' -> '(x)'
261      lenhotkey += HOTK_LEN;            // each button needs a hotkey
262      if (idx < HAS_HOTKEY_LEN - 1) {
263        has_hotkey[++idx] = false;
264      }
265    } else if (*r == DLG_HOTKEY_CHAR) {
266      r++;
267      button_len++;                     // '&a' -> '[a]'
268      if (idx < HAS_HOTKEY_LEN - 1) {
269        has_hotkey[idx] = true;
270      }
271    }
272
273    // Advance to the next character
274    MB_PTR_ADV(r);
275  }
276
277  msg_len += (int)strlen(message) + 3;     // for the NL's and NUL
278  button_len += (int)strlen(buttons) + 3;  // for the ": " and NUL
279  lenhotkey++;                             // for the NUL
280
281  // If no hotkey is specified, first char is used.
282  if (!has_hotkey[0]) {
283    button_len += 2;                       // "x" -> "[x]"
284  }
285
286  // Now allocate space for the strings
287  confirm_msg = xmalloc((size_t)msg_len);
288  snprintf(confirm_msg, (size_t)msg_len, ui_has(kUIMessages) ? "%s" : "\n%s\n", message);
289
290  xfree(confirm_buttons);
291  confirm_buttons = xmalloc((size_t)button_len);
292
293  return xmalloc((size_t)lenhotkey);
294}
295
296/// Format the dialog string, and display it at the bottom of
297/// the screen. Return a string of hotkey chars (if defined) for
298/// each 'button'. If a button has no hotkey defined, the first character of
299/// the button is used.
300/// The hotkeys can be multi-byte characters, but without combining chars.
301///
302/// @return  an allocated string with hotkeys.
303static char *msg_show_console_dialog(const char *message, const char *buttons, int dfltbutton)
304  FUNC_ATTR_NONNULL_RET
305{
306  bool has_hotkey[HAS_HOTKEY_LEN] = { false };
307  char *hotk = console_dialog_alloc(message, buttons, has_hotkey);
308
309  copy_confirm_hotkeys(buttons, dfltbutton, has_hotkey, hotk);
310
311  display_confirm_msg();
312  return hotk;
313}
314
315/// Copies hotkeys into the memory allocated for it
316///
317/// @param buttons String containing button names
318/// @param default_button_idx Number of default button
319/// @param has_hotkey An element in this array is true if corresponding button
320///                   has a hotkey
321/// @param[out] hotkeys_ptr Pointer to the memory location where hotkeys will be copied
322static void copy_confirm_hotkeys(const char *buttons, int default_button_idx,
323                                 const bool has_hotkey[], char *hotkeys_ptr)
324{
325  // Define first default hotkey. Keep the hotkey string NUL
326  // terminated to avoid reading past the end.
327  hotkeys_ptr[copy_char(buttons, hotkeys_ptr, true)] = NUL;
328
329  bool first_hotkey = false;  // Is the first char of button a hotkey
330  if (!has_hotkey[0]) {
331    first_hotkey = true;     // If no hotkey is specified, first char is used
332  }
333
334  // Remember where the choices start, sent as prompt to cmdline.
335  char *msgp = confirm_buttons;
336
337  int idx = 0;
338  const char *r = buttons;
339  while (*r) {
340    if (*r == DLG_BUTTON_SEP) {
341      *msgp++ = ',';
342      *msgp++ = ' ';                    // '\n' -> ', '
343
344      // Advance to next hotkey and set default hotkey
345      hotkeys_ptr += strlen(hotkeys_ptr);
346      hotkeys_ptr[copy_char(r + 1, hotkeys_ptr, true)] = NUL;
347
348      if (default_button_idx) {
349        default_button_idx--;
350      }
351
352      // If no hotkey is specified, first char is used.
353      if (idx < HAS_HOTKEY_LEN - 1 && !has_hotkey[++idx]) {
354        first_hotkey = true;
355      }
356    } else if (*r == DLG_HOTKEY_CHAR || first_hotkey) {
357      if (*r == DLG_HOTKEY_CHAR) {
358        r++;
359      }
360
361      first_hotkey = false;
362      if (*r == DLG_HOTKEY_CHAR) {                 // '&&a' -> '&a'
363        *msgp++ = *r;
364      } else {
365        // '&a' -> '[a]'
366        *msgp++ = (default_button_idx == 1) ? '[' : '(';
367        msgp += copy_char(r, msgp, false);
368        *msgp++ = (default_button_idx == 1) ? ']' : ')';
369
370        // redefine hotkey
371        hotkeys_ptr[copy_char(r, hotkeys_ptr, true)] = NUL;
372      }
373    } else {
374      // everything else copy literally
375      msgp += copy_char(r, msgp, false);
376    }
377
378    // advance to the next character
379    MB_PTR_ADV(r);
380  }
381
382  *msgp++ = ':';
383  *msgp++ = ' ';
384  *msgp = NUL;
385}
386
387int vim_dialog_yesno(int type, char *title, char *message, int dflt)
388{
389  if (do_dialog(type,
390                title == NULL ? _("Question") : title,
391                message,
392                _("&Yes\n&No"), dflt, NULL, false) == 1) {
393    return VIM_YES;
394  }
395  return VIM_NO;
396}
397
398int vim_dialog_yesnocancel(int type, char *title, char *message, int dflt)
399{
400  switch (do_dialog(type,
401                    title == NULL ? _("Question") : title,
402                    message,
403                    _("&Yes\n&No\n&Cancel"), dflt, NULL, false)) {
404  case 1:
405    return VIM_YES;
406  case 2:
407    return VIM_NO;
408  }
409  return VIM_CANCEL;
410}
411
412int vim_dialog_yesnoallcancel(int type, char *title, char *message, int dflt)
413{
414  switch (do_dialog(type,
415                    title == NULL ? "Question" : title,
416                    message,
417                    _("&Yes\n&No\nSave &All\n&Discard All\n&Cancel"),
418                    dflt, NULL, false)) {
419  case 1:
420    return VIM_YES;
421  case 2:
422    return VIM_NO;
423  case 3:
424    return VIM_ALL;
425  case 4:
426    return VIM_DISCARDALL;
427  }
428  return VIM_CANCEL;
429}