/*
        TextFinder.m
        Copyright (c) 1995-2001 by Apple Computer, Inc., all rights reserved.f
        Author: Ali Ozer

        Find and replace functionality with a minimal panel...
        Would be nice to have the buttons in the panel validate; this would allow the 
            replace buttons to become disabled for readonly docs
*/
/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation, 
 modification or redistribution of this Apple software constitutes acceptance of these 
 terms.  If you do not agree with these terms, please do not use, install, modify or 
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and subject to these 
 terms, Apple grants you a personal, non-exclusive license, under AppleÕs copyrights in 
 this original Apple software (the "Apple Software"), to use, reproduce, modify and 
 redistribute the Apple Software, with or without modifications, in source and/or binary 
 forms; provided that if you redistribute the Apple Software in its entirety and without 
 modifications, you must retain this notice and the following text and disclaimers in all 
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks 
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from 
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your 
 derivative works or by other works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES, 
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, 
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS 
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL 
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, 
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND 
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR 
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Regular expression code added 3/11/2003 by Matthew Weinstein for the TAMS Analyzer project
*/

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "TextFinder.h"
#import "AGRegex.h"
#import "utils.h"
#import "stringCategories.h"
#define COUNTSTRING @"REGEXCOUNT"
//#define oldReplaceREGEX 1
#define oneAtATimeReplaceRegex 1



@implementation TextFinder

static id sharedFindObject = nil;

+ (id)sharedInstance {
    if (!sharedFindObject) {
        [[self allocWithZone:[[NSApplication sharedApplication] zone]] init];
    }
    return sharedFindObject;
}

- (id)init {
    if (sharedFindObject) {
        [super dealloc];
        return sharedFindObject;
    }

    if (!(self = [super init])) return nil;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidActivate:) name:NSApplicationDidBecomeActiveNotification object:[NSApplication sharedApplication]];

    [self setFindString:@"" writeToPasteboard:NO];
    [self loadFindStringFromPasteboard];

    sharedFindObject = self;
    return self;
}
- (BOOL) entireFile
{
	return [scopeFlag state] == NSOnState;

}
- (void)appDidActivate:(NSNotification *)notification {
    [self loadFindStringFromPasteboard];
}

- (void)loadFindStringFromPasteboard {
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSFindPboard];
    if ([[pasteboard types] containsObject:NSStringPboardType]) {
        NSString *string = [pasteboard stringForType:NSStringPboardType];
        if (string && [string length]) {
            [self setFindString:string writeToPasteboard:NO];
        }
    }
}

- (void)loadFindStringToPasteboard {
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSFindPboard];
    [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
    [pasteboard setString:[self findString] forType:NSStringPboardType];
}

- (void)loadUI {
if(!findTextField)NSLog(@"no text field\n");else NSLog(@"yes text field\n");
    if (!findTextField) {
        if (![NSBundle loadNibNamed:@"FindPanel" owner:self])  {
            NSLog(@"Failed to load FindPanel.nib");
            NSBeep();
        }
	if (self == sharedFindObject) [[findTextField window] setFrameAutosaveName:@"Find"];
    }
    [findTextField setStringValue:[self findString]];
}

- (void)dealloc {
    if (self != sharedFindObject) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [findString release];
        [super dealloc];
    }
}

- (NSString *)findString {
    return findString;
}

- (void)setFindString:(NSString *)string {
    [self setFindString:string writeToPasteboard:YES];
}

-(NSString *) getFindString
{
     if([regexButton intValue] == 0) return[self convertEscapeString: [findTextField stringValue]];
    else return [findTextField stringValue];
}
-(NSString *) getReplaceString
{
    return [self convertEscapeString: [replaceTextField stringValue]];
}
-(NSString *)convertEscapeString: (NSString *) oString
{
   int n, i;
    unichar ch, chn;
    NSMutableString *newString = [[NSMutableString alloc] init];
    //go through the replace string
    n = [oString length];
    for(i = 0; i < n; i++)
    {
        ch = [oString characterAtIndex: i];
        if(ch == '\\' && i < n - 1)
        {
            chn = [oString characterAtIndex: ++i];
            switch(chn)
            {
                case 't':
                    [newString ADDCHAR('\t')];
                    break;
                case 'n':
                    [newString ADDCHAR('\n')];
                    break;
                case 'r':
                    [newString ADDCHAR('\r')];
                    break;
                default:
                    [newString ADDCHAR('\\')];
                    [newString ADDCHAR(chn)];
                    break;
            }
        }
        else
            [newString ADDCHAR( ch)];
    }
    [newString autorelease];
    return newString;

}

- (void)setFindString:(NSString *)string writeToPasteboard:(BOOL)flag {
    if ([string isEqualToString:findString]) return;
    [findString autorelease];
    findString = [string copyWithZone:[self zone]];
    if (findTextField) {
        [findTextField setStringValue:string];
        [findTextField selectText:nil];
    }
    if (flag) [self loadFindStringToPasteboard];
}

- (NSTextView *)textObjectToSearchIn {
    id obj = [[NSApp mainWindow] firstResponder];
    return (obj && [obj isKindOfClass:[NSTextView class]]) ? obj : nil;
}

- (NSPanel *)findPanel {
    if (!findTextField) [self loadUI];
    return (NSPanel *)[findTextField window];
}

/* The primitive for finding; this ends up setting the status field (and beeping if necessary)...
*/
- (BOOL)find:(BOOL)direction {
    unsigned options;
    NSTextView *text = [self textObjectToSearchIn];
    lastFindWasSuccessful = NO;
    if (text) {
        NSString *textContents = [text string];
        unsigned textLength;
        if (textContents && (textLength = [textContents length])) {
            NSRange range;
            BOOL regexSrch;
            BOOL mlflag;
            
            if([regexButton state]) 
            {
                regexSrch = YES;
                if([multilineButton state]) mlflag = YES;
                else mlflag = NO;
            }
            else 
            {
                regexSrch = NO; mlflag = NO;
            }
            options = 0;
            if (direction == Backward) options |= NSBackwardsSearch;
            if ([ignoreCaseButton state]) options |= NSCaseInsensitiveSearch;
            range = [textContents findString:[self findString] selectedRange:[text selectedRange] options:options wrap:YES regex: regexSrch multiline: mlflag];
            if (range.length) {
                [text setSelectedRange:range];
                [text scrollRangeToVisible:range];
                lastFindWasSuccessful = YES;
            }
        
        }
    }
    if (!lastFindWasSuccessful) {
        NSBeep();
        [statusField setStringValue:NSLocalizedStringFromTable(@"Not found", @"FindPanel", @"Status displayed in find panel when the find string is not found.")];
    } else {
        [statusField setStringValue:@""];
    }
    return lastFindWasSuccessful;
}

- (void)orderFrontFindPanel:(id)sender {
    NSPanel *panel;
	NSLog(@"about to get panel\n");
panel = [self findPanel];
	NSLog(@"in orderFront\n");
    [findTextField selectText:nil];
    [panel makeKeyAndOrderFront:nil];
}

/**** Action methods for gadgets in the find panel; these should all end up setting or clearing the status field ****/

-(IBAction) setRegexState: (id) Sender
{
    //turn off prev
    if([regexButton state])
    {
        [findPrevButton setEnabled: NO];
        [multilineButton setEnabled: YES];
    }
    else
    {
        [findPrevButton setEnabled: YES];
        [multilineButton setEnabled: NO];
    }
    
}


- (void)findNextAndOrderFindPanelOut:(id)sender {
    [findNextButton performClick:nil];
    if (lastFindWasSuccessful) {
        [[self findPanel] orderOut:sender];
    } else {
	[findTextField selectText:nil];
    }
}

- (void)findNext:(id)sender {
    if (findTextField) [self setFindString:[self getFindString]];	/* findTextField should be set */
    (void)[self find:Forward];
}

- (void)findPrevious:(id)sender {
    if (findTextField) [self setFindString:[self getFindString]];	/* findTextField should be set */
    (void)[self find:Backward];
}

- (void)replace:(id)sender 
{
    NSTextView *text = [self textObjectToSearchIn];
    AGRegex *regex;
    
    // shouldChangeTextInRange:... should return NO if !isEditable, but doesn't...
    
    if (text && [text isEditable] && [text shouldChangeTextInRange:[text selectedRange] replacementString:[self getReplaceString]]) 
    {
        int regexOpt;
        int rawflag;
        
        if([regexButton state])
        {
            NSString *ss;
            regexOpt = 0;
            regexOpt |= ([ignoreCaseButton state])? AGRegexCaseInsensitive : 0;
            regexOpt |= ([multilineButton state])? AGRegexMultiline : 0;
            
            regex = [[AGRegex alloc] initWithPattern: [self findString] options: regexOpt];
            ss = [regex replaceWithStringWithEscape: [replaceTextField stringValue]
                                           inString: [[text string] substringWithRange: [text selectedRange]]
                                                raw: 0];
            if(!ss) NSBeep();
            else
                [[text textStorage] replaceCharactersInRange:[text selectedRange] withString: ss];
            [regex release];
            [text didChangeText];
    
            
        }
        else
        {
            [[text textStorage] replaceCharactersInRange:[text selectedRange] withString:[self getReplaceString]];
            [text didChangeText];
        }
    }
     else 
    {
        NSBeep();
    }
    [statusField setStringValue:@""];
}

- (void)replaceAndFind:(id)sender {
    [self replace:sender];
    [self findNext:sender];
}

#define ReplaceAllScopeEntireFile 42
#define ReplaceAllScopeSelection 43

/* The replaceAll: code is somewhat complex.  One reason for this is to support undo well --- To play along with the undo mechanism in the text object, this method goes through the shouldChangeTextInRange:replacementString: mechanism. In order to do that, it precomputes the section of the string that is being updated. An alternative would be for this method to handle the undo for the replaceAll: operation itself, and register the appropriate changes. However, this is simpler...

Turns out this approach of building the new string and inserting it at the appropriate place in the actual text storage also has an added benefit of performance; it avoids copying the contents of the string around on every replace, which is significant in large files with many replacements. Of course there is the added cost of the temporary replacement string, but we try to compute that as tightly as possible beforehand to reduce the memory requirements.
*/
- (void)replaceAll:(id)sender {
    NSTextView *text = [self textObjectToSearchIn];
    if (!text || ![text isEditable]) {
	[statusField setStringValue:@""];
        NSBeep();
    } 
    else if([regexButton state])
    {
        NSArray *foundStrings;
        AGRegex *reg;
        AGRegexMatch *match;
        NSString *regResult;
        NSMutableString *cntResult;
        int regexOpt,  n;
        NSRange tr, br;
        NSTextStorage *textStorage = [text textStorage];

        BOOL entireFile = [self entireFile];
         
        /*
            Our strategy is different than the non regex
            We will do an array of found strings and then 
            work our way backwards through it and pay the cost;
            without a find backwards we cannot simply modify the alorithm
            
        */
            regexOpt = 0;
            regexOpt |= ([ignoreCaseButton state])? AGRegexCaseInsensitive : 0;
            regexOpt |= ([multilineButton state])? AGRegexMultiline : 0;
        tr = (entireFile )? NSMakeRange(0, [textStorage length]) : [text selectedRange];
        {
            NSRange range, er, strPart;
            BOOL regexSrch;
            NSString *textContents = [text string];
            BOOL mlflag;
            unsigned textLength;
            NSMutableAttributedString *temp;
            NSAutoreleasePool *ap;
            unsigned options;
            BOOL direction = Forward;
            NSString *ss;
            NSMutableString *ss2;
            int rgxcnt;
            unsigned long lastOne;
            textLength = [textContents length];
            er = tr;
            temp = [[NSMutableAttributedString alloc] init];

            if(!(textContents && textLength)) return;
            tr = (entireFile )? NSMakeRange(0, 0) : [text selectedRange];
            strPart = (entireFile )? NSMakeRange(0, textLength) : [text selectedRange];
            [temp beginEditing];
            ap = [[NSAutoreleasePool alloc] init];
            if (findTextField) [self setFindString:[self getFindString]];
            [temp appendAttributedString:[textStorage attributedSubstringFromRange: strPart]];	            
            reg = [[AGRegex alloc] initWithPattern: [self findString] options: regexOpt];
            br = [text selectedRange];
            //get the whole range
            //go forever
            n = 0;
            lastOne = 0;
            if([regexButton state]) 
            {
                regexSrch = YES;
                if([multilineButton state]) mlflag = YES;
                else mlflag = NO;
            }
            options = 0;
            if (direction == Backward) options |= NSBackwardsSearch;
            if ([ignoreCaseButton state]) options |= AGRegexCaseInsensitive;
            rgxcnt = 1;
            for(;;)
            {
                int ssize;
                //find it in the range
                if(tr.length + tr.location <= [[temp string] length])
                range = [[temp string] findString:[self findString] selectedRange:tr options:options wrap:NO regex: regexSrch multiline: mlflag];
                else break;
                
                if (range.location == NSNotFound) //here's the great escape
                    break;
                /*
                 the problem here is that er was the orginal range
                 but this is a moving target
                 */
                if(NSEqualRanges(er,NSUnionRange(er, range)) == NO) break; //are we out of range?
                
                ss = [reg replaceWithStringWithEscape: [replaceTextField stringValue]
                                             inString: [[temp string] substringWithRange: range] raw:0];
                if([ss rangeOfString: COUNTSTRING].location != NSNotFound)
                {
                    ss2= [NSMutableString stringWithString: ss];
                    [ss2 replaceOccurrencesOfString: COUNTSTRING withString: [NSString stringWithFormat: @"%d", rgxcnt] options: NSCaseInsensitiveSearch range: NSMakeRange(0, [ss length])];
                    rgxcnt++;
                    ss = ss2;
                }
                    
                ssize = [ss length];
                if(ssize < range.length) er.length -= range.length - ssize;
                else if (ssize > range.length) er.length += ssize - range.length;
                //ss = [NSString string];
                //if(range.location <= lastOne) break;
                //else lastOne = range.location;
                tr.length = 0;
                tr.location = range.location+ssize;
                    
                //tr.location = range.location+range.length + (range.length - ssize);
               n++;
                if(!ss) NSBeep();
                else
                    [temp replaceCharactersInRange: range withString: ss];
                //[statusField setStringValue: [NSString stringWithFormat: @"%d replaced", n]];
                /*
                [statusField setStringValue:[NSString
                localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced",
                                                                     @"FindPanel",
                                                                     @"Status displayed in find panel when indicated number of matches are replaced."), 
                    
                    n]];*/
                if(n%20 == 0) 
                {
                    [ap release];
                    ap = [[NSAutoreleasePool alloc] init];
                }
            }
            [temp endEditing];
            if(n)
            {
                if ([text shouldChangeTextInRange:strPart replacementString:[temp string]]) 
                    [textStorage replaceCharactersInRange:strPart withAttributedString:temp];  
                [text didChangeText];
            }
            //[text didChangeText];
            //make the replace string
            //replace it
            //have we done 20?
            //get re do it;
            
            [text setSelectedRange: br];
            [reg release];
            [ap release];
            [temp release];
            [statusField setStringValue:[NSString
                localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced",
                                                                    @"FindPanel",
                                                                    @"Status displayed in find panel when indicated number of matches are replaced"), 
                n]];
                
        }
    }
    else 
    
    {
        NSTextStorage *textStorage = [text textStorage];
        NSString *textContents = [text string];
        BOOL entireFile = [self entireFile];
        NSRange replaceRange = entireFile ? NSMakeRange(0, [textStorage length]) : [text selectedRange];
        unsigned searchOption = ([ignoreCaseButton state] ? NSCaseInsensitiveSearch : 0);
        unsigned replaced = 0;
        NSRange firstOccurence;
        
        if (findTextField) [self setFindString:[self getFindString]];

        // Find the first occurence of the string being replaced; if not found, we're done!
        firstOccurence = [textContents rangeOfString:[self findString] options:searchOption range:replaceRange];
        if (firstOccurence.length > 0) {
	    NSAutoreleasePool *pool;
	    NSString *targetString = [self findString];
	    NSString *replaceString = [self getReplaceString];
             NSMutableAttributedString *temp;	/* This is the temporary work string in which we will do the replacements... */
            NSRange rangeInOriginalString;	/* Range in the original string where we do the searches */
           [replaceString retain];

	    // Find the last occurence of the string and union it with the first occurence to compute the tightest range...
            rangeInOriginalString = replaceRange = NSUnionRange(firstOccurence, [textContents rangeOfString:targetString options:NSBackwardsSearch|searchOption range:replaceRange]);

            temp = [[NSMutableAttributedString alloc] init];

            [temp beginEditing];

	    // The following loop can execute an unlimited number of times, and it could have autorelease activity.
	    // To keep things under control, we use a pool, but to be a bit efficient, instead of emptying everytime through
	    // the loop, we do it every so often. We can only do this as long as autoreleased items are not supposed to
	    // survive between the invocations of the pool!

    	    pool = [[NSAutoreleasePool alloc] init];

            while (rangeInOriginalString.length > 0) {
                NSRange foundRange = [textContents rangeOfString:targetString options:searchOption range:rangeInOriginalString];
                if (foundRange.length == 0) {
                    [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeInOriginalString]];	// Copy the remainder
                    rangeInOriginalString.length = 0;	// And signal that we're done
                } else {
                    NSRange rangeToCopy = NSMakeRange(rangeInOriginalString.location, foundRange.location - rangeInOriginalString.location + 1);	// Copy upto the start of the found range plus one char (to maintain attributes with the overlap)...
                    [temp appendAttributedString:[textStorage attributedSubstringFromRange:rangeToCopy]];
                    [temp replaceCharactersInRange:NSMakeRange([temp length] - 1, 1) withString:replaceString];
                    rangeInOriginalString.length -= NSMaxRange(foundRange) - rangeInOriginalString.location;
                    rangeInOriginalString.location = NSMaxRange(foundRange);
                    replaced++;
                    if (replaced % 100 == 0) {	// Refresh the pool... See warning above!
                        [pool release];
                        pool = [[NSAutoreleasePool alloc] init];
                    }
                }
            }

	    [pool release];
            [replaceString autorelease];
            [temp endEditing];

	    // Now modify the original string
            if ([text shouldChangeTextInRange:replaceRange replacementString:[temp string]]) {
                [textStorage replaceCharactersInRange:replaceRange withAttributedString:temp];
                [text didChangeText];
            } else {	// For some reason the string didn't want to be modified. Bizarre...
                replaced = 0;
            }

            [temp release];
        }
        if (replaced == 0) {
            NSBeep();
            [statusField setStringValue:NSLocalizedStringFromTable(@"Not found", @"FindPanel", @"Status displayed in find panel when the find string is not found.")];
        } else {
            [statusField setStringValue:[NSString localizedStringWithFormat:NSLocalizedStringFromTable(@"%d replaced", @"FindPanel", @"Status displayed in find panel when indicated number of matches are replaced."), replaced]];
        }
    }
}

- (void)takeFindStringFromSelection:(id)sender {
    NSTextView *textView = [self textObjectToSearchIn];
    if (textView) {
        NSString *selection = [[textView string] substringWithRange:[textView selectedRange]];
        [self setFindString:selection];
    }
}

- (void) jumpToSelection:sender {
    NSTextView *textView = [self textObjectToSearchIn];
    if (textView) {
        [textView scrollRangeToVisible:[textView selectedRange]];
    }
}

@end
