#include "stdafx.h"
#include "..\\Include\\CEditOutputStream.h"
#include <algorithm>
using namespace kaBasicClasses;
using namespace std;
CEditOutputStreamBuffer::CEditOutputStreamBuffer( CEdit* p )
: theBufferSize(1000)
{
theBuffer.reserve(theBufferSize+3);
setp( theBuffer.begin(), theBuffer.begin()+(theBufferSize-1));
theEditor=p;
}
CEditOutputStreamBuffer::~CEditOutputStreamBuffer()
{
flush();
}
void CEditOutputStreamBuffer::insertText( charType* string )
{
setCursorAtPosition(getCursorPosition()); //remove selection if any.
theEditor->ReplaceSel(string);
}
int CEditOutputStreamBuffer::flush()
{
int num=pptr()-pbase();
//I would like to say
// *pptr()='\0';
// insertText(&*theBuffer.begin());
//However, in the buffer of the CEdit, the end of line is represented
//by a couple of characters: /r/n: ascii(13) followed by ascii(10). So, the end
//of line has to be handled here.
bufferType::iterator startOfLine=theBuffer.begin();
bufferType::iterator endOfLine=startOfLine;
while( startOfLine<pptr() )
{
endOfLine=find(startOfLine,pptr(),charType('\n'));
charType ch1=*endOfLine;
charType ch2=*(endOfLine+1);
charType ch3=*(endOfLine+2);
if( endOfLine!=pptr() ) //the '\n' was found
{
*endOfLine=charType(13);
*(endOfLine+1)=charType(10);
*(endOfLine+2)=charType(0); //insertText requires a null terminated array of characters
insertText(&*startOfLine);
*endOfLine=ch1;
*(endOfLine+1)=ch2;
*(endOfLine+2)=ch3;
}
else //'\n' was not found: the regular string
{
*endOfLine=charType(0);
insertText(&*startOfLine);
*endOfLine=ch1;
}
startOfLine=endOfLine+1;
if( startOfLine<pptr() && *startOfLine==charType(13) )
startOfLine++;
}
pbump(-num);
return num;
}
CEditOutputStreamBuffer::int_type CEditOutputStreamBuffer::overflow( int_type c )
{
if( c!=EOF )
{
*pptr()=c;
pbump(1);
}
flush();
return c;
}
int CEditOutputStreamBuffer::getCursorPosition()
{
int n1, n2;
theEditor->GetSel(n1,n2);
return n2;
}
int CEditOutputStreamBuffer::getMaximalCursorPosition()
{
return theEditor->GetWindowTextLength();
}
void CEditOutputStreamBuffer::setCursorAtPosition( int pos )
{
theEditor->SetSel(pos,pos);
}
void CEditOutputStreamBuffer::setCursorAtBeginning()
{
theEditor->SetSel(0,0);
}
void CEditOutputStreamBuffer::setCursorAtEnd()
{
int n=getMaximalCursorPosition();
theEditor->SetSel(n,n);
}
void CEditOutputStreamBuffer::moveCursorBy( int pos )
{
setCursorAtPosition(getCursorPosition()+pos);
}