fix panel_scroll_pages start page
[midnight-commander.git] / src / user.c
blob5e45cde13bfac80e818f10bec54db4be6c588b2e
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>
24 #include "global.h"
25 #include "tty.h"
26 #include "dialog.h"
27 #include "color.h"
28 #include "dir.h"
29 #include "panel.h"
30 #include "main.h"
31 #include "subshell.h" /* for subshell_pty */
32 #include "user.h"
33 #include "layout.h"
34 #include "setup.h"
35 #include "../vfs/vfs.h"
37 /* For the simple listbox manager */
38 #include "dlg.h"
39 #include "widget.h"
40 #include "wtools.h"
42 #include "view.h" /* for default_* externs */
44 /* "$Id$" */
46 #define MAX_ENTRIES 16
47 #define MAX_ENTRY_LEN 60
49 static int debug_flag = 0;
50 static int debug_error = 0;
51 static char *menu = NULL;
53 /* Formats defined:
54 %% The % character
55 %f The current file (if non-local vfs, file will be copied locally and
56 %f will be full path to it).
57 %p The current file
58 %d The current working directory
59 %s "Selected files"; the tagged files if any, otherwise the current file
60 %t Tagged files
61 %u Tagged files (and they are untagged on return from expand_format)
62 %view Runs the commands and pipes standard output to the view command.
63 If %view is immediately followed by '{', recognize keywords
64 ascii, hex, nroff and unform
66 If the format letter is in uppercase, it refers to the other panel.
68 With a number followed the % character you can turn quoting on (default)
69 and off. For example:
70 %f quote expanded macro
71 %1f ditto
72 %0f don't quote expanded macro
74 expand_format returns a memory block that must be free()d.
77 /* Returns how many characters we should advance if %view was found */
78 int check_format_view (const char *p)
80 const char *q = p;
81 if (!strncmp (p, "view", 4)) {
82 q += 4;
83 if (*q == '{'){
84 for (q++;*q && *q != '}';q++) {
85 if (!strncmp (q, "ascii", 5)) {
86 default_hex_mode = 0;
87 q += 4;
88 } else if (!strncmp (q, "hex", 3)) {
89 default_hex_mode = 1;
90 q += 2;
91 } else if (!strncmp (q, "nroff", 5)) {
92 default_nroff_flag = 1;
93 q += 4;
94 } else if (!strncmp (q, "unform", 6)) {
95 default_nroff_flag = 0;
96 q += 5;
99 if (*q == '}')
100 q++;
102 return q - p;
104 return 0;
107 int check_format_cd (const char *p)
109 return (strncmp (p, "cd", 2)) ? 0 : 3;
112 /* Check if p has a "^var\{var-name\}" */
113 /* Returns the number of skipped characters (zero on not found) */
114 /* V will be set to the expanded variable name */
115 int check_format_var (const char *p, char **v)
117 const char *q = p;
118 char *var_name;
119 char *value;
120 const char *dots = 0;
122 *v = 0;
123 if (!strncmp (p, "var{", 4)){
124 for (q += 4; *q && *q != '}'; q++){
125 if (*q == ':')
126 dots = q+1;
128 if (!*q)
129 return 0;
131 if (!dots || dots == q+5){
132 message (1,
133 _(" Format error on file Extensions File "),
134 !dots ? _(" The %%var macro has no default ")
135 : _(" The %%var macro has no variable "));
136 return 0;
139 /* Copy the variable name */
140 var_name = g_malloc (dots - p);
141 strncpy (var_name, p+4, dots-2 - (p+3));
142 var_name [dots-2 - (p+3)] = 0;
144 value = getenv (var_name);
145 g_free (var_name);
146 if (value){
147 *v = g_strdup (value);
148 return q-p;
150 var_name = g_malloc (q - dots + 1);
151 strncpy (var_name, dots, q - dots + 1);
152 var_name [q-dots] = 0;
153 *v = var_name;
154 return q-p;
156 return 0;
159 /* strip file's extension */
160 static char *
161 strip_ext(char *ss)
163 register char *s = ss;
164 char *e = NULL;
165 while(*s) {
166 if(*s == '.') e = s;
167 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
168 s++;
170 if(e) *e = 0;
171 return ss;
174 char *
175 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':
205 return (*quote_func) (fname, 0);
206 case 'x':
207 return (*quote_func) (extension (fname), 0);
208 case 'd':
209 return (*quote_func) (panel->cwd, 0);
210 case 'i': /* indent equal number cursor position in line */
211 if (edit_widget)
212 return g_strnfill (edit_widget->curs_col, ' ');
213 break;
214 case 'y': /* syntax type */
215 if (edit_widget && edit_widget->syntax_type)
216 return g_strdup (edit_widget->syntax_type);
217 break;
218 case 'k': /* block file name */
219 case 'b': /* block file name / strip extension */ {
220 if (edit_widget) {
221 char *file = g_strconcat (home_dir, BLOCK_FILE, 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':
239 if (!panel->marked)
240 return (*quote_func) (fname, 0);
242 /* Fall through */
244 case 't':
245 case 'u':
247 int length = 2, i;
248 char *block, *tmp;
250 for (i = 0; i < panel->count; i++)
251 if (panel->dir.list[i].f.marked)
252 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
254 block = g_malloc (length * 2 + 1);
255 *block = 0;
256 for (i = 0; i < panel->count; i++)
257 if (panel->dir.list[i].f.marked) {
258 strcat (block, tmp =
259 (*quote_func) (panel->dir.list[i].fname, 0));
260 g_free (tmp);
261 strcat (block, " ");
262 if (c == 'u')
263 do_file_mark (panel, i, 0);
265 return block;
266 } /* sub case block */
267 } /* switch */
268 return g_strdup ("");
271 /* Checks for shell patterns definition */
272 char *check_patterns (char *p)
274 static const char def_name [] = "shell_patterns=";
275 int value;
277 if (strncmp (p, def_name, sizeof (def_name) - 1) == 0){
278 p += sizeof (def_name) - 1;
279 value = *p++ - '0';
280 if (value == 0 || value == 1)
281 easy_patterns = value;
282 else
283 message (1, MSG_ERROR, _(" Invalid shell pattern definition \"%c\". "), value + '0');
285 while (*p == '\n' || *p == '\t' || *p == ' ') p++;
286 return p;
289 /* Copies a whitespace separated argument from p to arg. Returns the
290 point after argument. */
291 static char *extract_arg (char *p, char *arg)
293 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
294 p++;
295 /* support quote space .mnu */
296 while (*p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n')
297 *arg++ = *p++;
298 *arg = 0;
299 if (!*p || *p == '\n')
300 p --;
301 return p;
304 /* Tests whether the selected file in the panel is of any of the types
305 specified in argument. */
306 static int test_type (WPanel *panel, char *arg)
308 int result = 0; /* False by default */
309 int st_mode = panel->dir.list [panel->selected].buf.st_mode;
311 for (;*arg != 0; arg++){
312 switch (*arg){
313 case 'n': /* Not a directory */
314 result |= !S_ISDIR (st_mode);
315 break;
316 case 'r': /* Regular file */
317 result |= S_ISREG (st_mode);
318 break;
319 case 'd': /* Directory */
320 result |= S_ISDIR (st_mode);
321 break;
322 case 'l': /* Link */
323 result |= S_ISLNK (st_mode);
324 break;
325 case 'c': /* Character special */
326 result |= S_ISCHR (st_mode);
327 break;
328 case 'b': /* Block special */
329 result |= S_ISBLK (st_mode);
330 break;
331 case 'f': /* Fifo (named pipe) */
332 result |= S_ISFIFO (st_mode);
333 break;
334 case 's': /* Socket */
335 result |= S_ISSOCK (st_mode);
336 break;
337 case 'x': /* Executable */
338 result |= (st_mode & 0111) ? 1 : 0;
339 break;
340 case 't':
341 result |= panel->marked ? 1 : 0;
342 break;
343 default:
344 debug_error = 1;
345 break;
348 return result;
351 /* Calculates the truth value of the next condition starting from
352 p. Returns the point after condition. */
353 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
355 WPanel *panel;
356 char arg [256];
358 /* Handle one condition */
359 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
360 /* support quote space .mnu */
361 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
362 continue;
363 if (*p >= 'a')
364 panel = cpanel;
365 else {
366 if (get_other_type () == view_listing)
367 panel = other_panel;
368 else
369 panel = NULL;
371 *p |= 0x20;
373 switch (*p++){
374 case '!':
375 p = test_condition (edit_widget, p, condition);
376 *condition = ! *condition;
377 p--;
378 break;
379 case 'f': /* file name pattern */
380 p = extract_arg (p, arg);
381 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
382 break;
383 case 'y': /* syntax pattern */
384 if (edit_widget && edit_widget->syntax_type) {
385 p = extract_arg (p, arg);
386 *condition = panel &&
387 regexp_match (arg, edit_widget->syntax_type, match_normal);
389 break;
390 case 'd':
391 p = extract_arg (p, arg);
392 *condition = panel && regexp_match (arg, panel->cwd, match_file);
393 break;
394 case 't':
395 p = extract_arg (p, arg);
396 *condition = panel && test_type (panel, arg);
397 break;
398 case 'x': /* executable */
400 struct stat status;
402 p = extract_arg (p, arg);
403 if (stat (arg, &status) == 0)
404 *condition = is_exe (status.st_mode);
405 else
406 *condition = 0;
407 break;
409 default:
410 debug_error = 1;
411 break;
412 } /* switch */
414 } /* while */
415 return p;
418 /* General purpose condition debug output handler */
419 static void
420 debug_out (char *start, char *end, int cond)
422 static char msg [256];
423 int len;
425 if (start == NULL && end == NULL){
426 if (cond == 0){
427 /* Init */
428 msg [0] = 0;
429 } else {
430 /* Show output */
431 if (!debug_flag)
432 return;
433 len = strlen (msg);
434 if (len)
435 msg [len - 1] = 0;
436 message (0, _(" Debug "), "%s", msg);
437 debug_flag = 0;
439 } else {
440 /* Save debug info for later output */
441 if (!debug_flag)
442 return;
443 /* Save the result of the condition */
444 if (debug_error){
445 strcat (msg, _(" ERROR: "));
446 debug_error = 0;
448 else if (cond)
449 strcat (msg, _(" True: "));
450 else
451 strcat (msg, _(" False: "));
452 /* Copy condition statement */
453 len = strlen (msg);
454 if (end == NULL){
455 /* Copy one character */
456 msg [len] = *start;
457 msg [len + 1] = 0;
458 } else {
459 /* Copy many characters */
460 while (start < end){
461 msg [len++] = *start++;
463 msg [len] = 0;
465 strcat (msg, " \n");
469 /* Calculates the truth value of one lineful of conditions. Returns
470 the point just before the end of line. */
471 static char *test_line (WEdit *edit_widget, char *p, int *result)
473 int condition;
474 char operator;
475 char *debug_start, *debug_end;
477 /* Init debugger */
478 debug_out (NULL, NULL, 0);
479 /* Repeat till end of line */
480 while (*p && *p != '\n') {
481 /* support quote space .mnu */
482 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
483 p++;
484 if (!*p || *p == '\n')
485 break;
486 operator = *p++;
487 if (*p == '?'){
488 debug_flag = 1;
489 p++;
491 /* support quote space .mnu */
492 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
493 p++;
494 if (!*p || *p == '\n')
495 break;
496 condition = 1; /* True by default */
498 debug_start = p;
499 p = test_condition (edit_widget, p, &condition);
500 debug_end = p;
501 /* Add one debug statement */
502 debug_out (debug_start, debug_end, condition);
504 switch (operator){
505 case '+':
506 case '=':
507 /* Assignment */
508 *result = condition;
509 break;
510 case '&': /* Logical and */
511 *result &= condition;
512 break;
513 case '|': /* Logical or */
514 *result |= condition;
515 break;
516 default:
517 debug_error = 1;
518 break;
519 } /* switch */
520 /* Add one debug statement */
521 debug_out (&operator, NULL, *result);
523 } /* while (*p != '\n') */
524 /* Report debug message */
525 debug_out (NULL, NULL, 1);
527 if (!*p || *p == '\n')
528 p --;
529 return p;
532 /* FIXME: recode this routine on version 3.0, it could be cleaner */
533 static void
534 execute_menu_command (WEdit *edit_widget, char *commands)
536 FILE *cmd_file;
537 int cmd_file_fd;
538 int expand_prefix_found = 0;
539 char *parameter = 0;
540 int do_quote = 0;
541 char prompt [80];
542 int col;
543 char *file_name;
544 #ifdef NATIVE_WIN32
545 char *p;
546 #endif
547 /* Skip menu entry title line */
548 commands = strchr (commands, '\n');
549 if (!commands){
550 return;
553 cmd_file_fd = mc_mkstemps(&file_name, "mcusr", SCRIPT_SUFFIX);
555 if (cmd_file_fd == -1){
556 message (1, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
557 unix_error_string (errno));
558 return;
560 cmd_file = fdopen (cmd_file_fd, "w");
561 commands++;
563 for (col = 0; *commands; commands++){
564 if (col == 0) {
565 if (*commands != ' ' && *commands != '\t')
566 break;
567 while (*commands == ' ' || *commands == '\t')
568 commands++;
570 col++;
571 if (*commands == '\n')
572 col = 0;
573 if (parameter){
574 if (*commands == '}'){
575 char *tmp;
576 *parameter = 0;
577 parameter = input_dialog (_(" Parameter "), prompt, "");
578 if (!parameter || !*parameter){
579 /* User canceled */
580 fclose (cmd_file);
581 unlink (file_name);
582 g_free (file_name);
583 return;
585 if (do_quote) {
586 fputs (tmp = name_quote (parameter, 0), cmd_file);
587 g_free (tmp);
588 } else
589 fputs (parameter, cmd_file);
590 g_free (parameter);
591 parameter = 0;
592 } else {
593 if (parameter < &prompt [sizeof (prompt) - 1]) {
594 *parameter++ = *commands;
597 } else if (expand_prefix_found){
598 expand_prefix_found = 0;
599 if (isdigit ((unsigned)*commands)) {
600 do_quote = atoi (commands);
601 while (isdigit ((unsigned)*commands))
602 commands++;
604 if (*commands == '{')
605 parameter = prompt;
606 else{
607 char *text = expand_format (edit_widget, *commands, do_quote);
608 fputs (text, cmd_file);
609 g_free (text);
611 } else {
612 if (*commands == '%') {
613 do_quote = 1; /* Default: Quote expanded macro */
614 expand_prefix_found = 1;
615 } else
616 fputc (*commands, cmd_file);
619 fclose (cmd_file);
620 chmod (file_name, S_IRWXU);
621 execute (file_name);
622 unlink (file_name);
623 g_free (file_name);
627 ** Check owner of the menu file. Using menu file is allowed, if
628 ** owner of the menu is root or the actual user. In either case
629 ** file should not be group and word-writable.
631 ** Q. Should we apply this routine to system and home menu (and .ext files)?
633 static int
634 menu_file_own(char* path)
636 struct stat st;
638 if (stat (path, &st) == 0
639 && (!st.st_uid || (st.st_uid == geteuid ()))
640 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
642 return 1;
644 if (verbose)
646 message (0, _(" Warning -- ignoring file "),
647 _("File %s is not owned by root or you or is world writable.\n"
648 "Using it may compromise your security"),
649 path
652 return 0;
656 if edit_widget = pointer then it is file menu from cool edit
657 if edit_widget = NULL then routine is invoke from file menu of mc.
659 void user_menu_cmd (WEdit *edit_widget)
661 char *p;
662 char *data, **entries;
663 int max_cols, menu_lines, menu_limit;
664 int col, i, accept_entry = 1;
665 int selected, old_patterns;
666 Listbox *listbox;
668 if (!vfs_current_is_local ()){
669 message (1, _(" Oops... "),
670 _(" I can't run programs while logged on a non local directory "));
671 return;
674 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
675 if (!exist_file (menu) || !menu_file_own (menu)){
676 g_free (menu);
677 menu = concat_dir_and_file \
678 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
679 if (!exist_file (menu)){
680 g_free (menu);
681 menu = concat_dir_and_file \
682 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
686 if ((data = load_file (menu)) == NULL){
687 message (1, MSG_ERROR, _(" Cannot open file %s \n %s "),
688 menu, unix_error_string (errno));
689 g_free (menu);
690 menu = NULL;
691 return;
694 max_cols = 0;
695 selected = 0;
696 menu_limit = 0;
697 entries = 0;
699 /* Parse the menu file */
700 old_patterns = easy_patterns;
701 p = check_patterns (data);
702 for (menu_lines = col = 0; *p; p++){
703 if (menu_lines >= menu_limit){
704 char ** new_entries;
706 menu_limit += MAX_ENTRIES;
707 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
709 if (new_entries == 0)
710 break;
712 entries = new_entries;
713 new_entries += menu_limit;
714 while (--new_entries >= &entries[menu_lines])
715 *new_entries = 0;
717 if (col == 0 && !entries [menu_lines]){
718 if (*p == '#'){
719 /* A commented menu entry */
720 accept_entry = 1;
721 } else if (*p == '+'){
722 if (*(p+1) == '='){
723 /* Combined adding and default */
724 p = test_line (edit_widget, p, &accept_entry);
725 if (selected == 0 && accept_entry)
726 selected = menu_lines;
727 } else {
728 /* A condition for adding the entry */
729 p = test_line (edit_widget, p, &accept_entry);
731 } else if (*p == '='){
732 if (*(p+1) == '+'){
733 /* Combined adding and default */
734 p = test_line (edit_widget, p, &accept_entry);
735 if (selected == 0 && accept_entry)
736 selected = menu_lines;
737 } else {
738 /* A condition for making the entry default */
739 i = 1;
740 p = test_line (edit_widget, p, &i);
741 if (selected == 0 && i)
742 selected = menu_lines;
745 else if (*p != ' ' && *p != '\t' && is_printable (*p)) {
746 /* A menu entry title line */
747 if (accept_entry)
748 entries [menu_lines] = p;
749 else
750 accept_entry = 1;
753 if (*p == '\n'){
754 if (entries [menu_lines]){
755 menu_lines++;
756 accept_entry = 1;
758 max_cols = max (max_cols, col);
759 col = 0;
760 } else {
761 if (*p == '\t')
762 *p = ' ';
763 col++;
767 if (menu_lines == 0) {
768 message (1, MSG_ERROR, _(" No appropriative entries found in %s "), menu);
769 } else {
771 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
773 /* Create listbox */
774 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
775 "[Menu File Edit]");
776 /* insert all the items found */
777 for (i = 0; i < menu_lines; i++) {
778 p = entries [i];
779 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
780 extract_line (p, p + MAX_ENTRY_LEN), p
783 /* Select the default entry */
784 listbox_select_by_number (listbox->list, selected);
786 selected = run_listbox (listbox);
787 if (selected >= 0)
788 execute_menu_command (edit_widget, entries [selected]);
790 do_refresh ();
793 easy_patterns = old_patterns;
794 g_free (menu);
795 menu = NULL;
796 if (entries)
797 g_free (entries);
798 g_free (data);