changed includes from ../mhl/ to <mhl/...>
[midnight-commander.git] / src / user.c
blob01022aa97e28806bec39301caa71cfaee5a1b014
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 "global.h"
27 #include "tty.h"
28 #include "color.h"
29 #include "dir.h"
30 #include "panel.h"
31 #include "main.h"
32 #include "user.h"
33 #include "layout.h"
34 #include "execute.h"
35 #include "setup.h"
37 #include "../edit/edit.h" /* BLOCK_FILE */
38 #include "../edit/edit-widget.h" /* WEdit */
40 /* For the simple listbox manager */
41 #include "dialog.h"
42 #include "widget.h"
43 #include "wtools.h"
45 #include "view.h" /* for default_* externs */
47 #define MAX_ENTRIES 16
48 #define MAX_ENTRY_LEN 60
50 static int debug_flag = 0;
51 static int debug_error = 0;
52 static char *menu = NULL;
54 /* Formats defined:
55 %% The % character
56 %f The current file (if non-local vfs, file will be copied locally and
57 %f will be full path to it).
58 %p The current file
59 %d The current working directory
60 %s "Selected files"; the tagged files if any, otherwise the current file
61 %t Tagged files
62 %u Tagged files (and they are untagged on return from expand_format)
63 %view Runs the commands and pipes standard output to the view command.
64 If %view is immediately followed by '{', recognize keywords
65 ascii, hex, nroff and unform
67 If the format letter is in uppercase, it refers to the other panel.
69 With a number followed the % character you can turn quoting on (default)
70 and off. For example:
71 %f quote expanded macro
72 %1f ditto
73 %0f don't quote expanded macro
75 expand_format returns a memory block that must be free()d.
78 /* Returns how many characters we should advance if %view was found */
79 int check_format_view (const char *p)
81 const char *q = p;
82 if (!strncmp (p, "view", 4)) {
83 q += 4;
84 if (*q == '{'){
85 for (q++;*q && *q != '}';q++) {
86 if (!strncmp (q, "ascii", 5)) {
87 default_hex_mode = 0;
88 q += 4;
89 } else if (!strncmp (q, "hex", 3)) {
90 default_hex_mode = 1;
91 q += 2;
92 } else if (!strncmp (q, "nroff", 5)) {
93 default_nroff_flag = 1;
94 q += 4;
95 } else if (!strncmp (q, "unform", 6)) {
96 default_nroff_flag = 0;
97 q += 5;
100 if (*q == '}')
101 q++;
103 return q - p;
105 return 0;
108 int check_format_cd (const char *p)
110 return (strncmp (p, "cd", 2)) ? 0 : 3;
113 /* Check if p has a "^var\{var-name\}" */
114 /* Returns the number of skipped characters (zero on not found) */
115 /* V will be set to the expanded variable name */
116 int check_format_var (const char *p, char **v)
118 const char *q = p;
119 char *var_name;
120 const char *value;
121 const char *dots = 0;
123 *v = 0;
124 if (!strncmp (p, "var{", 4)){
125 for (q += 4; *q && *q != '}'; q++){
126 if (*q == ':')
127 dots = q+1;
129 if (!*q)
130 return 0;
132 if (!dots || dots == q+5){
133 message (1,
134 _(" Format error on file Extensions File "),
135 !dots ? _(" The %%var macro has no default ")
136 : _(" The %%var macro has no variable "));
137 return 0;
140 /* Copy the variable name */
141 var_name = g_strndup (p + 4, dots-2 - (p+3));
143 value = getenv (var_name);
144 g_free (var_name);
145 if (value){
146 *v = g_strdup (value);
147 return q-p;
149 var_name = g_strndup (dots, q - dots);
150 *v = var_name;
151 return q-p;
153 return 0;
156 /* strip file's extension */
157 static char *
158 strip_ext(char *ss)
160 register char *s = ss;
161 char *e = NULL;
162 while(*s) {
163 if(*s == '.') e = s;
164 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
165 s++;
167 if(e) *e = 0;
168 return ss;
171 char *
172 expand_format (struct WEdit *edit_widget, char c, int quote)
174 WPanel *panel = NULL;
175 char *(*quote_func) (const char *, int);
176 char *fname;
177 char *result;
178 char c_lc;
180 if (c == '%')
181 return g_strdup ("%");
183 if (edit_one_file != NULL)
184 fname = edit_widget->filename;
185 else {
186 if (islower ((unsigned char) c))
187 panel = current_panel;
188 else {
189 if (get_other_type () != view_listing)
190 return g_strdup ("");
191 panel = other_panel;
193 fname = panel->dir.list[panel->selected].fname;
196 if (quote)
197 quote_func = name_quote;
198 else
199 quote_func = fake_name_quote;
201 c_lc = tolower ((unsigned char) c);
203 switch (c_lc) {
204 case 'f':
205 case 'p':
206 return (*quote_func) (fname, 0);
207 case 'x':
208 return (*quote_func) (extension (fname), 0);
209 case 'd':
211 char *cwd;
212 char *qstr;
214 cwd = g_malloc(MC_MAXPATHLEN + 1);
216 if (panel)
217 g_strlcpy(cwd, panel->cwd, MC_MAXPATHLEN + 1);
218 else
219 mc_get_current_wd(cwd, MC_MAXPATHLEN + 1);
221 qstr = (*quote_func) (cwd, 0);
223 g_free (cwd);
225 return qstr;
227 case 'i': /* indent equal number cursor position in line */
228 if (edit_widget)
229 return g_strnfill (edit_widget->curs_col, ' ');
230 break;
231 case 'y': /* syntax type */
232 if (edit_widget && edit_widget->syntax_type)
233 return g_strdup (edit_widget->syntax_type);
234 break;
235 case 'k': /* block file name */
236 case 'b': /* block file name / strip extension */ {
237 if (edit_widget) {
238 char *file = g_strconcat (home_dir, PATH_SEP_STR BLOCK_FILE, (char *) NULL);
239 fname = (*quote_func) (file, 0);
240 g_free (file);
241 return fname;
242 } else if (c_lc == 'b') {
243 return strip_ext ((*quote_func) (fname, 0));
245 break;
247 case 'n': /* strip extension in editor */
248 if (edit_widget)
249 return strip_ext ((*quote_func) (fname, 0));
250 break;
251 case 'm': /* menu file name */
252 if (menu)
253 return (*quote_func) (menu, 0);
254 break;
255 case 's':
256 if (!panel || !panel->marked)
257 return (*quote_func) (fname, 0);
259 /* Fall through */
261 case 't':
262 case 'u':
264 int length = 2, i;
265 char *block, *tmp;
267 if (!panel)
268 return g_strdup ("");
270 for (i = 0; i < panel->count; i++)
271 if (panel->dir.list[i].f.marked)
272 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
274 block = g_malloc (length * 2 + 1);
275 *block = 0;
276 for (i = 0; i < panel->count; i++)
277 if (panel->dir.list[i].f.marked) {
278 strcat (block, tmp =
279 (*quote_func) (panel->dir.list[i].fname, 0));
280 g_free (tmp);
281 strcat (block, " ");
282 if (c_lc == 'u')
283 do_file_mark (panel, i, 0);
285 return block;
286 } /* sub case block */
287 } /* switch */
288 result = g_strdup ("% ");
289 result[1] = c;
290 return result;
294 * Check for the "shell_patterns" directive. If it's found and valid,
295 * interpret it and move the pointer past the directive. Return the
296 * current pointer.
298 static char *
299 check_patterns (char *p)
301 static const char def_name[] = "shell_patterns=";
302 char *p0 = p;
304 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
305 return p0;
307 p += sizeof (def_name) - 1;
308 if (*p == '1')
309 easy_patterns = 1;
310 else if (*p == '0')
311 easy_patterns = 0;
312 else
313 return p0;
315 /* Skip spaces */
316 p++;
317 while (*p == '\n' || *p == '\t' || *p == ' ')
318 p++;
319 return p;
322 /* Copies a whitespace separated argument from p to arg. Returns the
323 point after argument. */
324 static char *extract_arg (char *p, char *arg, int size)
326 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
327 p++;
328 /* support quote space .mnu */
329 while (size > 1 && *p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n') {
330 *arg++ = *p++;
331 size--;
333 *arg = 0;
334 if (!*p || *p == '\n')
335 p --;
336 return p;
339 /* Tests whether the selected file in the panel is of any of the types
340 specified in argument. */
341 static int test_type (WPanel *panel, char *arg)
343 int result = 0; /* False by default */
344 int st_mode = panel->dir.list [panel->selected].st.st_mode;
346 for (;*arg != 0; arg++){
347 switch (*arg){
348 case 'n': /* Not a directory */
349 result |= !S_ISDIR (st_mode);
350 break;
351 case 'r': /* Regular file */
352 result |= S_ISREG (st_mode);
353 break;
354 case 'd': /* Directory */
355 result |= S_ISDIR (st_mode);
356 break;
357 case 'l': /* Link */
358 result |= S_ISLNK (st_mode);
359 break;
360 case 'c': /* Character special */
361 result |= S_ISCHR (st_mode);
362 break;
363 case 'b': /* Block special */
364 result |= S_ISBLK (st_mode);
365 break;
366 case 'f': /* Fifo (named pipe) */
367 result |= S_ISFIFO (st_mode);
368 break;
369 case 's': /* Socket */
370 result |= S_ISSOCK (st_mode);
371 break;
372 case 'x': /* Executable */
373 result |= (st_mode & 0111) ? 1 : 0;
374 break;
375 case 't':
376 result |= panel->marked ? 1 : 0;
377 break;
378 default:
379 debug_error = 1;
380 break;
383 return result;
386 /* Calculates the truth value of the next condition starting from
387 p. Returns the point after condition. */
388 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
390 WPanel *panel;
391 char arg [256];
393 /* Handle one condition */
394 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
395 /* support quote space .mnu */
396 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
397 continue;
398 if (*p >= 'a')
399 panel = current_panel;
400 else {
401 if (get_other_type () == view_listing)
402 panel = other_panel;
403 else
404 panel = NULL;
406 *p |= 0x20;
408 switch (*p++){
409 case '!':
410 p = test_condition (edit_widget, p, condition);
411 *condition = ! *condition;
412 p--;
413 break;
414 case 'f': /* file name pattern */
415 p = extract_arg (p, arg, sizeof (arg));
416 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
417 break;
418 case 'y': /* syntax pattern */
419 if (edit_widget && edit_widget->syntax_type) {
420 p = extract_arg (p, arg, sizeof (arg));
421 *condition = panel &&
422 regexp_match (arg, edit_widget->syntax_type, match_normal);
424 break;
425 case 'd':
426 p = extract_arg (p, arg, sizeof (arg));
427 *condition = panel && regexp_match (arg, panel->cwd, match_file);
428 break;
429 case 't':
430 p = extract_arg (p, arg, sizeof (arg));
431 *condition = panel && test_type (panel, arg);
432 break;
433 case 'x': /* executable */
435 struct stat status;
437 p = extract_arg (p, arg, sizeof (arg));
438 if (stat (arg, &status) == 0)
439 *condition = is_exe (status.st_mode);
440 else
441 *condition = 0;
442 break;
444 default:
445 debug_error = 1;
446 break;
447 } /* switch */
449 } /* while */
450 return p;
453 /* General purpose condition debug output handler */
454 static void
455 debug_out (char *start, char *end, int cond)
457 static char *msg;
458 int len;
460 if (start == NULL && end == NULL){
461 /* Show output */
462 if (debug_flag && msg) {
463 len = strlen (msg);
464 if (len)
465 msg [len - 1] = 0;
466 message (0, _(" Debug "), "%s", msg);
469 debug_flag = 0;
470 g_free (msg);
471 msg = NULL;
472 } else {
473 const char *type;
474 char *p;
476 /* Save debug info for later output */
477 if (!debug_flag)
478 return;
479 /* Save the result of the condition */
480 if (debug_error){
481 type = _(" ERROR: ");
482 debug_error = 0;
484 else if (cond)
485 type = _(" True: ");
486 else
487 type = _(" False: ");
488 /* This is for debugging, don't need to be super efficient. */
489 if (end == NULL)
490 p = g_strdup_printf ("%s%s%c \n", msg ? msg : "", type, *start);
491 else
492 p = g_strdup_printf ("%s%s%.*s \n", msg ? msg : "", type,
493 (int) (end - start), start);
494 g_free (msg);
495 msg = p;
499 /* Calculates the truth value of one lineful of conditions. Returns
500 the point just before the end of line. */
501 static char *test_line (WEdit *edit_widget, char *p, int *result)
503 int condition;
504 char operator;
505 char *debug_start, *debug_end;
507 /* Repeat till end of line */
508 while (*p && *p != '\n') {
509 /* support quote space .mnu */
510 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
511 p++;
512 if (!*p || *p == '\n')
513 break;
514 operator = *p++;
515 if (*p == '?'){
516 debug_flag = 1;
517 p++;
519 /* support quote space .mnu */
520 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
521 p++;
522 if (!*p || *p == '\n')
523 break;
524 condition = 1; /* True by default */
526 debug_start = p;
527 p = test_condition (edit_widget, p, &condition);
528 debug_end = p;
529 /* Add one debug statement */
530 debug_out (debug_start, debug_end, condition);
532 switch (operator){
533 case '+':
534 case '=':
535 /* Assignment */
536 *result = condition;
537 break;
538 case '&': /* Logical and */
539 *result &= condition;
540 break;
541 case '|': /* Logical or */
542 *result |= condition;
543 break;
544 default:
545 debug_error = 1;
546 break;
547 } /* switch */
548 /* Add one debug statement */
549 debug_out (&operator, NULL, *result);
551 } /* while (*p != '\n') */
552 /* Report debug message */
553 debug_out (NULL, NULL, 1);
555 if (!*p || *p == '\n')
556 p --;
557 return p;
560 /* FIXME: recode this routine on version 3.0, it could be cleaner */
561 static void
562 execute_menu_command (WEdit *edit_widget, const char *commands)
564 FILE *cmd_file;
565 int cmd_file_fd;
566 int expand_prefix_found = 0;
567 char *parameter = 0;
568 int do_quote = 0;
569 char prompt [80];
570 int col;
571 char *file_name;
572 int run_view = 0;
574 /* Skip menu entry title line */
575 commands = strchr (commands, '\n');
576 if (!commands){
577 return;
580 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
582 if (cmd_file_fd == -1){
583 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
584 unix_error_string (errno));
585 return;
587 cmd_file = fdopen (cmd_file_fd, "w");
588 fputs ("#! /bin/sh\n", cmd_file);
589 commands++;
591 for (col = 0; *commands; commands++){
592 if (col == 0) {
593 if (*commands != ' ' && *commands != '\t')
594 break;
595 while (*commands == ' ' || *commands == '\t')
596 commands++;
597 if (*commands == 0)
598 break;
600 col++;
601 if (*commands == '\n')
602 col = 0;
603 if (parameter){
604 if (*commands == '}'){
605 char *tmp;
606 *parameter = 0;
607 parameter = input_dialog (_(" Parameter "), prompt, "");
608 if (!parameter || !*parameter){
609 /* User canceled */
610 fclose (cmd_file);
611 unlink (file_name);
612 g_free (file_name);
613 return;
615 if (do_quote) {
616 fputs (tmp = name_quote (parameter, 0), cmd_file);
617 g_free (tmp);
618 } else
619 fputs (parameter, cmd_file);
620 g_free (parameter);
621 parameter = 0;
622 } else {
623 if (parameter < &prompt [sizeof (prompt) - 1]) {
624 *parameter++ = *commands;
627 } else if (expand_prefix_found){
628 expand_prefix_found = 0;
629 if (isdigit ((unsigned char) *commands)) {
630 do_quote = atoi (commands);
631 while (isdigit ((unsigned char) *commands))
632 commands++;
634 if (*commands == '{')
635 parameter = prompt;
636 else{
637 char *text = expand_format (edit_widget, *commands, do_quote);
638 fputs (text, cmd_file);
639 g_free (text);
641 } else {
642 if (*commands == '%') {
643 int i = check_format_view (commands + 1);
644 if (i) {
645 commands += i;
646 run_view = 1;
647 } else {
648 do_quote = 1; /* Default: Quote expanded macro */
649 expand_prefix_found = 1;
651 } else
652 fputc (*commands, cmd_file);
655 fclose (cmd_file);
656 chmod (file_name, S_IRWXU);
657 if (run_view) {
658 run_view = 0;
659 mc_internal_viewer (file_name, NULL, &run_view, 0);
660 } else {
661 /* execute the command indirectly to allow execution even
662 * on no-exec filesystems. */
663 char *cmd = g_strconcat("/bin/sh ", file_name, (char *)NULL);
664 shell_execute (cmd, EXECUTE_HIDE);
665 g_free(cmd);
667 unlink (file_name);
668 g_free (file_name);
672 ** Check owner of the menu file. Using menu file is allowed, if
673 ** owner of the menu is root or the actual user. In either case
674 ** file should not be group and word-writable.
676 ** Q. Should we apply this routine to system and home menu (and .ext files)?
678 static int
679 menu_file_own(char* path)
681 struct stat st;
683 if (stat (path, &st) == 0
684 && (!st.st_uid || (st.st_uid == geteuid ()))
685 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
687 return 1;
689 if (verbose)
691 message (0, _(" Warning -- ignoring file "),
692 _("File %s is not owned by root or you or is world writable.\n"
693 "Using it may compromise your security"),
694 path
697 return 0;
701 * If edit_widget is NULL then we are called from the mc menu,
702 * otherwise we are called from the mcedit menu.
704 void
705 user_menu_cmd (struct WEdit *edit_widget)
707 char *p;
708 char *data, **entries;
709 int max_cols, menu_lines, menu_limit;
710 int col, i, accept_entry = 1;
711 int selected, old_patterns;
712 Listbox *listbox;
714 if (!vfs_current_is_local ()){
715 message (1, MSG_ERROR,
716 _(" Cannot execute commands on non-local filesystems"));
717 return;
720 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
721 if (!exist_file (menu) || !menu_file_own (menu)){
722 g_free (menu);
723 menu = concat_dir_and_file \
724 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
725 if (!exist_file (menu)){
726 g_free (menu);
727 menu = concat_dir_and_file \
728 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
732 if ((data = load_file (menu)) == NULL){
733 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
734 menu, unix_error_string (errno));
735 g_free (menu);
736 menu = NULL;
737 return;
740 max_cols = 0;
741 selected = 0;
742 menu_limit = 0;
743 entries = 0;
745 /* Parse the menu file */
746 old_patterns = easy_patterns;
747 p = check_patterns (data);
748 for (menu_lines = col = 0; *p; p++){
749 if (menu_lines >= menu_limit){
750 char ** new_entries;
752 menu_limit += MAX_ENTRIES;
753 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
755 if (new_entries == 0)
756 break;
758 entries = new_entries;
759 new_entries += menu_limit;
760 while (--new_entries >= &entries[menu_lines])
761 *new_entries = 0;
763 if (col == 0 && !entries [menu_lines]){
764 if (*p == '#'){
765 /* A commented menu entry */
766 accept_entry = 1;
767 } else if (*p == '+'){
768 if (*(p+1) == '='){
769 /* Combined adding and default */
770 p = test_line (edit_widget, p + 1, &accept_entry);
771 if (selected == 0 && accept_entry)
772 selected = menu_lines;
773 } else {
774 /* A condition for adding the entry */
775 p = test_line (edit_widget, p, &accept_entry);
777 } else if (*p == '='){
778 if (*(p+1) == '+'){
779 /* Combined adding and default */
780 p = test_line (edit_widget, p + 1, &accept_entry);
781 if (selected == 0 && accept_entry)
782 selected = menu_lines;
783 } else {
784 /* A condition for making the entry default */
785 i = 1;
786 p = test_line (edit_widget, p, &i);
787 if (selected == 0 && i)
788 selected = menu_lines;
791 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
792 /* A menu entry title line */
793 if (accept_entry)
794 entries [menu_lines] = p;
795 else
796 accept_entry = 1;
799 if (*p == '\n'){
800 if (entries [menu_lines]){
801 menu_lines++;
802 accept_entry = 1;
804 max_cols = max (max_cols, col);
805 col = 0;
806 } else {
807 if (*p == '\t')
808 *p = ' ';
809 col++;
813 if (menu_lines == 0) {
814 message (1, MSG_ERROR, _(" No suitable entries found in %s "), menu);
815 } else {
817 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
819 /* Create listbox */
820 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
821 "[Menu File Edit]");
822 /* insert all the items found */
823 for (i = 0; i < menu_lines; i++) {
824 p = entries [i];
825 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
826 extract_line (p, p + MAX_ENTRY_LEN), p
829 /* Select the default entry */
830 listbox_select_by_number (listbox->list, selected);
832 selected = run_listbox (listbox);
833 if (selected >= 0)
834 execute_menu_command (edit_widget, entries [selected]);
836 do_refresh ();
839 easy_patterns = old_patterns;
840 g_free (menu);
841 menu = NULL;
842 g_free (entries);
843 g_free (data);