/*
   Controller.m
   
   Controller object for mySTEP Workspace

   Copyright (C) 1996 Free Software Foundation, Inc.
   
   Author:  Felipe A. Rodriguez <far@ix.netcom.com>
   Date:	November 1998
   
   This file is part of the mySTEP Library and is provided
   under the terms of the GNU Library General Public License.
*/

#include <AppKit/AppKit.h>

#include "Shelf.h"
#include "Controller.h"
#include "Browser.h"
#include "Finder.h"
#include "Matrix.h"
#include "Cell.h"


@implementation Controller

- (void) applicationDidFinishLaunching:(NSNotification *)aNotification
{
id browserCell;
NSRect wr = {{100, 100}, {550, 580}};
NSRect browserRect = {{0, 0}, {520, 340}};
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float h = [[defaults objectForKey:@"Divider"] floatValue];

	[NSApp setApplicationIconImage:[NSImage imageNamed:@"cabinet.tiff"]];
																
	browserCell = [[[BrowserCell alloc] init] autorelease];

	if(h > 0 && h < NSHeight(wr))
		NSHeight(browserRect) = h;						 
	_browser = [[Browser alloc] initWithFrame: browserRect];	// create the
	[_browser setDelegate: [IconViewDelegate new]];				// file browser
	[_browser setMaxVisibleColumns: 1];
	[_browser setCellPrototype:browserCell];
	[_browser setHasHorizontalScroller:NO];
	_iconView = [_browser retain];

	_shelf = [[Shelf alloc] initWithFrame:wr rows:3 cols:7 subView:_browser];
	[[_shelf matrix] restoreState];
	[_shelf makeFirstResponder:_browser];		
	[_shelf setTitle:@"Workspace"];
	[_shelf display];
	[_shelf orderFront:nil];
}

- (void) applicationWillTerminate:(NSNotification *)aNotification
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int h = (int)[_browser frame].size.height;
NSString *dividerLocation = [[NSNumber numberWithInt: h] stringValue];

	[defaults setObject:dividerLocation forKey:@"Divider"];
	[defaults setObject: [[_shelf matrix] saveState] forKey: @"Shelf"];
	[defaults synchronize];
}

- (BOOL) application:(NSApplication *)sender openFile:(NSString *)filename 
{
	[self performFileOperation:NSWorkspaceDecompressOperation
		  destination:filename];

    return YES;
}

- (NSString *) path
{															// query browser
  	return [_browser path];									// for it's path
}

- (BOOL) setPath:(NSString *)path					
{ 
  	return [_browser setPath: path];
}

- (void) toggleBrowserView:(id)sender
{
NSString *path = [_browser path];

	if(!(_listView))
		{
		_listView = [[NSBrowser alloc] initWithFrame: [_browser frame]];
		[_listView retain];
		[_listView setDelegate: [ListViewDelegate new]];
		[_listView setMaxVisibleColumns: 6];
		[_listView setMinColumnWidth: 150];
		[_listView setTitled: NO];
		[_listView setAutoresizingMask:NSViewHeightSizable|NSViewWidthSizable];
		}

	if (_browser == _listView)
		{
		[[_browser superview] replaceSubview:_listView with:_iconView];
		_browser = _iconView;
		}
	else
		{
		[[_browser superview] replaceSubview:_iconView with:_listView];
		_browser = _listView;
		}

	[_browser scrollColumnToVisible: 0];
	[_browser setPath: path];
	[_browser display];
}

- (void) doDoubleClick:(id)sender				
{
NSFileManager *fm = [NSFileManager defaultManager];
NSMutableArray *files = [NSMutableArray new];
NSBrowser *browser = [(Shelf *)[NSApp mainWindow] browser];
int count = 1;

	if([sender isKindOfClass: [NSBrowser class]])
		{
		NSArray *cells = [sender selectedCells];

		if ((count = [cells count]) == 1)
			[files addObject:[sender path]];
		else
			{
			NSString *path = [sender pathToColumn:[sender lastColumn]];
			NSEnumerator *e = [cells objectEnumerator];
			NSBrowserCell *cell;

			for(;(cell = [e nextObject]);)
				{
				NSString *f = [cell stringValue];
				NSString *s = [path stringByAppendingPathComponent:f];
	
				[files addObject:s];
		}	}	}
	else
		{
		id cell = [sender selectedCell];
		NSString *p = ([cell respondsToSelector: @selector(path)])
					? [cell path] : [cell stringValue];

		[files addObject:p];
		}

	while (count--)
		{
		NSString *p = [files objectAtIndex: count];
		BOOL isDir = NO, isApp = NO;

		if(![fm fileExistsAtPath:p isDirectory:&isDir])
			continue;

		if(isDir && !(isApp = [[p pathExtension] isEqualToString: @"app"]))
			{
			if(browser && ![p isEqualToString:[browser path]])
				[self setPath: p];
	
			continue;
			}

		NS_DURING											// open or launch
			if(!isApp && ![fm isExecutableFileAtPath:p]) 
				[[NSWorkspace sharedWorkspace] openFile:p withApplication:nil];
			else
				[[NSWorkspace sharedWorkspace] launchApplication: p];	
		NS_HANDLER
			NSRunAlertPanel(nil, [localException reason], @"Continue",nil,nil);
		NS_ENDHANDLER
		}
}

- (void) doClick:(id)sender						{}

- (void) openFinder:(id)menuCell
{
	[[Finder sharedFinder] display];
	[[Finder sharedFinder] makeKeyAndOrderFront:nil];
}

- (void) openXTerm:(id)menuCell
{
NSBrowser *browser = [(Shelf *)[NSApp mainWindow] browser];

	if (browser)
		{
		NSString *path = [browser pathToColumn:[browser lastColumn]];
		NSTask *aTask = [[NSTask new] autorelease];
		NSArray *args = [NSArray arrayWithObjects: @"-geometry", @"+165+12",
										@"-sl", @"256", @"-sb", @"-ls", nil];

		[aTask setCurrentDirectoryPath:path];
		[aTask setLaunchPath:@"/usr/X11R6/bin/xterm"];
		[aTask setArguments:args];
		[aTask launch];
		}
}

- (void) updateViewer:(id)menuCell
{
NSBrowser *browser = [(Shelf *)[NSApp mainWindow] browser];

	if (browser)
		[browser reloadColumn:[browser lastColumn]];
}

- (void) destroy:(id)menuCell
{
	[self performFileOperation:NSWorkspaceDestroyOperation destination:nil];
}

- (void) duplicate:(id)menuCell
{
	[self performFileOperation:NSWorkspaceDuplicateOperation destination:nil];
}

- (void) performFileOperation:(NSString *)operation
				  destination:(NSString *)destination
{
NSBrowser *b = [(Shelf *)[NSApp mainWindow] browser];
NSMutableArray *files;
NSString *source;
int returnTag;

	if (operation == NSWorkspaceDestroyOperation
			|| operation == NSWorkspaceDecompressOperation
			|| operation == NSWorkspaceDuplicateOperation)
		{
		NSArray *cells = [b selectedCells];
		NSEnumerator *e = [cells objectEnumerator];
		NSBrowserCell *cell;

		source = [b pathToColumn:[b selectedColumn]];
		files = [NSMutableArray new];
		for(;(cell = [e nextObject]);)
			[files addObject:[cell stringValue]];
		}
	else
		{
		NSPasteboard *p = [NSPasteboard pasteboardWithName:NSDragPboard];
		NSDictionary *d = [p propertyListForType:NSFilenamesPboardType];

		source = [d objectForKey:@"SourcePath"];
		source = [source stringByDeletingLastPathComponent];
		files = [d objectForKey:@"SelectedFiles"];
		}

	if ([[NSWorkspace sharedWorkspace] performFileOperation: operation
									   source: source
									   destination: destination
									   files:files
									   tag:&returnTag])
		{
		[b reloadColumn:[b lastColumn]];
		if (b != _browser)
			[_browser reloadColumn:[_browser lastColumn]];
		[(SplitView*)[b superview] setFileSize:@""];
		}
}

- (BOOL) validateMenuItem:(NSMenuItem *)item
{
	if ([[item title] isEqualToString: @"Open Folder..."])
		{
		Browser *browser = [(Shelf *)[NSApp mainWindow] browser];

		if (browser)
			{
			NSFileManager *fm = [NSFileManager defaultManager];
			NSString *p = [browser path];
			BOOL isDir;

			if ([fm fileExistsAtPath:p isDirectory:&isDir] && isDir)
				return YES;
			}

		return NO;
		}

	return YES;
}

- (void) openFolder:(id)menuCell
{
Browser *browser = [(Shelf *)[NSApp mainWindow] browser];

	if (browser)
		[browser setPath: [browser path]];
  	NSLog (@"openFolder invoked from cell with title '%@'", [menuCell title]);
}

- (void) method:(id)menuCell
{
  	NSLog (@"method invoked from cell with title '%@'", [menuCell title]);
}

@end /* Controller */


@implementation	NSWorkspace (WorkspaceExtension)

- (BOOL) selectFile:(NSString *)fullPath
		 inFileViewerRootedAtPath:(NSString *)rootFullpath
{
id browserCell = [[[BrowserCell alloc] init] autorelease];
NSRect wr = {{200, 200}, {400, 400}};
NSRect browserRect = {{0, 0}, {370, 300}};
NSBrowser *b = [[Browser alloc] initWithFrame: browserRect];
Shelf *shelf;

	[b setDelegate: [IconViewDelegate new]];
	[b setMaxVisibleColumns: 1];
	[b setCellPrototype:browserCell];
	[b setHasHorizontalScroller:NO];
	[b setPath: rootFullpath];

	shelf = [[Shelf alloc] initWithFrame:wr rows:1 cols:3 subView:b];
	[shelf makeFirstResponder:b];		
	[shelf setTitle: fullPath];
	[shelf display];
	[shelf orderFront:nil];

	return YES;
}

@end /* NSWorkspace (WorkspaceExtension) */
