chiark / gitweb /
set explicit colors instead of using rc file
[disorder] / disobedience / choose.c
index 2f1543ac50e78e78708e3559035fc9b9b7597bfe..e69f4b51d118ceae2cd642b9a745e143cc31815a 100644 (file)
@@ -80,6 +80,7 @@ struct choosenode {
 #define CN_RESOLVING_FILES 0x0020       /**< @brief resolved files inbound */
 #define CN_GETTING_DIRS 0x0040          /**< @brief directories inbound */
 #define CN_GETTING_ANY 0x0070           /**< @brief getting something */
+#define CN_CONTINGENT 0x0080            /**< @brief expansion contingent on search */
   struct nodevector children;           /**< @brief vector of children */
   void (*fill)(struct choosenode *);    /**< @brief request child fill or 0 for leaf */
   GtkWidget *container;                 /**< @brief the container for this row */
@@ -90,6 +91,8 @@ struct choosenode {
 
   when_filled_callback *whenfilled;     /**< @brief called when filled or 0 */
   void *wfu;                            /**< @brief passed to @c whenfilled */
+  int ymin;                             /**< @brief least Y value */
+  int ymax;                             /**< @brief greatest Y value */
 };
 
 /** @brief One item in the popup menu */
@@ -116,18 +119,25 @@ struct choose_menuitem {
 /* Variables */
 
 static GtkWidget *chooselayout;
+static GtkAdjustment *vadjust;
 static GtkWidget *searchentry;          /**< @brief search terms */
+static GtkWidget *nextsearch;           /**< @brief next search result */
+static GtkWidget *prevsearch;           /**< @brief previous search result */
 static struct choosenode *root;
-static struct choosenode *realroot;
 static GtkWidget *track_menu;           /**< @brief track popup menu */
 static GtkWidget *dir_menu;             /**< @brief directory popup menu */
 static struct choosenode *last_click;   /**< @brief last clicked node for selection */
 static int files_visible;               /**< @brief total files visible */
 static int files_selected;              /**< @brief total files selected */
+static int gets_in_flight;              /**< @brief total gets in flight */
 static int search_in_flight;            /**< @brief a search is underway */
 static int search_obsolete;             /**< @brief the current search is void */
 static char **searchresults;            /**< @brief search results */
 static int nsearchresults;              /**< @brief number of results */
+static int nsearchvisible;      /**< @brief number of search results visible */
+static struct hash *searchhash;         /**< @brief hash of search results */
+static struct progress_window *spw;     /**< @brief progress window */
+static struct choosenode **searchnodes; /**< @brief choosenodes of search results */
 
 /* Forward Declarations */
 
@@ -139,13 +149,12 @@ static struct choosenode *newnode(struct choosenode *parent,
                                   unsigned flags,
                                   void (*fill)(struct choosenode *));
 static void fill_root_node(struct choosenode *cn);
-static void fill_letter_node(struct choosenode *cn);
 static void fill_directory_node(struct choosenode *cn);
 static void got_files(void *v, int nvec, char **vec);
 static void got_resolved_file(void *v, const char *track);
 static void got_dirs(void *v, int nvec, char **vec);
 
-static void expand_node(struct choosenode *cn);
+static void expand_node(struct choosenode *cn, int contingent);
 static void contract_node(struct choosenode *cn);
 static void updated_node(struct choosenode *cn, int redisplay);
 
@@ -157,6 +166,8 @@ static struct displaydata display_tree(struct choosenode *cn, int x, int y);
 static void undisplay_tree(struct choosenode *cn);
 static void initiate_search(void);
 static void delete_widgets(struct choosenode *cn);
+static void expand_from(struct choosenode *cn);
+static struct choosenode *first_search_result(struct choosenode *cn);
 
 static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
                                GdkEventButton *event,
@@ -191,9 +202,49 @@ static struct choose_menuitem dir_menuitems[] = {
   { 0, 0, 0, 0, 0 }
 };
 
-
 /* Maintaining the data structure ------------------------------------------ */
 
+static char *cnflags(const struct choosenode *cn) {
+  unsigned f = cn->flags, n;
+  struct dynstr d[1];
+  
+  static const char *bits[] = {
+    "expandable",
+    "expanded",
+    "displayed",
+    "selected",
+    "getting_files",
+    "resolving_files",
+    "getting_dirs",
+    "contingent"
+  };
+#define NBITS (sizeof bits / sizeof *bits)
+
+  dynstr_init(d);
+  if(!f)
+    dynstr_append(d, '0');
+  else {
+    for(n = 0; n < NBITS; ++n) {
+      const unsigned bit = 1 << n;
+      if(f & bit) {
+        if(d->nvec)
+          dynstr_append(d, '|');
+        dynstr_append_string(d, bits[n]);
+        f ^= bit;
+      }
+    }
+    if(f) {
+      char buf[32];
+      if(d->nvec)
+        dynstr_append(d, '|');
+      sprintf(buf, "%#x", f);
+      dynstr_append_string(d, buf);
+    }
+  }
+  dynstr_terminate(d);
+  return d->vec;
+}
+
 /** @brief Create a new node */
 static struct choosenode *newnode(struct choosenode *parent,
                                   const char *path,
@@ -231,39 +282,33 @@ static void filled(struct choosenode *cn) {
     cn->whenfilled = 0;
     whenfilled(cn, cn->wfu);
   }
+  if(nsearchvisible < nsearchresults) {
+    /* There is still search expansion work to do */
+    D(("filled %s %d/%d", cn->path, nsearchvisible, nsearchresults));
+    expand_from(cn);
+  }
+  if(gets_in_flight == 0 && nsearchvisible < nsearchresults)
+    expand_from(root);
 }
 
 /** @brief Fill the root */
 static void fill_root_node(struct choosenode *cn) {
-  int ch;
-  char *name;
   struct callbackdata *cbd;
 
   D(("fill_root_node"));
   clear_children(cn);
-  if(choosealpha) {
-    if(!cn->children.nvec) {              /* Only need to do this once */
-      for(ch = 'A'; ch <= 'Z'; ++ch) {
-        byte_xasprintf(&name, "%c", ch);
-        newnode(cn, "<letter>", name, name, CN_EXPANDABLE, fill_letter_node);
-      }
-      newnode(cn, "<letter>", "*", "~", CN_EXPANDABLE, fill_letter_node);
-    }
-    updated_node(cn, 1);
-    filled(cn);
-  } else {
-    /* More de-duping possible here */
-    if(cn->flags & CN_GETTING_ANY)
-      return;
-    gtk_label_set_text(GTK_LABEL(report_label), "getting files");
-    cbd = xmalloc(sizeof *cbd);
-    cbd->u.choosenode = cn;
-    disorder_eclient_dirs(client, got_dirs, "", 0, cbd);
-    cbd = xmalloc(sizeof *cbd);
-    cbd->u.choosenode = cn;
-    disorder_eclient_files(client, got_files, "", 0, cbd);
-    cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
-  }
+  /* More de-duping possible here */
+  if(cn->flags & CN_GETTING_ANY)
+    return;
+  gtk_label_set_text(GTK_LABEL(report_label), "getting files");
+  cbd = xmalloc(sizeof *cbd);
+  cbd->u.choosenode = cn;
+  disorder_eclient_dirs(client, got_dirs, "", 0, cbd);
+  cbd = xmalloc(sizeof *cbd);
+  cbd->u.choosenode = cn;
+  disorder_eclient_files(client, got_files, "", 0, cbd);
+  cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
+  gets_in_flight += 2;
 }
 
 /** @brief Delete all the widgets owned by @p cn */
@@ -312,52 +357,28 @@ static void clear_children(struct choosenode *cn) {
   cn->children.nvec = 0;
 }
 
-/** @brief Fill a letter node */
-static void fill_letter_node(struct choosenode *cn) {
-  const char *regexp;
-  struct callbackdata *cbd;
-
-  D(("fill_letter_node %s", cn->display));
-  if(cn->flags & CN_GETTING_ANY)
-    return;
-  switch(cn->display[0]) {
-  default:
-    byte_xasprintf((char **)&regexp, "^(the )?%c", tolower(cn->display[0]));
-    break;
-  case 'T':
-    regexp = "^(?!the [^t])t";
-    break;
-  case '*':
-    regexp = "^[^a-z]";
-    break;
-  }
-  /* TODO: caching */
-  /* TODO: de-dupe against fill_directory_node */
-  gtk_label_set_text(GTK_LABEL(report_label), "getting files");
-  clear_children(cn);
-  cbd = xmalloc(sizeof *cbd);
-  cbd->u.choosenode = cn;
-  disorder_eclient_dirs(client, got_dirs, "", regexp, cbd);
-  cbd = xmalloc(sizeof *cbd);
-  cbd->u.choosenode = cn;
-  disorder_eclient_files(client, got_files, "", regexp, cbd);
-  cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
-}
-
 /** @brief Called with a list of files just below some node */
 static void got_files(void *v, int nvec, char **vec) {
   struct callbackdata *cbd = v;
   struct choosenode *cn = cbd->u.choosenode;
   int n;
 
-  D(("got_files %d files for %s", nvec, cn->path));
+  D(("got_files %d files for %s %s", nvec, cn->path, cnflags(cn)));
   /* Complicated by the need to resolve aliases.  We can save a bit of effort
    * by re-using cbd though. */
   cn->flags &= ~CN_GETTING_FILES;
-  cn->flags |= CN_RESOLVING_FILES;
-  cn->pending = nvec;
-  for(n = 0; n < nvec; ++n)
-    disorder_eclient_resolve(client, got_resolved_file, vec[n], cbd);
+  --gets_in_flight;
+  if((cn->pending = nvec)) {
+    cn->flags |= CN_RESOLVING_FILES;
+    for(n = 0; n < nvec; ++n) {
+      disorder_eclient_resolve(client, got_resolved_file, vec[n], cbd);
+      ++gets_in_flight;
+    }
+  }
+  /* If there are no files and the directories are all read by now, we're
+   * done */
+  if(!(cn->flags & CN_GETTING_ANY))
+    filled(cn);
 }
 
 /** @brief Called with an alias resolved filename */
@@ -365,11 +386,13 @@ static void got_resolved_file(void *v, const char *track) {
   struct callbackdata *cbd = v;
   struct choosenode *cn = cbd->u.choosenode, *file_cn;
 
+  D(("resolved %s %s %d left", cn->path, cnflags(cn), cn->pending - 1));
   /* TODO as below */
   file_cn = newnode(cn, track,
                     trackname_transform("track", track, "display"),
                     trackname_transform("track", track, "sort"),
                     0/*flags*/, 0/*fill*/);
+  --gets_in_flight;
   /* Only bother updating when we've got the lot */
   if(--cn->pending == 0) {
     cn->flags &= ~CN_RESOLVING_FILES;
@@ -385,7 +408,7 @@ static void got_dirs(void *v, int nvec, char **vec) {
   struct choosenode *cn = cbd->u.choosenode;
   int n;
 
-  D(("got_dirs %d dirs for %s", nvec, cn->path));
+  D(("got_dirs %d dirs for %s %s", nvec, cn->path, cnflags(cn)));
   /* TODO this depends on local configuration for trackname_transform().
    * This will work, since the defaults are now built-in, but it'll be
    * (potentially) different to the server's configured settings.
@@ -393,6 +416,7 @@ static void got_dirs(void *v, int nvec, char **vec) {
    * Really we want a variant of files/dirs that produces both the
    * raw filename and the transformed name for a chosen context.
    */
+  --gets_in_flight;
   for(n = 0; n < nvec; ++n)
     newnode(cn, vec[n],
             trackname_transform("dir", vec[n], "display"),
@@ -410,7 +434,6 @@ static void fill_directory_node(struct choosenode *cn) {
 
   D(("fill_directory_node %s", cn->path));
   /* TODO: caching */
-  /* TODO: de-dupe against fill_letter_node */
   if(cn->flags & CN_GETTING_ANY)
     return;
   assert(report_label != 0);
@@ -423,11 +446,12 @@ static void fill_directory_node(struct choosenode *cn) {
   cbd->u.choosenode = cn;
   disorder_eclient_files(client, got_files, cn->path, 0, cbd);
   cn->flags |= CN_GETTING_FILES|CN_GETTING_DIRS;
+  gets_in_flight += 2;
 }
 
 /** @brief Expand a node */
-static void expand_node(struct choosenode *cn) {
-  D(("expand_node %s", cn->path));
+static void expand_node(struct choosenode *cn, int contingent) {
+  D(("expand_node %s %d %s", cn->path, contingent, cnflags(cn)));
   assert(cn->flags & CN_EXPANDABLE);
   /* If node is already expanded do nothing. */
   if(cn->flags & CN_EXPANDED) return;
@@ -435,17 +459,78 @@ static void expand_node(struct choosenode *cn) {
    * completed it will called updated_node() and we can redraw at that
    * point. */
   cn->flags |= CN_EXPANDED;
+  if(contingent)
+    cn->flags |= CN_CONTINGENT;
+  else
+    cn->flags &= ~CN_CONTINGENT;
+  /* If this node is not contingently expanded, mark all its parents back to
+   * the root as not contingent either, so they won't be contracted when the
+   * search results change */
+  if(!contingent) {
+    struct choosenode *cnp;
+
+    for(cnp = cn->parent; cnp; cnp = cnp->parent)
+      cnp->flags &= ~CN_CONTINGENT;
+  }
   /* TODO: visual feedback */
   cn->fill(cn);
 }
 
+/** @brief Make sure all the search results below @p cn are expanded
+ * @param cn Node to start at
+ */
+static void expand_from(struct choosenode *cn) {
+  int n;
+
+  if(nsearchvisible == nsearchresults)
+    /* We're done */
+    return;
+  /* Are any of the search tracks at/below this point? */
+  if(!(cn == root || hash_find(searchhash, cn->path)))
+    return;
+  D(("expand_from %d/%d visible %s", 
+     nsearchvisible, nsearchresults, cn->path));
+  if(cn->flags & CN_EXPANDABLE) {
+    if(cn->flags & CN_EXPANDED)
+      /* This node is marked as expanded already.  children.nvec might be 0,
+       * indicating that expansion is still underway.  We should get another
+       * callback when it is expanded. */
+      for(n = 0; n < cn->children.nvec && gets_in_flight < 10; ++n)
+        expand_from(cn->children.vec[n]);
+    else {
+      /* This node is not expanded yet */
+      expand_node(cn, 1);
+    }
+  } else {
+    /* This is an actual search result */
+    ++nsearchvisible;
+    progress_window_progress(spw, nsearchvisible, nsearchresults);
+    if(nsearchvisible == nsearchresults) {
+      /* We've got the lot.  We make sure the first result is visible. */
+      cn = first_search_result(root);
+      gtk_adjustment_clamp_page(vadjust, cn->ymin, cn->ymax);
+    }
+  }
+}
+
+/** @brief Contract all contingently expanded nodes below @p cn */
+static void contract_contingent(struct choosenode *cn) {
+  int n;
+
+  if(cn->flags & CN_CONTINGENT)
+    contract_node(cn);
+  else
+    for(n = 0; n < cn->children.nvec; ++n)
+      contract_contingent(cn->children.vec[n]);
+}
+
 /** @brief Contract a node */
 static void contract_node(struct choosenode *cn) {
   D(("contract_node %s", cn->path));
   assert(cn->flags & CN_EXPANDABLE);
   /* If node is already contracted do nothing. */
   if(!(cn->flags & CN_EXPANDED)) return;
-  cn->flags &= ~CN_EXPANDED;
+  cn->flags &= ~(CN_EXPANDED|CN_CONTINGENT);
   /* Clear selection below this node */
   clear_selection(cn);
   /* Zot children.  We never used to do this but the result would be that over
@@ -483,62 +568,32 @@ static void updated_node(struct choosenode *cn, int redisplay) {
 
 /* Searching --------------------------------------------------------------- */
 
-/** @brief qsort() callback for ordering tracks */
-static int compare_track_for_qsort(const void *a, const void *b) {
-  return compare_path(*(char **)a, *(char **)b);
-}
-
-/** @brief Return true iff @p file is a child of @p dir */
-static int is_child(const char *dir, const char *file) {
-  const size_t dlen = strlen(dir);
-
-  return (!strncmp(file, dir, dlen)
-          && file[dlen] == '/'
-          && strchr(file + dlen + 1, '/') == 0);
-}
-
-/** @brief Return true iff @p file is a descendant of @p dir */
-static int is_descendant(const char *dir, const char *file) {
-  const size_t dlen = strlen(dir);
+/** @brief Return true if @p track is a search result
+ *
+ * In particular the return value is one more than the index of the track
+ * @p searchresults.
+ */
+static int is_search_result(const char *track) {
+  void *r;
 
-  return !strncmp(file, dir, dlen) && file[dlen] == '/';
+  if(searchhash && (r = hash_find(searchhash, track)))
+    return 1 + *(int *)r;
+  else
+    return 0;
 }
 
-/** @brief Called to fill a node in the search results tree */
-static void fill_search_node(struct choosenode *cn) {
+/** @brief Return the first search result at or below @p cn */
+static struct choosenode *first_search_result(struct choosenode *cn) {
   int n;
-  const size_t plen = strlen(cn->path);
-  const char *s;
-  char *dir, *last = 0;
+  struct choosenode *r;
 
-  D(("fill_search_node %s", cn->path));
-  /* We depend on the search results being sorted as by compare_path(). */
-  clear_children(cn);
-  for(n = 0; n < nsearchresults; ++n) {
-    /* We only care about descendants of CN */
-    if(!is_descendant(cn->path, searchresults[n]))
-       continue;
-    s = strchr(searchresults[n] + plen + 1, '/');
-    if(s) {
-      /* We've identified a subdirectory of CN. */
-      dir = xstrndup(searchresults[n], s - searchresults[n]);
-      if(!last || strcmp(dir, last)) {
-        /* Not a duplicate */
-        last = dir;
-        newnode(cn, dir,
-                trackname_transform("dir", dir, "display"),
-                trackname_transform("dir", dir, "sort"),
-                CN_EXPANDABLE, fill_search_node);
-      }
-    } else {
-      /* We've identified a file in CN */
-      newnode(cn, searchresults[n],
-              trackname_transform("track", searchresults[n], "display"),
-              trackname_transform("track", searchresults[n], "sort"),
-              0/*flags*/, 0/*fill*/);
-    }
-  }
-  updated_node(cn, 1);
+  if(cn->flags & CN_EXPANDABLE) {
+    for(n = 0; n < cn->children.nvec; ++n)
+      if((r = first_search_result(cn->children.vec[n])))
+        return r;
+  } else if(is_search_result(cn->path))
+    return cn;
+  return 0;
 }
 
 /** @brief Called with a list of search results
@@ -548,71 +603,59 @@ static void fill_search_node(struct choosenode *cn) {
  * we're not searching for anything in particular. */
 static void search_completed(void attribute((unused)) *v,
                              int nvec, char **vec) {
-  struct choosenode *cn;
   int n;
-  const char *dir;
+  char *s;
 
   search_in_flight = 0;
+  /* Contract any choosenodes that were only expanded to show search
+   * results */
+  contract_contingent(root);
   if(search_obsolete) {
     /* This search has been obsoleted by user input since it started.
      * Therefore we throw away the result and search again. */
     search_obsolete = 0;
     initiate_search();
   } else {
+    /* Stash the search results */
+    searchresults = vec;
+    nsearchresults = nvec;
     if(nvec) {
-      /* We will replace the choose tree with a tree structured view of search
-       * results.  First we must disabled the choose tree's widgets. */
-      delete_widgets(root);
-      /* Put the tracks into order, grouped by directory.  They'll probably
-       * come back this way anyway in current versions of the server, but it's
-       * cheap not to rely on it (compared with the massive effort we expend
-       * later on) */
-      qsort(vec, nvec, sizeof(char *), compare_track_for_qsort);
-      searchresults = vec;
-      nsearchresults = nvec;
-      cn = root = newnode(0/*parent*/, "", "Search results", "",
-                  CN_EXPANDABLE|CN_EXPANDED, fill_search_node);
-      /* Construct the initial tree.  We do this in a single pass and expand
-       * everything, so you can actually see your search results. */
-      for(n = 0; n < nsearchresults; ++n) {
-        /* Firstly we might need to go up a few directories to each an ancestor
-         * of this track */
-        while(!is_descendant(cn->path, searchresults[n])) {
-          /* We report the update on each node the last time we see it (With
-           * display=0, the main purpose of this is to get the order of the
-           * children right.) */
-          updated_node(cn, 0);
-          cn = cn->parent;
-        }
-        /* Secondly we might need to insert some new directories */
-        while(!is_child(cn->path, searchresults[n])) {
-          /* Figure out the subdirectory */
-          dir = xstrndup(searchresults[n],
-                         strchr(searchresults[n] + strlen(cn->path) + 1,
-                                '/') - searchresults[n]);
-          cn = newnode(cn, dir,
-                       trackname_transform("dir", dir, "display"),
-                       trackname_transform("dir", dir, "sort"),
-                       CN_EXPANDABLE|CN_EXPANDED, fill_search_node);
+      /* Create a new search hash for fast identification of results */
+      searchhash = hash_new(sizeof(int));
+      for(n = 0; n < nvec; ++n) {
+        int *const ip = xmalloc(sizeof (int *));
+        static const int minus_1 = -1;
+        *ip = n;
+        /* The filename itself lives in the hash */
+        hash_add(searchhash, vec[n], ip, HASH_INSERT_OR_REPLACE);
+        /* So do its ancestor directories */
+        for(s = vec[n] + 1; *s; ++s) {
+          if(*s == '/') {
+            *s = 0;
+            hash_add(searchhash, vec[n], &minus_1, HASH_INSERT_OR_REPLACE);
+            *s = '/';
+          }
         }
-        /* Finally we can insert the track as a child of the current
-         * directory */
-        newnode(cn, searchresults[n],
-                trackname_transform("track", searchresults[n], "display"),
-                trackname_transform("track", searchresults[n], "sort"),
-                0/*flags*/, 0/*fill*/);
       }
-      while(cn) {
-        /* Update all the nodes back up to the root */
-        updated_node(cn, 0);
-        cn = cn->parent;
+      /* We don't yet know that the results are visible */
+      nsearchvisible = 0;
+      if(spw) {
+        progress_window_progress(spw, 0, 0);
+        spw = 0;
       }
-      /* Now it's worth displaying the tree */
-      redisplay_tree();
-    } else if(root != realroot) {
-      delete_widgets(root);
-      root = realroot;
-      redisplay_tree();
+      if(nsearchresults > 50)
+        spw = progress_window_new("Fetching search results");
+      /* Initiate expansion */
+      expand_from(root);
+      /* The search results buttons are usable */
+      gtk_widget_set_sensitive(nextsearch, 1);
+      gtk_widget_set_sensitive(prevsearch, 1);
+    } else {
+      searchhash = 0;                   /* for the gc */
+      redisplay_tree();                 /* remove search markers */
+      /* The search results buttons are not usable */
+      gtk_widget_set_sensitive(nextsearch, 0);
+      gtk_widget_set_sensitive(prevsearch, 0);
     }
   }
 }
@@ -660,6 +703,50 @@ static void clearsearch_clicked(GtkButton attribute((unused)) *button,
   gtk_entry_set_text(GTK_ENTRY(searchentry), "");
 }
 
+/** @brief Called when the 'next search result' button is clicked */
+static void next_clicked(GtkButton attribute((unused)) *button,
+                         gpointer attribute((unused)) userdata) {
+  /* We want to find the highest (lowest ymax) track that is below the current
+   * visible range */
+  int n;
+  const gdouble bottom = gtk_adjustment_get_value(vadjust) + vadjust->page_size;
+  const struct choosenode *candidate = 0;
+
+  for(n = 0; n < nsearchresults; ++n) {
+    const struct choosenode *const cn = searchnodes[n];
+
+    if(cn
+       && cn->ymax > bottom
+       && (candidate == 0
+           || cn->ymax < candidate->ymax))
+      candidate = cn;
+  }
+  if(candidate)
+    gtk_adjustment_clamp_page(vadjust, candidate->ymin, candidate->ymax);
+}
+
+/** @brief Called when the 'previous search result' button is clicked */
+static void prev_clicked(GtkButton attribute((unused)) *button,
+                         gpointer attribute((unused)) userdata) {
+  /* We want to find the lowest (greated ymax) track that is above the current
+   * visible range */
+  int n;
+  const gdouble top = gtk_adjustment_get_value(vadjust);
+  const struct choosenode *candidate = 0;
+
+  for(n = 0; n < nsearchresults; ++n) {
+    const struct choosenode *const cn = searchnodes[n];
+
+    if(cn
+       && cn->ymin  < top
+       && (candidate == 0
+           || cn->ymax > candidate->ymax))
+      candidate = cn;
+  }
+  if(candidate)
+    gtk_adjustment_clamp_page(vadjust, candidate->ymin, candidate->ymax);
+}
+
 /* Display functions ------------------------------------------------------- */
 
 /** @brief Delete all the widgets in the tree */
@@ -684,6 +771,8 @@ static void redisplay_tree(void) {
   files_visible = 0;
   /* Correct the layout and find out how much space it uses */
   MTAG_PUSH("display_tree");
+  searchnodes = nsearchresults ? xcalloc(nsearchresults, 
+                                         sizeof (struct choosenode *)) : 0;
   d = display_tree(root, 0, 0);
   MTAG_POP();
   /* We must set the total size or scrolling will not work (it wouldn't be hard
@@ -704,6 +793,9 @@ static void redisplay_tree(void) {
 }
 
 /** @brief Recursive step for redisplay_tree()
+ * @param cn Node to display
+ * @param x X coordinate for @p cn
+ * @param y Y coordinate for @p cn
  *
  * Makes sure all displayed widgets from CN down exist and are in their proper
  * place and return the maximum space used.
@@ -713,6 +805,7 @@ static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
   GtkRequisition req;
   struct displaydata d, cd;
   GdkPixbuf *pb;
+  const int search_result = is_search_result(cn->path);
   
   D(("display_tree %s %d,%d", cn->path, x, y));
 
@@ -758,13 +851,21 @@ static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
     g_signal_connect(cn->container, "button-press-event", 
                      G_CALLBACK(clicked_choosenode), cn);
     g_object_ref(cn->container);
-    gtk_widget_set_name(cn->label, "choose");
-    gtk_widget_set_name(cn->container, "choose");
     /* Show everything by default */
     gtk_widget_show_all(cn->container);
     MTAG_POP();
   }
   assert(cn->container);
+  /* Set colors */
+  if(search_result)
+    gtk_widget_modify_bg(cn->container, GTK_STATE_NORMAL, &search_bg);
+  else
+    gtk_widget_modify_bg(cn->container, GTK_STATE_NORMAL, &layout_bg);
+  gtk_widget_modify_bg(cn->container, GTK_STATE_SELECTED, &selected_bg);
+  gtk_widget_modify_bg(cn->container, GTK_STATE_PRELIGHT, &selected_bg);
+  gtk_widget_modify_fg(cn->label, GTK_STATE_NORMAL, &item_fg);
+  gtk_widget_modify_fg(cn->label, GTK_STATE_SELECTED, &selected_fg);
+  gtk_widget_modify_fg(cn->label, GTK_STATE_PRELIGHT, &selected_fg);
   /* Make sure the icon is right */
   if(cn->flags & CN_EXPANDABLE)
     gtk_arrow_set(GTK_ARROW(cn->arrow),
@@ -790,6 +891,8 @@ static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
   gtk_widget_size_request(cn->container, &req);
   d.width = x + req.width;
   d.height = y + req.height;
+  cn->ymin = y;
+  cn->ymax = d.height;
   if(cn->flags & CN_EXPANDED) {
     /* We'll offset children by the size of the arrow whatever it might be. */
     assert(cn->arrow);
@@ -810,6 +913,9 @@ static struct displaydata display_tree(struct choosenode *cn, int x, int y) {
     if(cn->flags & CN_SELECTED)
       ++files_selected;
   }
+  /* update the search results array */
+  if(search_result)
+    searchnodes[search_result - 1] = cn;
   /* report back how much space we used */
   D(("display_tree %s %d,%d total size %dx%d", cn->path, x, y,
      d.width, d.height));
@@ -892,7 +998,7 @@ static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
       if(cn->flags & CN_EXPANDED)
         contract_node(cn);
       else
-        expand_node(cn);
+        expand_node(cn, 0/*!contingent*/);
       last_click = 0;
     } else {
       /* This is a file.  Adjust selection status */
@@ -974,6 +1080,7 @@ static void clicked_choosenode(GtkWidget attribute((unused)) *widget,
       menuitems[n].handlerid = g_signal_connect
         (menuitems[n].w, "activate", G_CALLBACK(menuitems[n].activate), cn);
     }
+    set_tool_colors(menu);
     /* Pop up the menu */
     gtk_widget_show_all(menu);
     gtk_menu_popup(GTK_MENU(menu), 0, 0, 0, 0,
@@ -1104,7 +1211,7 @@ static void call_with_dir(struct choosenode *cn,
      * opened */
     cn->whenfilled = whenfilled;
     cn->wfu = wfu;
-    expand_node(cn);
+    expand_node(cn, 0/*not contingnet upon search*/);
   }
 }
 
@@ -1185,6 +1292,15 @@ static const struct tabtype tabtype_choose = {
 
 /* Public entry points ----------------------------------------------------- */
 
+/** @brief Called to entirely reset the choose screen */
+static void choose_reset(void) {
+  if(root)
+    undisplay_tree(root);
+  root = newnode(0/*parent*/, "<root>", "All files", "",
+                 CN_EXPANDABLE, fill_root_node);
+  expand_node(root, 0);                 /* will call redisplay_tree */
+}
+
 /** @brief Create a track choice widget */
 GtkWidget *choose_widget(void) {
   int n;
@@ -1220,27 +1336,54 @@ GtkWidget *choose_widget(void) {
   /* Cancel button to clear the search */
   NW(button);
   clearsearch = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
+  gtk_widget_modify_bg(clearsearch, GTK_STATE_NORMAL, &tool_bg);
+  gtk_widget_modify_bg(clearsearch, GTK_STATE_ACTIVE, &tool_active);
+  gtk_widget_modify_bg(clearsearch, GTK_STATE_PRELIGHT, &tool_active);
+  gtk_widget_modify_bg(clearsearch, GTK_STATE_SELECTED, &tool_active);
   g_signal_connect(G_OBJECT(clearsearch), "clicked",
                    G_CALLBACK(clearsearch_clicked), 0);
   gtk_tooltips_set_tip(tips, clearsearch, "Clear search terms", "");
 
-
-  /* hbox packs the search box and the cancel button together on a line */
+  /* Up and down buttons to find previous/next results; initially they are not
+   * usable as there are no search results. */
+  prevsearch = iconbutton("up.png", "Previous search result");
+  g_signal_connect(G_OBJECT(prevsearch), "clicked",
+                   G_CALLBACK(prev_clicked), 0);
+  gtk_widget_set_sensitive(prevsearch, 0);
+  gtk_widget_modify_bg(prevsearch, GTK_STATE_NORMAL, &tool_bg);
+  gtk_widget_modify_bg(prevsearch, GTK_STATE_ACTIVE, &tool_active);
+  gtk_widget_modify_bg(prevsearch, GTK_STATE_PRELIGHT, &tool_active);
+  gtk_widget_modify_bg(prevsearch, GTK_STATE_SELECTED, &tool_active);
+  gtk_widget_modify_bg(prevsearch, GTK_STATE_INSENSITIVE, &tool_active);
+  nextsearch = iconbutton("down.png", "Next search result");
+  g_signal_connect(G_OBJECT(nextsearch), "clicked",
+                   G_CALLBACK(next_clicked), 0);
+  gtk_widget_set_sensitive(nextsearch, 0);
+  gtk_widget_modify_bg(nextsearch, GTK_STATE_NORMAL, &tool_bg);
+  gtk_widget_modify_bg(nextsearch, GTK_STATE_ACTIVE, &tool_active);
+  gtk_widget_modify_bg(nextsearch, GTK_STATE_PRELIGHT, &tool_active);
+  gtk_widget_modify_bg(nextsearch, GTK_STATE_SELECTED, &tool_active);
+  gtk_widget_modify_bg(nextsearch, GTK_STATE_INSENSITIVE, &tool_active);
+
+  /* hbox packs the search tools button together on a line */
   NW(hbox);
   hbox = gtk_hbox_new(FALSE/*homogeneous*/, 1/*spacing*/);
   gtk_box_pack_start(GTK_BOX(hbox), searchentry,
                      TRUE/*expand*/, TRUE/*fill*/, 0/*padding*/);
-  gtk_box_pack_end(GTK_BOX(hbox), clearsearch,
-                   FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
+  gtk_box_pack_start(GTK_BOX(hbox), prevsearch,
+                     FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
+  gtk_box_pack_start(GTK_BOX(hbox), nextsearch,
+                     FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
+  gtk_box_pack_start(GTK_BOX(hbox), clearsearch,
+                     FALSE/*expand*/, FALSE/*fill*/, 0/*padding*/);
   
   /* chooselayout contains the currently visible subset of the track
    * namespace */
   NW(layout);
   chooselayout = gtk_layout_new(0, 0);
-  root = newnode(0/*parent*/, "<root>", "All files", "",
-                 CN_EXPANDABLE, fill_root_node);
-  realroot = root;
-  expand_node(root);                    /* will call redisplay_tree */
+  gtk_widget_modify_bg(chooselayout, GTK_STATE_NORMAL, &layout_bg);
+  choose_reset();
+  register_reset(choose_reset);
   /* Create the popup menus */
   NW(menu);
   track_menu = gtk_menu_new();
@@ -1265,7 +1408,8 @@ GtkWidget *choose_widget(void) {
                     0, 1, n, n + 1);
   }
   /* The layout is scrollable */
-  scrolled = scroll_widget(GTK_WIDGET(chooselayout), "choose");
+  scrolled = scroll_widget(chooselayout);
+  vadjust = gtk_layout_get_vadjustment(GTK_LAYOUT(chooselayout));
 
   /* The scrollable layout and the search hbox go together in a vbox */
   NW(vbox);