r1996: Cope slightly better with invalid filenames in various places (reported by
[rox-filer.git] / ROX-Filer / src / type.c
blob88c1a86de2c32c343571371c2c9333d7155c495b
1 /*
2 * $Id$
4 * ROX-Filer, filer for the ROX desktop project
5 * Copyright (C) 2002, the ROX-Filer team.
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the Free
9 * Software Foundation; either version 2 of the License, or (at your option)
10 * any later version.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
17 * You should have received a copy of the GNU General Public License along with
18 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19 * Place, Suite 330, Boston, MA 02111-1307 USA
22 /* type.c - code for dealing with filetypes */
24 #include "config.h"
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <ctype.h>
30 #include <time.h>
31 #include <sys/param.h>
32 #include <fnmatch.h>
33 #include <sys/types.h>
34 #include <fcntl.h>
36 #ifdef WITH_GNOMEVFS
37 # include <libgnomevfs/gnome-vfs.h>
38 # include <libgnomevfs/gnome-vfs-mime.h>
39 # include <libgnomevfs/gnome-vfs-mime-handlers.h>
40 # include <libgnomevfs/gnome-vfs-application-registry.h>
41 #endif
43 #include "global.h"
45 #include "string.h"
46 #include "fscache.h"
47 #include "main.h"
48 #include "pixmaps.h"
49 #include "run.h"
50 #include "gui_support.h"
51 #include "choices.h"
52 #include "type.h"
53 #include "support.h"
54 #include "diritem.h"
55 #include "dnd.h"
56 #include "options.h"
57 #include "filer.h"
58 #include "action.h" /* (for action_chmod) */
60 /* Colours for file types (same order as base types) */
61 static gchar *opt_type_colours[][2] = {
62 {"display_err_colour", "#ff0000"},
63 {"display_unkn_colour", "#000000"},
64 {"display_dir_colour", "#000080"},
65 {"display_pipe_colour", "#444444"},
66 {"display_sock_colour", "#ff00ff"},
67 {"display_file_colour", "#000000"},
68 {"display_cdev_colour", "#000000"},
69 {"display_bdev_colour", "#000000"},
70 {"display_door_colour", "#ff00ff"},
71 {"display_exec_colour", "#006000"},
72 {"display_adir_colour", "#006000"}
74 #define NUM_TYPE_COLOURS\
75 (sizeof(opt_type_colours) / sizeof(opt_type_colours[0]))
77 /* Parsed colours for file types */
78 static Option o_type_colours[NUM_TYPE_COLOURS];
79 static GdkColor type_colours[NUM_TYPE_COLOURS];
81 /* Static prototypes */
82 static void load_mime_types(void);
83 static void alloc_type_colours(void);
84 char *get_action_save_path(GtkWidget *dialog);
85 static void edit_mime_types(guchar *unused);
86 static MIME_type *get_mime_type(const gchar *type_name, gboolean can_create);
87 static GList *build_type_edit(Option *none, xmlNode *node, guchar *label);
89 /* When working out the type for a file, this hash table is checked
90 * first...
92 static GHashTable *literal_hash = NULL; /* name -> MIME-type */
94 /* Maps extensions to MIME_types (eg 'png'-> MIME_type *).
95 * Extensions may contain dots; 'tar.gz' matches '*.tar.gz', etc.
96 * The hash table is consulted from each dot in the string in turn
97 * (First .ps.gz, then try .gz)
99 static GHashTable *extension_hash = NULL;
101 /* The first pattern in the list which matches is used */
102 typedef struct pattern {
103 gint len; /* Used for sorting */
104 gchar *glob;
105 MIME_type *type;
106 } Pattern;
107 static GPtrArray *glob_patterns = NULL; /* [Pattern] */
109 /* Hash of all allocated MIME types, indexed by "media/subtype".
110 * MIME_type structs are never freed; this table prevents memory leaks
111 * when rereading the config files.
113 static GHashTable *type_hash = NULL;
115 /* Most things on Unix are text files, so this is the default type */
116 MIME_type *text_plain;
117 MIME_type *inode_directory;
118 MIME_type *inode_pipe;
119 MIME_type *inode_socket;
120 MIME_type *inode_block_dev;
121 MIME_type *inode_char_dev;
122 MIME_type *application_executable;
123 MIME_type *inode_unknown;
124 MIME_type *inode_door;
126 static Option o_display_colour_types;
128 void type_init(void)
130 int i;
132 extension_hash = g_hash_table_new(g_str_hash, g_str_equal);
133 type_hash = g_hash_table_new(g_str_hash, g_str_equal);
135 text_plain = get_mime_type("text/plain", TRUE);
136 inode_directory = get_mime_type("inode/directory", TRUE);
137 inode_pipe = get_mime_type("inode/fifo", TRUE);
138 inode_socket = get_mime_type("inode/socket", TRUE);
139 inode_block_dev = get_mime_type("inode/blockdevice", TRUE);
140 inode_char_dev = get_mime_type("inode/chardevice", TRUE);
141 application_executable = get_mime_type("application/x-executable", TRUE);
142 inode_unknown = get_mime_type("inode/unknown", TRUE);
143 inode_door = get_mime_type("inode/door", TRUE);
145 load_mime_types();
147 option_register_widget("type-edit", build_type_edit);
149 option_add_int(&o_display_colour_types, "display_colour_types", TRUE);
151 for (i = 0; i < NUM_TYPE_COLOURS; i++)
152 option_add_string(&o_type_colours[i],
153 opt_type_colours[i][0],
154 opt_type_colours[i][1]);
155 alloc_type_colours();
157 option_add_notify(alloc_type_colours);
160 /* Read-load all the glob patterns */
161 void reread_mime_files(void)
163 load_mime_types();
166 /* Returns the MIME_type structure for the given type name. It is looked
167 * up in type_hash and returned if found. If not found (and can_create is
168 * TRUE) then a new MIME_type is made, added to type_hash and returned.
169 * NULL is returned if type_name is not in type_hash and can_create is
170 * FALSE, or if type_name does not contain a '/' character.
172 static MIME_type *get_mime_type(const gchar *type_name, gboolean can_create)
174 MIME_type *mtype;
175 gchar *slash;
177 mtype = g_hash_table_lookup(type_hash, type_name);
178 if (mtype || !can_create)
179 return mtype;
181 slash = strchr(type_name, '/');
182 g_return_val_if_fail(slash != NULL, NULL); /* XXX: Report nicely */
184 mtype = g_new(MIME_type, 1);
185 mtype->media_type = g_strndup(type_name, slash - type_name);
186 mtype->subtype = g_strdup(slash + 1);
187 mtype->image = NULL;
189 g_hash_table_insert(type_hash, g_strdup(type_name), mtype);
191 return mtype;
194 const char *basetype_name(DirItem *item)
196 if (item->flags & ITEM_FLAG_SYMLINK)
197 return _("Sym link");
198 else if (item->flags & ITEM_FLAG_MOUNT_POINT)
199 return _("Mount point");
200 else if (item->flags & ITEM_FLAG_APPDIR)
201 return _("App dir");
203 switch (item->base_type)
205 case TYPE_FILE:
206 return _("File");
207 case TYPE_DIRECTORY:
208 return _("Dir");
209 case TYPE_CHAR_DEVICE:
210 return _("Char dev");
211 case TYPE_BLOCK_DEVICE:
212 return _("Block dev");
213 case TYPE_PIPE:
214 return _("Pipe");
215 case TYPE_SOCKET:
216 return _("Socket");
217 case TYPE_DOOR:
218 return _("Door");
221 return _("Unknown");
224 /* MIME-type guessing */
226 /* Get the type of this file - stats the file and uses that if
227 * possible. For regular or missing files, uses the pathname.
229 MIME_type *type_get_type(const guchar *path)
231 struct stat info;
232 MIME_type *type = NULL;
233 int base = TYPE_FILE;
234 gboolean exec = FALSE;
236 if (mc_stat(path, &info) == 0)
238 base = mode_to_base_type(info.st_mode);
239 if (info.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
240 exec = TRUE;
243 if (base == TYPE_FILE)
244 type = type_from_path(path);
246 if (!type)
248 if (base == TYPE_FILE && exec)
249 type = application_executable;
250 else
251 type = mime_type_from_base_type(base);
254 return type;
257 /* Returns a pointer to the MIME-type.
258 * NULL if we can't think of anything.
260 MIME_type *type_from_path(const char *path)
262 const char *ext, *dot, *leafname;
263 char *lower;
264 MIME_type *type = NULL;
265 int i;
267 #if 0
268 # ifdef WITH_GNOMEVFS
269 if (o_use_gnomevfs.int_value)
270 return get_mime_type(gnome_vfs_mime_type_from_name(path), TRUE);
271 # endif
272 #endif
274 leafname = g_basename(path);
276 type = g_hash_table_lookup(literal_hash, leafname);
277 if (type)
278 return type;
279 lower = g_utf8_strdown(leafname, -1);
280 type = g_hash_table_lookup(literal_hash, lower);
281 if (type)
282 goto out;
284 ext = leafname;
286 while ((dot = strchr(ext, '.')))
288 ext = dot + 1;
290 type = g_hash_table_lookup(extension_hash, ext);
292 if (type)
293 goto out;
295 type = g_hash_table_lookup(extension_hash,
296 lower + (ext - leafname));
297 if (type)
298 goto out;
301 for (i = 0; i < glob_patterns->len; i++)
303 Pattern *p = glob_patterns->pdata[i];
305 if (fnmatch(p->glob, leafname, 0) == 0 ||
306 fnmatch(p->glob, lower, 0) == 0)
308 type = p->type;
309 goto out;
313 out:
314 g_free(lower);
316 return type;
319 /* Returns the file/dir in Choices for handling this type.
320 * NULL if there isn't one. g_free() the result.
322 static char *handler_for(MIME_type *type)
324 char *type_name;
325 char *open;
327 type_name = g_strconcat(type->media_type, "_", type->subtype, NULL);
328 open = choices_find_path_load(type_name, "MIME-types");
329 g_free(type_name);
331 if (!open)
332 open = choices_find_path_load(type->media_type, "MIME-types");
334 return open;
337 /* Actions for types */
339 gboolean type_open(const char *path, MIME_type *type)
341 gchar *argv[] = {NULL, NULL, NULL};
342 char *open;
343 gboolean retval;
344 struct stat info;
346 argv[1] = (char *) path;
348 open = handler_for(type);
349 if (!open)
350 return FALSE;
352 if (stat(open, &info))
354 report_error("stat(%s): %s", open, g_strerror(errno));
355 g_free(open);
356 return FALSE;
359 if (info.st_mode & S_IWOTH)
361 gchar *choices_dir;
362 GList *paths;
364 report_error(_("Executable '%s' is world-writeable! Refusing "
365 "to run. Please change the permissions now (this "
366 "problem may have been caused by a bug in earlier "
367 "versions of the filer).\n\n"
368 "Having (non-symlink) run actions world-writeable "
369 "means that other people who use your computer can "
370 "replace your run actions with malicious versions.\n\n"
371 "If you trust everyone who could write to these files "
372 "then you needn't worry. Otherwise, you should check, "
373 "or even just delete, all the existing run actions."),
374 open);
375 choices_dir = g_dirname(open);
376 paths = g_list_append(NULL, choices_dir);
377 action_chmod(paths, TRUE, _("go-w (Fix security problem)"));
378 g_free(choices_dir);
379 g_list_free(paths);
380 g_free(open);
381 return TRUE;
384 if (S_ISDIR(info.st_mode))
385 argv[0] = g_strconcat(open, "/AppRun", NULL);
386 else
387 argv[0] = open;
389 retval = rox_spawn(home_dir, (const gchar **) argv);
391 if (argv[0] != open)
392 g_free(argv[0]);
394 g_free(open);
396 return retval;
399 /* Return the image for this type, loading it if needed.
400 * Places to check are: (eg type="text_plain", base="text")
401 * 1. Choices:MIME-icons/<type>
402 * 2. Choices:MIME-icons/<base>
403 * 3. Unknown type icon.
405 * Note: You must g_object_unref() the image afterwards.
407 MaskedPixmap *type_to_icon(MIME_type *type)
409 char *path;
410 char *type_name;
411 time_t now;
413 if (type == NULL)
415 g_object_ref(im_unknown);
416 return im_unknown;
419 now = time(NULL);
420 /* Already got an image? */
421 if (type->image)
423 /* Yes - don't recheck too often */
424 if (abs(now - type->image_time) < 2)
426 g_object_ref(type->image);
427 return type->image;
429 g_object_unref(type->image);
430 type->image = NULL;
433 type_name = g_strconcat(type->media_type, "_",
434 type->subtype, ".png", NULL);
435 path = choices_find_path_load(type_name, "MIME-icons");
436 if (!path)
438 strcpy(type_name + strlen(type->media_type), ".png");
439 path = choices_find_path_load(type_name, "MIME-icons");
442 g_free(type_name);
444 if (path)
446 type->image = g_fscache_lookup(pixmap_cache, path);
447 g_free(path);
450 if (!type->image)
452 /* One ref from the type structure, one returned */
453 type->image = im_unknown;
454 g_object_ref(im_unknown);
457 type->image_time = now;
459 g_object_ref(type->image);
460 return type->image;
463 GdkAtom type_to_atom(MIME_type *type)
465 char *str;
466 GdkAtom retval;
468 g_return_val_if_fail(type != NULL, GDK_NONE);
470 str = g_strconcat(type->media_type, "/", type->subtype, NULL);
471 retval = gdk_atom_intern(str, FALSE);
472 g_free(str);
474 return retval;
477 static void show_shell_help(gpointer data)
479 info_message(_("Enter a shell command which will load \"$@\" into "
480 "a suitable program. Eg:\n\n"
481 "gimp \"$@\""));
484 /* Called if the user clicks on the OK button. Returns FALSE if an error
485 * was displayed instead of performing the action.
487 static gboolean set_shell_action(GtkWidget *dialog)
489 GtkEntry *entry;
490 GtkToggleButton *for_all;
491 const guchar *command;
492 gchar *tmp, *path;
493 int error = 0, len;
494 int fd;
496 entry = g_object_get_data(G_OBJECT(dialog), "shell_command");
497 for_all = g_object_get_data(G_OBJECT(dialog), "set_for_all");
498 g_return_val_if_fail(entry != NULL, FALSE);
500 command = gtk_entry_get_text(entry);
502 if (!strchr(command, '$'))
504 show_shell_help(NULL);
505 return FALSE;
508 path = get_action_save_path(dialog);
509 if (!path)
510 return FALSE;
512 tmp = g_strdup_printf("#! /bin/sh\nexec %s\n", command);
513 len = strlen(tmp);
515 fd = open(path, O_CREAT | O_WRONLY, 0755);
516 if (fd == -1)
517 error = errno;
518 else
520 FILE *file;
522 file = fdopen(fd, "w");
523 if (file)
525 if (fwrite(tmp, 1, len, file) < len)
526 error = errno;
527 if (fclose(file) && error == 0)
528 error = errno;
530 else
531 error = errno;
534 if (error)
535 report_error(g_strerror(error));
537 g_free(tmp);
538 g_free(path);
540 gtk_widget_destroy(dialog);
542 return TRUE;
545 static void set_action_response(GtkWidget *dialog, gint response, gpointer data)
547 if (response == GTK_RESPONSE_OK)
548 if (!set_shell_action(dialog))
549 return;
550 gtk_widget_destroy(dialog);
553 /* Called when a URI list is dropped onto the box in the Set Run Action
554 * dialog. Make sure it's an application, and make that the default
555 * handler.
557 static void drag_app_dropped(GtkWidget *eb,
558 GdkDragContext *context,
559 gint x,
560 gint y,
561 GtkSelectionData *selection_data,
562 guint info,
563 guint32 time,
564 GtkWidget *dialog)
566 GList *uris;
567 const gchar *app = NULL;
568 DirItem *item;
570 if (!selection_data->data)
571 return; /* Timeout? */
573 uris = uri_list_to_glist(selection_data->data);
575 if (g_list_length(uris) == 1)
576 app = get_local_path((guchar *) uris->data);
577 g_list_free(uris);
579 if (!app)
581 delayed_error(
582 _("You should drop a single (local) application "
583 "onto the drop box - that application will be "
584 "used to load files of this type in future"));
585 return;
588 item = diritem_new("");
589 diritem_restat(app, item, NULL);
590 if (item->flags & (ITEM_FLAG_APPDIR | ITEM_FLAG_EXEC_FILE))
592 guchar *path;
594 path = get_action_save_path(dialog);
596 if (path)
598 if (symlink(app, path))
599 delayed_error("symlink: %s",
600 g_strerror(errno));
601 else
602 destroy_on_idle(dialog);
604 g_free(path);
607 else
608 delayed_error(
609 _("This is not a program! Give me an application "
610 "instead!"));
612 diritem_free(item);
615 /* Find the current command which is used to run files of this type.
616 * Returns NULL on failure. g_free() the result.
618 static guchar *get_current_command(MIME_type *type)
620 struct stat info;
621 char *handler, *nl, *data = NULL;
622 long len;
623 guchar *command = NULL;
625 handler = handler_for(type);
627 if (!handler)
628 return NULL; /* No current handler */
630 if (stat(handler, &info))
631 goto out; /* Can't stat */
633 if ((!S_ISREG(info.st_mode)) || info.st_size > 256)
634 goto out; /* Only use small regular files */
636 if (!load_file(handler, &data, &len))
637 goto out; /* Didn't load OK */
639 if (strncmp(data, "#! /bin/sh\nexec ", 16) != 0)
640 goto out; /* Not one of ours */
642 nl = strchr(data + 16, '\n');
643 if (!nl)
644 goto out; /* No newline! */
646 command = g_strndup(data + 16, nl - data - 16);
647 out:
648 g_free(handler);
649 g_free(data);
650 return command;
653 /* Find the current command which is used to run files of this type,
654 * and return a textual description of it.
655 * g_free() the result.
657 gchar *describe_current_command(MIME_type *type)
659 char *handler;
660 char *desc = NULL;
661 struct stat info;
662 char *target;
664 g_return_val_if_fail(type != NULL, NULL);
666 if (type == application_executable)
667 return g_strdup(_("Execute file"));
669 handler = handler_for(type);
671 if (!handler)
672 return g_strdup(_("No run action defined"));
674 target = readlink_dup(handler);
675 if (target)
677 /* Cope with relative paths (shouldn't normally be needed) */
679 if (target[0] == '/')
681 g_free(handler);
682 handler = target;
684 else
686 gchar *dir;
688 dir = g_dirname(handler);
689 g_free(handler);
690 handler = g_strconcat(dir, "/", target, NULL);
691 g_free(target);
692 g_free(dir);
696 if (mc_stat(handler, &info) !=0 )
698 desc = g_strdup_printf(_("Error in handler %s: %s"), handler,
699 g_strerror(errno));
700 goto out;
703 if (S_ISDIR(info.st_mode))
705 gchar *tmp;
706 uid_t dir_uid = info.st_uid;
708 tmp = make_path(handler, "AppRun")->str;
710 if (mc_lstat(tmp, &info) != 0 || info.st_uid != dir_uid
711 || !(info.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
712 desc = g_strdup_printf(
713 _("Invalid application %s (bad AppRun)"),
714 handler);
715 /* Else, just report handler... */
717 goto out;
720 /* It's not an application directory, and it's not a symlink... */
722 if (access(handler, X_OK) != 0)
724 desc = g_strdup_printf(_("Non-executable %s"), handler);
725 goto out;
728 desc = get_current_command(type);
729 out:
730 if (!desc)
731 desc = handler;
732 else
733 g_free(handler);
735 return desc;
738 /* Display a dialog box allowing the user to set the default run action
739 * for this type.
741 void type_set_handler_dialog(MIME_type *type)
743 guchar *tmp;
744 gchar *handler;
745 GtkDialog *dialog;
746 GtkWidget *frame, *entry, *label;
747 GtkWidget *radio, *eb, *hbox;
748 GtkTargetEntry targets[] = {
749 {"text/uri-list", 0, TARGET_URI_LIST},
752 g_return_if_fail(type != NULL);
754 dialog = GTK_DIALOG(gtk_dialog_new());
755 gtk_dialog_set_has_separator(dialog, FALSE);
756 gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_MOUSE);
758 g_object_set_data(G_OBJECT(dialog), "mime_type", type);
760 gtk_window_set_title(GTK_WINDOW(dialog), _("Set run action"));
762 tmp = g_strdup_printf(_("Set default for all `%s/<anything>'"),
763 type->media_type);
764 radio = gtk_radio_button_new_with_label(NULL, tmp);
765 g_free(tmp);
766 g_object_set_data(G_OBJECT(dialog), "set_for_all", radio);
768 tmp = g_strdup_printf(_("Only for the type `%s/%s'"), type->media_type,
769 type->subtype);
770 gtk_box_pack_start(GTK_BOX(dialog->vbox), radio, FALSE, TRUE, 0);
771 radio = gtk_radio_button_new_with_label(
772 gtk_radio_button_get_group(GTK_RADIO_BUTTON(radio)),
773 tmp);
774 g_free(tmp);
775 gtk_box_pack_start(GTK_BOX(dialog->vbox), radio, FALSE, TRUE, 0);
776 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), TRUE);
778 frame = gtk_frame_new(NULL);
779 gtk_box_pack_start(GTK_BOX(dialog->vbox), frame, TRUE, TRUE, 4);
780 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN);
781 eb = gtk_event_box_new();
782 gtk_container_add(GTK_CONTAINER(frame), eb);
784 gtk_container_set_border_width(GTK_CONTAINER(eb), 4);
786 handler = handler_for(type);
787 if (handler)
789 char *link;
791 link = readlink_dup(handler);
792 if (link)
794 char *msg;
796 msg = g_strdup_printf(_("Currently %s"), link);
797 gtk_tooltips_set_tip(tooltips, eb, msg, NULL);
798 g_free(link);
799 g_free(msg);
801 g_free(handler);
804 gtk_drag_dest_set(eb, GTK_DEST_DEFAULT_ALL,
805 targets, sizeof(targets) / sizeof(*targets),
806 GDK_ACTION_COPY);
807 g_signal_connect(eb, "drag_data_received",
808 G_CALLBACK(drag_app_dropped), dialog);
810 label = gtk_label_new(_("Drop a suitable\napplication here"));
811 gtk_misc_set_padding(GTK_MISC(label), 10, 20);
812 gtk_container_add(GTK_CONTAINER(eb), label);
814 hbox = gtk_hbox_new(FALSE, 4);
815 gtk_box_pack_start(GTK_BOX(dialog->vbox), hbox, FALSE, TRUE, 4);
816 gtk_box_pack_start(GTK_BOX(hbox), gtk_hseparator_new(), TRUE, TRUE, 0);
817 gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("OR")),
818 FALSE, TRUE, 0);
819 gtk_box_pack_start(GTK_BOX(hbox), gtk_hseparator_new(), TRUE, TRUE, 0);
821 hbox = gtk_hbox_new(FALSE, 4);
822 gtk_box_pack_start(GTK_BOX(dialog->vbox), hbox, FALSE, TRUE, 0);
824 label = gtk_label_new(_("Enter a shell command:")),
825 gtk_misc_set_alignment(GTK_MISC(label), 0, .5);
826 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 4);
828 gtk_box_pack_start(GTK_BOX(hbox),
829 new_help_button(show_shell_help, NULL), FALSE, TRUE, 0);
831 entry = gtk_entry_new();
832 gtk_box_pack_start(GTK_BOX(dialog->vbox), entry, FALSE, TRUE, 0);
833 gtk_widget_grab_focus(entry);
834 g_object_set_data(G_OBJECT(dialog), "shell_command", entry);
835 gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
837 /* If possible, fill in the entry box with the current command */
838 tmp = get_current_command(type);
839 if (tmp)
841 gtk_entry_set_text(GTK_ENTRY(entry), tmp);
842 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
843 g_free(tmp);
845 else
847 gtk_entry_set_text(GTK_ENTRY(entry), " \"$@\"");
848 gtk_editable_set_position(GTK_EDITABLE(entry), 0);
851 gtk_dialog_add_buttons(dialog,
852 GTK_STOCK_CANCEL, GTK_RESPONSE_DELETE_EVENT,
853 GTK_STOCK_OK, GTK_RESPONSE_OK,
854 NULL);
856 hbox = gtk_hbox_new(TRUE, 4);
857 gtk_box_pack_start(GTK_BOX(dialog->vbox), hbox, FALSE, TRUE, 0);
859 gtk_dialog_set_default_response(dialog, GTK_RESPONSE_OK);
861 g_signal_connect(dialog, "response",
862 G_CALLBACK(set_action_response), NULL);
864 gtk_widget_show_all(GTK_WIDGET(dialog));
867 /* The user wants to set a new default action for files of this type.
868 * Removes the current binding if possible and returns the path to
869 * save the new one to. NULL means cancel. g_free() the result.
871 char *get_action_save_path(GtkWidget *dialog)
873 guchar *path = NULL;
874 struct stat info;
875 guchar *type_name = NULL;
876 MIME_type *type;
877 GtkToggleButton *for_all;
879 g_return_val_if_fail(dialog != NULL, NULL);
880 type = g_object_get_data(G_OBJECT(dialog), "mime_type");
881 for_all = g_object_get_data(G_OBJECT(dialog), "set_for_all");
882 g_return_val_if_fail(for_all != NULL && type != NULL, NULL);
884 if (gtk_toggle_button_get_active(for_all))
885 type_name = g_strdup(type->media_type);
886 else
887 type_name = g_strconcat(type->media_type, "_",
888 type->subtype, NULL);
890 path = choices_find_path_save("", PROJECT, FALSE);
891 if (!path)
893 report_error(
894 _("Choices saving is disabled by CHOICESPATH variable"));
895 goto out;
897 g_free(path);
899 path = choices_find_path_save(type_name, "MIME-types", TRUE);
901 if (lstat(path, &info) == 0)
903 /* A binding already exists... */
904 if (S_ISREG(info.st_mode) && info.st_size > 256)
906 if (get_choice(PROJECT,
907 _("A run action already exists and is quite "
908 "a big program - are you sure you want to "
909 "delete it?"), 2,
910 _("Cancel"), _("Delete")) != 1)
912 null_g_free(&path);
913 goto out;
917 if (unlink(path))
919 report_error(_("Can't remove %s: %s"),
920 path, g_strerror(errno));
921 null_g_free(&path);
922 goto out;
926 out:
927 g_free(type_name);
928 return path;
931 MIME_type *mime_type_from_base_type(int base_type)
933 switch (base_type)
935 case TYPE_FILE:
936 return text_plain;
937 case TYPE_DIRECTORY:
938 return inode_directory;
939 case TYPE_PIPE:
940 return inode_pipe;
941 case TYPE_SOCKET:
942 return inode_socket;
943 case TYPE_BLOCK_DEVICE:
944 return inode_block_dev;
945 case TYPE_CHAR_DEVICE:
946 return inode_char_dev;
947 case TYPE_DOOR:
948 return inode_door;
950 return inode_unknown;
953 /* Takes the st_mode field from stat() and returns the base type.
954 * Should not be a symlink.
956 int mode_to_base_type(int st_mode)
958 if (S_ISREG(st_mode))
959 return TYPE_FILE;
960 else if (S_ISDIR(st_mode))
961 return TYPE_DIRECTORY;
962 else if (S_ISBLK(st_mode))
963 return TYPE_BLOCK_DEVICE;
964 else if (S_ISCHR(st_mode))
965 return TYPE_CHAR_DEVICE;
966 else if (S_ISFIFO(st_mode))
967 return TYPE_PIPE;
968 else if (S_ISSOCK(st_mode))
969 return TYPE_SOCKET;
970 else if (S_ISDOOR(st_mode))
971 return TYPE_DOOR;
973 return TYPE_ERROR;
976 /* Returns TRUE is this is something that is run by looking up its type
977 * in MIME-types and, hence, can have its run action set.
979 gboolean can_set_run_action(DirItem *item)
981 g_return_val_if_fail(item != NULL, FALSE);
983 return item->base_type == TYPE_FILE &&
984 !(item->mime_type == application_executable);
987 /* To edit the MIME types, open a filer window for <Choices>/MIME-info */
988 static void edit_mime_types(guchar *unused)
990 const gchar *path;
991 struct stat info;
993 mkdir(make_path(home_dir, ".mime")->str, 0700);
994 path = make_path(home_dir, ".mime/packages")->str;
995 mkdir(path, 0700);
996 filer_opendir(path, NULL, NULL);
998 path = "/usr/local/share/mime/packages";
999 if (mc_stat(path, &info) == 0)
1000 filer_opendir(path, NULL, NULL);
1002 path = "/usr/share/mime/packages";
1003 if (mc_stat(path, &info) == 0)
1004 filer_opendir(path, NULL, NULL);
1007 static GList *build_type_edit(Option *none, xmlNode *node, guchar *label)
1009 GtkWidget *button, *align;
1011 g_return_val_if_fail(none == NULL, NULL);
1013 align = gtk_alignment_new(0.1, 0, 0.1, 0);
1014 button = gtk_button_new_with_label(_(label));
1015 gtk_container_add(GTK_CONTAINER(align), button);
1017 g_signal_connect_swapped(button, "clicked",
1018 G_CALLBACK(edit_mime_types), NULL);
1020 return g_list_append(NULL, align);
1023 /* Parse file type colours and allocate/free them as necessary */
1024 static void alloc_type_colours(void)
1026 gboolean success[NUM_TYPE_COLOURS];
1027 int change_count = 0; /* No. needing realloc */
1028 int i;
1029 static gboolean allocated = FALSE;
1031 /* Parse colours */
1032 for (i = 0; i < NUM_TYPE_COLOURS; i++)
1034 GdkColor *c = &type_colours[i];
1035 gushort r = c->red;
1036 gushort g = c->green;
1037 gushort b = c->blue;
1039 gdk_color_parse(o_type_colours[i].value, &type_colours[i]);
1041 if (allocated && (c->red != r || c->green != g || c->blue != b))
1042 change_count++;
1045 /* Free colours if they were previously allocated and
1046 * have changed or become unneeded.
1048 if (allocated && (change_count || !o_display_colour_types.int_value))
1050 gdk_colormap_free_colors(gdk_rgb_get_colormap(),
1051 type_colours, NUM_TYPE_COLOURS);
1052 allocated = FALSE;
1055 /* Allocate colours, unless they are still allocated (=> they didn't
1056 * change) or we don't want them anymore.
1057 * XXX: what should be done if allocation fails?
1059 if (!allocated && o_display_colour_types.int_value)
1061 gdk_colormap_alloc_colors(gdk_rgb_get_colormap(),
1062 type_colours, NUM_TYPE_COLOURS,
1063 FALSE, TRUE, success);
1064 allocated = TRUE;
1068 /* Return a pointer to a (static) colour for this item. If colouring is
1069 * off, returns normal.
1071 GdkColor *type_get_colour(DirItem *item, GdkColor *normal)
1073 int type = item->base_type;
1075 if (!o_display_colour_types.int_value)
1076 return normal;
1078 if (item->flags & ITEM_FLAG_EXEC_FILE)
1079 type = TYPE_EXEC;
1080 else if (item->flags & ITEM_FLAG_APPDIR)
1081 type = TYPE_APPDIR;
1083 g_return_val_if_fail(type >= 0 && type < NUM_TYPE_COLOURS, normal);
1085 return &type_colours[type];
1088 /* Process the 'Patterns' value */
1089 static void add_pattern(MIME_type *type, const char *pattern, GHashTable *globs)
1091 if (pattern[0] == '*' && pattern[1] == '.' &&
1092 strpbrk(pattern + 2, "*?[") == NULL)
1094 g_hash_table_insert(extension_hash,
1095 g_strdup(pattern + 2),
1096 type);
1098 else if (strpbrk(pattern, "*?[") == NULL)
1099 g_hash_table_insert(literal_hash, g_strdup(pattern), type);
1100 else
1101 g_hash_table_insert(globs, g_strdup(pattern), type);
1104 /* Load and parse this file. literal_hash and extension_hash are updated
1105 * directly. Other patterns are added to 'globs'.
1107 static void import_file(const gchar *file, GHashTable *globs)
1109 MIME_type *type = NULL;
1110 GError *error = NULL;
1111 gchar *data, *line;
1113 if (access(file, F_OK) != 0)
1114 return; /* Doesn't exist. No problem. */
1116 if (!g_file_get_contents(file, &data, NULL, &error))
1118 delayed_error(_("Error loading MIME database:\n%s"),
1119 error->message);
1120 g_error_free(error);
1121 return;
1124 line = data;
1126 while (line && *line)
1128 char *nl;
1130 nl = strchr(line, '\n');
1131 if (!nl)
1132 break;
1133 *nl = '\0';
1135 if (*line != '#')
1137 const gchar *colon;
1138 gchar *name;
1140 colon = strchr(line, ':');
1141 if (!colon)
1143 delayed_error(_("File '%s' corrupted!"), file);
1144 break;
1147 name = g_strndup(line, colon - line);
1148 type = get_mime_type(name, TRUE);
1149 g_free(name);
1150 if (!type)
1151 g_warning("Invalid type in '%s'", file);
1153 add_pattern(type, colon + 1, globs);
1156 line = nl + 1;
1159 g_free(data);
1162 static void add_to_glob_patterns(gpointer key, gpointer value, gpointer unused)
1164 Pattern *pattern;
1166 pattern = g_new(Pattern, 1);
1167 pattern->glob = g_strdup((gchar *) key);
1168 pattern->type = (MIME_type *) value;
1169 pattern->len = strlen(pattern->glob);
1171 g_ptr_array_add(glob_patterns, pattern);
1174 static gint sort_by_strlen(gconstpointer a, gconstpointer b)
1176 const Pattern *pa = *(const Pattern **) a;
1177 const Pattern *pb = *(const Pattern **) b;
1179 if (pa->len > pb->len)
1180 return -1;
1181 else if (pa->len == pb->len)
1182 return 0;
1183 return 1;
1186 /* Clear all currently stored information and re-read everything */
1187 static void load_mime_types(void)
1189 GHashTable *globs;
1190 gchar *tmp;
1192 if (!glob_patterns)
1193 glob_patterns = g_ptr_array_new();
1194 else
1196 int i;
1198 for (i = glob_patterns->len - 1; i >= 0; i--)
1200 Pattern *p = glob_patterns->pdata[i];
1201 g_free(p->glob);
1202 g_free(p);
1204 g_ptr_array_set_size(glob_patterns, 0);
1207 if (literal_hash)
1208 g_hash_table_destroy(literal_hash);
1209 if (extension_hash)
1210 g_hash_table_destroy(extension_hash);
1211 literal_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1212 g_free, NULL);
1213 extension_hash = g_hash_table_new_full(g_str_hash, g_str_equal,
1214 g_free, NULL);
1215 globs = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1217 import_file("/usr/share/mime/globs", globs);
1218 import_file("/usr/local/share/mime/globs", globs);
1220 tmp = g_strconcat(home_dir, "/.mime/globs", NULL);
1221 import_file(tmp, globs);
1222 g_free(tmp);
1224 /* Turn the globs hash into a pointer array */
1225 g_hash_table_foreach(globs, add_to_glob_patterns, NULL);
1226 g_hash_table_destroy(globs);
1227 globs = NULL;
1229 if (glob_patterns->len)
1230 g_ptr_array_sort(glob_patterns, sort_by_strlen);
1232 if (g_hash_table_size(extension_hash) == 0)
1234 delayed_error(_("The standard MIME type database "
1235 "(version 0.8 or later) was not found. "
1236 "The filer will probably not show the correct "
1237 "types for different files. You should download and "
1238 "install the 'shared-mime-info-0.8' package from "
1239 "here:\n"
1240 "http://www.freedesktop.org/standards/shared-mime-info.html"));
1243 filer_update_all();