/*
** 1998-05-25 -	This module deals with formatting directory pane entries for display.
**		That's all it does, but since that's a fairly involved thing to do
**		(we aim for plenty of flexibility here), it deserves a module of its
**		own.
** 1999-05-15 -	Added the utility dpf_set_default_format() funtion, for cfg_dirpane.
** 1999-05-20 -	Adapted for the new ultra-flexible & dynamic styles subsystem. Now
**		does three hash-lookups rather than three vector-dittos per row. :)
*/

#include "gentoo.h"

#include <time.h>

#include "dpformat.h"
#include "userinfo.h"
#include "iconutil.h"
#include "sizeutil.h"
#include "strutil.h"

/* ----------------------------------------------------------------------------------------- */

static const gchar	*content_name[] = {"Name", "Size", "Blocks", "Smart Size", "Mode, numerical", "Mode, string",
			"Number of links", "Owner ID", "Owner Name", "Group ID",
			"Group Name",
			"Device Number", "Device Number, major", "Device Number, minor",
			"Date of last Access", "Date of last Modification", "Date of Creation",
			"Type Name",
			"Icon" },
			*content_title[] = {"Name", "Size", "Blocks", "IQSize", "Mode", "Mode",
			"Nlink", "Uid", "Uname", "Gid",
			"Gname", "Device", "DevMaj",
			"DevMin", "Accessed", "Modified", "Created", "Type",
			"I" };

/* ----------------------------------------------------------------------------------------- */

/* 1999-05-15 -	Get the "official" content name for column content number <content>. */
const gchar * dpf_get_content_name(DPContent content)
{
	if(content >= 0 && content < sizeof content_name / sizeof content_name[0])
		return content_name[content];
	return NULL;
}

/* 1999-05-15 -	Map a string to a DPContent integer. Returns an illegal index if <name> is bad. */
DPContent dpf_get_content_from_name(const gchar *name)
{
	guint	i;

	for(i = 0; i < sizeof content_name / sizeof content_name[0]; i++)
	{
		if(strcmp(content_name[i], name) == 0)
			return (DPContent) i;
	}
	return DPC_NUM_TYPES;
}

/* 1999-05-15 -	Get a recommended column title for a column showing <content>. */
const gchar * dpf_get_content_title(DPContent content)
{
	if(content >= 0 && content < sizeof content_title / sizeof content_title[0])
		return content_title[content];
	return NULL;
}

/* ----------------------------------------------------------------------------------------- */

void dpf_set_default_format(DpCFmt *fmt, DPContent content)
{
	str_strncpy(fmt->title, dpf_get_content_title(content), sizeof fmt->title);
	fmt->content = content;
	fmt->just = GTK_JUSTIFY_LEFT;
	fmt->width = 50;

	switch(fmt->content)
	{
		case DPC_NAME:
			fmt->extra.name.show_type = 0;
			fmt->width = 250;
			break;
		case DPC_SIZE:
			str_strncpy(fmt->extra.size.format, "%lu", sizeof fmt->extra.size.format);
			fmt->extra.size.dir_show_fs_size = 1;
			fmt->just = GTK_JUSTIFY_RIGHT;
			break;
		case DPC_BLOCKS:
			str_strncpy(fmt->extra.blocks.format, "%lu", sizeof fmt->extra.blocks.format);
			break;
		case DPC_IQSIZE:
			fmt->extra.iqsize.dir_show_fs_size = 1;
			break;
		case DPC_MODENUM:
			str_strncpy(fmt->extra.mode.format, "%o", sizeof fmt->extra.mode.format);
			break;
		case DPC_NLINK:
			str_strncpy(fmt->extra.nlink.format, "%u", sizeof fmt->extra.nlink.format);
			fmt->width = 75;
			break;
		case DPC_UIDNUM:
			str_strncpy(fmt->extra.uidnum.format, "%u", sizeof fmt->extra.uidnum.format);
			fmt->width = 75;
			break;
		case DPC_GIDNUM:
			str_strncpy(fmt->extra.gidnum.format, "%u", sizeof fmt->extra.gidnum.format);
			fmt->width = 75;
			break;
		case DPC_DEVICE:
			str_strncpy(fmt->extra.device.format, "%u", sizeof fmt->extra.device.format);
			fmt->width = 75;
			break;
		case DPC_DEVMAJ:
			str_strncpy(fmt->extra.devmaj.format, "%u", sizeof fmt->extra.devmaj.format);
			fmt->width = 75;
			break;
		case DPC_DEVMIN:
			str_strncpy(fmt->extra.devmin.format, "%u", sizeof fmt->extra.devmin.format);
			fmt->width = 75;
			break;
		case DPC_ATIME:
			str_strncpy(fmt->extra.a_time.format, "%Y-%m-%d %H:%M:%S", sizeof fmt->extra.a_time.format);
			fmt->width = 184;
			break;
		case DPC_CTIME:
			str_strncpy(fmt->extra.c_time.format, "%Y-%m-%d %H:%M:%S", sizeof fmt->extra.c_time.format);
			fmt->width = 184;
			break;
		case DPC_MTIME:
			str_strncpy(fmt->extra.m_time.format, "%Y-%m-%d %H:%M:%S", sizeof fmt->extra.c_time.format);
			fmt->width = 184;
			break;
		case DPC_TYPE:
			break;
		case DPC_ICON:
			fmt->width = 16;
			fmt->just = GTK_JUSTIFY_CENTER;
			break;
		default:
			;
	}
}

/* 1998-10-15 -	Moved this old code out of the main module, since it really didn't belong
**		in there.
** 1999-05-15 -	Thanks to the slightly more general routine above, this could be simplified. Great.
** 1999-05-16 -	Now also initializes the default colors.
*/
void dpf_init_defaults(CfgInfo *cfg)
{
	DPFormat	*fmt = &cfg->dp_format[0];
	guint		i;

	for(i = 0; i < 15; i++)
		dpf_set_default_format(&fmt->format[i], (DPContent) i);
	fmt->num_columns = i;

	fmt->sort.column = 0;
	fmt->sort.invert = FALSE;
	fmt->sort.mode   = DPS_DIRS_FIRST;

	strcpy(fmt->def_path, ".");
	fmt->path_above = 0;
	fmt->hide_allowed = 1;
	fmt->scrollbar_always = 0;
	fmt->ctrl_mode = CTM_SET;

	cfg->dp_format[1] = cfg->dp_format[0];

	strcpy(cfg->dp_format[1].def_path, ".");

	cfg->dp_colors.color[DPCOL_PANE_SELECTED].red	= 0xEFBE;
	cfg->dp_colors.color[DPCOL_PANE_SELECTED].green	= 0xEBAD;
	cfg->dp_colors.color[DPCOL_PANE_SELECTED].blue	= 0xFFFF;
	cfg->dp_colors.color[DPCOL_PANE_SELECTED].pixel	= 0UL;

	cfg->dp_colors.color[DPCOL_FOCUS_UNSELECTED].red   = 0xAEBA;
	cfg->dp_colors.color[DPCOL_FOCUS_UNSELECTED].green = 0x0000;
	cfg->dp_colors.color[DPCOL_FOCUS_UNSELECTED].blue  = 0xF7DE;
	cfg->dp_colors.color[DPCOL_FOCUS_UNSELECTED].pixel = 0UL;

	cfg->dp_colors.color[DPCOL_FOCUS_SELECTED].red	   = 0xAEBA;
	cfg->dp_colors.color[DPCOL_FOCUS_SELECTED].green   = 0x0000;
	cfg->dp_colors.color[DPCOL_FOCUS_SELECTED].blue	   = 0x9E79;
	cfg->dp_colors.color[DPCOL_FOCUS_SELECTED].pixel   = 0UL;
}

/* ----------------------------------------------------------------------------------------- */

/* 1998-09-22 -	Format a name with additional type information in it (slash for directories,
**		asterisk for executables, et cetera). Think ls -F.
*/
static void format_typed_name(gchar *out, const gchar *name, mode_t mode)
{
	if(S_ISLNK(mode))
		sprintf(out, "%s@", name);
	else if(S_ISDIR(mode))
		sprintf(out, "%s/", name);
	else if(S_ISREG(mode) && (mode & S_IXUSR))
		sprintf(out, "%s*", name);
	else if(S_ISFIFO(mode))
		sprintf(out, "%s|", name);
	else if(S_ISSOCK(mode))
		sprintf(out, "%s=", name);
	else
		strcpy(out, name);
}

/* ----------------------------------------------------------------------------------------- */

/* 1999-01-08 -	Put a size (regular or "IQSize") at <out>. Assumes <out> can hold 64 bytes.
** 1999-03-27 -	Rewritten for new flags handling. Cleaner & shorter, too!
*/
static void put_size(gchar *out, const gchar *fmt, DirRow *row, gint iq, gint dir_fs)
{
	gsize	size = DP_ROW_LSTAT(row).st_size;

	out[0] = '\0';

	if(DP_ROW_FLAGS_CHK(row, DPRF_HAS_SIZE))		/* Does the row have a "real" size? */
	{
		if(iq)
			sze_put_size(size, out, 64, SZE_AUTO);
		else
			g_snprintf(out, 64, fmt, size);
	}
	else if(S_ISDIR(DP_ROW_LSTAT(row).st_mode) && dir_fs)	/* If no, do we show directories' fs sizes? */
	{
		gint	len;

		out[0] = '(';
		if(iq)
			len = sze_put_size(size, out + 1, 63, SZE_AUTO);
		else
			len = g_snprintf(out + 1, 63, fmt, size);
		out[len + 1] = ')';
		out[len + 2] = '\0';
	}
}

/* 1998-05-23 -	Format column <column> of given directory line into <out>.
** 1998-05-31 -	Added support for showing the device number (and also to split it into its major and minor
**		components, of course).
** 1998-06-21 -	Added the <dp> argument, since it is required to find the formatting info nowadays.
**		Implemented framework for supporting column-specific configuration. Excellent place to stuff
**		the formatting strings used for date columns, for example.
** 1998-06-24 -	By direct logical extension, I made all numerical columns' formatting configurable.
** 1998-08-10 -	Made this routine a bit more complex, and added it's friend the post-insertion
**		dpf_post_format_column() function (below). If a call to that function is necessary _after_
**		the row being formatted has been added, this function will return 1. Otherwise 0 is returned.
*/
gint dpf_format_column(MainInfo *min, DirPane *dp, DirRow *row, guint column, gchar *out)
{
	DPFormat	*fmt;
	DpCFmt		*col_fmt;
	struct tm	*tm;
	const char	*name;

	fmt = &min->cfg.dp_format[dp->index];
	if(column < fmt->num_columns)
	{
		col_fmt = &fmt->format[column];

		switch(col_fmt->content)
		{
			case DPC_NAME:
				if(col_fmt->extra.name.show_type)
					format_typed_name(out, DP_ROW_NAME(row), DP_ROW_LSTAT(row).st_mode);
				else
					sprintf(out, "%s", DP_ROW_NAME(row));
				if(S_ISLNK(DP_ROW_LSTAT(row).st_mode) && col_fmt->extra.name.show_linkname)
				{
					strcat(out, " -> ");
					strcat(out, DP_ROW_LINKNAME(row));
				}
				break;
			case DPC_SIZE:
				put_size(out, col_fmt->extra.size.format, row, FALSE, col_fmt->extra.size.dir_show_fs_size);
				break;
			case DPC_BLOCKS:
				sprintf(out, col_fmt->extra.blocks.format, DP_ROW_LSTAT(row).st_blocks);
				break;
			case DPC_IQSIZE:
				put_size(out, NULL, row, TRUE, col_fmt->extra.iqsize.dir_show_fs_size);
				break;
			case DPC_MODENUM:
				sprintf(out, col_fmt->extra.mode.format, DP_ROW_LSTAT(row).st_mode);
				break;
			case DPC_MODESTR:
				str_mode_to_text(out, DP_ROW_LSTAT(row).st_mode, 32);
				break;
			case DPC_NLINK:
				sprintf(out, col_fmt->extra.nlink.format, DP_ROW_LSTAT(row).st_nlink);
				break;
			case DPC_UIDNUM:
				sprintf(out, col_fmt->extra.uidnum.format, DP_ROW_LSTAT(row).st_uid);
				break;
			case DPC_UIDSTR:
				if((name = usr_lookup_uname(DP_ROW_LSTAT(row).st_uid)) != NULL)
					strcpy(out, name);
				else
					sprintf(out, "%d", (int) DP_ROW_LSTAT(row).st_uid);
				break;
			case DPC_GIDNUM:
				sprintf(out, col_fmt->extra.gidnum.format, DP_ROW_LSTAT(row).st_gid);
				break;
			case DPC_GIDSTR:
				if((name = usr_lookup_gname(DP_ROW_LSTAT(row).st_gid)) != NULL)
					strcpy(out, name);
				else
					sprintf(out, "%d", (int) DP_ROW_LSTAT(row).st_gid);
				break;

			case DPC_DEVICE:
				sprintf(out, col_fmt->extra.device.format, DP_ROW_LSTAT(row).st_rdev);
				break;
			case DPC_DEVMAJ:
				sprintf(out, col_fmt->extra.devmaj.format, DP_ROW_LSTAT(row).st_rdev >> 8);
				break;
			case DPC_DEVMIN:
				sprintf(out, col_fmt->extra.devmin.format, DP_ROW_LSTAT(row).st_rdev & 0xFF);
				break;

			case DPC_ATIME:
				if((tm = localtime(&DP_ROW_LSTAT(row).st_atime)) != NULL)
					strftime(out, 32, col_fmt->extra.a_time.format, tm);
				break;
			case DPC_MTIME:
				if((tm = localtime(&DP_ROW_LSTAT(row).st_mtime)) != NULL)
					strftime(out, 32, col_fmt->extra.m_time.format, tm);
				break;
			case DPC_CTIME:
				if((tm = localtime(&DP_ROW_LSTAT(row).st_ctime)) != NULL)
					strftime(out, 32, col_fmt->extra.c_time.format, tm);
				break;
			case DPC_TYPE:
				if(DP_ROW_TYPE(row) != NULL)
					sprintf(out, "%s", DP_ROW_TYPE(row)->name);
				else
					sprintf(out, "<NULL>");
				break;
			case DPC_ICON:
				out[0] = '\0';
				return 1;
			case DPC_NUM_TYPES:
				fprintf(stderr, "**DPFORMAT: Mysterious!\n");
				break;
		}
	}
	return 0;
}

/* 1998-08-11 -	Format the given row, once it has actually been added to the dirpane. Modified
**		from a routine created yesterday. Takes into account the selection-state for
**		the row, and sets the colors accordingly. This is called when the user does a
**		selection/unselection, too.
** 1998-09-19 -	Something in the clist color setting seems to clear errno sometimes (!), which
**		really isn't acceptable. So now we just save and restore errno. Stupid.
** 1999-03-04 -	No longer cares about the old "selected" flag, since it's no longer there.
*/
void dpf_post_format_row(MainInfo *min, DirPane *dp, gint row)
{
	DPFormat	*fmt;
	const gchar	*iname;
	guint		col;
	gint		oe = errno;
	Style		*stl;
	GdkPixmap	*ipix;
	GdkBitmap	*imsk;

	fmt = &min->cfg.dp_format[dp->index];
	stl = DP_ROW_TYPE(&dp->dir.line[row])->style;
	if(stl == NULL)
	{
		fprintf(stderr, "DPFORMAT: No style for '%s'\n", DP_ROW_NAME(&dp->dir.line[row]));
		return;
	}

	iname = stl_style_property_get_icon(stl, SPN_ICON_UNSEL);
	for(col = 0; col < min->cfg.dp_format[dp->index].num_columns; col++)
	{
		if(fmt->format[col].content == DPC_ICON)
		{
			if((ipix = ico_icon_get(min, GTK_WIDGET(dp->list)->window, iname, &imsk)) != NULL)
				gtk_clist_set_pixmap(GTK_CLIST(dp->list), row, col, ipix, imsk);
			else
				gtk_clist_set_text(GTK_CLIST(dp->list), row, col, "");
		}
	}
	dpf_format_colors_row(dp, row);
	errno = oe;
}

/* 1999-05-10 -	Set colors of <row> in <dp> to the correct style's colors. */
void dpf_format_colors_row(DirPane *dp, gint row)
{
	Style	*stl;

	stl = DP_ROW_TYPE(&dp->dir.line[row])->style;

	gtk_clist_set_background(GTK_CLIST(dp->list), row, (GdkColor *) stl_style_property_get_color(stl, SPN_COL_UNSEL_BG));
	gtk_clist_set_foreground(GTK_CLIST(dp->list), row, (GdkColor *) stl_style_property_get_color(stl, SPN_COL_UNSEL_FG));
}
