Add another flag to autohide the manager when there are no devices
[pmount-gui.git] / main.c
diff --git a/main.c b/main.c
index 6be83527e43da5809cace5ad328f1f0eff36f286..81bc4bffd77899c9b3a80e6ee34f8e98c426c393 100644 (file)
--- a/main.c
+++ b/main.c
@@ -1,3 +1,5 @@
+/* Required for strdup, snprintf, getopt */
+#define _XOPEN_SOURCE 500
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
@@ -5,9 +7,13 @@
 #include <fcntl.h>
 #include <dirent.h>
 #include <mntent.h>
+#include <errno.h>
 #include <sys/stat.h>
 #include <sys/wait.h>
+#include <sys/select.h>
+#include <sys/inotify.h>
 #include <gtk/gtk.h>
+#include <gdk/gdkkeysyms.h>
 
 typedef struct sProperty
 {
@@ -18,14 +24,34 @@ typedef struct sProperty
 typedef struct sDevice
 {
        char *node;
+       char *devname;
        char *label;
        char *description;
-       int mounted;
+       char *mount_point;
        time_t time;
 } Device;
 
+typedef struct sGuiContext
+{
+       int manager;
+       int autohide;
+       Device *devices;
+       GtkWidget *window;
+       GtkWidget *list;
+       GtkWidget *button;
+       char *post_mount_command;
+       int inotify_fd;
+       int dev_wd;
+       GIOChannel *inotify_channel;
+       int refresh_pending;
+} GuiContext;
+
 int verbosity = 0;
 
+/**
+Parses a string of the form name=value and places the components in a Property
+structure.  Returns 0 on success, or -1 if the string wasn't a valid property.
+*/
 int parse_property(char *str, int size, Property *prop)
 {
        int equals = -1;
@@ -49,16 +75,28 @@ int parse_property(char *str, int size, Property *prop)
        return 0;
 }
 
+/**
+Retrieves all properties associated with a /dev node.  The returned array is
+terminated with an entry containing NULL values.  Use free_properties to free
+the array.
+*/
 Property *get_device_properties(char *node)
 {
        int pid;
        int pipe_fd[2];
+       char *buf;
+       int bufsize;
+       int pos = 0;
+       int eof = 0;
+       Property *props = NULL;
+       int n_props = 0;
 
        pipe(pipe_fd);
 
        pid = fork();
        if(pid==0)
        {
+               /* Child process */
                if(verbosity>=2)
                        printf("Running udevadm info -q property -n \"%s\"\n", node);
 
@@ -68,87 +106,88 @@ Property *get_device_properties(char *node)
                execl("/sbin/udevadm", "udevadm", "info", "-q", "property", "-n", node, NULL);
                _exit(1);
        }
-       else if(pid>0)
+       else if(pid<0)
        {
-               char *buf;
-               int bufsize;
-               int pos = 0;
-               int eof = 0;
-               Property *props = NULL;
-               int n_props = 0;
-
+               close(pipe_fd[0]);
                close(pipe_fd[1]);
 
-               bufsize = 256;
-               buf = (char *)malloc(bufsize);
-
-               while(1)
-               {
-                       int newline;
-                       int i;
-                       Property prop;
+               return NULL;
+       }
 
-                       if(!eof)
-                       {
-                               int len;
-
-                               len = read(pipe_fd[0], buf+pos, bufsize-pos);
-                               if(len==0)
-                                       eof = 1;
-                               else if(len==-1)
-                                       break;
-                               pos += len;
-                       }
+       /* Parent process */
+       close(pipe_fd[1]);
 
-                       newline = -1;
-                       for(i=0; (newline<0 && i<pos); ++i)
-                               if(buf[i]=='\n')
-                                       newline = i;
+       bufsize = 256;
+       buf = (char *)malloc(bufsize);
 
-                       if(newline<0)
-                       {
-                               if(eof)
-                                       break;
-                               bufsize *= 2;
-                               buf = (char *)realloc(buf, bufsize);
-                               continue;
-                       }
+       while(1)
+       {
+               int newline;
+               int i;
+               Property prop;
 
-                       if(parse_property(buf, newline, &prop)==0)
-                       {
-                               props = (Property *)realloc(props, (n_props+2)*sizeof(Property));
-                               props[n_props] = prop;
-                               ++n_props;
+               if(!eof)
+               {
+                       int len;
 
-                               memmove(buf, buf+newline+1, pos-newline-1);
-                               pos -= newline+1;
-                       }
-                       else
+                       len = read(pipe_fd[0], buf+pos, bufsize-pos);
+                       if(len==0)
+                               eof = 1;
+                       else if(len==-1)
                                break;
+                       pos += len;
                }
 
-               free(buf);
+               newline = -1;
+               for(i=0; (newline<0 && i<pos); ++i)
+                       if(buf[i]=='\n')
+                               newline = i;
 
-               if(props)
+               if(newline<0)
                {
-                       props[n_props].name = NULL;
-                       props[n_props].value = NULL;
+                       if(eof)
+                               break;
+
+                       /* There was no newline in the buffer but there is more output to
+                       be read.  Try again with a larger buffer. */
+                       bufsize *= 2;
+                       buf = (char *)realloc(buf, bufsize);
+                       continue;
                }
 
-               waitpid(pid, NULL, 0);
-               close(pipe_fd[0]);
+               if(parse_property(buf, newline, &prop)==0)
+               {
+                       /* Reserve space for a sentinel value as well. */
+                       props = (Property *)realloc(props, (n_props+2)*sizeof(Property));
+                       props[n_props] = prop;
+                       ++n_props;
 
-               return props;
+                       memmove(buf, buf+newline+1, pos-newline-1);
+                       pos -= newline+1;
+               }
+               else
+                       break;
        }
-       else
-       {
-               close(pipe_fd[0]);
-               close(pipe_fd[1]);
 
-               return NULL;
+       free(buf);
+
+       if(props)
+       {
+               /* Terminate the array with NULL pointers. */
+               props[n_props].name = NULL;
+               props[n_props].value = NULL;
        }
+
+       waitpid(pid, NULL, 0);
+       close(pipe_fd[0]);
+
+       return props;
 }
 
+/**
+Looks for a property in an array of properties and returns its value.  Returns
+NULL if the property was not found.
+*/
 char *get_property_value(Property *props, char *name)
 {
        int i;
@@ -158,6 +197,10 @@ char *get_property_value(Property *props, char *name)
        return NULL;
 }
 
+/**
+Checks if a property has a specific value.  A NULL value is matched if the
+property does not exist.
+*/
 int match_property_value(Property *props, char *name, char *value)
 {
        char *v = get_property_value(props, name);
@@ -166,6 +209,9 @@ int match_property_value(Property *props, char *name, char *value)
        return strcmp(v, value)==0;
 }
 
+/**
+Frees an array of properties and all strings contained in it.
+*/
 void free_properties(Property *props)
 {
        int i;
@@ -179,49 +225,65 @@ void free_properties(Property *props)
        free(props);
 }
 
-char **get_mounted_devices(void)
+/**
+Returns an array of user-mountable devices listed in fstab.
+*/
+char **get_fstab_devices(void)
 {
-       FILE *mtab;
+       FILE *file;
        struct mntent *me;
-       char **mounted = NULL;
-       int n_mounted = 0;
+       char **devices = NULL;
+       int n_devices = 0;
 
-       mtab = setmntent("/etc/mtab", "r");
-       if(!mtab)
+       file = setmntent("/etc/fstab", "r");
+       if(!file)
                return NULL;
 
-       while((me = getmntent(mtab)))
-       {
-               mounted = (char **)realloc(mounted, (n_mounted+2)*sizeof(char *));
-               mounted[n_mounted] = strdup(me->mnt_fsname);
-               ++n_mounted;
-       }
+       while((me = getmntent(file)))
+               if(hasmntopt(me, "user")!=NULL)
+               {
+                       devices = (char **)realloc(devices, (n_devices+2)*sizeof(char *));
+                       devices[n_devices] = strdup(me->mnt_fsname);
+                       ++n_devices;
+               }
 
-       endmntent(mtab);
-       mounted[n_mounted] = NULL;
+       endmntent(file);
+       if(devices)
+               devices[n_devices] = NULL;
 
-       return mounted;
+       return devices;
 }
 
-int is_mounted(char **mounted, char *devname)
+/**
+Checks if an array of strings contains the specified string.
+*/
+int is_in_array(char **array, char *str)
 {
        int i;
-       for(i=0; mounted[i]; ++i)
-               if(!strcmp(devname, mounted[i]))
+       if(!array || !str)
+               return 0;
+       for(i=0; array[i]; ++i)
+               if(!strcmp(str, array[i]))
                        return 1;
        return 0;
 }
 
-void free_mounted_devices(char **mounted)
+/**
+Frees an array of strings.
+*/
+void free_string_array(char **array)
 {
        int i;
-       if(!mounted)
+       if(!array)
                return;
-       for(i=0; mounted[i]; ++i)
-               free(mounted[i]);
-       free(mounted);
+       for(i=0; array[i]; ++i)
+               free(array[i]);
+       free(array);
 }
 
+/**
+Checks if a partition identified by a sysfs path is on a removable device.
+*/
 int is_removable(char *devpath)
 {
        char fnbuf[256];
@@ -230,11 +292,15 @@ int is_removable(char *devpath)
        int fd;
 
        len = snprintf(fnbuf, sizeof(fnbuf), "/sys%s", devpath);
+       /* Default to not removable if the path was too long. */
        if(len+10>=(int)sizeof(fnbuf))
                return 0;
 
+       /* We got a partition as a parameter, but the removable property is on the
+       disk.  Replace the last component with "removable". */
        for(ptr=fnbuf+len; (ptr>fnbuf && *ptr!='/'); --ptr) ;
        strcpy(ptr, "/removable");
+
        fd = open(fnbuf, O_RDONLY);
        if(fd!=-1)
        {
@@ -254,6 +320,11 @@ int is_removable(char *devpath)
        return 0;
 }
 
+/**
+Checks if a partition's disk or any of its parent devices are connected to any
+of a set of buses.  The device is identified by a sysfs path.  The bus array
+must be terminated with a NULL entry.
+*/
 int check_buses(char *devpath, char **buses)
 {
        char fnbuf[256];
@@ -261,6 +332,7 @@ int check_buses(char *devpath, char **buses)
        int len;
 
        len = snprintf(fnbuf, sizeof(fnbuf), "/sys%s", devpath);
+       /* Default to no match if the path was too long. */
        if(len+10>=(int)sizeof(fnbuf))
                return 0;
 
@@ -268,32 +340,52 @@ int check_buses(char *devpath, char **buses)
                if(*ptr=='/')
                {
                        char linkbuf[256];
+                       /* Replace the last component with "subsystem". */
                        strcpy(ptr, "/subsystem");
                        len = readlink(fnbuf, linkbuf, sizeof(linkbuf)-1);
-                       *ptr = 0;
 
                        if(len!=-1)
                        {
-                               int i;
                                linkbuf[len] = 0;
+                               /* Extract the last component of the subsystem symlink. */
                                for(; (len>0 && linkbuf[len-1]!='/'); --len) ;
+
                                if(verbosity>=2)
+                               {
+                                       *ptr = 0;
                                        printf("  Subsystem of %s is %s\n", fnbuf, linkbuf+len);
-                               for(i=0; buses[i]; ++i)
-                                       if(strcmp(linkbuf+len, buses[i])==0)
-                                               return 1;
+                               }
+
+                               if(is_in_array(buses, linkbuf+len))
+                                       return 1;
                        }
                }
 
        return 0;
 }
 
-int can_mount(Property *props)
+/**
+Check if an array of properties describes a device that can be mounted.  An
+array of explicitly allowed devices can be passed in as well.  Both arrays must
+be terminated by a NULL entry.
+*/
+int can_mount(Property *props, char **allowed)
 {
        static char *removable_buses[] = { "usb", "firewire", 0 };
+       char *devname;
        char *devpath;
-       int i;
+       char *bus;
+
+       devname = get_property_value(props, "DEVNAME");
+       if(is_in_array(allowed, devname))
+               return 1;
 
+       /* Special case for CD devices, since they are not partitions.  Only allow
+       mounting if media is inserted. */
+       if(match_property_value(props, "ID_TYPE", "cd") && match_property_value(props, "ID_CDROM_MEDIA", "1"))
+               return 1;
+
+       /* Only allow mounting partitions. */
        if(!match_property_value(props, "DEVTYPE", "partition"))
                return 0;
 
@@ -301,13 +393,20 @@ int can_mount(Property *props)
        if(is_removable(devpath))
                return 1;
 
-       for(i=0; removable_buses[i]; ++i)
-               if(match_property_value(props, "ID_BUS", removable_buses[i]))
-                       return 1;
+       /* Certain buses are removable by nature, but devices only advertise
+       themselves as removable if they support removable media, e.g. memory card
+       readers. */
+       bus = get_property_value(props, "ID_BUS");
+       if(is_in_array(removable_buses, bus))
+               return 1;
 
        return check_buses(devpath, removable_buses);
 }
 
+/**
+Returns an array of all device nodes in a directory.  Symbolic links are
+dereferenced.
+*/
 char **get_device_nodes(char *dirname)
 {
        DIR *dir;
@@ -330,6 +429,7 @@ char **get_device_nodes(char *dirname)
                char *node;
                int duplicate = 0;
 
+               /* Ignore . and .. entries. */
                if(de->d_name[0]=='.' && (de->d_name[1]==0 || (de->d_name[1]=='.' && de->d_name[2]==0)))
                        continue;
 
@@ -348,6 +448,8 @@ char **get_device_nodes(char *dirname)
                        }
                }
 
+               /* There may be multiple symlinks to the same device.  Only include each
+               device once in the returned array. */
                if(checked)
                {
                        for(i=0; (!duplicate && i<n_checked); ++i)
@@ -356,7 +458,7 @@ char **get_device_nodes(char *dirname)
                }
                if(duplicate)
                {
-                       if(verbosity>=1)
+                       if(verbosity>=2)
                                printf("Device %s is a duplicate\n", fnbuf);
                        continue;
                }
@@ -384,23 +486,58 @@ char **get_device_nodes(char *dirname)
        return nodes;
 }
 
+/**
+Reads the list of mounted devices from /etc/mtab and records the mount points.
+*/
+void check_mounts(Device *devices)
+{
+       FILE *file;
+       struct mntent *me;
+
+       file = setmntent("/etc/mtab", "r");
+       if(!file)
+               return;
+
+       while((me = getmntent(file)))
+       {
+               int i;
+
+               for(i=0; devices[i].node; ++i)
+                       if(!strcmp(devices[i].devname, me->mnt_fsname))
+                       {
+                               devices[i].mount_point = strdup(me->mnt_dir);
+
+                               if(verbosity>=1)
+                                       printf("Device %s is mounted on %s\n", devices[i].node, devices[i].mount_point);
+                       }
+       }
+
+       endmntent(file);
+}
+
+/**
+Returns an array of all mountable devices.
+*/
 Device *get_devices(void)
 {
        char **nodes = NULL;
        Device *devices = NULL;
        int n_devices = 0;
        char **mounted = NULL;
+       char **fstab = NULL;
        int i;
 
        nodes = get_device_nodes("/dev/disk/by-id");
-       mounted = get_mounted_devices();
+       fstab = get_fstab_devices();
 
        for(i=0; nodes[i]; ++i)
        {
+               Property *props;
+
                if(verbosity>=1)
                        printf("Examining device %s\n", nodes[i]);
 
-               Property *props = get_device_properties(nodes[i]);
+               props = get_device_properties(nodes[i]);
                if(!props)
                {
                        if(verbosity>=2)
@@ -415,7 +552,7 @@ Device *get_devices(void)
                                printf("  %s = %s\n", props[j].name, props[j].value);
                }
 
-               if(can_mount(props))
+               if(can_mount(props, fstab))
                {
                        char *devname;
                        char *label;
@@ -430,6 +567,8 @@ Device *get_devices(void)
 
                        devname = get_property_value(props, "DEVNAME");
 
+                       /* Get a human-readable label for the device.  Use filesystem label,
+                       filesystem UUID or device node name in order of preference. */
                        label = get_property_value(props, "ID_FS_LABEL");
                        if(!label)
                                label = get_property_value(props, "ID_FS_UUID");
@@ -452,11 +591,13 @@ Device *get_devices(void)
 
                        stat(nodes[i], &st);
 
+                       /* Reserve space for a sentinel entry. */
                        devices = (Device *)realloc(devices, (n_devices+2)*sizeof(Device));
                        devices[n_devices].node = nodes[i];
+                       devices[n_devices].devname = strdup(devname);
                        devices[n_devices].label = strdup(label);
                        devices[n_devices].description = strdup(buf);
-                       devices[n_devices].mounted = is_mounted(mounted, devname);
+                       devices[n_devices].mount_point = NULL;
                        devices[n_devices].time = st.st_mtime;
                        ++n_devices;
                }
@@ -466,18 +607,26 @@ Device *get_devices(void)
        }
 
        free(nodes);
-       free_mounted_devices(mounted);
+       free_string_array(mounted);
 
        if(devices)
        {
+               /* Terminate the array with NULL pointers. */
                devices[n_devices].node = NULL;
+               devices[n_devices].devname = NULL;
                devices[n_devices].label = NULL;
                devices[n_devices].description = NULL;
+               devices[n_devices].mount_point = NULL;
+
+               check_mounts(devices);
        }
 
        return devices;
 }
 
+/**
+Frees an array of devices and all strings contained in it.
+*/
 void free_devices(Device *devices)
 {
        int i;
@@ -486,109 +635,409 @@ void free_devices(Device *devices)
        for(i=0; devices[i].node; ++i)
        {
                free(devices[i].node);
+               free(devices[i].devname);
                free(devices[i].label);
                free(devices[i].description);
+               if(devices[i].mount_point)
+                       free(devices[i].mount_point);
        }
        free(devices);
 }
 
-void row_activated(GtkTreeView *list, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data)
+/**
+Mounts a device if it was not mounted, or unmounts if it was.
+*/
+int toggle_device(Device *device, char *out_buf, int out_size)
 {
-       GtkTreeModel *model;
-       GtkTreeIter iter;
-       int umount = *(int *)user_data;
+       int umount = !!device->mount_point;
+       char mount_point[1024];
+       int pos = 0;
+       int status = 0;
+       fd_set fds;
+       struct timeval timeout;
+       int pid;
+       int pipe_fd[2];
+       char suffix = 0;
 
-       model = gtk_tree_view_get_model(list);
+       out_buf[0] = 0;
 
-       if(gtk_tree_model_get_iter(model, &iter, path))
+       /* Find a mount point that does not exist yet. */
+       while(1)
        {
-               Device *device;
-               int pid;
-               int pipe_fd[2];
+               int len;
 
-               gtk_tree_model_get(model, &iter, 1, &device, -1);
+               len = snprintf(mount_point, sizeof(mount_point), "/media/%s", device->label);
+               if(len+2>=(int)sizeof(mount_point))
+                       return -1;
 
-               pipe(pipe_fd);
+               if(suffix)
+                       len += snprintf(mount_point+len, sizeof(mount_point)-len, "_%c", suffix);
 
-               pid = fork();
-               if(pid==0)
-               {
-                       if(verbosity>=2)
-                       {
-                               if(umount)
-                                       printf("Running pumount %s\n", device->node);
-                               else
-                                       printf("Running pmount %s %s\n", device->node, device->label);
-                       }
+               if(access(mount_point, F_OK)<0 && errno==ENOENT)
+                       break;
 
-                       close(pipe_fd[0]);
-                       dup2(pipe_fd[1], 1);
-                       dup2(pipe_fd[1], 2);
+               if(suffix==0)
+                       suffix = '1';
+               else if(suffix<'9')
+                       ++suffix;
+               else
+                       return -1;
+       }
 
+       pipe(pipe_fd);
+
+       pid = fork();
+       if(pid==0)
+       {
+               /* Child process */
+               if(verbosity>=1)
+               {
                        if(umount)
-                               execl("/usr/bin/pumount", "pumount", device->node, NULL);
+                               printf("Running pumount %s\n", device->node);
                        else
-                               execl("/usr/bin/pmount", "pmount", device->node, device->label, NULL);
-                       _exit(1);
+                               printf("Running pmount %s %s\n", device->node, mount_point+7);
                }
-               else if(pid>0)
+
+               close(pipe_fd[0]);
+               dup2(pipe_fd[1], 1);
+               dup2(pipe_fd[1], 2);
+
+               if(umount)
+                       execl("/usr/bin/pumount", "pumount", device->node, NULL);
+               else
+                       execl("/usr/bin/pmount", "pmount", device->node, mount_point+7, NULL);
+               _exit(1);
+       }
+       else if(pid<0)
+               return -1;
+
+       /* Parent process */
+
+       close(pipe_fd[1]);
+       FD_ZERO(&fds);
+       FD_SET(pipe_fd[0], &fds);
+       timeout.tv_sec = 0;
+       timeout.tv_usec = 200000;
+
+       while(1)
+       {
+               /* The write fd for the pipe may be inherited by a fuse server
+               process and stay open indefinitely. */
+               if(select(pipe_fd[0]+1, &fds, NULL, NULL, &timeout))
                {
-                       char buf[1024];
-                       int pos = 0;
-                       int status;
+                       int len;
 
-                       close(pipe_fd[1]);
+                       len = read(pipe_fd[0], out_buf+pos, out_size-pos-1);
+                       if(len<=0)
+                               break;
+                       pos += len;
+               }
+               else if(waitpid(pid, &status, 0))
+               {
+                       pid = 0;
+                       break;
+               }
+       }
 
-                       while(1)
-                       {
-                               int len;
+       close(pipe_fd[0]);
+       if(pid)
+               waitpid(pid, &status, 0);
 
-                               len = read(pipe_fd[0], buf+pos, sizeof(buf)-pos-1);
-                               if(len<=0)
-                                       break;
-                               pos += len;
-                       }
+       out_buf[pos] = 0;
+
+       if(verbosity>=1)
+       {
+               if(WIFEXITED(status))
+               {
+                       if(WEXITSTATUS(status))
+                               printf("Command exited successfully\n");
+                       else
+                               printf("Command exited with status %d\n", WEXITSTATUS(status));
+               }
+               else if(WIFSIGNALED(status))
+                       printf("Command terminated with signal %d\n", WTERMSIG(status));
+               else
+                       printf("Command exited with unknown result %04X\n", status);
+       }
 
-                       buf[pos] = 0;
+       if(!WIFEXITED(status) || WEXITSTATUS(status))
+               return -1;
 
-                       waitpid(pid, &status, 0);
-                       if(!WIFEXITED(status) || WEXITSTATUS(status))
-                       {
-                               GtkWidget *dialog;
+       if(umount)
+       {
+               free(device->mount_point);
+               device->mount_point = NULL;
+       }
+       else
+               device->mount_point = strdup(mount_point);
 
-                               dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", buf);
-                               g_signal_connect(dialog, "response", &gtk_main_quit, NULL);
-                               gtk_widget_show_all(dialog);
+       return 0;
+}
+
+/**
+Refreshes both the internal devices array and the GUI list.
+*/
+int refresh_devices(GuiContext *context, int umount)
+{
+       GtkListStore *store;
+       GtkTreeSelection *selection;
+       int n_listed;
+       time_t latest;
+       int i;
+       GtkTreeIter iter;
+
+       store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(context->list)));
+       gtk_list_store_clear(store);
+
+       free_devices(context->devices);
+
+       context->devices = get_devices();
+       if(!context->devices)
+               return 0;
+
+       selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context->list));
+
+       /* Populate the list with devices in appropriate state. */
+       n_listed = 0;
+       latest = 0;
+       for(i=0; context->devices[i].node; ++i)
+       {
+               Device *dev;
+
+               dev = &context->devices[i];
+               if(umount<0 || !dev->mount_point==!umount)
+               {
+                       gtk_list_store_append(store, &iter);
+                       gtk_list_store_set(store, &iter,
+                               0, dev->description,
+                               1, dev,
+                               2, !!dev->mount_point,
+                               3, dev->mount_point,
+                               -1);
+                       if(dev->time>latest)
+                       {
+                               /* Pre-select the device that appeared on the system most recently. */
+                               latest = dev->time;
+                               gtk_tree_selection_select_iter(selection, &iter);
                        }
-                       else
-                               gtk_main_quit();
+
+                       ++n_listed;
                }
+       }
+
+       return n_listed;
+}
+
+/**
+Handles an automatic refresh of the device list in response to inotify events.
+*/
+gboolean refresh_devices_idle(gpointer data)
+{
+       GuiContext *context = (GuiContext *)data;
+       int n_listed;
+
+       n_listed = refresh_devices(context, -1);
+       context->refresh_pending = 0;
+
+       if(context->autohide)
+       {
+               if(n_listed)
+                       gtk_widget_show_all(context->window);
                else
+                       gtk_widget_hide(context->window);
+       }
+
+       return FALSE;
+}
+
+/**
+Callback for selection in the device list changing.  Updates the action button
+label according to device status.
+*/
+void selection_changed(GtkTreeSelection *selection, gpointer user_data)
+{
+       GuiContext *context = (GuiContext *)user_data;
+       GtkTreeIter iter;
+       GtkTreeModel *model;
+       Device *device;
+
+       if(!gtk_tree_selection_get_selected(selection, &model, &iter))
+               return;
+
+       gtk_tree_model_get(model, &iter, 1, &device, -1);
+       gtk_button_set_label(GTK_BUTTON(context->button), (device->mount_point ? "Unmount" : "Mount"));
+}
+
+/**
+Callback for activating a row in the device list.  Mounts or unmounts the
+device depending on operating mode.
+*/
+void row_activated(GtkTreeView *list, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data)
+{
+       GuiContext *context = (GuiContext *)user_data;
+       GtkTreeModel *model;
+       GtkTreeIter iter;
+       Device *device;
+       int ret;
+       char output[1024];
+       int pid;
+
+       model = gtk_tree_view_get_model(list);
+
+       if(!gtk_tree_model_get_iter(model, &iter, path))
+               return;
+
+       gtk_tree_model_get(model, &iter, 1, &device, -1);
+       ret = toggle_device(device, output, sizeof(output));
+       if(ret)
+       {
+               GtkWidget *dialog;
+
+               /* Pmount terminated with nonzero status or a signal.  Display an
+               error to the user. */
+               dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", output);
+               if(context->manager)
+                       g_signal_connect(dialog, "response", G_CALLBACK(&gtk_widget_destroy), dialog);
+               else
+                       g_signal_connect(dialog, "response", G_CALLBACK(&gtk_main_quit), NULL);
+               gtk_widget_show_all(dialog);
+               return;
+       }
+
+       if(context->manager)
+       {
+               gtk_list_store_set(GTK_LIST_STORE(model), &iter,
+                       2, !!device->mount_point,
+                       3, device->mount_point,
+                       -1);
+
+               gtk_button_set_label(GTK_BUTTON(context->button), (device->mount_point ? "Unmount" : "Mount"));
+       }
+       else
+               gtk_main_quit();
+
+       if(context->post_mount_command && device->mount_point)
+       {
+               if(verbosity>=1)
+                       printf("Running %s in %s\n", context->post_mount_command, device->mount_point);
+
+               pid = fork();
+               if(pid==0)
                {
+                       chdir(device->mount_point);
+                       execlp(context->post_mount_command, context->post_mount_command, NULL);
+                       _exit(1);
                }
        }
 
        (void)column;
+       (void)user_data;
+}
+
+/**
+Callback for the mount/unmount button.  Causes the selected row in the device
+list to be activated.
+*/
+void button_clicked(GtkButton *button, gpointer user_data)
+{
+       GuiContext *context = (GuiContext *)user_data;
+       GtkTreeSelection *selection;
+       GtkTreeIter iter;
+       GtkTreeModel *model;
+       GtkTreePath *path;
+       GtkTreeViewColumn *column;
+
+       selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context->list));
+       gtk_tree_selection_get_selected(selection, &model, &iter);
+       path = gtk_tree_model_get_path(model, &iter);
+       column = gtk_tree_view_get_column(GTK_TREE_VIEW(context->list), 0);
+       gtk_tree_view_row_activated(GTK_TREE_VIEW(context->list), path, column);
+       gtk_tree_path_free(path);
+
+       (void)button;
+}
+
+/**
+Global key press callback for the window.
+*/
+gboolean key_press(GtkWidget *widget, GdkEvent *event, gpointer user_data)
+{
+       if(event->key.keyval==GDK_KEY_Escape)
+       {
+               gtk_main_quit();
+               return TRUE;
+       }
+
+       (void)widget;
+       (void)user_data;
+
+       return FALSE;
+}
+
+/**
+Callback for inotify events.
+*/
+gboolean inotify_event_available(GIOChannel *source, GIOCondition condition, gpointer user_data)
+{
+       GuiContext *context = (GuiContext *)user_data;
+       int fd;
+       char eventbuf[sizeof(struct inotify_event)+NAME_MAX+1];
+       int len;
+
+       fd = g_io_channel_unix_get_fd(source);
+       len = read(fd, eventbuf, sizeof(eventbuf));
+       if(len>=(int)sizeof(struct inotify_event))
+       {
+               if(!context->refresh_pending)
+               {
+                       g_timeout_add(500, &refresh_devices_idle, context);
+                       context->refresh_pending = 1;
+               }
+       }
+
+       (void)condition;
+
+       return TRUE;
+}
+
+void show_help(void)
+{
+       printf("pmount-gui\n"
+               "Copyright (c) 2011-2015 Mikko Rasa, Mikkosoft Productions\n\n"
+               "Usage: pmount-gui [-v] [-u] [-r <command>] [-h]\n\n"
+               "Options:\n"
+               "  -v  Increase verbosity\n"
+               "  -u  Unmount a device (default is mount)\n"
+               "  -r  Run a command after mounting\n"
+               "  -m  Start a persistent mount manager\n"
+               "  -M  Like -m, but hide the window if there are no devices\n"
+               "  -h  Display this help\n");
 }
 
 int main(int argc, char **argv)
 {
-       GtkWidget *window;
+       GuiContext context;
+       GtkWidget *box;
        GtkWidget *viewport;
-       GtkWidget *list;
        GtkListStore *store;
        GtkTreeSelection *selection;
-       GtkTreeIter iter;
-       Device *devices;
-       int i;
-       time_t latest;
+       GtkCellRenderer *mounted_toggle;
        int opt;
        int umount = 0;
        int n_listed;
 
+       context.manager = 0;
+       context.autohide = 0;
+       context.devices = NULL;
+       context.post_mount_command = NULL;
+       context.inotify_fd = -1;
+       context.dev_wd = -1;
+       context.inotify_channel = NULL;
+       context.refresh_pending = 0;
+
        gtk_init(&argc, &argv);
 
-       while((opt = getopt(argc, argv, "vu"))!=-1) switch(opt)
+       while((opt = getopt(argc, argv, "vur:mMh"))!=-1) switch(opt)
        {
        case 'v':
                ++verbosity;
@@ -596,63 +1045,102 @@ int main(int argc, char **argv)
        case 'u':
                umount = 1;
                break;
+       case 'r':
+               context.post_mount_command = optarg;
+               break;
+       case 'm':
+               context.manager = 1;
+               context.autohide = 0;
+               break;
+       case 'M':
+               context.manager = 1;
+               context.autohide = 1;
+               break;
+       case 'h':
+               show_help();
+               return 0;
        }
 
-       window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
-       gtk_container_set_border_width(GTK_CONTAINER(window), 5);
-       g_signal_connect(window, "destroy", &gtk_main_quit, NULL);
+       context.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
+       gtk_container_set_border_width(GTK_CONTAINER(context.window), 5);
+       g_signal_connect(context.window, "destroy", G_CALLBACK(&gtk_main_quit), NULL);
+       g_signal_connect(context.window, "key-press-event", G_CALLBACK(&key_press), NULL);
+
+       box = gtk_vbox_new(FALSE, 5);
+       gtk_container_add(GTK_CONTAINER(context.window), box);
 
        viewport = gtk_viewport_new(NULL, NULL);
        gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_IN);
-       gtk_container_add(GTK_CONTAINER(window), viewport);
+       gtk_box_pack_start(GTK_BOX(box), viewport, TRUE, TRUE, 0);
 
-       list = gtk_tree_view_new();
-       gtk_container_add(GTK_CONTAINER(viewport), list);
-       g_signal_connect(list, "row-activated", (GCallback)&row_activated, &umount);
+       context.list = gtk_tree_view_new();
+       gtk_container_add(GTK_CONTAINER(viewport), context.list);
+       g_signal_connect(context.list, "row-activated", G_CALLBACK(&row_activated), &context);
 
-       store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_POINTER);
-       gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));
-       gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(list),
+       store = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_BOOLEAN, G_TYPE_STRING);
+       gtk_tree_view_set_model(GTK_TREE_VIEW(context.list), GTK_TREE_MODEL(store));
+       gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(context.list),
                -1, "Device", gtk_cell_renderer_text_new(), "text", 0, NULL);
 
-       selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
-
-       devices = get_devices();
-       n_listed = 0;
-       if(devices)
+       if(context.manager)
        {
-               latest = 0;
-               for(i=0; devices[i].node; ++i)
-                       if(!devices[i].mounted==!umount)
-                       {
-                               gtk_list_store_append(store, &iter);
-                               gtk_list_store_set(store, &iter, 0, devices[i].description, 1, &devices[i], -1);
-                               if(devices[i].time>latest)
-                               {
-                                       latest = devices[i].time;
-                                       gtk_tree_selection_select_iter(selection, &iter);
-                               }
+               GtkTreeViewColumn *mounted_column;
+               GtkCellRenderer *mount_point_renderer;
 
-                               ++n_listed;
-                       }
+               mounted_column = gtk_tree_view_column_new();
+               gtk_tree_view_column_set_title(mounted_column, "Mounted");
+
+               mounted_toggle = gtk_cell_renderer_toggle_new();
+               gtk_tree_view_column_pack_start(mounted_column, mounted_toggle, FALSE);
+               gtk_tree_view_column_add_attribute(mounted_column, mounted_toggle, "active", 2);
+
+               mount_point_renderer = gtk_cell_renderer_text_new();
+               gtk_tree_view_column_pack_start(mounted_column, mount_point_renderer, TRUE);
+               gtk_tree_view_column_add_attribute(mounted_column, mount_point_renderer, "text", 3);
+
+               gtk_tree_view_insert_column(GTK_TREE_VIEW(context.list), mounted_column, -1);
+
+               context.inotify_fd = inotify_init();
+               if(context.inotify_fd>=0)
+               {
+                       context.dev_wd = inotify_add_watch(context.inotify_fd, "/dev/disk/by-id", IN_CREATE|IN_DELETE);
+
+                       context.inotify_channel = g_io_channel_unix_new(context.inotify_fd);
+                       g_io_add_watch(context.inotify_channel, G_IO_IN, &inotify_event_available, &context);
+               }
+               else
+                       printf("Warning: Unable to initialize inotify\n");
 
+               umount = -1;
        }
 
-       if(n_listed)
-               gtk_widget_show_all(window);
-       else
+       selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context.list));
+       g_signal_connect(selection, "changed", G_CALLBACK(&selection_changed), &context);
+
+       context.button = gtk_button_new_with_label(umount ? "Unmount" : "Mount");
+       g_signal_connect(context.button, "clicked", G_CALLBACK(&button_clicked), &context);
+       gtk_box_pack_start(GTK_BOX(box), context.button, FALSE, TRUE, 0);
+
+       n_listed = refresh_devices(&context, umount);
+
+       if(n_listed || (context.manager && !context.autohide))
+               gtk_widget_show_all(context.window);
+       else if(!context.manager)
        {
                GtkWidget *dialog;
 
+               /* Don't show the main window if no devices were listed. */
                dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK,
                        "No devices to %s", (umount ? "unmount" : "mount"));
-               g_signal_connect(dialog, "response", &gtk_main_quit, NULL);
+               g_signal_connect(dialog, "response", G_CALLBACK(&gtk_main_quit), NULL);
                gtk_widget_show_all(dialog);
        }
 
        gtk_main();
 
-       free_devices(devices);
+       free_devices(context.devices);
+       if(context.inotify_fd>=0)
+               close(context.inotify_fd);
 
        return 0;
 }