Added functions to convert GError messages (which are in UTF-8 charset)
[midnight-commander.git] / src / user.c
blob771d932aa35832cf811dc830c5b0f5bc992267c5
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"
36 #include "history.h"
37 #include "strutil.h"
39 #include "../edit/edit.h" /* BLOCK_FILE */
40 #include "../edit/edit-widget.h" /* WEdit */
42 /* For the simple listbox manager */
43 #include "dialog.h"
44 #include "widget.h"
45 #include "wtools.h"
47 #include "view.h" /* for default_* externs */
49 #define MAX_ENTRIES 16
50 #define MAX_ENTRY_LEN 60
52 static int debug_flag = 0;
53 static int debug_error = 0;
54 static char *menu = NULL;
56 /* Formats defined:
57 %% The % character
58 %f The current file (if non-local vfs, file will be copied locally and
59 %f will be full path to it).
60 %p The current file
61 %d The current working directory
62 %s "Selected files"; the tagged files if any, otherwise the current file
63 %t Tagged files
64 %u Tagged files (and they are untagged on return from expand_format)
65 %view Runs the commands and pipes standard output to the view command.
66 If %view is immediately followed by '{', recognize keywords
67 ascii, hex, nroff and unform
69 If the format letter is in uppercase, it refers to the other panel.
71 With a number followed the % character you can turn quoting on (default)
72 and off. For example:
73 %f quote expanded macro
74 %1f ditto
75 %0f don't quote expanded macro
77 expand_format returns a memory block that must be free()d.
80 /* Returns how many characters we should advance if %view was found */
81 int check_format_view (const char *p)
83 const char *q = p;
84 if (!strncmp (p, "view", 4)) {
85 q += 4;
86 if (*q == '{'){
87 for (q++;*q && *q != '}';q++) {
88 if (!strncmp (q, "ascii", 5)) {
89 default_hex_mode = 0;
90 q += 4;
91 } else if (!strncmp (q, "hex", 3)) {
92 default_hex_mode = 1;
93 q += 2;
94 } else if (!strncmp (q, "nroff", 5)) {
95 default_nroff_flag = 1;
96 q += 4;
97 } else if (!strncmp (q, "unform", 6)) {
98 default_nroff_flag = 0;
99 q += 5;
102 if (*q == '}')
103 q++;
105 return q - p;
107 return 0;
110 int check_format_cd (const char *p)
112 return (strncmp (p, "cd", 2)) ? 0 : 3;
115 /* Check if p has a "^var\{var-name\}" */
116 /* Returns the number of skipped characters (zero on not found) */
117 /* V will be set to the expanded variable name */
118 int check_format_var (const char *p, char **v)
120 const char *q = p;
121 char *var_name;
122 const char *value;
123 const char *dots = 0;
125 *v = 0;
126 if (!strncmp (p, "var{", 4)){
127 for (q += 4; *q && *q != '}'; q++){
128 if (*q == ':')
129 dots = q+1;
131 if (!*q)
132 return 0;
134 if (!dots || dots == q+5){
135 message (D_ERROR,
136 _(" Format error on file Extensions File "),
137 !dots ? _(" The %%var macro has no default ")
138 : _(" The %%var macro has no variable "));
139 return 0;
142 /* Copy the variable name */
143 var_name = g_strndup (p + 4, dots-2 - (p+3));
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_strndup (dots, q - dots);
152 *v = var_name;
153 return q-p;
155 return 0;
158 /* strip file's extension */
159 static char *
160 strip_ext(char *ss)
162 register char *s = ss;
163 char *e = NULL;
164 while(*s) {
165 if(*s == '.') e = s;
166 if(*s == PATH_SEP && e) e=NULL; /* '.' in *directory* name */
167 s++;
169 if(e) *e = 0;
170 return ss;
173 char *
174 expand_format (struct WEdit *edit_widget, char c, int quote)
176 WPanel *panel = NULL;
177 char *(*quote_func) (const char *, int);
178 char *fname;
179 char *result;
180 char c_lc;
182 if (c == '%')
183 return g_strdup ("%");
185 if (edit_one_file != NULL)
186 fname = edit_widget->filename;
187 else {
188 if (g_ascii_islower ((gchar) c))
189 panel = current_panel;
190 else {
191 if (get_other_type () != view_listing)
192 return g_strdup ("");
193 panel = other_panel;
195 fname = panel->dir.list[panel->selected].fname;
198 if (quote)
199 quote_func = name_quote;
200 else
201 quote_func = fake_name_quote;
203 c_lc = g_ascii_tolower ((gchar) c);
205 switch (c_lc) {
206 case 'f':
207 case 'p':
208 return (*quote_func) (fname, 0);
209 case 'x':
210 return (*quote_func) (extension (fname), 0);
211 case 'd':
213 char *cwd;
214 char *qstr;
216 cwd = g_malloc(MC_MAXPATHLEN + 1);
218 if (panel)
219 g_strlcpy(cwd, panel->cwd, MC_MAXPATHLEN + 1);
220 else
221 mc_get_current_wd(cwd, MC_MAXPATHLEN + 1);
223 qstr = (*quote_func) (cwd, 0);
225 g_free (cwd);
227 return qstr;
229 case 'i': /* indent equal number cursor position in line */
230 if (edit_widget)
231 return g_strnfill (edit_widget->curs_col, ' ');
232 break;
233 case 'y': /* syntax type */
234 if (edit_widget && edit_widget->syntax_type)
235 return g_strdup (edit_widget->syntax_type);
236 break;
237 case 'k': /* block file name */
238 case 'b': /* block file name / strip extension */ {
239 if (edit_widget) {
240 char *file = g_strconcat (home_dir, PATH_SEP_STR BLOCK_FILE, (char *) NULL);
241 fname = (*quote_func) (file, 0);
242 g_free (file);
243 return fname;
244 } else if (c_lc == 'b') {
245 return strip_ext ((*quote_func) (fname, 0));
247 break;
249 case 'n': /* strip extension in editor */
250 if (edit_widget)
251 return strip_ext ((*quote_func) (fname, 0));
252 break;
253 case 'm': /* menu file name */
254 if (menu)
255 return (*quote_func) (menu, 0);
256 break;
257 case 's':
258 if (!panel || !panel->marked)
259 return (*quote_func) (fname, 0);
261 /* Fall through */
263 case 't':
264 case 'u':
266 int length = 2, i;
267 char *block, *tmp;
269 if (!panel)
270 return g_strdup ("");
272 for (i = 0; i < panel->count; i++)
273 if (panel->dir.list[i].f.marked)
274 length += strlen (panel->dir.list[i].fname) + 1; /* for space */
276 block = g_malloc (length * 2 + 1);
277 *block = 0;
278 for (i = 0; i < panel->count; i++)
279 if (panel->dir.list[i].f.marked) {
280 strcat (block, tmp =
281 (*quote_func) (panel->dir.list[i].fname, 0));
282 g_free (tmp);
283 strcat (block, " ");
284 if (c_lc == 'u')
285 do_file_mark (panel, i, 0);
287 return block;
288 } /* sub case block */
289 } /* switch */
290 result = g_strdup ("% ");
291 result[1] = c;
292 return result;
296 * Check for the "shell_patterns" directive. If it's found and valid,
297 * interpret it and move the pointer past the directive. Return the
298 * current pointer.
300 static char *
301 check_patterns (char *p)
303 static const char def_name[] = "shell_patterns=";
304 char *p0 = p;
306 if (strncmp (p, def_name, sizeof (def_name) - 1) != 0)
307 return p0;
309 p += sizeof (def_name) - 1;
310 if (*p == '1')
311 easy_patterns = 1;
312 else if (*p == '0')
313 easy_patterns = 0;
314 else
315 return p0;
317 /* Skip spaces */
318 p++;
319 while (*p == '\n' || *p == '\t' || *p == ' ')
320 p++;
321 return p;
324 /* Copies a whitespace separated argument from p to arg. Returns the
325 point after argument. */
326 static char *extract_arg (char *p, char *arg, int size)
328 char *np;
330 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
331 p++;
332 /* support quote space .mnu */
333 while (*p && (*p != ' ' || *(p-1) == '\\') && *p != '\t' && *p != '\n') {
334 np = str_get_next_char (p);
335 if (np - p >= size) break;
336 memcpy (arg, p, np - p);
337 arg+= np - p;
338 size-= np - p;
339 p = np;
341 *arg = 0;
342 if (!*p || *p == '\n')
343 str_prev_char (&p);
344 return p;
347 /* Tests whether the selected file in the panel is of any of the types
348 specified in argument. */
349 static int test_type (WPanel *panel, char *arg)
351 int result = 0; /* False by default */
352 int st_mode = panel->dir.list [panel->selected].st.st_mode;
354 for (;*arg != 0; arg++){
355 switch (*arg){
356 case 'n': /* Not a directory */
357 result |= !S_ISDIR (st_mode);
358 break;
359 case 'r': /* Regular file */
360 result |= S_ISREG (st_mode);
361 break;
362 case 'd': /* Directory */
363 result |= S_ISDIR (st_mode);
364 break;
365 case 'l': /* Link */
366 result |= S_ISLNK (st_mode);
367 break;
368 case 'c': /* Character special */
369 result |= S_ISCHR (st_mode);
370 break;
371 case 'b': /* Block special */
372 result |= S_ISBLK (st_mode);
373 break;
374 case 'f': /* Fifo (named pipe) */
375 result |= S_ISFIFO (st_mode);
376 break;
377 case 's': /* Socket */
378 result |= S_ISSOCK (st_mode);
379 break;
380 case 'x': /* Executable */
381 result |= (st_mode & 0111) ? 1 : 0;
382 break;
383 case 't':
384 result |= panel->marked ? 1 : 0;
385 break;
386 default:
387 debug_error = 1;
388 break;
391 return result;
394 /* Calculates the truth value of the next condition starting from
395 p. Returns the point after condition. */
396 static char *test_condition (WEdit *edit_widget, char *p, int *condition)
398 WPanel *panel;
399 char arg [256];
401 /* Handle one condition */
402 for (;*p != '\n' && *p != '&' && *p != '|'; p++){
403 /* support quote space .mnu */
404 if ((*p == ' ' && *(p-1) != '\\') || *p == '\t')
405 continue;
406 if (*p >= 'a')
407 panel = current_panel;
408 else {
409 if (get_other_type () == view_listing)
410 panel = other_panel;
411 else
412 panel = NULL;
414 *p |= 0x20;
416 switch (*p++){
417 case '!':
418 p = test_condition (edit_widget, p, condition);
419 *condition = ! *condition;
420 str_prev_char (&p);
421 break;
422 case 'f': /* file name pattern */
423 p = extract_arg (p, arg, sizeof (arg));
424 *condition = panel && regexp_match (arg, panel->dir.list [panel->selected].fname, match_file);
425 break;
426 case 'y': /* syntax pattern */
427 if (edit_widget && edit_widget->syntax_type) {
428 p = extract_arg (p, arg, sizeof (arg));
429 *condition = panel &&
430 regexp_match (arg, edit_widget->syntax_type, match_normal);
432 break;
433 case 'd':
434 p = extract_arg (p, arg, sizeof (arg));
435 *condition = panel && regexp_match (arg, panel->cwd, match_file);
436 break;
437 case 't':
438 p = extract_arg (p, arg, sizeof (arg));
439 *condition = panel && test_type (panel, arg);
440 break;
441 case 'x': /* executable */
443 struct stat status;
445 p = extract_arg (p, arg, sizeof (arg));
446 if (stat (arg, &status) == 0)
447 *condition = is_exe (status.st_mode);
448 else
449 *condition = 0;
450 break;
452 default:
453 debug_error = 1;
454 break;
455 } /* switch */
457 } /* while */
458 return p;
461 /* General purpose condition debug output handler */
462 static void
463 debug_out (char *start, char *end, int cond)
465 static char *msg;
466 int len;
468 if (start == NULL && end == NULL){
469 /* Show output */
470 if (debug_flag && msg) {
471 len = strlen (msg);
472 if (len)
473 msg [len - 1] = 0;
474 message (D_NORMAL, _(" Debug "), "%s", msg);
477 debug_flag = 0;
478 g_free (msg);
479 msg = NULL;
480 } else {
481 const char *type;
482 char *p;
484 /* Save debug info for later output */
485 if (!debug_flag)
486 return;
487 /* Save the result of the condition */
488 if (debug_error){
489 type = _(" ERROR: ");
490 debug_error = 0;
492 else if (cond)
493 type = _(" True: ");
494 else
495 type = _(" False: ");
496 /* This is for debugging, don't need to be super efficient. */
497 if (end == NULL)
498 p = g_strdup_printf ("%s%s%c \n", msg ? msg : "", type, *start);
499 else
500 p = g_strdup_printf ("%s%s%.*s \n", msg ? msg : "", type,
501 (int) (end - start), start);
502 g_free (msg);
503 msg = p;
507 /* Calculates the truth value of one lineful of conditions. Returns
508 the point just before the end of line. */
509 static char *test_line (WEdit *edit_widget, char *p, int *result)
511 int condition;
512 char operator;
513 char *debug_start, *debug_end;
515 /* Repeat till end of line */
516 while (*p && *p != '\n') {
517 /* support quote space .mnu */
518 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
519 p++;
520 if (!*p || *p == '\n')
521 break;
522 operator = *p++;
523 if (*p == '?'){
524 debug_flag = 1;
525 p++;
527 /* support quote space .mnu */
528 while ((*p == ' ' && *(p-1) != '\\' ) || *p == '\t')
529 p++;
530 if (!*p || *p == '\n')
531 break;
532 condition = 1; /* True by default */
534 debug_start = p;
535 p = test_condition (edit_widget, p, &condition);
536 debug_end = p;
537 /* Add one debug statement */
538 debug_out (debug_start, debug_end, condition);
540 switch (operator){
541 case '+':
542 case '=':
543 /* Assignment */
544 *result = condition;
545 break;
546 case '&': /* Logical and */
547 *result &= condition;
548 break;
549 case '|': /* Logical or */
550 *result |= condition;
551 break;
552 default:
553 debug_error = 1;
554 break;
555 } /* switch */
556 /* Add one debug statement */
557 debug_out (&operator, NULL, *result);
559 } /* while (*p != '\n') */
560 /* Report debug message */
561 debug_out (NULL, NULL, 1);
563 if (!*p || *p == '\n')
564 str_prev_char (&p);
565 return p;
568 /* FIXME: recode this routine on version 3.0, it could be cleaner */
569 static void
570 execute_menu_command (WEdit *edit_widget, const char *commands)
572 FILE *cmd_file;
573 int cmd_file_fd;
574 int expand_prefix_found = 0;
575 char *parameter = 0;
576 int do_quote = 0;
577 char prompt [80];
578 int col;
579 char *file_name;
580 int run_view = 0;
582 /* Skip menu entry title line */
583 commands = strchr (commands, '\n');
584 if (!commands){
585 return;
588 cmd_file_fd = mc_mkstemps (&file_name, "mcusr", SCRIPT_SUFFIX);
590 if (cmd_file_fd == -1){
591 message (D_ERROR, MSG_ERROR, _(" Cannot create temporary command file \n %s "),
592 unix_error_string (errno));
593 return;
595 cmd_file = fdopen (cmd_file_fd, "w");
596 fputs ("#! /bin/sh\n", cmd_file);
597 commands++;
599 for (col = 0; *commands; commands++){
600 if (col == 0) {
601 if (*commands != ' ' && *commands != '\t')
602 break;
603 while (*commands == ' ' || *commands == '\t')
604 commands++;
605 if (*commands == 0)
606 break;
608 col++;
609 if (*commands == '\n')
610 col = 0;
611 if (parameter){
612 if (*commands == '}'){
613 char *tmp;
614 *parameter = 0;
615 parameter = input_dialog (_(" Parameter "), prompt, MC_HISTORY_FM_MENU_EXEC_PARAM, "");
616 if (!parameter || !*parameter){
617 /* User canceled */
618 fclose (cmd_file);
619 unlink (file_name);
620 g_free (file_name);
621 return;
623 if (do_quote) {
624 fputs (tmp = name_quote (parameter, 0), cmd_file);
625 g_free (tmp);
626 } else
627 fputs (parameter, cmd_file);
628 g_free (parameter);
629 parameter = 0;
630 } else {
631 if (parameter < &prompt [sizeof (prompt) - 1]) {
632 *parameter++ = *commands;
635 } else if (expand_prefix_found){
636 expand_prefix_found = 0;
637 if (g_ascii_isdigit ((gchar) *commands)) {
638 do_quote = atoi (commands);
639 while (g_ascii_isdigit ((gchar) *commands))
640 commands++;
642 if (*commands == '{')
643 parameter = prompt;
644 else{
645 char *text = expand_format (edit_widget, *commands, do_quote);
646 fputs (text, cmd_file);
647 g_free (text);
649 } else {
650 if (*commands == '%') {
651 int i = check_format_view (commands + 1);
652 if (i) {
653 commands += i;
654 run_view = 1;
655 } else {
656 do_quote = 1; /* Default: Quote expanded macro */
657 expand_prefix_found = 1;
659 } else
660 fputc (*commands, cmd_file);
663 fclose (cmd_file);
664 chmod (file_name, S_IRWXU);
665 if (run_view) {
666 run_view = 0;
667 mc_internal_viewer (file_name, NULL, &run_view, 0);
668 } else {
669 /* execute the command indirectly to allow execution even
670 * on no-exec filesystems. */
671 char *cmd = g_strconcat("/bin/sh ", file_name, (char *)NULL);
672 shell_execute (cmd, EXECUTE_HIDE);
673 g_free(cmd);
675 unlink (file_name);
676 g_free (file_name);
680 ** Check owner of the menu file. Using menu file is allowed, if
681 ** owner of the menu is root or the actual user. In either case
682 ** file should not be group and word-writable.
684 ** Q. Should we apply this routine to system and home menu (and .ext files)?
686 static int
687 menu_file_own(char* path)
689 struct stat st;
691 if (stat (path, &st) == 0
692 && (!st.st_uid || (st.st_uid == geteuid ()))
693 && ((st.st_mode & (S_IWGRP | S_IWOTH)) == 0)
695 return 1;
697 if (verbose)
699 message (D_NORMAL, _(" Warning -- ignoring file "),
700 _("File %s is not owned by root or you or is world writable.\n"
701 "Using it may compromise your security"),
702 path
705 return 0;
709 * If edit_widget is NULL then we are called from the mc menu,
710 * otherwise we are called from the mcedit menu.
712 void
713 user_menu_cmd (struct WEdit *edit_widget)
715 char *p;
716 char *data, **entries;
717 int max_cols, menu_lines, menu_limit;
718 int col, i, accept_entry = 1;
719 int selected, old_patterns;
720 Listbox *listbox;
722 if (!vfs_current_is_local ()){
723 message (D_ERROR, MSG_ERROR,
724 _(" Cannot execute commands on non-local filesystems"));
725 return;
728 menu = g_strdup (edit_widget ? CEDIT_LOCAL_MENU : MC_LOCAL_MENU);
729 if (!exist_file (menu) || !menu_file_own (menu)){
730 g_free (menu);
731 menu = concat_dir_and_file \
732 (home_dir, edit_widget ? CEDIT_HOME_MENU : MC_HOME_MENU);
733 if (!exist_file (menu)){
734 g_free (menu);
735 menu = concat_dir_and_file \
736 (mc_home, edit_widget ? CEDIT_GLOBAL_MENU : MC_GLOBAL_MENU);
740 if ((data = load_file (menu)) == NULL){
741 message (D_ERROR, MSG_ERROR, _(" Cannot open file %s \n %s "),
742 menu, unix_error_string (errno));
743 g_free (menu);
744 menu = NULL;
745 return;
748 max_cols = 0;
749 selected = 0;
750 menu_limit = 0;
751 entries = 0;
753 /* Parse the menu file */
754 old_patterns = easy_patterns;
755 p = check_patterns (data);
756 for (menu_lines = col = 0; *p; str_next_char (&p)){
757 if (menu_lines >= menu_limit){
758 char ** new_entries;
760 menu_limit += MAX_ENTRIES;
761 new_entries = g_realloc (entries, sizeof (new_entries[0]) * menu_limit);
763 if (new_entries == 0)
764 break;
766 entries = new_entries;
767 new_entries += menu_limit;
768 while (--new_entries >= &entries[menu_lines])
769 *new_entries = 0;
771 if (col == 0 && !entries [menu_lines]){
772 if (*p == '#'){
773 /* A commented menu entry */
774 accept_entry = 1;
775 } else if (*p == '+'){
776 if (*(p+1) == '='){
777 /* Combined adding and default */
778 p = test_line (edit_widget, p + 1, &accept_entry);
779 if (selected == 0 && accept_entry)
780 selected = menu_lines;
781 } else {
782 /* A condition for adding the entry */
783 p = test_line (edit_widget, p, &accept_entry);
785 } else if (*p == '='){
786 if (*(p+1) == '+'){
787 /* Combined adding and default */
788 p = test_line (edit_widget, p + 1, &accept_entry);
789 if (selected == 0 && accept_entry)
790 selected = menu_lines;
791 } else {
792 /* A condition for making the entry default */
793 i = 1;
794 p = test_line (edit_widget, p, &i);
795 if (selected == 0 && i)
796 selected = menu_lines;
799 else if (*p != ' ' && *p != '\t' && str_isprint (p)) {
800 /* A menu entry title line */
801 if (accept_entry)
802 entries [menu_lines] = p;
803 else
804 accept_entry = 1;
807 if (*p == '\n'){
808 if (entries [menu_lines]){
809 menu_lines++;
810 accept_entry = 1;
812 max_cols = max (max_cols, col);
813 col = 0;
814 } else {
815 if (*p == '\t')
816 *p = ' ';
817 col++;
821 if (menu_lines == 0) {
822 message (D_ERROR, MSG_ERROR, _(" No suitable entries found in %s "), menu);
823 } else {
825 max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);
827 /* Create listbox */
828 listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
829 "[Menu File Edit]");
830 /* insert all the items found */
831 for (i = 0; i < menu_lines; i++) {
832 p = entries [i];
833 LISTBOX_APPEND_TEXT (listbox, (unsigned char) p[0],
834 extract_line (p, p + MAX_ENTRY_LEN), p
837 /* Select the default entry */
838 listbox_select_by_number (listbox->list, selected);
840 selected = run_listbox (listbox);
841 if (selected >= 0)
842 execute_menu_command (edit_widget, entries [selected]);
844 do_refresh ();
847 easy_patterns = old_patterns;
848 g_free (menu);
849 menu = NULL;
850 g_free (entries);
851 g_free (data);