* dlg.h (struct Dlg_head): Fold fields "raw" and "has_menubar"
[midnight-commander.git] / src / user.c
blobee43c696c66bba08f7ab0c799597d43036d54c56
1 /* User Menu implementation
2 Copyright (C) 1994 Miguel de Icaza, Janne Kukonlehto
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 #include <config.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
25 #include "global.h"
26 #include "tty.h"
27 #include "dialog.h"
28 #include "color.h"
29 #include "dir.h"
30 #include "panel.h"
31 #include "main.h"
32 #include "subshell.h" /* for subshell_pty */
33 #include "user.h"
34 #include "layout.h"
35 #include "setup.h"
36 #include "../vfs/vfs.h"
38 /* For the simple listbox manager */
39 #include "dlg.h"
40 #include "widget.h"
41 #include "wtools.h"
43 #include "view.h" /* for default_* externs */
45 /* "$Id$" */
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 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_malloc (dots - p);
142 strncpy (var_name, p+4, dots-2 - (p+3));
143 var_name [dots-2 - (p+3)] = 0;
145 value = getenv (var_name);
146 g_free (var_name);
147 if (value){
148 *v = g_strdup (value);
149 return q-p;
151 var_name = g_malloc (q - dots + 1);
152 strncpy (var_name, dots, q - dots + 1);
153 var_name [q-dots] = 0;
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 *expand_format (WEdit *edit_widget, char c, int quote)
177 WPanel *panel;
178 char *(*quote_func)(const char *, int);
179 char *fname;
181 if (c == '%')
182 return g_strdup ("%");
184 if (islower ((unsigned)c))
185 panel = cpanel;
186 else {
187 if (get_other_type () != view_listing)
188 return g_strdup ("");
189 panel = other_panel;
191 if (!panel)
192 panel = cpanel;
194 if (quote)
195 quote_func = name_quote;
196 else
197 quote_func = fake_name_quote;
199 c = tolower (c);
200 fname = panel->dir.list [panel->selected].fname;
202 switch (c){
203 case 'f':
204 case 'p': return (*quote_func) (fname, 0);
205 case 'x': return (*quote_func) (extension(fname), 0);
206 case 'd': return (*quote_func) (panel->cwd, 0);
207 case 'i': /* indent equal number cursor position in line */
208 if (edit_widget)
209 return g_strnfill (edit_widget->curs_col, ' ');
210 break;
211 case 'y': /* syntax type */
212 if (edit_widget && edit_widget->syntax_type)
213 return g_strdup (edit_widget->syntax_type);
214 break;
215 case 'e': /* error file name */
216 case 'k': /* block file name */
217 case 'b': /* block file name / strip extension */ {
218 if (edit_widget) {
219 char *file = g_strconcat (home_dir,
220 (c == 'e') ? ERROR_FILE : BLOCK_FILE,
221 NULL);
222 fname = (*quote_func) (file, 0);
223 g_free (file);
224 return fname;
225 } else if (c == 'b') {
226 return strip_ext((*quote_func) (fname, 0));
228 break;
230 case 'n': /* strip extension in editor */
231 if (edit_widget)
232 return strip_ext((*quote_func) (fname, 0));
233 break;
234 case 'm': /* menu file name */
235 if (menu)
236 return (*quote_func) (menu, 0);
237 break;
238 case 's': if (!panel->marked)
239 return (*quote_func) (fname, 0);
241 /* Fall through */
243 case 't':
244 case 'u':
246 int length = 2, i;
247 char *block, *tmp;
249 for (i = 0; i < panel->count; i++)
250 if (panel->dir.list [i].f.marked)
251 length += strlen (panel->dir.list [i].fname) + 1; /* for space */
253 block = g_malloc (length*2+1);
254 *block = 0;
255 for (i = 0; i < panel->count; i++)
256 if (panel->dir.list [i].f.marked){
257 strcat (block, tmp = (*quote_func) (panel->dir.list [i].fname, 0));
258 g_free (tmp);
259 strcat (block, " ");
260 if (c == 'u')
261 do_file_mark (panel, i, 0);
263 return block;
264 } /* sub case block */
265 } /* switch */
266 return g_strdup ("");
269 /* Checks for shell patterns definition */
270 char *check_patterns (char *p)
272 static const char def_name [] = "shell_patterns=";
273 int value;
275 if (strncmp (p, def_name, sizeof (def_name) - 1) == 0){
276 p += sizeof (def_name) - 1;
277 value = *p++ - '0';
278 if (value == 0 || value == 1)
279 easy_patterns = value;
280 else
281 message (1, MSG_ERROR, _(" Invalid shell pattern definition \"%c\". "), value + '0');
283 while (*p == '\n' || *p == '\t' || *p == ' ') p++;
284 return p;
287 /* Copies a whitespace separated argument from p to arg. Returns the
288 point after argument. */
289 static char *extract_arg (char *p, char *arg)
291 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
292 p++;
293 /* support quote space .mnu */
294 while (*p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n')
295 *arg++ = *p++;
296 *arg = 0;
297 if (!*p || *p == '\n')
298 p --;
299 return p;
302 /* Tests whether the selected file in the panel is of any of the types
303 specified in argument. */
304 static int test_type (WPanel *panel, char *arg)
306 int result = 0; /* False by default */
307 int st_mode = panel->dir.list [panel->selected].buf.st_mode;
309 for (;*arg != 0; arg++){
310 switch (*arg){
311 case 'n': /* Not a directory */
312 result |= !S_ISDIR (st_mode);
313 break;
314 case 'r': /* Regular file */
315 result |= S_ISREG (st_mode);
316 break;
317 case 'd': /* Directory */
318 result |= S_ISDIR (st_mode);
319 break;
320 case 'l': /* Link */
321 result |= S_ISLNK (st_mode);
322 break;
323 case 'c': /* Character special */
324 result |= S_ISCHR (st_mode);
325 break;
326 case 'b': /* Block special */
327 result |= S_ISBLK (st_mode);
328 break;
329 case 'f': /* Fifo (named pipe) */
330 result |= S_ISFIFO (st_mode);
331 break;
332 case 's': /* Socket */
333 result |= S_ISSOCK (st_mode);
334 break;
335 case 'x': /* Executable */
336 result |= (st_mode & 0111) ? 1 : 0;
337 break;
338 case 't':
339 result |= panel->marked ? 1 : 0;
340 break;
341 default:
342 debug_error = 1;
343 break;
346 return result;
349 /* Calculates the truth value of the next condition starting from
350 p. Returns the point after condition. */
351 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
353 WPanel *panel;
354 char arg [256];
356 /* Handle one condition */
357 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
358 /* support quote space .mnu */
359 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
360 continue;
361 if (*p >= 'a')
362 panel = cpanel;
363 else {
364 if (get_other_type () == view_listing)
365 panel = other_panel;
366 else
367 panel = NULL;
369 *p |= 0x20;
371 switch (*p++){
372 case '!':
373 p = test_condition (edit_widget, p, condition);
374 *condition = ! *condition;
375 p--;
376 break;
377 case 'f': /* file name pattern */
378 p = extract_arg (p, arg);
379 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
380 break;
381 case 'y': /* syntax pattern */
382 if (edit_widget && edit_widget->syntax_type) {
383 p = extract_arg (p, arg);
384 *condition = panel &&
385 regexp_match (arg, edit_widget->syntax_type, match_normal);
387 break;
388 case 'd':
389 p = extract_arg (p, arg);
390 *condition = panel && regexp_match (arg, panel->cwd, match_file);
391 break;
392 case 't':
393 p = extract_arg (p, arg);
394 *condition = panel && test_type (panel, arg);
395 break;
396 case 'x': /* executable */
398 struct stat status;
400 p = extract_arg (p, arg);
401 if (stat (arg, &status) == 0)
402 *condition = is_exe (status.st_mode);
403 else
404 *condition = 0;
405 break;
407 default:
408 debug_error = 1;
409 break;
410 } /* switch */
412 } /* while */
413 return p;
416 /* General purpose condition debug output handler */
417 static void
418 debug_out (char *start, char *end, int cond)
420 static char msg [256];
421 int len;
423 if (start == NULL && end == NULL){
424 if (cond == 0){
425 /* Init */
426 msg [0] = 0;
427 } else {
428 /* Show output */
429 if (!debug_flag)
430 return;
431 len = strlen (msg);
432 if (len)
433 msg [len - 1] = 0;
434 message (0, _(" Debug "), msg);
435 debug_flag = 0;
437 } else {
438 /* Save debug info for later output */
439 if (!debug_flag)
440 return;
441 /* Save the result of the condition */
442 if (debug_error){
443 strcat (msg, _(" ERROR: "));
444 debug_error = 0;
446 else if (cond)
447 strcat (msg, _(" True: "));
448 else
449 strcat (msg, _(" False: "));
450 /* Copy condition statement */
451 len = strlen (msg);
452 if (end == NULL){
453 /* Copy one character */
454 msg [len] = *start;
455 msg [len + 1] = 0;
456 } else {
457 /* Copy many characters */
458 while (start < end){
459 msg [len++] = *start++;
461 msg [len] = 0;
463 strcat (msg, " \n");
467 /* Calculates the truth value of one lineful of conditions. Returns
468 the point just before the end of line. */
469 static char *test_line (WEdit *edit_widget, char *p, int *result)
471 int condition;
472 char operator;
473 char *debug_start, *debug_end;
475 /* Init debugger */
476 debug_out (NULL, NULL, 0);
477 /* Repeat till end of line */
478 while (*p && *p != '\n') {
479 /* support quote space .mnu */
480 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
481 p++;
482 if (!*p || *p == '\n')
483 break;
484 operator = *p++;
485 if (*p == '?'){
486 debug_flag = 1;
487 p++;
489 /* support quote space .mnu */
490 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
491 p++;
492 if (!*p || *p == '\n')
493 break;
494 condition = 1; /* True by default */
496 debug_start = p;
497 p = test_condition (edit_widget, p, &condition);
498 debug_end = p;
499 /* Add one debug statement */
500 debug_out (debug_start, debug_end, condition);
502 switch (operator){
503 case '+':
504 case '=':
505 /* Assignment */
506 *result = condition;
507 break;
508 case '&': /* Logical and */
509 *result &= condition;
510 break;
511 case '|': /* Logical or */
512 *result |= condition;
513 break;
514 default:
515 debug_error = 1;
516 break;
517 } /* switch */
518 /* Add one debug statement */
519 debug_out (&operator, NULL, *result);
521 } /* while (*p != '\n') */
522 /* Report debug message */
523 debug_out (NULL, NULL, 1);
525 if (!*p || *p == '\n')
526 p --;
527 return p;
530 /* FIXME: recode this routine on version 3.0, it could be cleaner */
531 static void
532 execute_menu_command (WEdit *edit_widget, char *commands)
534 FILE *cmd_file;
535 int cmd_file_fd;
536 int expand_prefix_found = 0;
537 char *parameter = 0;
538 int do_quote = 0;
539 char prompt [80];
540 int col;
541 char *file_name;
542 #ifdef OS2_NT
543 char *p;
544 #endif
545 /* Skip menu entry title line */
546 commands = strchr (commands, '\n');
547 if (!commands){
548 return;
551 cmd_file_fd = mc_mkstemps(&file_name, "mcusr", SCRIPT_SUFFIX);
553 if (cmd_file_fd == -1){
554 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
555 unix_error_string (errno));
556 return;
558 cmd_file = fdopen (cmd_file_fd, "w");
559 commands++;
561 for (col = 0; *commands; commands++){
562 if (col == 0) {
563 if (*commands != ' ' && *commands != '\t')
564 break;
565 while (*commands == ' ' || *commands == '\t')
566 commands++;
568 col++;
569 if (*commands == '\n')
570 col = 0;
571 if (parameter){
572 if (*commands == '}'){
573 char *tmp;
574 *parameter = 0;
575 parameter = input_dialog (_(" Parameter "), prompt, "");
576 if (!parameter || !*parameter){
577 /* User canceled */
578 fclose (cmd_file);
579 unlink (file_name);
580 g_free (file_name);
581 return;
583 if (do_quote) {
584 fputs (tmp = name_quote (parameter, 0), cmd_file);
585 g_free (tmp);
586 } else
587 fputs (parameter, cmd_file);
588 g_free (parameter);
589 parameter = 0;
590 } else {
591 if (parameter < &prompt [sizeof (prompt) - 1]) {
592 *parameter++ = *commands;
595 } else if (expand_prefix_found){
596 expand_prefix_found = 0;
597 if (isdigit ((unsigned)*commands)) {
598 do_quote = atoi (commands);
599 while (isdigit ((unsigned)*commands))
600 commands++;
602 if (*commands == '{')
603 parameter = prompt;
604 else{
605 char *text = expand_format (edit_widget, *commands, do_quote);
606 fputs (text, cmd_file);
607 g_free (text);
609 } else {
610 if (*commands == '%') {
611 do_quote = 1; /* Default: Quote expanded macro */
612 expand_prefix_found = 1;
613 } else
614 fputc (*commands, cmd_file);
617 fclose (cmd_file);
618 chmod (file_name, S_IRWXU);
619 execute (file_name);
620 unlink (file_name);
621 g_free (file_name);
625 ** Check owner of the menu file. Using menu file is allowed, if
626 ** owner of the menu is root or the actual user. In either case
627 ** file should not be group and word-writable.
629 ** Q. Should we apply this routine to system and home menu (and .ext files)?
631 static int
632 menu_file_own(char* path)
634 struct stat st;
636 if (stat (path, &st) == 0
637 && (!st.st_uid || (st.st_uid == geteuid ()))
638 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
640 return 1;
642 if (verbose)
644 message (0, _(" Warning -- ignoring file "),
645 _("File %s is not owned by root or you or is world writable.\n"
646 "Using it may compromise your security"),
647 path
650 return 0;
654 if edit_widget = pointer then it is file menu from cool edit
655 if edit_widget = NULL then routine is invoke from file menu of mc.
657 void user_menu_cmd (WEdit *edit_widget)
659 char *p;
660 char *data, **entries;
661 int max_cols, menu_lines, menu_limit;
662 int col, i, accept_entry = 1;
663 int selected, old_patterns;
664 Listbox *listbox;
666 if (!vfs_current_is_local ()){
667 message (1, _(" Oops... "),
668 _(" I can't run programs while logged on a non local directory "));
669 return;
672 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
673 if (!exist_file (menu) || !menu_file_own (menu)){
674 g_free (menu);
675 menu = concat_dir_and_file \
676 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
677 if (!exist_file (menu)){
678 g_free (menu);
679 menu = concat_dir_and_file \
680 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
684 if ((data = load_file (menu)) == NULL){
685 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
686 menu, unix_error_string (errno));
687 g_free (menu);
688 menu = NULL;
689 return;
692 max_cols = 0;
693 selected = 0;
694 menu_limit = 0;
695 entries = 0;
697 /* Parse the menu file */
698 old_patterns = easy_patterns;
699 p = check_patterns (data);
700 for (menu_lines = col = 0; *p; p++){
701 if (menu_lines >= menu_limit){
702 char ** new_entries;
704 menu_limit += MAX_ENTRIES;
705 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
707 if (new_entries == 0)
708 break;
710 entries = new_entries;
711 new_entries += menu_limit;
712 while (--new_entries >= &entries[menu_lines])
713 *new_entries = 0;
715 if (col == 0 && !entries [menu_lines]){
716 if (*p == '#'){
717 /* A commented menu entry */
718 accept_entry = 1;
719 } else if (*p == '+'){
720 if (*(p+1) == '='){
721 /* Combined adding and default */
722 p = test_line (edit_widget, p, &accept_entry);
723 if (selected == 0 && accept_entry)
724 selected = menu_lines;
725 } else {
726 /* A condition for adding the entry */
727 p = test_line (edit_widget, p, &accept_entry);
729 } else if (*p == '='){
730 if (*(p+1) == '+'){
731 /* Combined adding and default */
732 p = test_line (edit_widget, p, &accept_entry);
733 if (selected == 0 && accept_entry)
734 selected = menu_lines;
735 } else {
736 /* A condition for making the entry default */
737 i = 1;
738 p = test_line (edit_widget, p, &i);
739 if (selected == 0 && i)
740 selected = menu_lines;
743 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
744 /* A menu entry title line */
745 if (accept_entry)
746 entries [menu_lines] = p;
747 else
748 accept_entry = 1;
751 if (*p == '\n'){
752 if (entries [menu_lines]){
753 menu_lines++;
754 accept_entry = 1;
756 max_cols = max (max_cols, col);
757 col = 0;
758 } else {
759 if (*p == '\t')
760 *p = ' ';
761 col++;
765 if (menu_lines == 0) {
766 message (1, MSG_ERROR, _(" No appropriative entries found in %s "), menu);
767 } else {
769 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
771 /* Create listbox */
772 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
773 "[Menu File Edit]");
774 /* insert all the items found */
775 for (i = 0; i < menu_lines; i++) {
776 p = entries [i];
777 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
778 extract_line (p, p + MAX_ENTRY_LEN), p
781 /* Select the default entry */
782 listbox_select_by_number (listbox->list, selected);
784 selected = run_listbox (listbox);
785 if (selected >= 0)
786 execute_menu_command (edit_widget, entries [selected]);
788 do_refresh ();
791 easy_patterns = old_patterns;
792 g_free (menu);
793 menu = NULL;
794 if (entries)
795 g_free (entries);
796 g_free (data);