/*
    gutils.c - Gtk/Glib utilitis
    Copyright (c) 2006  Joey Schulze <joey@infodrom.org>

    This file is part of the Gerstensaft package.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*/

#include "gutils.h"
#include <gtk/gtk.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

int clist_contains (GtkCList *clist, int column, char *needle)
{
  GList *row;
  char *tmp;

  if (! GTK_IS_CLIST(clist))
    return 0;

    for (row = GTK_CLIST(clist)->row_list;
       row;
       row = row->next) {
      
      gtk_clist_get_text(GTK_CLIST(clist), (int)row->data, column, &tmp);

      if (!strcmp(tmp, needle))
	return 1;
    }

  return 0;
}

int filebox_append (GtkCList *filebox, char *fullname)
{
  char *fname;
  char asize[10];
  char *dummy = "";
  char *clp[3] = {dummy, fullname, asize};
  struct stat st;
  GdkColor background;
  GdkColormap *colormap;
  int i;

  for (i=0; i < GTK_CLIST(filebox)->rows; i++) {
    gtk_clist_get_text (GTK_CLIST(filebox), i, 1, &fname);

    if (!strcmp (fname, fullname))
      return 0;
  }

  /* Obviously the file wasn't found, so it needs to be added */
  if (stat (fullname, &st))
    return 0;

#if defined _FILE_OFFSET_BITS && _FILE_OFFSET_BITS == 64
  snprintf (asize, sizeof (asize), "%lld", (st.st_size+1023)/1024);
#else
  snprintf (asize, sizeof (asize), "%ld", (st.st_size+1023)/1024);
#endif

  gtk_clist_append (GTK_CLIST(filebox), clp);

  background.red = background.green = background.blue =  ~0;
  colormap = gdk_colormap_get_system();
  gdk_color_alloc (colormap, &background);

  gtk_clist_set_background (GTK_CLIST(filebox), GTK_CLIST(filebox)->rows-1, &background);
  if (S_ISDIR(st.st_mode)) 
    gtk_clist_set_pixmap (GTK_CLIST(filebox), GTK_CLIST(filebox)->rows-1, 0, dir_pixmap, dir_mask);
  else
    gtk_clist_set_pixmap (GTK_CLIST(filebox), GTK_CLIST(filebox)->rows-1, 0, doc_pixmap, doc_mask);

  return 1;
}

