/*
 
 controller.m ... Controllers/Delegates for Views in Getsure
 (It made it based on 邃修lipboard.)
 
 邃修lipboard.
 Copyright (c) 2009, KennyTM~
 All rights reserved.
 
 Mouse Gesture logic refers to Mouse Gesture Recognition.(http://www.bytearray.org/?p=91)
 (It is RPL License.)
 
 GestureKeyboard
 Copyright (c) 2009, NochiNa
 All rights reserved.
 
 
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the KennyTM~ nor the names of its contributors may be
   used to endorse or promote products derived from this software without
   specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 */


#import "controller.h"
#import <iKeyEx/KeyboardLoader.h>
#import <iKeyEx/UIKBSpecialKeyButtons.h>
#import <UIKit2/UIKeyboardImpl.h>
#import <UIKit2/UICalloutView.h>
#import <UIKit2/UIKeyboardInput.h>
#import <WebCore/PublicDOMInterfaces.h>
#import <UIKit/UITextView.h>


#include <objc/runtime.h>
#import "jpHenkan.h"

#import <UIKit2/UIKeyboardInputManagerAlphabet.h>
#import <UIKit2/CandWord.h>
#include <stdlib.h>

//#import "clipboard.h"
#import "views.h"



// LS = Localized string
#define LS(s) [bundle localizedStringForKey:(s) value:nil table:nil]
#define PNG(fn) [UIImage imageWithContentsOfFile:[bundle pathForResource:(fn) ofType:@"png"]]

// Some dummy interfaces 
@interface UIWebDocumentView : UIView<UIKeyboardInput>
@end
@interface UITextViewLegacy : UIView
@property(assign) NSRange* selectedRange;
@end



#pragma mark -
// Provide a concrete container of a weak reference.
//  (break the retain cycle & allows being part of a container.)
@interface WeakReference : NSObject<NSCopying> {
	NSObject* reference;
}
@property(assign) NSObject* reference;
+(id)weakReferenceWithReference:(NSObject*)ref;
-(id)initWithReference:(NSObject*)ref;
-(BOOL)isEqual:(id<NSObject>)obj;
-(NSUInteger)hash;
-(id)copyWithZone:(NSZone*)zone;
@end

@implementation WeakReference 
@synthesize reference;
+(id)weakReferenceWithReference:(NSObject*)ref { return [[[WeakReference alloc] initWithReference:ref] autorelease]; }
-(id)initWithReference:(NSObject*)ref {
	if ((self = [super init]))
		reference = ref;
	return self;
}
-(BOOL)isEqual:(id<NSObject>)obj {
	if ([obj isMemberOfClass:[WeakReference class]]) {
		// probably I should use [reference isEqual:obj->reference] for correctness,
		// but the usage of WeakReference is limited so direct comparison is OK.
		return reference == ((WeakReference*)obj)->reference;
	} else
		return NO;
}
-(NSUInteger)hash { return [reference hash]; }
-(id)copyWithZone:(NSZone*)zone { return [[WeakReference allocWithZone:zone] initWithReference:reference]; }
@end


#pragma mark -
@implementation UICalloutViewShower
@synthesize boundaryRect;
-(id)initWithView:(UIView*)instf {
	if ((self = [super init])) {
		installView = instf;
		boundaryRect = instf.bounds;
		calloutView = [[UICalloutView alloc] initWithFrame:CGRectZero];
		calloutStrings = [[NSMutableDictionary alloc] init];
	}
	return self;
}
-(void)dealloc {
	for (WeakReference* p_btn in calloutStrings) {
		UIButton* btn = (UIButton*)(p_btn.reference);
		[btn removeTarget:self
				   action:@selector(show:) forControlEvents:UIControlEventTouchDown];
		[btn removeTarget:self
				   action:@selector(hide) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchDragOutside|UIControlEventTouchCancel];
	}
	
	[calloutView release];
	[calloutStrings release];
	[super dealloc];
}


-(void)registerButton:(UIButton*)btn withCalloutString:(NSString*)str {
	WeakReference* p_btn = [[WeakReference alloc] initWithReference:btn];
	if ([calloutStrings objectForKey:p_btn] == nil) {
		[btn addTarget:self 
				action:@selector(show:) forControlEvents:UIControlEventTouchDown];
		[btn addTarget:self
				action:@selector(hide) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchDragOutside|UIControlEventTouchCancel];
	}
	[calloutStrings setObject:str forKey:p_btn];
	[p_btn release];

}
-(void)show:(UIButton*)sender {
	WeakReference* p_btn = [[WeakReference alloc] initWithReference:sender];
	NSString* str = [calloutStrings objectForKey:p_btn];
	if (str != nil) {
		calloutView.title = str;
		[calloutView setAnchorPoint:[sender convertPoint:CGPointZero toView:installView]
					   boundaryRect:boundaryRect
							animate:YES];
		[installView addSubview:calloutView];
	}
	[p_btn release];
}
-(void)hide {
	[calloutView fadeOutWithDuration:0.25];
	[calloutView removeFromSuperview];
}
@end



#pragma mark -
@implementation hGestureLayoutController
@synthesize view, bundle,bSymbol;

-(id)init {
	if ((self = [super init])) {
		view = nil;
		bundle = nil;
		
		bShift = NO;
		bCaps = NO;
		bSymbol = NO;
		
		//selectState = NO;
		//selectIndex = 0;
		
		// A list of applications that pasting a multi-character string does
		// not work or even crashes. For these apps, paste char by char instead.
		multicharBlacklist = [[NSSet alloc] initWithObjects:@"com.googlecode.mobileterminal", nil];
	}
	return self;
}

-(void)dealloc {
	[bundle release];
	[multicharBlacklist release];
	[super dealloc];
}

//-(void)copyText:(NSString*)txt {
//	if ([txt length] > 0) {
//		[view->clipboardView.clipboard addData:txt];
//		[view->clipboardView flashFirstRow];
//	}
//}

//-(void)copyText {
//	[self copyText:[UIKeyboardImpl sharedInstance].delegate.text];
//}

-(void)paste:(NSString*)txt {


	UIKeyboardImpl* impl = [UIKeyboardImpl sharedInstance];

	if([txt compare:@"BACKSPACE"]==NSOrderedSame)
	{
		if(bSymbol == YES)
		{
			bSymbol = NO;
		}
 		else
 		{
			[[UIKeyboardImpl sharedInstance] handleDelete];
		}
	}
	else if([txt compare:@"SHIFT"]==NSOrderedSame)
	{
		if(bShift == YES)
		{
		//シフト入っていた場合
			if(bCaps == YES)
			{
				bCaps = NO;
			}
			else
			{
				bCaps = YES;
			}
			//CAPS入れ替え
			bShift = NO;
			//シフト抜く
		}
		else
		{
		//シフト入っていなかった場合
			bShift = YES;
		//シフト入れる
		}
	}	
	else if(([txt compare:@"DOT"]==NSOrderedSame)&&(bSymbol==NO))
	{
		bSymbol = YES;
	}
	else
	{
		NSString *pasteText = nil;

		if([txt compare:@"DOT"]==NSOrderedSame)
		{
			pasteText = @".";
		}
		else if([txt compare:@"SPACE"]==NSOrderedSame)
		{
			pasteText = @" ";
		}
		else
		{
			if((bShift == YES)&&(bCaps == NO)||(bShift == NO)&&(bCaps == YES))
			{
				pasteText = txt;
			}
			else
			{
				pasteText = [txt lowercaseString];			
			}
		}
		bShift = NO;
		bSymbol = NO;
		
		if ([multicharBlacklist containsObject:[[NSBundle mainBundle] bundleIdentifier]]) {
			NSUInteger txtLen = [pasteText length];
			for (NSUInteger i = 0; i < txtLen; ++i)
				[impl addInputString:[pasteText substringWithRange:NSMakeRange(i, 1)]];
		} else
			[impl addInputString:pasteText];
	}
}

//-(void)moveToBeginning {
//	NSObject<UIKeyboardInput>* del = [UIKeyboardImpl sharedInstance].delegate;
//	if ([del isKindOfClass:objc_getClass("UIFieldEditor")]) {
//		[del setSelection:NSMakeRange(0,0)];
//		return;
//	} else if ([del isKindOfClass:[UIWebDocumentView class]]) {
//		UIView* mySuperview = [(UIWebDocumentView*)del superview];
//		if ([mySuperview isKindOfClass:[UITextView class]] || [mySuperview isKindOfClass:[UITextViewLegacy class]]) {
//			((UITextView*)mySuperview).selectedRange = NSMakeRange(0,0);
//			return;
//		}
//	} else if ([del isKindOfClass:[DOMElement class]]) {
//		((DOMElement*)del).scrollTop = 0;
//		((DOMElement*)del).scrollLeft = 0;
//		[((DOMElement*)del) focus];
//	}
//	
//	[del selectAll];
//	DOMRange* range = del.selectedDOMRange;
//	[range collapse:YES];
//	[del setSelectedDOMRange:range affinityDownstream:NO];
//}

//-(void)moveToEnd {
//	NSObject<UIKeyboardInput>* del = [UIKeyboardImpl sharedInstance].delegate;
//	if ([del isKindOfClass:objc_getClass("UIFieldEditor")]) {
//		NSUInteger txtLen = [del.text length];
//		[del setSelection:NSMakeRange(txtLen,0)];
//		return;
//	} else if ([del isKindOfClass:[UIWebDocumentView class]]) {
//		UIView* mySuperview = [(UIWebDocumentView*)del superview];
//		if ([mySuperview isKindOfClass:[UITextView class]] || [mySuperview isKindOfClass:[UITextViewLegacy class]]) {
//			NSUInteger txtLen = [del.text length];
//			((UITextView*)mySuperview).selectedRange = NSMakeRange(txtLen,0);
//			return;
//		}
//	} else if ([del isKindOfClass:[DOMElement class]]) {
//		((DOMElement*)del).scrollTop = ((DOMElement*)del).scrollHeight;
//		((DOMElement*)del).scrollLeft = ((DOMElement*)del).scrollWidth;
//		[((DOMElement*)del) focus];
//	}
//	
//	[del selectAll];
//	DOMRange* range = del.selectedDOMRange;
//	[range collapse:NO];
//	[del setSelectedDOMRange:range affinityDownstream:NO];
//}

//-(void)markSelection:(UIButton*)sender {
//	UIKeyboardImpl* impl = [UIKeyboardImpl sharedInstance];
//	id<UIKeyboardInput> del = impl.delegate;
//	NSUInteger loc = del.selectionRange.location;
//	if (selectState) {
//		NSString* copyStr = nil;
//		// force selectedIndex <= loc.
//		if (loc < selectIndex) {
//			NSUInteger tmp = selectIndex;
//			selectIndex = loc;
//			loc = tmp;
//		}
//		NSString* txt = del.text;
//		NSUInteger txtLen = [txt length];
//		if (selectIndex < txtLen) {
//			if (loc < txtLen)
//				copyStr = [txt substringWithRange:NSMakeRange(selectIndex, loc-selectIndex)];
//			else
//				copyStr = [txt substringFromIndex:selectIndex];
//		}
//		[self copyText:copyStr];
//		selectState = NO;
//		[view->calloutShower registerButton:sender withCalloutString:LS(@"Select from here...")];
//		[sender setImage:PNG(@"selectStart") forState:UIControlStateNormal];
//	} else {
//		selectIndex = loc;
//		selectState = YES;
//		[view->calloutShower registerButton:sender 
//		 withCalloutString:LS([view->clipboardView isDefaultClipboard] ?
//							  @"Select to here and copy" :
//							  @"Select to here and add to templates")];
//		[sender setImage:PNG(@"selectEnd") forState:UIControlStateNormal];
//	}
//}
//
//-(void)switchClipboard:(UIKBSpecialKeyButton*)sender {
//	BOOL isDefault = [view->clipboardView switchClipboard];
//	if (isDefault) {
//		[view->clipboardView setPlaceholderText:LS(@"Clipboard is empty")];
//		[sender setImage:PNG(@"toTemplate") forState:UIControlStateNormal];
//		[view->calloutShower registerButton:sender withCalloutString:LS(@"Switch to Templates")];
//		[view->calloutShower registerButton:view->copyBtn withCalloutString:LS(@"Copy")];
//	} else {
//		[view->clipboardView setPlaceholderText:LS(@"No templates")];
//		[sender setImage:PNG(@"toClipboard") forState:UIControlStateNormal];
//		[view->calloutShower registerButton:sender withCalloutString:LS(@"Switch to Clipboard")];
//		[view->calloutShower registerButton:view->copyBtn withCalloutString:LS(@"Add to templates")];
//	}
//}
-(void)test
{
//	NSString * txt = @"TEST!!!";
	UIKeyboardImpl* impl = [UIKeyboardImpl sharedInstance];
//	if ([multicharBlacklist containsObject:[[NSBundle mainBundle] bundleIdentifier]]) {
//		NSUInteger txtLen = [txt length];
//		for (NSUInteger i = 0; i < txtLen; ++i)
//			[impl addInputString:[txt substringWithRange:NSMakeRange(i, 1)]];
//	} else
		//[impl addInputString:txt];
[impl addInputString:@"T"];

}

-(BOOL)getCaps
{
	if((bShift == YES)&&(bCaps == NO)||(bShift == NO)&&(bCaps == YES))
	{
		return YES;
	}
	else
	{
		return NO;
	}
}
-(BOOL)getSymbol
{
	return bSymbol;
}

@end



@interface GestureManager : UIKeyboardInputManager {
	NSMutableString* inputString;
	//NSMutableString* PWD;
	
	//NSArray* allValidPaths;
	//NSFileManager* fileManager;
		
	id<UIKeyboardInput> delegate;
	UIKeyboardImpl* impl;
	BOOL selectedDirectory;
	
	jpHenkan* henkanClass;	
	
}
-(id)init;
-(void)dealloc;
-(NSUInteger)inputCount;
@property(assign) NSUInteger inputIndex;
@property(copy,readonly) NSString* inputString;
-(void)addInput:(NSString*)str flags:(NSUInteger)flg point:(CGPoint)point;
-(void)setInput:(NSString*)str;
-(void)deleteFromInput;
-(void)textAccepted:(NSString*)str;
-(BOOL)shouldExtendPriorWord;
-(BOOL)stringEndsWord:(NSString*)character;

@property(assign) BOOL shallowPrediction;
@end



@implementation GestureManager

-(BOOL)shouldExtendPriorWord { return YES; }
-(BOOL)stringEndsWord:(NSString*)character { return NO; }

-(NSArray*)candidates {
	NSArray *candidatesArray = [henkanClass getCandidate];


	NSMutableArray* resArray = [[[NSMutableArray alloc] initWithCapacity:[candidatesArray count]] autorelease];

//	if ([candidatesArray count] == 0)
//		return resArray;
		
	for (NSString* candidateString in candidatesArray) { 
		
		CandWord* cw = [CandWord alloc];
		
		cw = [cw initWithWord:candidateString];
		[resArray addObject:cw];
		[cw release];
	}		
	
/*
	if ([allValidPaths count] == 0)
		return nil;
	
	// Chop the part of directories that's known.
	NSUInteger PWDLen = [PWD length];
	
	// Candidates must be an NSArray of CandWords, not NSString.
	NSMutableArray* resArray = [[[NSMutableArray alloc] initWithCapacity:[allValidPaths count]] autorelease];
	for (NSString* path in allValidPaths) { 
		
		BOOL isFolder = NO;
		[fileManager fileExistsAtPath:path isDirectory:&isFolder];
		
		CandWord* cw = [CandWord alloc];
		
		// append "/" if the path points to a directory.
		if (isFolder)
			cw = [cw initWithWord:[[path substringFromIndex:PWDLen] stringByAppendingString:@"/"]];
		else
			cw = [cw initWithWord:[path substringFromIndex:PWDLen]];
		[resArray addObject:cw];
		[cw release];
	}
*/
	
	return resArray;
}

-(BOOL)usesCandidateSelection { return YES; }
-(BOOL)suppressesCandidateDisplay { return NO;}
-(CandWord*)defaultCandidate { return [[[CandWord alloc] initWithWord:inputString] autorelease]; }
-(BOOL)suppliesCompletions { return selectedDirectory; }

@dynamic shallowPrediction;
-(BOOL)shallowPrediction { return NO; }
-(void)setShallowPrediction:(BOOL)val {}


//------------------------------------------------------------------------------
// Path finding engine.

-(void)PFLog:(NSString*)funcName {
//	NSLog(@"%30s, PWD=[%@], inputString=[%@]", [funcName UTF8String], PWD, inputString);
}

// Set text as marked.
-(void)PFSetMarkedText:(NSString*)text {
	NSLog(@"delegate.text=%@; text=%@; mt=%@", delegate.text, text, delegate.markedText);
//	for (NSUInteger i = [text length]; i != 0; -- i) {
//		NSLog(@"%d", i);
//		[delegate deleteBackward];
//	}
	NSLog(@"delegate.text=%@; text=%@; mt=%@", delegate.text, text, delegate.markedText);
	delegate.markedText = text;
}

// Manually confirm marked text.
-(void)PFConfirm {
//	@throw @"sosad";

	[delegate confirmMarkedText:inputString];
	[inputString setString:@""];
	
	[self PFLog:@"PFConfirm"];
}

-(BOOL)PFGenerateCandidates {
	//NSString* incompletePath = [[PWD stringByAppendingString:inputString] stringByExpandingTildeInPath];

	[henkanClass setCandidate:inputString mode:YES];
	NSArray *candidatesArray = [henkanClass getCandidate];
//	if ([candidatesArray count] == 0)
//		return NO;
//	else
		return YES;
/*
	if ([incompletePath rangeOfString:@"/"].location != NSNotFound) {
		// test completion.
		NSString* dummy = nil;
		[allValidPaths release];
		NSUInteger count = [incompletePath completePathIntoString:&dummy caseSensitive:NO matchesIntoArray:&allValidPaths filterTypes:nil];
		
		// cannot complete. fail.
		if (count == 0) {
			allValidPaths = nil;
			[PWD setString:@""];
			[self PFLog:@"PFGenerateCandidates(count==0)"];
			
			return NO;
		} else {
			[allValidPaths retain];
			
			[self PFLog:@"PFGenerateCandidates(count!=0)"];
			
			return YES;
		}
	} else {
		[self PFLog:@"PFGenerateCandidates(invalid)"];
		return NO;
	}
*/	
}

-(void)PFAppend:(unichar)chr {
	if (chr < ' ')
	{
		[inputString setString:@""];
		return;
	}
	NSString* chrAsString = [NSString stringWithCharacters:&chr length:1];
	//if (chr == '/') {
	//	// entered a "/". Push inputString to PWD.
	//	[PWD appendString:inputString];
	//	NSLog(@"pwd=%@", PWD);
	//	[self PFConfirm];
	//	NSLog(@"pwd=%@", PWD);
	//	[inputString setString:chrAsString];
	//	
	//	// Nothing left. Repeat from beginning.
	//	if (![self PFGenerateCandidates]) {
	//		[inputString setString:chrAsString];
	//		[self PFGenerateCandidates];
	//	}
	//} else {
		[inputString appendString:chrAsString];
		if (![self PFGenerateCandidates]) {
			[inputString deleteCharactersInRange:NSMakeRange([inputString length]-1, 1)];
			[self PFConfirm];
	//		if (chr == '~') {
	//			[inputString setString:chrAsString];
	//			[self PFGenerateCandidates];
	//		} else {
				[inputString setString:@""];
	//		}
//		}
	}
	
	[self PFLog:@"PFAppend"];
}

-(void)PFRefresh {
/*
	// recompute the PWD & inputString.
	
	NSString* wholeString = [delegate.text substringToIndex:delegate.selectionRange.location];
	NSUInteger wholeLength = [wholeString length];
		
	NSLog(@"ws=%@", wholeString);
	
	NSUInteger smallestIndex = 0;
	NSUInteger largestIndex = wholeLength;
	
	// a valid path to feed into completePathIntoString:[etc] must either contain a / or begins with ~.
	NSUInteger tildeIndex = [wholeString rangeOfString:@"~"].location;
	NSUInteger slashIndex = [wholeString rangeOfString:@"/" options:NSBackwardsSearch].location;
	if (slashIndex == NSNotFound) {
		if (tildeIndex == NSNotFound) {
			[self PFLog:@"PFRefresh(invalid)"];
			return; 
		} else {
			smallestIndex = tildeIndex;
			largestIndex = tildeIndex+1;
		}
	} else {
		largestIndex = slashIndex+1;
	}
	
	for (; smallestIndex < largestIndex; ++ smallestIndex) {
		NSString* substr = [wholeString substringFromIndex:smallestIndex];
		NSString* potentialValidPath = nil;
		if([substr completePathIntoString:&potentialValidPath caseSensitive:NO matchesIntoArray:NULL filterTypes:nil]) {
			if (slashIndex != NSNotFound) {
				[PWD setString:[wholeString substringWithRange:NSMakeRange(smallestIndex, slashIndex-smallestIndex)]];
				[inputString setString:[wholeString substringFromIndex:slashIndex]];
			} else {
				[PWD setString:@""];
				[inputString setString:substr];
			}
			[self PFGenerateCandidates];
			[self PFSetMarkedText:inputString];
			break;
		}
	}
	
	[self PFLog:@"PFRefresh"];
*/	
	[self PFGenerateCandidates];
	[self PFSetMarkedText:inputString];
}

-(void)PFDelete {
	// input string not empty, simply delete last index.
	if (![@"" isEqualToString:inputString]) {
		NSUInteger inputLength = [inputString length];
		[inputString deleteCharactersInRange:NSMakeRange(inputLength-1, 1)];
		
//		// input string is now empty.
//		if (inputLength == 1) {
//			NSUInteger slashIndex = [PWD rangeOfString:@"/" options:NSBackwardsSearch].location;
//			// PWD has remaining path components. Pop that part to input string.
//			if (slashIndex != NSNotFound) {
//				[inputString setString:[PWD substringFromIndex:slashIndex]];
//				[PWD deleteCharactersInRange:NSMakeRange(slashIndex, [PWD length]-slashIndex)];
//			
//			// PWD has everything consumed. Don't bother unless PWD starts with ~
//			} else {
//				if ([PWD hasPrefix:@"~"]) {
//					[inputString setString:PWD];
//					[PWD setString:@""];
//				} else {
//					[PWD setString:@""];
//					[self PFLog:@"PFDelete(invalid)"];
//					return;
//				}
//			}
//		}
		
		[self PFSetMarkedText:inputString];
		[self PFGenerateCandidates];
	} else {
		[self PFRefresh];
	}
	
	[self PFLog:@"PFDelete"];
}


// The rest is pretty much about maintaining the user input state.
-(id)init {
	if ((self = [super init])) {
		selectedDirectory = NO;
	//	PWD = [[NSMutableString alloc] init];
		inputString = [[NSMutableString alloc] init];
		//fileManager = [NSFileManager defaultManager];
		impl = [UIKeyboardImpl sharedInstance];
		delegate = impl.delegate;
		henkanClass = [[jpHenkan alloc]initDic];
	}
	return self;
}
-(void)dealloc {
	[inputString release];
	//[PWD release];
	[henkanClass release];
	
	[super dealloc];
}

-(NSUInteger)inputCount { return [inputString length]; }
@synthesize inputString;
@dynamic inputIndex;
-(NSUInteger)inputIndex { return [inputString length]; }
-(void)setInputIndex:(NSUInteger)newIndex {
	[self PFRefresh];
}

-(void)addInput:(NSString*)str flags:(NSUInteger)flg point:(CGPoint)point {
	NSUInteger strLen = [str length];
	unichar* chars = malloc(sizeof(unichar)*strLen);
	[str getCharacters:chars];
	for (NSUInteger i = 0; i < strLen; ++ i)
		[self PFAppend:chars[i]];
		
}

-(void)setInput:(NSString*)str {
	[self PFConfirm];
	[self PFRefresh];
}

-(void)deleteFromInput {
	[self PFDelete];
}

-(void)textAccepted:(NSString*)str {
	if([str length]>0)
	{
		selectedDirectory = YES;
	}
	if (selectedDirectory) {
		[henkanClass setCandidate:str mode:NO];
		[inputString setString:@""];
	} else {
		[inputString setString:@""];
	}
}

-(void)clearInput {
	delegate = [UIKeyboardImpl sharedInstance].delegate;
}

@end



