# The GIMP -- an image manipulation program
# Copyright (C) 1995, 1996, 1997 Spencer Kimball and Peter Mattis
# Copyright (C) 1997 Josh MacDonald

# 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-1307, USA.

# "Perlized" from C source by Manish Singh <yosh@gimp.org>

sub pdb_misc {
    $author = $copyright = 'Josh MacDonald';
    $date = '1997';
}

sub list_arg {
    my ($type, $name, $desc, $example) = @_;
    push @inargs, { name => $name, type => 'string', no_success => 1,
		    desc => qq/comma separated list of $desc this handler
			       can $type (i.e. "$example")/ }
}

sub handler_args {
    my $type = shift;

    my $action = $type;
    $action =~ s/e$//;
    $action .= 'ing';

    push @inargs, { name => 'procedure_name', type => 'string',
		    desc => "The name of the procedure to be used for $action",
		    alias => 'name' };

    foreach ([ 'extensions', 'jpg,jpeg' ], [ 'prefixes', 'http:,ftp:' ]) {
	&list_arg($type, $_->[0], @$_);
    }
}

# The defs

sub file_load {
    $blurb = 'Loads a file by extension.';

    $help = <<'HELP';
This procedure invokes the correct file load handler according to the file's
extension and/or prefix. The name of the file to load is typically a full
pathname, and the name entered is what the user actually typed before
prepending a directory path. The reason for this is that if the user types
http://www.xcf/~gimp/ he wants to fetch a URL, and the full pathname will not
look like a URL.
HELP

    &pdb_misc;

    @inargs = (
	{ name => 'run_mode',
	  type => 'enum RunModeType (no RUN_WITH_LAST_VALS)',
	  desc => 'The run mode: %%desc%%' },
	{ name => 'filename', type => 'string',
	  desc => 'The name of the file to load' },
	{ name => 'raw_filename', type => 'string',
	  desc => 'The name entered' }
    );

    @outargs = ( &std_image_arg );
    $outargs[0]->{desc} = 'The output image';

    %invoke = (
	proc => [ 'proc->name', 'args' ],
	vars => [ 'PlugInProcDef *file_proc', 'ProcRecord *proc' ],
	code => <<'CODE'
{
  file_proc = file_proc_find (load_procs, %%raw_filename%%);
  if (!file_proc)
    return %%fail%%;

  proc = &file_proc->db_info;

  return %%exec%%;
}
CODE
    );
}

sub file_save {
    $blurb = 'Saves a file by extension.';

    $help = <<'HELP';
This procedure invokes the correct file save handler according to the file's
extension and/or prefix. The name of the file to save is typically a full
pathname, and the name entered is what the user actually typed before
prepending a directory path. The reason for this is that if the user types
http://www.xcf/~gimp/ she wants to fetch a URL, and the full pathname will not
look like a URL.
HELP

    &pdb_misc;

    @inargs = (
	{ name => 'run_mode',
	  type => 'enum RunModeType (no RUN_WITH_LAST_VALS)',
	  desc => 'The run mode: %%desc%%' },
	{ name => 'image', type => 'image',
	  desc => 'Input image' },
	{ name => 'drawable', type => 'drawable',
	  desc => 'Drawable to save' },
	{ name => 'filename', type => 'string',
	  desc => 'The name of the file to save the image in' },
	{ name => 'raw_filename', type => 'string',
	  desc => 'The name of the file to save the image in' }
    );


    %invoke = (
	headers => [ qw(<string.h>) ],
	proc => [ 'proc->name', 'new_args' ],
	args => [ 'new_args', 'return_vals' ],
	vars => [ 'PlugInProcDef *file_proc', 'ProcRecord *proc', 'gint i' ],
	code => <<'CODE'
{
  file_proc = file_proc_find (save_procs, %%raw_filename%%);
  if (!file_proc) 
    return %%fail%%;

  proc = &file_proc->db_info;

  new_args = g_new (%%argtype%%, proc->num_args);
  memset (new_args, 0, sizeof (%%argtype%%) * proc->num_args);
  memcpy (new_args, args, sizeof (%%argtype%%) * 5);

  for (i=5; i<proc->num_args; i++)
  {
    new_args[i].arg_type = proc->args[i].arg_type;
    if (proc->args[i].arg_type == PDB_STRING)
      new_args[i].value.pdb_pointer = g_strdup("\0");
  }

  return_vals = %%exec%%;
  g_free (new_args);

  return return_vals;
}
CODE
    );
}

sub file_load_thumbnail {
    $blurb = 'Loads the thumbnail for a file.';

    $help = <<'HELP';
This procedure tries to load a thumbnail that belongs to the file with
the given filename. This name is a full pathname. The returned data is 
an array of colordepth 3 (RGB), regardless of the image type. Width and 
height of the thumbnail are also returned. Don't use this function if 
you need a thumbnail of an already opened image, use gimp_image_thumbnail 
instead.
HELP

    $author = $copyright = 'Adam D. Moss, Sven Neumann';
    $date = '1999-2000';

    @inargs = (
	{ name => 'filename', type => 'string',
	  desc => 'The name of the file that owns the thumbnail to load' },
    );

    @outargs = ( 
	{ name => 'width', type => 'int32', init => 1,
	  desc => 'The width of the thumbnail' },
	{ name => 'height', type => 'int32', init => 1, 
	  desc => 'The height of the thumbnail' },
	{ name => 'thumb_data', type => 'int8array', init => 1,
	  desc => 'The thumbnail data', 
          array =>  { name => 'thumbnail_data_count',
		      desc => 'The number of bytes in thumbnail data',
		      alias => 'num_bytes', init => 1 } },
    );

    %invoke = (
        headers => [ qw("fileopsP.h") ],
	vars => [ 'gchar *pname', 'gchar *fname', 'gchar *tname',
		  'guchar *raw_thumb', 'gchar *imginfo = NULL', 'gint i' ],
	code => <<'CODE'
{
  pname = g_dirname (filename);
  fname = g_basename (filename);
  tname = g_strconcat (pname, G_DIR_SEPARATOR_S, ".xvpics", G_DIR_SEPARATOR_S,
		       fname,
		       NULL);
  g_free (pname);
  raw_thumb = readXVThumb (tname, &width, &height, &imginfo);
  g_free (tname);

  if (raw_thumb)
    {
      num_bytes = 3 * width * height;
      thumb_data = g_malloc (num_bytes);
	  
      for (i=0; i<width*height; i++)
        {
	  thumb_data[i*3  ] = ((raw_thumb[i]>>5)*255)/7;
	  thumb_data[i*3+1] = (((raw_thumb[i]>>2)&7)*255)/7;
	  thumb_data[i*3+2] = (((raw_thumb[i])&3)*255)/3;
	}
      g_free (raw_thumb);
      success = TRUE;
    }
  else
    success = FALSE;
}
CODE
    );
}

sub file_save_thumbnail {
    $blurb = 'Saves a thumbnail for the given image';

    $help = <<'HELP';
This procedure saves a thumbnail in the .xvpics format for the given image.
The thumbnail is saved so that it belongs to the file with the given
filename. This means you have to save the image under this name first, 
otherwise this procedure will fail. This procedure may become useful if
you want to explicitely save a thumbnail with a file. 
HELP

    &pdb_misc;

    @inargs = (
	&std_image_arg,
	{ name => 'filename', type => 'string',
	  desc => 'The name of the file the thumbnail belongs to' },
    );

    %invoke = (
        headers => [ qw("fileopsP.h") ],
	vars => [ 'TempBuf *thumb' ],
	code => <<'CODE'
{
  thumb = make_thumb_tempbuf (gimage);
  if (file_save_thumbnail (gimage, filename, thumb))
    success = TRUE;
}
CODE
    );
}

sub temp_name {
    $blurb = 'Generates a unique filename.';

    $help = <<'HELP';
Generates a unique filename using the temp path supplied in the user's gimprc.
HELP

    &pdb_misc;

    @inargs = (
	{ name => 'extension', type => 'string',
	  desc => 'The extension the file will have' }
    );

    @outargs = (
	{ name => 'name', type => 'string', init => 1,
	  desc => 'The new temp filename' }
    );

    %invoke = (
	headers => [ qw("gimprc.h") ],
	vars => [ 'static gint id = 0', 'static gint pid' ],
	code => <<'CODE'
{
  if (id == 0)
    pid = getpid();

  name = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "gimp_temp.%d%d.%s",
			  temp_path, pid, id++, extension);
}
CODE
    );
}

sub register_magic_load_handler {
    $blurb = 'Registers a file load handler procedure.';

    $help = <<'HELP';
Registers a procedural database procedure to be called to load files of a 
particular file format using magic file information.
HELP

    &std_pdb_misc;

    &handler_args('load');
    &list_arg('load', 'magics', 'magic file information', '0,string,GIF');

    %invoke = (
	vars => [ 'ProcRecord *proc', 'PlugInProcDef *file_proc' ],
	code => <<'CODE'
{
  success = FALSE;

  proc = procedural_db_lookup (name);

  if (proc && ((proc->num_args < 3) ||
	       (proc->num_values < 1) ||
	       (proc->args[0].arg_type != PDB_INT32) ||
	       (proc->args[1].arg_type != PDB_STRING) ||
	       (proc->args[2].arg_type != PDB_STRING) ||
	       (proc->values[0].arg_type != PDB_IMAGE)))
    {
      g_message ("load handler \"%s\" does not take the standard load handler args",
		 name);
      goto done;
    }

  file_proc = plug_in_file_handler (name, extensions, prefixes, magics);

  if (!file_proc)
    {
      g_message ("attempt to register non-existant load handler \"%s\"",
		 name);
      goto done;
    }

  load_procs = g_slist_prepend (load_procs, file_proc);

  success = TRUE;

done: ;
}
CODE
    );
}

sub register_load_handler {
    $blurb = 'Registers a file load handler procedure.';

    $help = <<'HELP';
Registers a procedural database procedure to be called to load files of a
particular file format.
HELP

    &std_pdb_misc;

    &handler_args('load');

    %invoke = (
	pass_through => 'register_magic_load_handler',
	pass_args => [ 0..2 ],
	make_args => [ { type => 'string', code => '%%arg%% = NULL;' } ]
    );
}

sub register_save_handler {
    $blurb = 'Registers a file save handler procedure.';

    $help = <<'HELP';
Registers a procedural database procedure to be called to save files in a
particular file format.
HELP

    &std_pdb_misc;

    &handler_args('save');

    %invoke = (
	vars => [ 'ProcRecord *proc', 'PlugInProcDef *file_proc' ],
	code => <<'CODE'
{
  success = FALSE;

  proc = procedural_db_lookup (name);

  if (proc && ((proc->num_args < 5) ||
	       (proc->args[0].arg_type != PDB_INT32) ||
	       (proc->args[1].arg_type != PDB_IMAGE) ||
	       (proc->args[2].arg_type != PDB_DRAWABLE) ||
	       (proc->args[3].arg_type != PDB_STRING) ||
	       (proc->args[4].arg_type != PDB_STRING)))
    {
      g_message ("save handler \"%s\" does not take the standard save handler args",
		 name);
      goto done;
    }

  file_proc = plug_in_file_handler (name, extensions, prefixes, NULL);

  if (!file_proc)
    {
      g_message ("attempt to register non-existant save handler \"%s\"",
		 name);
      goto done;
    }

  save_procs = g_slist_prepend (save_procs, file_proc);

  success = TRUE;

done: ;
}
CODE
    );
}

@headers = qw("fileops.h" "plug_in.h" "config.h" <unistd.h>);

@procs = qw(file_load file_save file_load_thumbnail file_save_thumbnail
	    temp_name register_magic_load_handler register_load_handler
	    register_save_handler);
%exports = (app => [@procs], lib => [@procs[5..7]]);

$desc = 'File Operations';

1;
