/*
 * Simple GTK version of less, requires objc-runtime with threads!
 */

#include <stdio.h>
#include <stdlib.h>
#include <Foundation/NSAutoreleasePool.h>
#include <Foundation/NSString.h>
#include <Foundation/NSThread.h>
#include <GToolKit/GToolKit.h>

@interface GLess : NSObject
{
    GTKText *text;
    GdkFont *font;
}
- (void) readInput:(id) ignore;
@end

@implementation GLess

- init
{
    GTKWindow *window = [GTKWindow windowWithType:GTK_WINDOW_TOPLEVEL];
    GTKScrolledWindow *scroll =
	[GTKScrolledWindow scrolledWindowWithHadjustment:nil vadjustment:nil];

    [super init];
    text = [GTKText textWithHadj:nil vadj:nil];
    font = gdk_font_load("-*-courier-medium-r-*--12-*-*-*-m-*-iso8859-1");

    [scroll add:text];
    [scroll setPolicy:GTK_POLICY_NEVER vscrollbarPolicy:GTK_POLICY_ALWAYS];

    [window setTitle:@"GLess - Output Window"];
    [window setBorderWidth:2];
    [window add:scroll];
    [window setUsize:480 height:240];
    [window show];

    [text setEditable:NO];
    [text grabFocus];

    [NSThread detachNewThreadSelector:@selector(readInput:)
	      toTarget:self withObject:nil];
    return self;
}

/*
 * This method will read blocks of data from stdin (in the background).
 */
- (void) readInput:(id) ignore
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    char buffer[256];
    size_t length;

    while ((length = fread(buffer, 1, sizeof buffer, stdin)) > 0)
    {
	gdk_threads_enter();

	[text freeze];		// this should not be necessary
	[text insert:font fore:NULL back:NULL
	      chars:[NSString stringWithCString:buffer] length:length];
	[text thaw];

	gdk_threads_leave();
    }

    [pool release];
}
@end

int main (int argc, char *argv[])
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
#ifdef LIB_FOUNDATION_LIBRARY
    extern char **environ;
    [NSProcessInfo initializeWithArguments:argv count:argc environment:environ];
#endif

    /* initialize glib thread support */
    g_thread_init(NULL);

    if (argc > 1 && !freopen(argv[1], "r", stdin)) perror(argv[1]), exit(1);

    [[GTKApplication alloc] initWithArgc:&argc argv:&argv];
    [[GLess new] autorelease];

    [GTKApp run];
    [pool release];
    return 0;
}
