
#pragma .h #import <IconKit/iconkit.h>

#include <stdlib.h>
#include <string.h>

#import <AppKit/NSApplication.h>
#import <AppKit/NSWorkspace.h>

#import "File.h"
#import "FileManager.h"
#import "AppDelegate.h"


static int compare_names (const void * one,  const void * two)
{
    id A = * ((id *) one),
       B = * ((id *) two);

    return [[(IKFolder *)A name] compare:[(IKFolder *)B name] options:NSCaseInsensitiveSearch];
}


@implementation FileManager: IKBrowserManager
{
    id window;
    id shelf;
}

#define OFFSET	30

static int viewers = 0;

- init
{
    if(self = [super init]) {
        NSRect	frame;
        int	dx = (viewers++ % 10) * OFFSET;

        [NSBundle loadNibNamed:@"FileManager.nib" owner:self];
        [shelf setClassToHold:@"File"];
        [shelf addListener: [File  class]];
        [shelf setTarget:browser];
        [shelf setAction:@selector(takePathFrom:)];
        [shelf setDoubleAction:@selector(doDoubleClick:)];

        [browser setAllowsBranchSelection:YES];

        frame = [window frame];
        frame.origin.x += dx;
        frame.origin.y -= dx;
        [window setFrameOrigin:frame.origin];
    }
    return self;
}

- (void)dealloc
{
    [shelf removeListener:[File class]];
    [window release];
    window = nil;
    [super dealloc];
}

- sort: (id *) files  count: (int) n  for: (int) column
{
    qsort(files, n, sizeof(id), compare_names);
    return self;
}

- browserDoubleClicked:sender
{
    id	 file = [[[browser iconPath] selectedCell] delegate];
    NSString *appName;
    NSString *type;

    [[NSWorkspace sharedWorkspace]  getInfoForFile:[file path] application:&appName type:&type];
    if([type isEqual:NSDirectoryFileType]) {
        [self openFolder:sender];
    } else {
        [self openFile:sender];
    }
    return self;
}

- (void)openFile:(id)sender
{
    NSRect frame;
    id	   iconPath = [browser  iconPath],
           cell = [iconPath  selectedCell],
           file = [cell  delegate];

    frame = [iconPath  cellFrameAtRow:0  column:[iconPath selectedColumn]];
    frame = [cell  imageRectForBounds:frame];
    frame.origin.y += frame.size.height;

    [[NSWorkspace sharedWorkspace] openFile: [file path]
                                  fromImage: [file  image]
                                         at:frame.origin
                                     inView: iconPath];
}

- (void)openFolder:(id)sender
{
    id file = [[[browser iconPath] selectedCell] delegate];
    id fileManager = [[FileManager alloc] init];
    [fileManager setRoot:file];
    [[[fileManager shelf] cellAtRow:0 column:0] setDelegate:file];
    [[fileManager window] setTitleWithRepresentedFilename:[file path]];
    [[fileManager window] makeKeyAndOrderFront:self];
}

- (void)windowWillClose:(NSNotification *)notification
{
    [window setDelegate:nil];
    [self autorelease];
}

- window
{
    return window;
}

- browser
{
    return browser;
}

- shelf
{
    return shelf;
}

@end
