#!/usr/local/bin/pike
// This is -*- pike -*- code.

// This small (when you reamove all comments. :-)) program displays
// images in windows.

// A window that shows an (optinally shaped) image. The window has the
// override-redirect flag set, this means that it won't get any
// decorations from the window manager, and it is thus not possible ot
// move it. Therefore there is also code in here to let the user move
// the window in a somewhat intuitive fashion.
class MoveableShapedWindow
{
  inherit GTK.Window;
  static GTK.DrawingArea da;

  static int x,y; // Position of the last mouse button press

  static void moved(int i, object wi, mapping evnt)
  {
    set_uposition( (int)(evnt->x_root-x), (int)(evnt->y_root-y) );
  }

  static void pressed(int i, object wi, mapping evnt)
  {
    x = (int)evnt->x;
    y = (int)evnt->y;
  }

  int set_shaped_image(string f)
  {
    mapping i = GTK.Util.load_image( f );

    if(!i) 
      return 0; // No such image, bad luck.

    // Set the size of the window, the background of the drawing area
    // (which recides in the window) and the shape of the window.
    set_usize( i->img->xsize(), i->img->ysize() );
    da->set_background( i->img );

    if(i->alpha) 
      shape_combine_mask( i->alpha, 0, 0 );

    return 1; // all ok.
  }

  // The constructor.
  void create()
  {
    ::create( GTK.WindowPopup ); // Call the constructor in the parent.
    
    // Do not let the user resize the window, but automatically resize
    // to fit the contents.
    set_policy(0,0,1);

    // Let the window receive button press and button motion events,
    // and bind them to the callback functions
    set_events( GDK.ButtonPressMask | GDK.Button1MotionMask );
    signal_connect(GTK.button_press_event, pressed );
    signal_connect(GTK.motion_notify_event, moved );

    // Add a drawing area.
    da = GTK.DrawingArea();
    add( da->show() );
  }
}


int main(int argc, array(string) argv)
{
  int loaded;
  // Set up GTK, the name of the client is 'gwashuu'.
  GTK.setup_gtk("gwashuu");

  // For each file, create a window with the image in it.
  foreach(argv[1..], string file)
  {
    MoveableShapedWindow win = MoveableShapedWindow()->show();
    if(!win->set_shaped_image( file ))
    {
      werror("Failed to use image '"+file+"'\n");
      destruct(win);
    } else
      loaded++;
  }

  if(!loaded)
  {
    werror("Failed to load any images at all.\n");
    _exit(1);
  }
  return -1;
}

