tar: type accuracy.
[midnight-commander.git] / src / usermenu.c
blobc32887182840c5a88fb48ac422600299cf5a3152
1 /*
2 User Menu implementation
4 Copyright (C) 1994-2023
5 Free Software Foundation, Inc.
7 Written by:
8 Slava Zanko <slavazanko@gmail.com>, 2013
9 Andrew Borodin <aborodin@vmail.ru>, 2013
11 This file is part of the Midnight Commander.
13 The Midnight Commander is free software: you can redistribute it
14 and/or modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation, either version 3 of the License,
16 or (at your option) any later version.
18 The Midnight Commander is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 /** \file usermenu.c
28 * \brief Source: user menu implementation
31 #include <config.h>
33 #include <ctype.h>
34 #include <errno.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
39 #include "lib/global.h"
40 #include "lib/fileloc.h"
41 #include "lib/tty/tty.h"
42 #include "lib/skin.h"
43 #include "lib/search.h"
44 #include "lib/vfs/vfs.h"
45 #include "lib/strutil.h"
46 #include "lib/util.h"
48 #ifdef USE_INTERNAL_EDIT
49 #include "src/editor/edit.h" /* WEdit */
50 #endif
51 #include "src/viewer/mcviewer.h" /* for default_* externs */
53 #include "src/args.h" /* mc_run_param0 */
54 #include "src/execute.h"
55 #include "src/setup.h"
56 #include "src/history.h"
58 #include "src/filemanager/dir.h"
59 #include "src/filemanager/filemanager.h"
60 #include "src/filemanager/layout.h"
62 #include "usermenu.h"
64 /*** global variables ****************************************************************************/
66 /*** file scope macro definitions ****************************************************************/
68 #define MAX_ENTRIES 16
69 #define MAX_ENTRY_LEN 60
71 /*** file scope type declarations ****************************************************************/
73 /*** forward declarations (file scope functions) *************************************************/
75 /*** file scope variables ************************************************************************/
77 static gboolean debug_flag = FALSE;
78 static gboolean debug_error = FALSE;
79 static char *menu = NULL;
81 /* --------------------------------------------------------------------------------------------- */
82 /*** file scope functions ************************************************************************/
83 /* --------------------------------------------------------------------------------------------- */
85 /** strip file's extension */
86 static char *
87 strip_ext (char *ss)
89 char *s = ss;
90 char *e = NULL;
92 while (*s != '\0')
94 if (*s == '.')
95 e = s;
96 if (IS_PATH_SEP (*s) && e != NULL)
97 e = NULL; /* '.' in *directory* name */
98 s++;
100 if (e != NULL)
101 *e = '\0';
102 return ss;
105 /* --------------------------------------------------------------------------------------------- */
107 * Check for the "shell_patterns" directive. If it's found and valid,
108 * interpret it and move the pointer past the directive. Return the
109 * current pointer.
112 static char *
113 check_patterns (char *p)
115 static const char def_name[] = "shell_patterns=";
116 char *p0 = p;
118 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
119 return p0;
121 p += sizeof (def_name) - 1;
122 if (*p == '1')
123 easy_patterns = TRUE;
124 else if (*p == '0')
125 easy_patterns = FALSE;
126 else
127 return p0;
129 /* Skip spaces */
130 p++;
131 while (whiteness (*p))
132 p++;
133 return p;
136 /* --------------------------------------------------------------------------------------------- */
137 /** Copies a whitespace separated argument from p to arg. Returns the
138 point after argument. */
140 static char *
141 extract_arg (char *p, char *arg, int size)
143 while (*p != '\0' && whiteness (*p))
144 p++;
146 /* support quote space .mnu */
147 while (*p != '\0' && (*p != ' ' || *(p - 1) == '\\') && *p != '\t' && *p != '\n')
149 char *np;
151 np = str_get_next_char (p);
152 if (np - p >= size)
153 break;
154 memcpy (arg, p, np - p);
155 arg += np - p;
156 size -= np - p;
157 p = np;
159 *arg = '\0';
160 if (*p == '\0' || *p == '\n')
161 str_prev_char (&p);
162 return p;
165 /* --------------------------------------------------------------------------------------------- */
166 /* Tests whether the selected file in the panel is of any of the types
167 specified in argument. */
169 static gboolean
170 test_type (WPanel * panel, char *arg)
172 int result = 0; /* False by default */
173 mode_t st_mode;
175 st_mode = panel_current_entry (panel)->st.st_mode;
177 for (; *arg != '\0'; arg++)
179 switch (*arg)
181 case 'n': /* Not a directory */
182 result |= !S_ISDIR (st_mode);
183 break;
184 case 'r': /* Regular file */
185 result |= S_ISREG (st_mode);
186 break;
187 case 'd': /* Directory */
188 result |= S_ISDIR (st_mode);
189 break;
190 case 'l': /* Link */
191 result |= S_ISLNK (st_mode);
192 break;
193 case 'c': /* Character special */
194 result |= S_ISCHR (st_mode);
195 break;
196 case 'b': /* Block special */
197 result |= S_ISBLK (st_mode);
198 break;
199 case 'f': /* Fifo (named pipe) */
200 result |= S_ISFIFO (st_mode);
201 break;
202 case 's': /* Socket */
203 result |= S_ISSOCK (st_mode);
204 break;
205 case 'x': /* Executable */
206 result |= (st_mode & 0111) != 0 ? 1 : 0;
207 break;
208 case 't':
209 result |= panel->marked != 0 ? 1 : 0;
210 break;
211 default:
212 debug_error = TRUE;
213 break;
217 return (result != 0);
220 /* --------------------------------------------------------------------------------------------- */
221 /** Calculates the truth value of the next condition starting from
222 p. Returns the point after condition. */
224 static char *
225 test_condition (const Widget * edit_widget, char *p, gboolean * condition)
227 char arg[256];
228 const mc_search_type_t search_type = easy_patterns ? MC_SEARCH_T_GLOB : MC_SEARCH_T_REGEX;
229 #ifdef USE_INTERNAL_EDIT
230 const WEdit *e = CONST_EDIT (edit_widget);
231 #endif
233 /* Handle one condition */
234 for (; *p != '\n' && *p != '&' && *p != '|'; p++)
236 WPanel *panel = NULL;
238 /* support quote space .mnu */
239 if ((*p == ' ' && *(p - 1) != '\\') || *p == '\t')
240 continue;
241 if (*p >= 'a')
242 panel = current_panel;
243 else if (get_other_type () == view_listing)
244 panel = other_panel;
246 *p |= 0x20;
248 switch (*p++)
250 case '!':
251 p = test_condition (edit_widget, p, condition);
252 *condition = !*condition;
253 str_prev_char (&p);
254 break;
255 case 'f': /* file name pattern */
256 p = extract_arg (p, arg, sizeof (arg));
257 #ifdef USE_INTERNAL_EDIT
258 if (e != NULL)
260 const char *edit_filename;
262 edit_filename = edit_get_file_name (e);
263 *condition = mc_search (arg, DEFAULT_CHARSET, edit_filename, search_type);
265 else
266 #endif
267 *condition = panel != NULL &&
268 mc_search (arg, DEFAULT_CHARSET, panel_current_entry (panel)->fname->str,
269 search_type);
270 break;
271 case 'y': /* syntax pattern */
272 #ifdef USE_INTERNAL_EDIT
273 if (e != NULL)
275 const char *syntax_type;
277 syntax_type = edit_get_syntax_type (e);
278 if (syntax_type != NULL)
280 p = extract_arg (p, arg, sizeof (arg));
281 *condition = mc_search (arg, DEFAULT_CHARSET, syntax_type, MC_SEARCH_T_NORMAL);
284 #endif
285 break;
286 case 'd':
287 p = extract_arg (p, arg, sizeof (arg));
288 *condition = panel != NULL
289 && mc_search (arg, DEFAULT_CHARSET, vfs_path_as_str (panel->cwd_vpath),
290 search_type);
291 break;
292 case 't':
293 p = extract_arg (p, arg, sizeof (arg));
294 *condition = panel != NULL && test_type (panel, arg);
295 break;
296 case 'x': /* executable */
298 struct stat status;
300 p = extract_arg (p, arg, sizeof (arg));
301 *condition = stat (arg, &status) == 0 && is_exe (status.st_mode);
302 break;
304 default:
305 debug_error = TRUE;
306 break;
307 } /* switch */
308 } /* while */
309 return p;
312 /* --------------------------------------------------------------------------------------------- */
313 /** General purpose condition debug output handler */
315 static void
316 debug_out (char *start, char *end, gboolean condition)
318 static char *msg = NULL;
320 if (start == NULL && end == NULL)
322 /* Show output */
323 if (debug_flag && msg != NULL)
325 size_t len;
327 len = strlen (msg);
328 if (len != 0)
329 msg[len - 1] = '\0';
330 message (D_NORMAL, _("Debug"), "%s", msg);
333 debug_flag = FALSE;
334 MC_PTR_FREE (msg);
336 else
338 const char *type;
339 char *p;
341 /* Save debug info for later output */
342 if (!debug_flag)
343 return;
344 /* Save the result of the condition */
345 if (debug_error)
347 type = _("ERROR:");
348 debug_error = FALSE;
350 else if (condition)
351 type = _("True:");
352 else
353 type = _("False:");
354 /* This is for debugging, don't need to be super efficient. */
355 if (end == NULL)
356 p = g_strdup_printf ("%s %s %c \n", msg ? msg : "", type, *start);
357 else
358 p = g_strdup_printf ("%s %s %.*s \n", msg ? msg : "", type, (int) (end - start), start);
359 g_free (msg);
360 msg = p;
364 /* --------------------------------------------------------------------------------------------- */
365 /** Calculates the truth value of one lineful of conditions. Returns
366 the point just before the end of line. */
368 static char *
369 test_line (const Widget * edit_widget, char *p, gboolean * result)
371 char operator;
373 /* Repeat till end of line */
374 while (*p != '\0' && *p != '\n')
376 char *debug_start, *debug_end;
377 gboolean condition = TRUE;
379 /* support quote space .mnu */
380 while ((*p == ' ' && *(p - 1) != '\\') || *p == '\t')
381 p++;
382 if (*p == '\0' || *p == '\n')
383 break;
384 operator = *p++;
385 if (*p == '?')
387 debug_flag = TRUE;
388 p++;
390 /* support quote space .mnu */
391 while ((*p == ' ' && *(p - 1) != '\\') || *p == '\t')
392 p++;
393 if (*p == '\0' || *p == '\n')
394 break;
396 debug_start = p;
397 p = test_condition (edit_widget, p, &condition);
398 debug_end = p;
399 /* Add one debug statement */
400 debug_out (debug_start, debug_end, condition);
402 switch (operator)
404 case '+':
405 case '=':
406 /* Assignment */
407 *result = condition;
408 break;
409 case '&': /* Logical and */
410 *result = *result && condition;
411 break;
412 case '|': /* Logical or */
413 *result = *result || condition;
414 break;
415 default:
416 debug_error = TRUE;
417 break;
418 } /* switch */
419 /* Add one debug statement */
420 debug_out (&operator, NULL, *result);
422 } /* while (*p != '\n') */
423 /* Report debug message */
424 debug_out (NULL, NULL, TRUE);
426 if (*p == '\0' || *p == '\n')
427 str_prev_char (&p);
428 return p;
431 /* --------------------------------------------------------------------------------------------- */
432 /** FIXME: recode this routine on version 3.0, it could be cleaner */
434 static void
435 execute_menu_command (const Widget * edit_widget, const char *commands, gboolean show_prompt)
437 FILE *cmd_file;
438 int cmd_file_fd;
439 gboolean expand_prefix_found = FALSE;
440 char *parameter = NULL;
441 gboolean do_quote = FALSE;
442 char lc_prompt[80];
443 int col;
444 vfs_path_t *file_name_vpath;
445 gboolean run_view = FALSE;
446 char *cmd;
448 /* Skip menu entry title line */
449 commands = strchr (commands, '\n');
450 if (commands == NULL)
451 return;
453 cmd_file_fd = mc_mkstemps (&file_name_vpath, "mcusr", SCRIPT_SUFFIX);
455 if (cmd_file_fd == -1)
457 message (D_ERROR, MSG_ERROR, _("Cannot create temporary command file\n%s"),
458 unix_error_string (errno));
459 return;
462 cmd_file = fdopen (cmd_file_fd, "w");
463 fputs ("#! /bin/sh\n", cmd_file);
464 commands++;
466 for (col = 0; *commands != '\0'; commands++)
468 if (col == 0)
470 if (!whitespace (*commands))
471 break;
472 while (whitespace (*commands))
473 commands++;
474 if (*commands == '\0')
475 break;
477 col++;
478 if (*commands == '\n')
479 col = 0;
480 if (parameter != NULL)
482 if (*commands == '}')
484 *parameter = '\0';
485 parameter =
486 input_dialog (_("Parameter"), lc_prompt, MC_HISTORY_FM_MENU_EXEC_PARAM, "",
487 INPUT_COMPLETE_FILENAMES | INPUT_COMPLETE_CD |
488 INPUT_COMPLETE_HOSTNAMES | INPUT_COMPLETE_VARIABLES |
489 INPUT_COMPLETE_USERNAMES);
490 if (parameter == NULL || *parameter == '\0')
492 /* User canceled */
493 g_free (parameter);
494 fclose (cmd_file);
495 mc_unlink (file_name_vpath);
496 vfs_path_free (file_name_vpath, TRUE);
497 return;
499 if (do_quote)
501 char *tmp;
503 tmp = name_quote (parameter, FALSE);
504 fputs (tmp, cmd_file);
505 g_free (tmp);
507 else
508 fputs (parameter, cmd_file);
510 MC_PTR_FREE (parameter);
512 else if (parameter < lc_prompt + sizeof (lc_prompt) - 1)
513 *parameter++ = *commands;
515 else if (expand_prefix_found)
517 expand_prefix_found = FALSE;
518 if (g_ascii_isdigit ((gchar) * commands))
520 do_quote = (atoi (commands) != 0);
521 while (g_ascii_isdigit ((gchar) * commands))
522 commands++;
524 if (*commands == '{')
525 parameter = lc_prompt;
526 else
528 char *text;
530 text = expand_format (edit_widget, *commands, do_quote);
531 fputs (text, cmd_file);
532 g_free (text);
535 else if (*commands == '%')
537 int i;
539 i = check_format_view (commands + 1);
540 if (i != 0)
542 commands += i;
543 run_view = TRUE;
545 else
547 do_quote = TRUE; /* Default: Quote expanded macro */
548 expand_prefix_found = TRUE;
551 else
552 fputc (*commands, cmd_file);
555 fclose (cmd_file);
556 mc_chmod (file_name_vpath, S_IRWXU);
558 /* Execute the command indirectly to allow execution even on no-exec filesystems. */
559 cmd = g_strconcat ("/bin/sh ", vfs_path_as_str (file_name_vpath), (char *) NULL);
561 if (run_view)
563 mcview_viewer (cmd, NULL, 0, 0, 0);
564 dialog_switch_process_pending ();
566 else if (show_prompt)
567 shell_execute (cmd, EXECUTE_HIDE);
568 else
570 gboolean ok;
572 /* Prepare the terminal by setting its flag to the initial ones. This will cause \r
573 * to work as expected, instead of being ignored. */
574 tty_reset_shell_mode ();
576 ok = (system (cmd) != -1);
578 /* Restore terminal configuration. */
579 tty_raw_mode ();
581 /* Redraw the original screen's contents. */
582 tty_clear_screen ();
583 repaint_screen ();
585 if (!ok)
586 message (D_ERROR, MSG_ERROR, "%s", _("Error calling program"));
589 g_free (cmd);
591 mc_unlink (file_name_vpath);
592 vfs_path_free (file_name_vpath, TRUE);
595 /* --------------------------------------------------------------------------------------------- */
597 ** Check owner of the menu file. Using menu file is allowed, if
598 ** owner of the menu is root or the actual user. In either case
599 ** file should not be group and word-writable.
601 ** Q. Should we apply this routine to system and home menu (and .ext files)?
604 static gboolean
605 menu_file_own (char *path)
607 struct stat st;
609 if (stat (path, &st) == 0 && (st.st_uid == 0 || (st.st_uid == geteuid ()) != 0)
610 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0))
611 return TRUE;
613 if (verbose)
614 message (D_NORMAL, _("Warning -- ignoring file"),
615 _("File %s is not owned by root or you or is world writable.\n"
616 "Using it may compromise your security"), path);
618 return FALSE;
621 /* --------------------------------------------------------------------------------------------- */
622 /*** public functions ****************************************************************************/
623 /* --------------------------------------------------------------------------------------------- */
625 /* Formats defined:
626 %% The % character
627 %f The current file in the active panel (if non-local vfs, file will be copied locally
628 and %f will be full path to it) or the opened file in the internal editor.
629 %p Likewise.
630 %d The current working directory
631 %s "Selected files"; the tagged files if any, otherwise the current file
632 %t Tagged files
633 %u Tagged files (and they are untagged on return from expand_format)
634 %view Runs the commands and pipes standard output to the view command.
635 If %view is immediately followed by '{', recognize keywords
636 ascii, hex, nroff and unform
638 If the format letter is in uppercase, it refers to the other panel.
640 With a number followed the % character you can turn quoting on (default)
641 and off. For example:
642 %f quote expanded macro
643 %1f ditto
644 %0f don't quote expanded macro
646 expand_format returns a memory block that must be free()d.
649 /* Returns how many characters we should advance if %view was found */
651 check_format_view (const char *p)
653 const char *q = p;
655 if (strncmp (p, "view", 4) == 0)
657 q += 4;
658 if (*q == '{')
660 for (q++; *q != '\0' && *q != '}'; q++)
662 if (strncmp (q, DEFAULT_CHARSET, 5) == 0)
664 mcview_global_flags.hex = FALSE;
665 q += 4;
667 else if (strncmp (q, "hex", 3) == 0)
669 mcview_global_flags.hex = TRUE;
670 q += 2;
672 else if (strncmp (q, "nroff", 5) == 0)
674 mcview_global_flags.nroff = TRUE;
675 q += 4;
677 else if (strncmp (q, "unform", 6) == 0)
679 mcview_global_flags.nroff = FALSE;
680 q += 5;
683 if (*q == '}')
684 q++;
686 return q - p;
688 return 0;
691 /* --------------------------------------------------------------------------------------------- */
694 check_format_cd (const char *p)
696 return (strncmp (p, "cd", 2)) != 0 ? 0 : 3;
699 /* --------------------------------------------------------------------------------------------- */
700 /* Check if p has a "^var\{var-name\}" */
701 /* Returns the number of skipped characters (zero on not found) */
702 /* V will be set to the expanded variable name */
705 check_format_var (const char *p, char **v)
707 *v = NULL;
709 if (strncmp (p, "var{", 4) == 0)
711 const char *q = p;
712 const char *dots = NULL;
713 const char *value;
714 char *var_name;
716 for (q += 4; *q != '\0' && *q != '}'; q++)
718 if (*q == ':')
719 dots = q + 1;
721 if (*q == '\0')
722 return 0;
724 if (dots == NULL || dots == q + 5)
726 message (D_ERROR,
727 _("Format error on file Extensions File"),
728 !dots ? _("The %%var macro has no default")
729 : _("The %%var macro has no variable"));
730 return 0;
733 /* Copy the variable name */
734 var_name = g_strndup (p + 4, dots - 2 - (p + 3));
735 value = getenv (var_name);
736 g_free (var_name);
738 if (value != NULL)
739 *v = g_strdup (value);
740 else
741 *v = g_strndup (dots, q - dots);
743 return q - p;
745 return 0;
748 /* --------------------------------------------------------------------------------------------- */
750 char *
751 expand_format (const Widget * edit_widget, char c, gboolean do_quote)
753 WPanel *panel = NULL;
754 char *(*quote_func) (const char *, gboolean);
755 const char *fname = NULL;
756 char *result;
757 char c_lc;
759 #ifdef USE_INTERNAL_EDIT
760 const WEdit *e = CONST_EDIT (edit_widget);
761 #else
762 (void) edit_widget;
763 #endif
765 if (c == '%')
766 return g_strdup ("%");
768 switch (mc_global.mc_run_mode)
770 case MC_RUN_FULL:
771 #ifdef USE_INTERNAL_EDIT
772 if (e != NULL)
773 fname = edit_get_file_name (e);
774 else
775 #endif
777 if (g_ascii_islower ((gchar) c))
778 panel = current_panel;
779 else
781 if (get_other_type () != view_listing)
782 return g_strdup ("");
783 panel = other_panel;
786 fname = panel_current_entry (panel)->fname->str;
788 break;
790 #ifdef USE_INTERNAL_EDIT
791 case MC_RUN_EDITOR:
792 fname = edit_get_file_name (e);
793 break;
794 #endif
796 case MC_RUN_VIEWER:
797 /* mc_run_param0 is not NULL here because mcviewer isn't run without input file */
798 fname = (const char *) mc_run_param0;
799 break;
801 default:
802 /* other modes don't use formats */
803 return g_strdup ("");
806 if (do_quote)
807 quote_func = name_quote;
808 else
809 quote_func = fake_name_quote;
811 c_lc = g_ascii_tolower ((gchar) c);
813 switch (c_lc)
815 case 'f':
816 case 'p':
817 result = quote_func (fname, FALSE);
818 goto ret;
819 case 'x':
820 result = quote_func (extension (fname), FALSE);
821 goto ret;
822 case 'd':
824 const char *cwd;
825 char *qstr;
827 if (panel != NULL)
828 cwd = vfs_path_as_str (panel->cwd_vpath);
829 else
830 cwd = vfs_get_current_dir ();
832 qstr = quote_func (cwd, FALSE);
834 result = qstr;
835 goto ret;
837 case 'c':
838 #ifdef USE_INTERNAL_EDIT
839 if (e != NULL)
841 result = g_strdup_printf ("%u", (unsigned int) edit_get_cursor_offset (e));
842 goto ret;
844 #endif
845 break;
846 case 'i': /* indent equal number cursor position in line */
847 #ifdef USE_INTERNAL_EDIT
848 if (e != NULL)
850 result = g_strnfill (edit_get_curs_col (e), ' ');
851 goto ret;
853 #endif
854 break;
855 case 'y': /* syntax type */
856 #ifdef USE_INTERNAL_EDIT
857 if (e != NULL)
859 const char *syntax_type;
861 syntax_type = edit_get_syntax_type (e);
862 if (syntax_type != NULL)
864 result = g_strdup (syntax_type);
865 goto ret;
868 #endif
869 break;
870 case 'k': /* block file name */
871 case 'b': /* block file name / strip extension */
872 #ifdef USE_INTERNAL_EDIT
873 if (e != NULL)
875 char *file;
877 file = mc_config_get_full_path (EDIT_HOME_BLOCK_FILE);
878 result = quote_func (file, FALSE);
879 g_free (file);
880 goto ret;
882 #endif
883 if (c_lc == 'b')
885 result = strip_ext (quote_func (fname, FALSE));
886 goto ret;
888 break;
889 case 'n': /* strip extension in editor */
890 #ifdef USE_INTERNAL_EDIT
891 if (e != NULL)
893 result = strip_ext (quote_func (fname, FALSE));
894 goto ret;
896 #endif
897 break;
898 case 'm': /* menu file name */
899 if (menu != NULL)
901 result = quote_func (menu, FALSE);
902 goto ret;
904 break;
905 case 's':
906 if (panel == NULL || panel->marked == 0)
908 result = quote_func (fname, FALSE);
909 goto ret;
912 MC_FALLTHROUGH;
914 case 't':
915 case 'u':
917 GString *block;
918 int i;
920 if (panel == NULL)
922 result = g_strdup ("");
923 goto ret;
926 block = g_string_sized_new (16);
928 for (i = 0; i < panel->dir.len; i++)
929 if (panel->dir.list[i].f.marked != 0)
931 char *tmp;
933 tmp = quote_func (panel->dir.list[i].fname->str, FALSE);
934 g_string_append (block, tmp);
935 g_string_append_c (block, ' ');
936 g_free (tmp);
938 if (c_lc == 'u')
939 do_file_mark (panel, i, 0);
941 result = g_string_free (block, FALSE);
942 goto ret;
943 } /* sub case block */
944 default:
945 break;
946 } /* switch */
948 result = g_strdup ("% ");
949 result[1] = c;
950 ret:
951 return result;
954 /* --------------------------------------------------------------------------------------------- */
956 * If edit_widget is NULL then we are called from the mc menu,
957 * otherwise we are called from the mcedit menu.
960 gboolean
961 user_menu_cmd (const Widget * edit_widget, const char *menu_file, int selected_entry)
963 char *p;
964 char *data, **entries;
965 int max_cols, menu_lines, menu_limit;
966 int col, i;
967 gboolean accept_entry = TRUE;
968 int selected;
969 gboolean old_patterns;
970 gboolean res = FALSE;
971 gboolean interactive = TRUE;
973 if (!vfs_current_is_local ())
975 message (D_ERROR, MSG_ERROR, "%s", _("Cannot execute commands on non-local filesystems"));
976 return FALSE;
978 if (menu_file != NULL)
979 menu = g_strdup (menu_file);
980 else
981 menu = g_strdup (edit_widget != NULL ? EDIT_LOCAL_MENU : MC_LOCAL_MENU);
982 if (!exist_file (menu) || !menu_file_own (menu))
984 if (menu_file != NULL)
986 message (D_ERROR, MSG_ERROR, _("Cannot open file %s\n%s"), menu,
987 unix_error_string (errno));
988 MC_PTR_FREE (menu);
989 return FALSE;
992 g_free (menu);
993 if (edit_widget != NULL)
994 menu = mc_config_get_full_path (EDIT_HOME_MENU);
995 else
996 menu = mc_config_get_full_path (MC_USERMENU_FILE);
998 if (!exist_file (menu))
1000 g_free (menu);
1001 menu =
1002 mc_build_filename (mc_config_get_home_dir (),
1003 edit_widget != NULL ? EDIT_GLOBAL_MENU : MC_GLOBAL_MENU,
1004 (char *) NULL);
1005 if (!exist_file (menu))
1007 g_free (menu);
1008 menu =
1009 mc_build_filename (mc_global.sysconfig_dir,
1010 edit_widget != NULL ? EDIT_GLOBAL_MENU : MC_GLOBAL_MENU,
1011 (char *) NULL);
1012 if (!exist_file (menu))
1014 g_free (menu);
1015 menu =
1016 mc_build_filename (mc_global.share_data_dir,
1017 edit_widget != NULL ? EDIT_GLOBAL_MENU : MC_GLOBAL_MENU,
1018 (char *) NULL);
1024 if (!g_file_get_contents (menu, &data, NULL, NULL))
1026 message (D_ERROR, MSG_ERROR, _("Cannot open file %s\n%s"), menu, unix_error_string (errno));
1027 MC_PTR_FREE (menu);
1028 return FALSE;
1031 max_cols = 0;
1032 selected = 0;
1033 menu_limit = 0;
1034 entries = NULL;
1036 /* Parse the menu file */
1037 old_patterns = easy_patterns;
1038 p = check_patterns (data);
1039 for (menu_lines = col = 0; *p != '\0'; str_next_char (&p))
1041 if (menu_lines >= menu_limit)
1043 char **new_entries;
1045 menu_limit += MAX_ENTRIES;
1046 new_entries = g_try_realloc (entries, sizeof (new_entries[0]) * menu_limit);
1047 if (new_entries == NULL)
1048 break;
1050 entries = new_entries;
1051 new_entries += menu_limit;
1052 while (--new_entries >= &entries[menu_lines])
1053 *new_entries = NULL;
1056 if (col == 0 && entries[menu_lines] == NULL)
1057 switch (*p)
1059 case '#':
1060 /* do not show prompt if first line of external script is #silent */
1061 if (selected_entry >= 0 && strncmp (p, "#silent", 7) == 0)
1062 interactive = FALSE;
1063 /* A commented menu entry */
1064 accept_entry = TRUE;
1065 break;
1067 case '+':
1068 if (*(p + 1) == '=')
1070 /* Combined adding and default */
1071 p = test_line (edit_widget, p + 1, &accept_entry);
1072 if (selected == 0 && accept_entry)
1073 selected = menu_lines;
1075 else
1077 /* A condition for adding the entry */
1078 p = test_line (edit_widget, p, &accept_entry);
1080 break;
1082 case '=':
1083 if (*(p + 1) == '+')
1085 /* Combined adding and default */
1086 p = test_line (edit_widget, p + 1, &accept_entry);
1087 if (selected == 0 && accept_entry)
1088 selected = menu_lines;
1090 else
1092 /* A condition for making the entry default */
1093 i = 1;
1094 p = test_line (edit_widget, p, &i);
1095 if (selected == 0 && i != 0)
1096 selected = menu_lines;
1098 break;
1100 default:
1101 if (!whitespace (*p) && str_isprint (p))
1103 /* A menu entry title line */
1104 if (accept_entry)
1105 entries[menu_lines] = p;
1106 else
1107 accept_entry = TRUE;
1109 break;
1112 if (*p == '\n')
1114 if (entries[menu_lines] != NULL)
1116 menu_lines++;
1117 accept_entry = TRUE;
1119 max_cols = MAX (max_cols, col);
1120 col = 0;
1122 else
1124 if (*p == '\t')
1125 *p = ' ';
1126 col++;
1130 if (menu_lines == 0)
1132 message (D_ERROR, MSG_ERROR, _("No suitable entries found in %s"), menu);
1133 res = FALSE;
1135 else
1137 if (selected_entry >= 0)
1138 selected = selected_entry;
1139 else
1141 Listbox *listbox;
1143 max_cols = MIN (MAX (max_cols, col), MAX_ENTRY_LEN);
1145 /* Create listbox */
1146 listbox = listbox_window_new (menu_lines, max_cols + 2, _("User menu"),
1147 "[Edit Menu File]");
1148 /* insert all the items found */
1149 for (i = 0; i < menu_lines; i++)
1151 p = entries[i];
1152 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
1153 extract_line (p, p + MAX_ENTRY_LEN), p, FALSE);
1155 /* Select the default entry */
1156 listbox_set_current (listbox->list, selected);
1158 selected = listbox_run (listbox);
1160 if (selected >= 0)
1162 execute_menu_command (edit_widget, entries[selected], interactive);
1163 res = TRUE;
1166 do_refresh ();
1169 easy_patterns = old_patterns;
1170 MC_PTR_FREE (menu);
1171 g_free (entries);
1172 g_free (data);
1173 return res;
1176 /* --------------------------------------------------------------------------------------------- */