/*------------------------------------------------------------*/
/*                                                            */
/*    Turbo Vision -  Version 1.0                             */
/*                                                            */
/*                                                            */
/*    Copyright (c) 1991 by Borland International             */
/*    All Rights Reserved.                                    */
/*                                                            */
/*------------------------------------------------------------*/

/*------------------------------------------------------------*/
/*                                                            */
/* Modified by Francis Gastellu for PowerPPL
/*                                                            */
/*------------------------------------------------------------*/

#define Uses_TKeys
#define Uses_TEditor
#define Uses_TFileEditor
#define Uses_TIndicator
#define Uses_TEvent
#define Uses_TScrollBar
#define Uses_TFindDialogRec
#define Uses_TReplaceDialogRec
#define Uses_opstream
#define Uses_ipstream
#define Uses_MsgBox
#include <tv.h>
#include "tagger.h"
#include "break.h"
#include "consts.h"

#include <stdlib.h>
#include <stdio.h>

#if !defined( __STRING_H )
#include <string.h>
#endif  // __STRING_H

#if !defined( __CTYPE_H )
#include <ctype.h>
#endif  // __CTYPE_H

#if !defined( __DOS_H )
#include <Dos.h>
#endif  // __DOS_H

#include "exevalid.h"

#define NORMALTEXT 1
#define COMMENTS   2
#define SYMBOLS    3
#define NUMBERS    4
#define STRINGS    5
#define LABELS     6
#define RESERVED   7
#define PREDEFINED 8
#define DIRECTIVES 9
#define BREAKPOINTS 10

extern void shiftTags(int line, int side);
int projectMain(void *ptr);

extern char curfilename[MAXPATH];
extern char tabLen;
extern int flat;
extern int alwaysflat;
extern int flatxnn;
TEditor *flatStatusPtr;
extern int countLines( void *buf, ushort count );
extern eEXEValidResult crcchk;
extern int entercount;
extern int thisWindow;

extern Boolean Tagger;
extern TTaggerWindow *TaggerWindow;
extern TCollection *taglist;
extern char desktopFile[256];
extern char drive3[MAXDRIVE];
extern char dir3[MAXDIR];
extern char fname3[MAXFILE];
extern char ext3[MAXEXT];
extern char errorFichier[256];

inline int isWordChar( int ch )
{
	return isalnum(ch) || ch == '_';
}

int findcolor(char *word);

char *palette;
extern int errorDisplayed;
extern int autoindentmode;
extern char creatBAK;
int drawnLine=0;

const ushort far firstKeys[] =
{
	37,
	kbCtrlA, cmWordLeft,
	kbCtrlC, cmPageDown,
	kbCtrlD, cmCharRight,
	kbCtrlE, cmLineUp,
	kbCtrlF, cmWordRight,
	kbCtrlG, cmDelChar,
	kbCtrlH, cmBackSpace,
	kbCtrlK, 0xFF02,
	kbCtrlL, cmSearchAgain,
	kbCtrlM, cmNewLine,
	kbCtrlO, cmIndentMode,
	kbCtrlQ, 0xFF01,
	kbCtrlR, cmPageUp,
	kbCtrlS, cmCharLeft,
	kbCtrlT, cmDelWord,
	kbAltU, cmUndo,
	kbCtrlV, cmInsMode,
	kbCtrlX, cmLineDown,
	kbCtrlY, cmDelLine,
	kbLeft, cmCharLeft,
	kbRight, cmCharRight,
	kbCtrlLeft, cmWordLeft,
	kbCtrlRight, cmWordRight,
	kbHome, cmLineStart,
    kbEnd, cmLineEnd,
	kbUp, cmLineUp,
	kbDown, cmLineDown,
    kbPgUp, cmPageUp,
    kbPgDn, cmPageDown,
    kbCtrlPgUp, cmTextStart,
	kbCtrlPgDn, cmTextEnd,
    kbIns, cmInsMode,
    kbDel, cmDelChar,
    kbShiftIns, cmPaste,
	kbShiftDel, cmCut,
    kbCtrlIns, cmCopy,
    kbCtrlDel, cmClear
};

const ushort far quickKeys[] =
{   8,
	'A', cmReplace,
    'C', cmTextEnd,
	'D', cmLineEnd,
	'F', cmFind,
	'H', cmDelStart,
	'R', cmTextStart,
    'S', cmLineStart,
    'Y', cmDelEnd
};

const ushort far blockKeys[] =
{   5,
	'B', cmStartSelect,
    'C', cmPaste,
    'H', cmHideSelect,
    'K', cmCopy,
	'Y', cmCut
};

const ushort * far keyMap[] = { firstKeys, quickKeys, blockKeys };

ushort defEditorDialog( int, ... );

#pragma warn -asc

ushort scanKeyMap( const void *keyMap, int keyCode )
{
asm {
    PUSH DS
	LDS SI,keyMap
    MOV DX,keyCode
	CLD
    LODSW
    MOV CX,AX
    }
__1:
asm {
	LODSW
	MOV BX,AX
    LODSW
    CMP BL,DL
	JNE __3
	OR  BH,BH
    JE  __4
    CMP BH,DH
	JE  __4
    }
__3:
asm {
	LOOP    __1
	XOR AX,AX
    }
__4:
asm POP DS
    return _AX;
}

#pragma warn .asc

#define cpEditor    "\x06\x07"

TEditor::TEditor( const TRect& bounds,
		  TScrollBar *aHScrollBar,
		  TScrollBar *aVScrollBar,
		  TIndicator *aIndicator,
		  ushort aBufSize ) :
    TView( bounds ),
    hScrollBar( aHScrollBar ),
    vScrollBar( aVScrollBar ),
	indicator( aIndicator ),
    bufSize( aBufSize ),
    canUndo( True ),
    selecting( False ),
    overwrite( False ),
	autoIndent( False ) ,
	lockCount( 0 ),
	keyState( 0 )
{
    growMode = gfGrowHiX | gfGrowHiY;
	options |= ofSelectable;
    if (creatBAK) editorFlags |= efBackupFiles; else editorFlags &= ~efBackupFiles;
    if (autoindentmode) autoIndent = True; else autoIndent = False;
	eventMask = evMouseDown | evKeyDown | evCommand | evBroadcast;
    showCursor();
	initBuffer();
	if( buffer != 0 )
	isValid = True;
    else
	{
	editorDialog( edOutOfMemory );
	bufSize = 0;
	isValid = False;
    }
	setBufLen(0);
}

TEditor::~TEditor()
{
}

void TEditor::shutDown()
{
	doneBuffer();
    TView::shutDown();
}

void TEditor::changeBounds( const TRect& bounds )
{
	setBounds(bounds);
	delta.x = max(0, min(delta.x, limit.x - size.x));
	delta.y = max(0, min(delta.y, limit.y - size.y));
	update(ufView);
}

int TEditor::charPos( ushort p, ushort target )
{
	int pos = 0;
	ushort pstart;
	pstart = p;

		if (flatStatusPtr != this) updateFlatStatus();

	if (flat || alwaysflat || flatxnn)
		{
		while( p < target )
			{
			if( bufChar(p) == '\x9' )
				pos |= tabLen-1;

			pos++;
			p++;
			}
		return pos;
		}

	int instring=0;
	unsigned char c;
	unsigned char d;
	unsigned char e;
	int rem=False;


	while( p < target )
		{
		c = bufChar(p);
		if ( c == ';' || c == '\'' || (c == '*' && p == pstart) )
			rem = True;
		if ( c == 34 && !rem )
			instring = !instring;

		if( c == '\x9' )
			pos |= tabLen-1;

		if (instring && c == '@' && bufChar(p+1) == 'X')
			{
			d = bufChar(p+2);
			e = bufChar(p+3);
			if ((((d >= '0') && (d <= '9')) || ((d >= 'A') && (d <= 'F'))) && (((e >= '0') && (e <= '9')) || ((e >= 'A') && (e <= 'F'))))
				{
				p +=3;
				pos--;
				}
			}
		pos++;
		if (p == pstart && c == ' ')
			pstart++;
		p++;
		}
	return pos;
}

ushort TEditor::charPtr( ushort p, int target )
{
  int pos = 0;
	ushort pstart;
	pstart = p;

  if (flatStatusPtr != this) updateFlatStatus();

  if (flat || alwaysflat || flatxnn)
	{
	  while( (pos < target) && (p < bufLen) && (bufChar(p) != '\x0D') )
		{
		if( bufChar(p) == '\x09' )
			pos |= tabLen-1;
		pos++;
		p++;
		}

	if( pos > target )
		p--;

	return p;
	}

  int instring=0;
  unsigned char c;
  unsigned char d;
  unsigned char e;
  int rem=False;

  while( (pos < target) && (p < bufLen) && (bufChar(p) != '\x0D') )
	{
	c = bufChar(p);
	if ( c == ';' || c == '\'' || (c == '*' && p == pstart) )
		rem = True;
	if ( c == 34 && !rem )
		instring = !instring;
	if( c == '\x09' )
		pos |= tabLen-1;

	if (instring && c == '@' && bufChar(p+1) == 'X')
		{
		d = bufChar(p+2);
		e = bufChar(p+3);
		if ((((d >= '0') && (d <= '9')) || ((d >= 'A') && (d <= 'F'))) && (((e >= '0') && (e <= '9')) || ((e >= 'A') && (e <= 'F'))))
			{
			p +=3;
			pos--;
			}
		}
	pos++;
	if (p == pstart && c == ' ')
		pstart++;
	p++;
	}
  if( pos > target )
	p--;
  return p;
}

Boolean TEditor::clipCopy()
{
	Boolean res = False;
	if( (clipboard != 0) && (clipboard != this) )
	{
	res = clipboard->insertFrom(this);
	selecting = False;
	update(ufUpdate);
	}
	return res;
}

void TEditor::clipCut()
{
    if( clipCopy() == True )
		deleteSelect();
}

void TEditor::clipPaste()
{
ushort a;
uchar selectMode = 0;

	if( (clipboard != 0) && (clipboard != this) )
	{
	if (selStart-selEnd != 0)
		{
		a = selStart;
		insertFrom(clipboard);
		setCurPtr(a, selectMode);
		}
	else
		{
		a = curPtr;
		insertFrom(clipboard);
		setCurPtr(a, selectMode);
		}
	}
}

void TEditor::convertEvent( TEvent& event )
{
    if( event.what == evKeyDown )
	{
	const uchar far *const shiftState = (uchar far *)MK_FP( 0x40, 0x17 );
	if( (*shiftState & 0x03) != 0 &&
		event.keyDown.charScan.scanCode >= 0x47 &&
		event.keyDown.charScan.scanCode <= 0x51
	  )
			event.keyDown.charScan.charCode = 0;

		ushort key = event.keyDown.keyCode;
	if( keyState != 0 )
            {
	    if( (key & 0xFF) >= 0x01 && (key & 0xFF) <= 0x1A )
				key += 0x40;
	    if( (key & 0xFF) >= 0x61 && (key & 0xFF) <= 0x7A )
		key -= 0x20;
			}
        key = scanKeyMap(keyMap[keyState], key);
		keyState = 0;
		if( key != 0 )
	    if( (key & 0xFF00) == 0xFF00 )
				{
                keyState = (key & 0xFF);
				clearEvent(event);
				}
			else
                {
				event.what = evCommand;
		event.message.command = key;
				}
	}
}

Boolean TEditor::cursorVisible()
{
  return Boolean((curPos.y >= delta.y) && (curPos.y < delta.y + size.y));
}

void TEditor::deleteRange( ushort startPtr,
						   ushort endPtr,
			   Boolean delSelect
						 )
{
	if( hasSelection() == True && delSelect == True )
		deleteSelect();
    else
        {
		setSelect(curPtr, endPtr, True);
	deleteSelect();
		setSelect(startPtr, curPtr, False);
	deleteSelect();
        }
}

void TEditor::deleteSelect()
{
	insertText( 0, 0, False );
}

void TEditor::doneBuffer()
{
	delete buffer;
}

void TEditor::doSearchReplace()
{
	int i;
	do  {
	i = cmCancel;
		if( search(findStr, editorFlags) == False )
		{
			if( (editorFlags & (efReplaceAll | efDoReplace)) !=
		(efReplaceAll | efDoReplace) )
					editorDialog( edSearchFailed );
		}
	else
			if( (editorFlags & efDoReplace) != 0 )
				{
				i = cmYes;
				if( (editorFlags & efPromptOnReplace) != 0 )
			{
					TPoint c = makeGlobal( cursor );
					i = editorDialog( edReplacePrompt, &c );
					}
				if( i == cmYes )
					{
					lock();
					insertText( replaceStr, strlen(replaceStr), False);
					trackCursor(False);
					unlock();
		    }
                }
	} while( i != cmCancel && (editorFlags & efReplaceAll) != 0 );
}

void TEditor::doUpdate()
{
    if( updateFlags != 0 )
        {
		setCursor(curPos.x - delta.x, curPos.y - delta.y);
	if( (updateFlags & ufView) != 0 )
			drawView();
        else
			if( (updateFlags & ufLine) != 0 )
				drawLines( curPos.y-delta.y, 1, lineStart(curPtr) );
		if( hScrollBar != 0 )
			hScrollBar->setParams(delta.x, 0, limit.x - size.x, size.x / 2, 1);
		if( vScrollBar != 0 )
		vScrollBar->setParams(delta.y, 0, limit.y - size.y, size.y - 1, 1);
		if( indicator != 0 )
		indicator->setValue(curPos, modified);
		if( (state & sfActive) != 0 )
		updateCommands();
		updateFlags = 0;
	}
}

void TEditor::draw()
{
	if( drawLine != delta.y )
		{
		drawPtr = lineMove( drawPtr, delta.y - drawLine );
		drawLine = delta.y;
		}
	drawLines( 0, size.y, drawPtr );
}

void TEditor::drawLines( int y, int count, ushort linePtr )
{

if (flatStatusPtr != this) updateFlatStatus();

	ushort color = getColor(0x0201);
    drawnLine = drawLine;
	while( count-- > 0 )
	{
	ushort b[maxLineLength];
	formatLine( b, linePtr, delta.x+size.x, color );
	writeBuf(0, y, size.x, 1, &b[delta.x]);
	linePtr = nextLine(linePtr);
	y++;
    drawnLine++;
	}
}

ushort TEditor::nextTrueChar( ushort p )
{
int wasAfterGap = False;

p -= (FP_OFF(buffer) );
if (p >= curPtr) wasAfterGap = True;
if (wasAfterGap)
	{
	if (p-gapLen == bufLen) goto _end;
	}
else
	{
	if (p == bufLen) goto _end;
	}
p++;
if (wasAfterGap)
	{
	if (p - gapLen >= curPtr && !wasAfterGap) p += gapLen;
	}
else
	{
	if (p >= curPtr && !wasAfterGap) p += gapLen;
	}
_end:
return (p + (FP_OFF(buffer) ));
}

ushort TEditor::prevTrueChar( ushort p )
{
int wasAfterGap = False;

p -= (FP_OFF(buffer) );
if (p >= curPtr) wasAfterGap = True;
if (wasAfterGap)
	{
	if (p-gapLen == 0) goto _end;
	}
else
	{
	if (p == 0) goto _end;
	}
p--;
if (wasAfterGap)
	{
	if (p - gapLen < curPtr && wasAfterGap) p -= gapLen;
	}
else
	{
	if (p < curPtr && wasAfterGap) p -= gapLen;
	}
_end:
return(p + (FP_OFF(buffer) ));

}

void TEditor::curWord(ushort p, char *dest)
{
int lowlimit = False;
char a;
char c[2] = "X";
strcpy(dest, "");


a = *(char *)MK_FP(FP_SEG(buffer),p);
while ((a >= '0' && a <= '9') || (a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z') || a == '_' || a == '@')
	{
	if (prevTrueChar(p) == p)
		{
		lowlimit = True;
		break;
		}
	p = prevTrueChar(p);
	a = *(char *)MK_FP(FP_SEG(buffer),p);
	}

if (!lowlimit) p = nextTrueChar(p);
a = *(char *)MK_FP(FP_SEG(buffer),p);
while ((a >= '0' && a <= '9') || (a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z') || a == '_' || a == '@')
	{
	if (nextTrueChar(p) == p) break;
	c[0] = *(char *)MK_FP(FP_SEG(buffer),p);
	if (strlen(dest) < 254)
		strcat(dest,c);
	p = nextTrueChar(p);
	a = *(char *)MK_FP(FP_SEG(buffer),p);
	}
}

void TEditor::curLine(ushort p, char *dest)
{
char c[2] = "X";
strcpy(dest, "");
char a;
int i;

p = lineStart(p);
if (p >= curPtr) p += gapLen;

a = ((char *)buffer+p)[0];

while (a != '\n' && a != '\r' && bufLen+gapLen > p)
	{
	if (strlen(dest) < 254)
		{
		if (nextTrueChar(p) == p) break;
		c[0] = a;
		if (a == '\t')
			{
			c[0] = ' ';
			for (i=0;i<tabLen;i++)
				strcat(dest,c);
			}
		else
			strcat(dest,c);
		}
	p = nextTrueChar(p);
	if (p == curPtr) p += gapLen;
	a = ((char *)buffer+p)[0];
	}
c[0] = ' ';
for (i = strlen(dest);i < 80;i++)
	strcat(dest,c);

}



#pragma warn -par
void TEditor::formatLine( void *b,  ushort linePtr, int x, ushort color)
{

if (flatStatusPtr != this) updateFlatStatus();

if (flat || alwaysflat)
	{
	formatFlatLine( b, linePtr, x, color);
	return;
	}


int count = 0;
int i,j;
ushort ptr2;
char *p;
char tmp[3]="XX",*tmpendptr;
unsigned char a, c, d;
void *pointeur;
int processing=0;
char word[256];
int first = True;
int block = False;
int colused = NORMALTEXT;
int nextcolused = 0;
unsigned char colorset[11];
unsigned char selcolor = (color & 0xFF00) >> 8;
signed int spccolor=-1;
int spccount=0;
int inString=0;
int breakLine=0;

if (projectMain(this))
	breakLine = isBreakPoint(drawnLine+1);

//int unknown = color & 0xFF;
/*int remarques = 0x17;
int ponctuation = 0x1F;
int chiffres = 0x1A;
int chaines = 0x1C;
int labels = 0x1D;
int predefined = 0x1B;
int reserved = 0x1F;*/


colorset[NORMALTEXT] = color & 0xFF;
colorset[COMMENTS] = palette[26];
colorset[SYMBOLS] = palette[24];
colorset[NUMBERS] = palette[25];
colorset[STRINGS] = palette[27];
colorset[LABELS] = palette[29];
colorset[RESERVED] = palette[23];
colorset[PREDEFINED] = palette[28];
colorset[DIRECTIVES] = palette[30];
colorset[BREAKPOINTS] = palette[31];


block = False;
ushort base = selStart;
pointeur = b;
processing++;
goto doit;

__1:

block = True;
base = curPtr;
processing++;
goto doit;

__2:

block = True;
base = selEnd+gapLen;
linePtr += gapLen;
processing++;
goto doit;

__3:

block = False;
base = bufSize;
processing++;
goto doit;



doit:
if (base > linePtr)
	{
	linePtr += FP_OFF(buffer);
	while (count < x && linePtr < base+FP_OFF(buffer))
		{
		p = (char *)MK_FP(FP_SEG(buffer),linePtr);
		a = *p;
        if (a=='\r' || a == '\n')
        	{
			a = ' ';
			colused = NORMALTEXT;
			if (breakLine)
				colused = BREAKPOINTS;
			for (count=count; count < x;count++)
				{
				*(char *)pointeur = a;
				if (!block) *((char *)pointeur+1) = colorset[colused]; else *((char *)pointeur+1) = selcolor;
				(char *)pointeur += 2;
				linePtr++;
				}
            break;
            }
		if (a != 0x09 && a != 0x0D)
			{
			if (colused == COMMENTS || colused == LABELS || colused == DIRECTIVES) goto clrfound2;
			if (first && a == '*')
				{
				colused = COMMENTS;
				goto clrfound2;
				}
			if (first && a == ':')
				{
				colused = LABELS;
				goto clrfound2;
				}
			if (first && a == '#')
				{
				colused = DIRECTIVES;
				goto clrfound2;
				}
			if (nextcolused != 0)
				{
				colused = nextcolused;
				nextcolused = 0;
				}
			if (((a == ';')||(a == '\'')) && !inString)
				{
				colused = COMMENTS;
				goto clrfound2;
				}
			if (a == 34)
				{
				if (!inString)
					{
					colused = STRINGS;
                    inString=1;
					}
				else
					{
					nextcolused = NORMALTEXT;
					spccolor = -1;
                    inString=0;
					}
				goto clrfound2;
				}
			if (((a < '0' || (a > '9' && a < 'A') || (a > 'Z' && a < 'a') || (a > 'z')) && (a != '_')) && colused != COMMENTS && !inString)
				{
				colused = NORMALTEXT;
				}
			if (!inString)
				{
				if (a == ' ')
					{
					colused = NORMALTEXT;
					goto colorfound;
					}
				if (a == '(' || a == ')'
						 || a == '{'
						 || a == '}'
						 || a == '['
						 || a == ']'
						 || a == '*'
						 || a == '^'
						 || a == '/'
						 || a == '%'
						 || a == '+'
						 || a == '-'
						 || a == '='
						 || a == '>'
						 || a == '<'
						 || a == '!'
						 || a == '&'
						 || a == '|'
						 || a == ':'
						 || a == ','
						 || a == '-')
					{
					colused = SYMBOLS;
					goto colorfound;
					}
				c = *(char *)MK_FP(FP_SEG(buffer),prevTrueChar(linePtr));
				if (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z') || (linePtr == FP_OFF(buffer)) || (prevTrueChar(linePtr) == linePtr)) c = 1; else c = 0;
				if (c)
					{
					curWord(linePtr, word);
					colused = findcolor(word);
										}
				if (c && (a >= '0' && a <= '9') && colused == NORMALTEXT)
					{
					colused = NUMBERS;
					goto colorfound;
					}
				if (a == '.') colused = NUMBERS;
				colorfound:
				}
			else
				{
				if (a == '@' && !flatxnn)
					if (*(char *)MK_FP(FP_SEG(buffer),nextTrueChar(linePtr)) == 'X')
						{
						ptr2 = nextTrueChar(linePtr);
						c = *(char *)MK_FP(FP_SEG(buffer),nextTrueChar(ptr2));
						ptr2 = nextTrueChar(ptr2);
						d = *(char *)MK_FP(FP_SEG(buffer),nextTrueChar(ptr2));
						if ((((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'F'))) && (((d >= '0') && (d <= '9')) || ((d >= 'A') && (d <= 'F'))))
							{
							tmp[0] = c;
							tmp[1] = d;
							spccolor = (signed int)strtol(tmp,&tmpendptr,16);
							spccount = 0;
							goto clrfound2;
							}
						}
				}
			clrfound2:
            if (breakLine)
				colused = BREAKPOINTS;
			if (spccolor != -1)
				{
				if (spccount == 4)
					{
                    if (breakLine)
		                spccolor = colorset[colused];
					*(char *)pointeur = a;
					if (!block) *((char *)pointeur+1) = spccolor; else *((char *)pointeur+1) = selcolor;
					(char *)pointeur += 2;
					if (a != ' ' && first) first = False;
					count++;
					linePtr++;
					}
				else
					{
					spccount++;
//					count++;
					linePtr++;
					}
				}
			else
				{
				*(char *)pointeur = a;
				if (!block) *((char *)pointeur+1) = colorset[colused]; else *((char *)pointeur+1) = selcolor;
				(char *)pointeur += 2;
				if (a != ' ' && first) first = False;
				count++;
				linePtr++;
 				}
			}
		else
			{
            if (breakLine)
				colused = BREAKPOINTS;
			if (a == 0x09)
				{
				a = ' ';
				j = ((((int)count/tabLen)+1)*tabLen)-count;
				for (i = 0; i < j; i++)
					{
					*(char *)pointeur = a;
					if (!block) *((char *)pointeur+1) = colorset[colused]; else *((char *)pointeur+1) = selcolor;
					(char *)pointeur += 2;
					count++;
					}
				linePtr++;
				}
/*			if (a == 0x0D)
				{
				a = ' ';
				for (count=count; count < x;count++)
					{
					*(char *)pointeur = a;
					if (!block) *((char *)pointeur+1) = colorset[NORMALTEXT]; else *((char *)pointeur+1) = selcolor;
					(char *)pointeur += 2;
					linePtr++;
					}
				}*/
			}
		}
	linePtr -= FP_OFF(buffer);
	}
if (processing == 1) goto __1;
if (processing == 2) goto __2;
if (processing == 3) goto __3;
}
#pragma warn .par

void TEditor::find()
{
	TFindDialogRec findRec( findStr, editorFlags );
    if( editorDialog( edFind, &findRec ) != cmCancel )
	{
	strcpy( findStr, findRec.find );
        editorFlags = findRec.options & ~efDoReplace;
	doSearchReplace();
        }
}

ushort TEditor::getMousePtr( TPoint m )
{
    TPoint mouse = makeLocal( m );
	mouse.x = max(0, min(mouse.x, size.x - 1));
    mouse.y = max(0, min(mouse.y, size.y - 1));
    return charPtr(lineMove(drawPtr, mouse.y + delta.y - drawLine),
	mouse.x + delta.x);
}

TPalette& TEditor::getPalette() const
{
    static TPalette palette( cpEditor, sizeof( cpEditor )-1 );
    return palette;
}

void TEditor::checkScrollBar( const TEvent& event,
			      TScrollBar *p,
				  int& d
				)
{
    if( (event.message.infoPtr == p) && (p->value != d) )
	{
	d = p->value;
	update( ufView );
	}
}

int projectMain(void *ptr)
{
char *p;
if (strcmp(&desktopFile[strlen(desktopFile)-10], "DESKTOP.PP"))
	{
	fnsplit(desktopFile,drive3,dir3,fname3,ext3);
	strcpy(errorFichier,fname3);
	strcat(errorFichier,".PPS");
    p = ((TFileEditor *)ptr)->fileName;
    while (*p) p++;
    p-=strlen(errorFichier);
    if (!strcmpi(p , errorFichier))
		return 1;
	}
return 0;
}

void TEditor::handleEvent( TEvent& event )
{
    TView::handleEvent( event );
    convertEvent( event );
    Boolean centerCursor = Boolean(!cursorVisible());
    uchar selectMode = 0;
    uchar far *shiftState = (uchar far *)MK_FP( 0x40, 0x17 );
    unsigned char c;
    int a;

	if( selecting == True || (*shiftState & 0x03) != 0 )
	selectMode = smExtend;

    switch( event.what )
	{

	case evMouseDown:
	    if( event.mouse.doubleClick == True )
		selectMode |= smDouble;

	    do  {
		lock();
		if( event.what == evMouseAuto )
		    {
		    TPoint mouse = makeLocal( event.mouse.where );
		    TPoint d = delta;
		    if( mouse.x < 0 )
			d.x--;
		    if( mouse.x >= size.x )
			d.x++;
			if( mouse.y < 0 )
			d.y--;
			if( mouse.y >= size.y )
			d.y++;
		    scrollTo(d.x, d.y);
		    }
		setCurPtr(getMousePtr(event.mouse.where), selectMode);
		selectMode |= smExtend;
		unlock();
		} while( mouseEvent(event, evMouseMove + evMouseAuto) );
	    break;

	case evKeyDown:
	    if (errorDisplayed)
		{
		update(ufView);
		errorDisplayed = False;
		}
		if( event.keyDown.keyCode == kbTab ||
		( event.keyDown.charScan.charCode >= 32 && event.keyDown.charScan.charCode < 255 ) )
			{

			lock();
			if( overwrite == True && hasSelection() == False )
			if( curPtr != lineEnd(curPtr) )
				selEnd = nextChar(curPtr);

			insertText( &event.keyDown.charScan.charCode, 1, False);
			trackCursor(centerCursor);
			unlock();
			break;
			}
		if( event.keyDown.charScan.charCode == kbCtrlP)
			{
			unsigned char C;
			asm{
				MOV AX, 0
				INT 16h
				CMP AL,0
				JE rtah
				MOV C, AL
				JMP rt
				}
			rtah:
			asm MOV C, AH
			rt:

			insertText( &C, 1, False);
			break;
			}
		if( event.keyDown.keyCode == 0x1709 && hasSelection() && (*shiftState & 0x03) == 0 )
			{
			lock();
			ushort endPtr,startPtr;
			endPtr = selEnd;
			startPtr = selStart;
			int cnt=0;
			setCurPtr (startPtr, selectMode);
			insertText( " ", 1, False);
			cnt++;

			while (curPtr < bufPtr(endPtr+cnt))
				{
				setCurPtr(nextTrueChar(curPtr),selectMode);
				if (bufChar(curPtr) == '\n')
					{
					setCurPtr( nextTrueChar(curPtr), selectMode);
					if (curPtr < bufPtr(endPtr+cnt-1))
						{
						insertText( " ", 1, False);
						cnt++;
						}
					}
				}
			setCurPtr(bufPtr(endPtr+cnt), selectMode);
			selStart = startPtr;
			selEnd = curPtr;
			trackCursor(centerCursor);
			unlock();
			break;
			}
		if( event.keyDown.keyCode == 0x1615 && hasSelection() && (*shiftState & 0x03) == 0 )
			{
			lock();
			ushort endPtr,startPtr;
			endPtr = selEnd;
			startPtr = selStart;
			int cnt=0;
			setCurPtr (startPtr, selectMode);
			if (bufChar(curPtr) == ' ')
				{
				deleteRange(curPtr, nextChar(curPtr), True);
				cnt++;
				}

			while (curPtr < bufPtr(endPtr-cnt))
				{
				setCurPtr(nextTrueChar(curPtr),selectMode);
				if (bufChar(curPtr) == '\n')
					{
					setCurPtr( nextTrueChar(curPtr), selectMode);
					if (curPtr < bufPtr(endPtr-cnt-1))
						if (bufChar(curPtr) == ' ')
							{
							deleteRange(curPtr, nextChar(curPtr), True);
							cnt++;
							}
					}
				}
			setCurPtr(bufPtr(endPtr-cnt), selectMode);
			selStart = startPtr;
			selEnd = curPtr;
			trackCursor(centerCursor);
			unlock();
			break;
			}

		return;

	case evCommand:
		switch( event.message.command )
		{
        case cmToggleBp:
        	if (projectMain(this))
            	{
	        	if (isBreakPoint(curPos.y+1))
	            	removeBreakPoint(curPos.y+1);
	            else
	            	addBreakPoint(curPos.y+1);
				update(ufView);
	            break;
                }
        case cmClearBp:
        	for (a=0;a<128;a++)
            	breakPoint[a]=0;
			update(ufView);
            break;
		case cmFind:
			find();
			break;
		case cmReplace:
			replace();
			break;
		case cmSearchAgain:
			doSearchReplace();
			break;
		default:
			if (errorDisplayed)
			{
			update(ufView);
			errorDisplayed = False;
			}
			lock();
			switch( event.message.command )
			{
			case cmCut:
				clipCut();
				break;
			case cmCopy:
				clipCopy();
				break;
			case cmPaste:
				clipPaste();
				break;
			case cmUndo:
				undo();
				break;
			case cmClear:
				deleteSelect();
				break;
			case cmCharLeft:
				c = *(char *)MK_FP(FP_SEG(buffer),FP_OFF(buffer)+prevTrueChar(curPtr));
				if (c != '\n')
				setCurPtr(prevChar(curPtr), selectMode);
				break;
			case cmCharRight:
				setCurPtr(nextChar(curPtr), selectMode);
				break;
			case cmWordLeft:
				setCurPtr(prevWord(curPtr), selectMode);
				break;
			case cmWordRight:
				setCurPtr(nextWord(curPtr), selectMode);
				break;
			case cmLineStart:
				setCurPtr(lineStart(curPtr), selectMode);
				break;
			case cmLineEnd:
				setCurPtr(lineEnd(curPtr), selectMode);
				break;
			case cmLineUp:
				setCurPtr(lineMove(curPtr, -1), selectMode);
				break;
			case cmLineDown:
				setCurPtr(lineMove(curPtr, 1), selectMode);
				break;
			case cmPageUp:
				setCurPtr(lineMove(curPtr, -(size.y-1)), selectMode);
				break;
			case cmPageDown:
				setCurPtr(lineMove(curPtr, size.y-1), selectMode);
				break;
			case cmTextStart:
				setCurPtr(0, selectMode);
				break;
			case cmTextEnd:
				setCurPtr(bufLen, selectMode);
				break;
			case cmNewLine:
				if (crcchk == kInvalid)
					entercount++;
	        	if (projectMain(this))
    	        	{
                    if (curPtr == lineStart(curPtr))
                	    {
		                shiftBreakPoints(curPos.y+1, 1);
					    shiftTags(curPos.y+1, 1);
				        if (Tagger)
						    TaggerWindow->update();
                        }
                    else
                	    {
		                shiftBreakPoints(curPos.y+2, 1);
					    shiftTags(curPos.y+2, 1);
				        if (Tagger)
						    TaggerWindow->update();
                        }
                    }
				newLine();
				break;
			case cmBackSpace:
	        	if (projectMain(this))
    	        	{
        	        if (curPtr == lineStart(curPtr))
            	    	{
		        	    shiftBreakPoints(curPos.y+1, -1);
						shiftTags(curPos.y+1, -1);
					    if (Tagger)
							TaggerWindow->update();
            	        }
                    }
				deleteRange(prevChar(curPtr), curPtr, True);
				break;
			case cmDelChar:
	        	if (projectMain(this))
    	        	{
        	        if (curPtr == lineEnd(curPtr))
            	    	{
						shiftBreakPoints(curPos.y+1, -1);
						shiftTags(curPos.y+1, -1);
					    if (Tagger)
							TaggerWindow->update();
            	        }
                    }
				deleteRange(curPtr, nextChar(curPtr), True);
				break;
			case cmDelWord:
				deleteRange(curPtr, nextWord(curPtr), False);
				break;
			case cmDelStart:
				deleteRange(lineStart(curPtr), curPtr, False);
				break;
			case cmDelEnd:
				deleteRange(curPtr, lineEnd(curPtr), False);
				break;
			case cmDelLine:
				deleteRange(lineStart(curPtr), nextLine(curPtr), False);
				break;
				case cmInsMode:
				toggleInsMode();
				break;
			case cmStartSelect:
				startSelect();
				break;
			case cmHideSelect:
				hideSelect();
				break;
			case cmIndentMode:
				autoIndent = Boolean(!autoIndent);
				break;
			default:
				unlock();
				return;
			}
			trackCursor(centerCursor);
			unlock();
			break;
		}

	case evBroadcast:
		switch( event.message.command )
		{
		case cmScrollBarChanged:
			checkScrollBar( event, hScrollBar, delta.x );
			checkScrollBar( event, vScrollBar, delta.y );
			break;

		case 1520:
			TPalette *p = (TPalette *)event.message.infoPtr;
			palette = p->data;
			palette++;
		    break;

		case 1534:
		    lock();
			if( overwrite == True && hasSelection() == False )
			if( curPtr != lineEnd(curPtr) )
				selEnd = nextChar(curPtr);
			insertText( &event.message.infoInt, 1, False);
			trackCursor(centerCursor);
			unlock();
			break;

		case 1548:
		    lock();
		    if( overwrite == True && hasSelection() == False )
			if( curPtr != lineEnd(curPtr) )
			    selEnd = nextChar(curPtr);
			char *colorcode = "XXXX";
			sprintf(colorcode, "@X%02X", event.message.infoInt);
			insertText(colorcode, 4, False);
			trackCursor(centerCursor);
			unlock();
			break;

		case 1544:
			if (autoindentmode) autoIndent = True; else autoIndent = False;
			if (creatBAK) editorFlags |= efBackupFiles; else editorFlags &= ~efBackupFiles;
			return;

		case 1549:
			lock();
			setCurPtr(curPtr, selectMode);
			trackCursor(centerCursor);
			unlock();
			break;

		default:
		    return;
		}
	}
	clearEvent(event);
}

void TEditor::updateFlatStatus()
{
if (!alwaysflat)
	{
	char temp[255];
	strcpy(temp,((TFileEditor *)this)->fileName);
	if (((strncmp(&temp[strlen(temp)-4], ".PP",3)) && (strcmp(temp, ""))) || (this == clipboard))
		flat = 1;
	else
		flat = 0;
	}
flatStatusPtr = this;
}

