Reverted the use of bool in favour of gboolean
[midnight-commander.git] / src / user.c
blob14e3d69945e35994c4779483c5df3ce720aafcff
1 /* User Menu implementation
2 Copyright (C) 1994, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19 #include <config.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <string.h>
26 #include <mhl/memory.h>
27 #include <mhl/string.h>
29 #include "global.h"
30 #include "tty.h"
31 #include "color.h"
32 #include "dir.h"
33 #include "panel.h"
34 #include "main.h"
35 #include "user.h"
36 #include "layout.h"
37 #include "execute.h"
38 #include "setup.h"
39 #include "history.h"
41 #include "../edit/edit.h" /* BLOCK_FILE */
42 #include "../edit/edit-widget.h" /* WEdit */
44 /* For the simple listbox manager */
45 #include "dialog.h"
46 #include "widget.h"
47 #include "wtools.h"
49 #include "view.h" /* for default_* externs */
51 #define MAX_ENTRIES 16
52 #define MAX_ENTRY_LEN 60
54 static int debug_flag = 0;
55 static int debug_error = 0;
56 static char *menu = NULL;
58 /* Formats defined:
59 %% The % character
60 %f The current file (if non-local vfs, file will be copied locally and
61 %f will be full path to it).
62 %p The current file
63 %d The current working directory
64 %s "Selected files"; the tagged files if any, otherwise the current file
65 %t Tagged files
66 %u Tagged files (and they are untagged on return from expand_format)
67 %view Runs the commands and pipes standard output to the view command.
68 If %view is immediately followed by '{', recognize keywords
69 ascii, hex, nroff and unform
71 If the format letter is in uppercase, it refers to the other panel.
73 With a number followed the % character you can turn quoting on (default)
74 and off. For example:
75 %f quote expanded macro
76 %1f ditto
77 %0f don't quote expanded macro
79 expand_format returns a memory block that must be free()d.
82 /* Returns how many characters we should advance if %view was found */
83 int check_format_view (const char *p)
85 const char *q = p;
86 if (!strncmp (p, "view", 4)) {
87 q += 4;
88 if (*q == '{'){
89 for (q++;*q && *q != '}';q++) {
90 if (!strncmp (q, "ascii", 5)) {
91 default_hex_mode = 0;
92 q += 4;
93 } else if (!strncmp (q, "hex", 3)) {
94 default_hex_mode = 1;
95 q += 2;
96 } else if (!strncmp (q, "nroff", 5)) {
97 default_nroff_flag = 1;
98 q += 4;
99 } else if (!strncmp (q, "unform", 6)) {
100 default_nroff_flag = 0;
101 q += 5;
104 if (*q == '}')
105 q++;
107 return q - p;
109 return 0;
112 int check_format_cd (const char *p)
114 return (strncmp (p, "cd", 2)) ? 0 : 3;
117 /* Check if p has a "^var\{var-name\}" */
118 /* Returns the number of skipped characters (zero on not found) */
119 /* V will be set to the expanded variable name */
120 int check_format_var (const char *p, char **v)
122 const char *q = p;
123 char *var_name;
124 const char *value;
125 const char *dots = 0;
127 *v = 0;
128 if (!strncmp (p, "var{", 4)){
129 for (q += 4; *q && *q != '}'; q++){
130 if (*q == ':')
131 dots = q+1;
133 if (!*q)
134 return 0;
136 if (!dots || dots == q+5){
137 message (D_ERROR,
138 _(" Format error on file Extensions File "),
139 !dots ? _(" The %%var macro has no default ")
140 : _(" The %%var macro has no variable "));
141 return 0;
144 /* Copy the variable name */
145 var_name = g_strndup (p + 4, dots-2 - (p+3));
147 value = getenv (var_name);
148 g_free (var_name);
149 if (value){
150 *v = g_strdup (value);
151 return q-p;
153 var_name = g_strndup (dots, q - dots);
154 *v = var_name;
155 return q-p;
157 return 0;
160 /* strip file's extension */
161 static char *
162 strip_ext(char *ss)
164 register char *s = ss;
165 char *e = NULL;
166 while(*s) {
167 if(*s == '.') e = s;
168 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
169 s++;
171 if(e) *e = 0;
172 return ss;
175 char *
176 expand_format (struct WEdit *edit_widget, char c, int quote)
178 WPanel *panel = NULL;
179 char *(*quote_func) (const char *, int);
180 char *fname;
181 char *result;
182 char c_lc;
184 if (c == '%')
185 return g_strdup ("%");
187 if (edit_one_file != NULL)
188 fname = edit_widget->filename;
189 else {
190 if (islower ((unsigned char) c))
191 panel = current_panel;
192 else {
193 if (get_other_type () != view_listing)
194 return g_strdup ("");
195 panel = other_panel;
197 fname = panel->dir.list[panel->selected].fname;
200 if (quote)
201 quote_func = name_quote;
202 else
203 quote_func = fake_name_quote;
205 c_lc = tolower ((unsigned char) c);
207 switch (c_lc) {
208 case 'f':
209 case 'p':
210 return (*quote_func) (fname, 0);
211 case 'x':
212 return (*quote_func) (extension (fname), 0);
213 case 'd':
215 char *cwd;
216 char *qstr;
218 cwd = g_malloc(MC_MAXPATHLEN + 1);
220 if (panel)
221 g_strlcpy(cwd, panel->cwd, MC_MAXPATHLEN + 1);
222 else
223 mc_get_current_wd(cwd, MC_MAXPATHLEN + 1);
225 qstr = (*quote_func) (cwd, 0);
227 g_free (cwd);
229 return qstr;
231 case 'i': /* indent equal number cursor position in line */
232 if (edit_widget)
233 return g_strnfill (edit_widget->curs_col, ' ');
234 break;
235 case 'y': /* syntax type */
236 if (edit_widget && edit_widget->syntax_type)
237 return g_strdup (edit_widget->syntax_type);
238 break;
239 case 'k': /* block file name */
240 case 'b': /* block file name / strip extension */ {
241 if (edit_widget) {
242 char *file = g_strconcat (home_dir, PATH_SEP_STR BLOCK_FILE, (char *) NULL);
243 fname = (*quote_func) (file, 0);
244 g_free (file);
245 return fname;
246 } else if (c_lc == 'b') {
247 return strip_ext ((*quote_func) (fname, 0));
249 break;
251 case 'n': /* strip extension in editor */
252 if (edit_widget)
253 return strip_ext ((*quote_func) (fname, 0));
254 break;
255 case 'm': /* menu file name */
256 if (menu)
257 return (*quote_func) (menu, 0);
258 break;
259 case 's':
260 if (!panel || !panel->marked)
261 return (*quote_func) (fname, 0);
263 /* Fall through */
265 case 't':
266 case 'u':
268 int length = 2, i;
269 char *block, *tmp;
271 if (!panel)
272 return g_strdup ("");
274 for (i = 0; i < panel->count; i++)
275 if (panel->dir.list[i].f.marked)
276 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
278 block = g_malloc (length * 2 + 1);
279 *block = 0;
280 for (i = 0; i < panel->count; i++)
281 if (panel->dir.list[i].f.marked) {
282 strcat (block, tmp =
283 (*quote_func) (panel->dir.list[i].fname, 0));
284 g_free (tmp);
285 strcat (block, " ");
286 if (c_lc == 'u')
287 do_file_mark (panel, i, 0);
289 return block;
290 } /* sub case block */
291 } /* switch */
292 result = g_strdup ("% ");
293 result[1] = c;
294 return result;
298 * Check for the "shell_patterns" directive. If it's found and valid,
299 * interpret it and move the pointer past the directive. Return the
300 * current pointer.
302 static char *
303 check_patterns (char *p)
305 static const char def_name[] = "shell_patterns=";
306 char *p0 = p;
308 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
309 return p0;
311 p += sizeof (def_name) - 1;
312 if (*p == '1')
313 easy_patterns = 1;
314 else if (*p == '0')
315 easy_patterns = 0;
316 else
317 return p0;
319 /* Skip spaces */
320 p++;
321 while (*p == '\n' || *p == '\t' || *p == ' ')
322 p++;
323 return p;
326 /* Copies a whitespace separated argument from p to arg. Returns the
327 point after argument. */
328 static char *extract_arg (char *p, char *arg, int size)
330 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
331 p++;
332 /* support quote space .mnu */
333 while (size > 1 && *p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n') {
334 *arg++ = *p++;
335 size--;
337 *arg = 0;
338 if (!*p || *p == '\n')
339 p --;
340 return p;
343 /* Tests whether the selected file in the panel is of any of the types
344 specified in argument. */
345 static int test_type (WPanel *panel, char *arg)
347 int result = 0; /* False by default */
348 int st_mode = panel->dir.list [panel->selected].st.st_mode;
350 for (;*arg != 0; arg++){
351 switch (*arg){
352 case 'n': /* Not a directory */
353 result |= !S_ISDIR (st_mode);
354 break;
355 case 'r': /* Regular file */
356 result |= S_ISREG (st_mode);
357 break;
358 case 'd': /* Directory */
359 result |= S_ISDIR (st_mode);
360 break;
361 case 'l': /* Link */
362 result |= S_ISLNK (st_mode);
363 break;
364 case 'c': /* Character special */
365 result |= S_ISCHR (st_mode);
366 break;
367 case 'b': /* Block special */
368 result |= S_ISBLK (st_mode);
369 break;
370 case 'f': /* Fifo (named pipe) */
371 result |= S_ISFIFO (st_mode);
372 break;
373 case 's': /* Socket */
374 result |= S_ISSOCK (st_mode);
375 break;
376 case 'x': /* Executable */
377 result |= (st_mode & 0111) ? 1 : 0;
378 break;
379 case 't':
380 result |= panel->marked ? 1 : 0;
381 break;
382 default:
383 debug_error = 1;
384 break;
387 return result;
390 /* Calculates the truth value of the next condition starting from
391 p. Returns the point after condition. */
392 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
394 WPanel *panel;
395 char arg [256];
397 /* Handle one condition */
398 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
399 /* support quote space .mnu */
400 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
401 continue;
402 if (*p >= 'a')
403 panel = current_panel;
404 else {
405 if (get_other_type () == view_listing)
406 panel = other_panel;
407 else
408 panel = NULL;
410 *p |= 0x20;
412 switch (*p++){
413 case '!':
414 p = test_condition (edit_widget, p, condition);
415 *condition = ! *condition;
416 p--;
417 break;
418 case 'f': /* file name pattern */
419 p = extract_arg (p, arg, sizeof (arg));
420 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
421 break;
422 case 'y': /* syntax pattern */
423 if (edit_widget && edit_widget->syntax_type) {
424 p = extract_arg (p, arg, sizeof (arg));
425 *condition = panel &&
426 regexp_match (arg, edit_widget->syntax_type, match_normal);
428 break;
429 case 'd':
430 p = extract_arg (p, arg, sizeof (arg));
431 *condition = panel && regexp_match (arg, panel->cwd, match_file);
432 break;
433 case 't':
434 p = extract_arg (p, arg, sizeof (arg));
435 *condition = panel && test_type (panel, arg);
436 break;
437 case 'x': /* executable */
439 struct stat status;
441 p = extract_arg (p, arg, sizeof (arg));
442 if (stat (arg, &status) == 0)
443 *condition = is_exe (status.st_mode);
444 else
445 *condition = 0;
446 break;
448 default:
449 debug_error = 1;
450 break;
451 } /* switch */
453 } /* while */
454 return p;
457 /* General purpose condition debug output handler */
458 static void
459 debug_out (char *start, char *end, int cond)
461 static char *msg;
462 int len;
464 if (start == NULL && end == NULL){
465 /* Show output */
466 if (debug_flag && msg) {
467 len = strlen (msg);
468 if (len)
469 msg [len - 1] = 0;
470 message (D_NORMAL, _(" Debug "), "%s", msg);
473 debug_flag = 0;
474 g_free (msg);
475 msg = NULL;
476 } else {
477 const char *type;
478 char *p;
480 /* Save debug info for later output */
481 if (!debug_flag)
482 return;
483 /* Save the result of the condition */
484 if (debug_error){
485 type = _(" ERROR: ");
486 debug_error = 0;
488 else if (cond)
489 type = _(" True: ");
490 else
491 type = _(" False: ");
492 /* This is for debugging, don't need to be super efficient. */
493 if (end == NULL)
494 p = g_strdup_printf ("%s%s%c \n", msg ? msg : "", type, *start);
495 else
496 p = g_strdup_printf ("%s%s%.*s \n", msg ? msg : "", type,
497 (int) (end - start), start);
498 g_free (msg);
499 msg = p;
503 /* Calculates the truth value of one lineful of conditions. Returns
504 the point just before the end of line. */
505 static char *test_line (WEdit *edit_widget, char *p, int *result)
507 int condition;
508 char operator;
509 char *debug_start, *debug_end;
511 /* Repeat till end of line */
512 while (*p && *p != '\n') {
513 /* support quote space .mnu */
514 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
515 p++;
516 if (!*p || *p == '\n')
517 break;
518 operator = *p++;
519 if (*p == '?'){
520 debug_flag = 1;
521 p++;
523 /* support quote space .mnu */
524 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
525 p++;
526 if (!*p || *p == '\n')
527 break;
528 condition = 1; /* True by default */
530 debug_start = p;
531 p = test_condition (edit_widget, p, &condition);
532 debug_end = p;
533 /* Add one debug statement */
534 debug_out (debug_start, debug_end, condition);
536 switch (operator){
537 case '+':
538 case '=':
539 /* Assignment */
540 *result = condition;
541 break;
542 case '&': /* Logical and */
543 *result &= condition;
544 break;
545 case '|': /* Logical or */
546 *result |= condition;
547 break;
548 default:
549 debug_error = 1;
550 break;
551 } /* switch */
552 /* Add one debug statement */
553 debug_out (&operator, NULL, *result);
555 } /* while (*p != '\n') */
556 /* Report debug message */
557 debug_out (NULL, NULL, 1);
559 if (!*p || *p == '\n')
560 p --;
561 return p;
564 /* FIXME: recode this routine on version 3.0, it could be cleaner */
565 static void
566 execute_menu_command (WEdit *edit_widget, const char *commands)
568 FILE *cmd_file;
569 int cmd_file_fd;
570 int expand_prefix_found = 0;
571 char *parameter = 0;
572 int do_quote = 0;
573 char prompt [80];
574 int col;
575 char *file_name;
576 int run_view = 0;
578 /* Skip menu entry title line */
579 commands = strchr (commands, '\n');
580 if (!commands){
581 return;
584 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
586 if (cmd_file_fd == -1){
587 message (D_ERROR, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
588 unix_error_string (errno));
589 return;
591 cmd_file = fdopen (cmd_file_fd, "w");
592 fputs ("#! /bin/sh\n", cmd_file);
593 commands++;
595 for (col = 0; *commands; commands++){
596 if (col == 0) {
597 if (*commands != ' ' && *commands != '\t')
598 break;
599 while (*commands == ' ' || *commands == '\t')
600 commands++;
601 if (*commands == 0)
602 break;
604 col++;
605 if (*commands == '\n')
606 col = 0;
607 if (parameter){
608 if (*commands == '}'){
609 char *tmp;
610 *parameter = 0;
611 parameter = input_dialog (_(" Parameter "), prompt, MC_HISTORY_FM_MENU_EXEC_PARAM, "");
612 if (!parameter || !*parameter){
613 /* User canceled */
614 fclose (cmd_file);
615 unlink (file_name);
616 g_free (file_name);
617 return;
619 if (do_quote) {
620 fputs (tmp = name_quote (parameter, 0), cmd_file);
621 g_free (tmp);
622 } else
623 fputs (parameter, cmd_file);
624 g_free (parameter);
625 parameter = 0;
626 } else {
627 if (parameter < &prompt [sizeof (prompt) - 1]) {
628 *parameter++ = *commands;
631 } else if (expand_prefix_found){
632 expand_prefix_found = 0;
633 if (isdigit ((unsigned char) *commands)) {
634 do_quote = atoi (commands);
635 while (isdigit ((unsigned char) *commands))
636 commands++;
638 if (*commands == '{')
639 parameter = prompt;
640 else{
641 char *text = expand_format (edit_widget, *commands, do_quote);
642 fputs (text, cmd_file);
643 g_free (text);
645 } else {
646 if (*commands == '%') {
647 int i = check_format_view (commands + 1);
648 if (i) {
649 commands += i;
650 run_view = 1;
651 } else {
652 do_quote = 1; /* Default: Quote expanded macro */
653 expand_prefix_found = 1;
655 } else
656 fputc (*commands, cmd_file);
659 fclose (cmd_file);
660 chmod (file_name, S_IRWXU);
661 if (run_view) {
662 run_view = 0;
663 mc_internal_viewer (file_name, NULL, &run_view, 0);
664 } else {
665 /* execute the command indirectly to allow execution even
666 * on no-exec filesystems. */
667 char *cmd = g_strconcat("/bin/sh ", file_name, (char *)NULL);
668 shell_execute (cmd, EXECUTE_HIDE);
669 g_free(cmd);
671 unlink (file_name);
672 g_free (file_name);
676 ** Check owner of the menu file. Using menu file is allowed, if
677 ** owner of the menu is root or the actual user. In either case
678 ** file should not be group and word-writable.
680 ** Q. Should we apply this routine to system and home menu (and .ext files)?
682 static int
683 menu_file_own(char* path)
685 struct stat st;
687 if (stat (path, &st) == 0
688 && (!st.st_uid || (st.st_uid == geteuid ()))
689 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
691 return 1;
693 if (verbose)
695 message (D_NORMAL, _(" Warning -- ignoring file "),
696 _("File %s is not owned by root or you or is world writable.\n"
697 "Using it may compromise your security"),
698 path
701 return 0;
705 * If edit_widget is NULL then we are called from the mc menu,
706 * otherwise we are called from the mcedit menu.
708 void
709 user_menu_cmd (struct WEdit *edit_widget)
711 char *p;
712 char *data, **entries;
713 int max_cols, menu_lines, menu_limit;
714 int col, i, accept_entry = 1;
715 int selected, old_patterns;
716 Listbox *listbox;
718 if (!vfs_current_is_local ()){
719 message (D_ERROR, MSG_ERROR,
720 _(" Cannot execute commands on non-local filesystems"));
721 return;
724 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
725 if (!exist_file (menu) || !menu_file_own (menu)){
726 g_free (menu);
727 menu = mhl_str_dir_plus_file \
728 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
729 if (!exist_file (menu)){
730 g_free (menu);
731 menu = mhl_str_dir_plus_file \
732 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
736 if ((data = load_file (menu)) == NULL){
737 message (D_ERROR, MSG_ERROR, _(" Cannot open file %s \n %s "),
738 menu, unix_error_string (errno));
739 g_free (menu);
740 menu = NULL;
741 return;
744 max_cols = 0;
745 selected = 0;
746 menu_limit = 0;
747 entries = 0;
749 /* Parse the menu file */
750 old_patterns = easy_patterns;
751 p = check_patterns (data);
752 for (menu_lines = col = 0; *p; p++){
753 if (menu_lines >= menu_limit){
754 char ** new_entries;
756 menu_limit += MAX_ENTRIES;
757 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
759 if (new_entries == 0)
760 break;
762 entries = new_entries;
763 new_entries += menu_limit;
764 while (--new_entries >= &entries[menu_lines])
765 *new_entries = 0;
767 if (col == 0 && !entries [menu_lines]){
768 if (*p == '#'){
769 /* A commented menu entry */
770 accept_entry = 1;
771 } else if (*p == '+'){
772 if (*(p+1) == '='){
773 /* Combined adding and default */
774 p = test_line (edit_widget, p + 1, &accept_entry);
775 if (selected == 0 && accept_entry)
776 selected = menu_lines;
777 } else {
778 /* A condition for adding the entry */
779 p = test_line (edit_widget, p, &accept_entry);
781 } else if (*p == '='){
782 if (*(p+1) == '+'){
783 /* Combined adding and default */
784 p = test_line (edit_widget, p + 1, &accept_entry);
785 if (selected == 0 && accept_entry)
786 selected = menu_lines;
787 } else {
788 /* A condition for making the entry default */
789 i = 1;
790 p = test_line (edit_widget, p, &i);
791 if (selected == 0 && i)
792 selected = menu_lines;
795 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
796 /* A menu entry title line */
797 if (accept_entry)
798 entries [menu_lines] = p;
799 else
800 accept_entry = 1;
803 if (*p == '\n'){
804 if (entries [menu_lines]){
805 menu_lines++;
806 accept_entry = 1;
808 max_cols = max (max_cols, col);
809 col = 0;
810 } else {
811 if (*p == '\t')
812 *p = ' ';
813 col++;
817 if (menu_lines == 0) {
818 message (D_ERROR, MSG_ERROR, _(" No suitable entries found in %s "), menu);
819 } else {
821 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
823 /* Create listbox */
824 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
825 "[Menu File Edit]");
826 /* insert all the items found */
827 for (i = 0; i < menu_lines; i++) {
828 p = entries [i];
829 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
830 extract_line (p, p + MAX_ENTRY_LEN), p
833 /* Select the default entry */
834 listbox_select_by_number (listbox->list, selected);
836 selected = run_listbox (listbox);
837 if (selected >= 0)
838 execute_menu_command (edit_widget, entries [selected]);
840 do_refresh ();
843 easy_patterns = old_patterns;
844 g_free (menu);
845 menu = NULL;
846 g_free (entries);
847 g_free (data);