History: Simple keyboard string editing
Source of version: 4 (current)
Copy to clipboard
This code snippet was originally created as a part of an in-game console. All it does is take key press events and either adds them to a string or otherwise manipulates it. This string can be retrieved at any time. It is currently setup for the use with ((OIS)), however this could be easily changed.
{maketoc}
!!Usage:
Define an instance any way you like:
{CODE(wrap="1", colors="c++")}EditString myEdit;
{CODE}
In an OIS keyboard listener:
{CODE(wrap="1", colors="c++")}
if( myEdit.injectKeyPress( arg ) == false )
{
// Did not use the key.
...
}
else
{
// Used the key so the string has possibly changed.
myTextBoxOverlayElement->SetCaption( myEdit.getText() );
...
// Display cursor somehow. Left as an exercise for the reader as
// I havn't figured out how I'm going to do it yet. :)
}
{CODE}
!!The Code
!!!EditString.h
{CODE(wrap="1", colors="c++")}
#pragma once
#include <string>
#define OIS_DYNAMIC_LIB
#include <OIS/OIS.h>
class EditString
{
public:
EditString(void) : mInsert(true), mPosition(mText.begin()), mCaret(0)
{}
EditString( std::string newText )
{
setText( newText );
}
~EditString(void)
{}
protected:
// The text for editing
std::string mText;
// Overwrite or insert
bool mInsert;
// Position for insert / overwrite
std::string::iterator mPosition;
// Caret Position - for positioning the cursor.
int mCaret;
public:
void setText( std::string & newText )
{
mText = newText;
mPosition = mText.end();
mCaret = (int)mText.length();
}
std::string & getText() { return mText; }
void clear()
{
mText.clear()
mPosition = mText.end();
mCaret = 0;
}
bool inserting() { return mInsert; }
bool injectKeyPress( const OIS::KeyEvent );
// gets the current position in the text for cursor placement
int getPosition(void) { return mCaret; }
};
{CODE}
!!!EditString.cpp
{CODE(wrap="1", colors="c++")}
#include "editstring.h"
// Process a key press. Return true if it was used.
bool EditString::injectKeyPress( const OIS::KeyEvent arg )
{
bool keyUsed = true;
if( isgraph( arg.text ) || isspace( arg.text ) )
{
if( mInsert || mPosition == mText.end() )
{
mPosition = mText.insert( mPosition, arg.text );
}
else
{
*mPosition = arg.text;
}
mPosition++;
mCaret++;
}
else
{
switch( arg.key )
{
case OIS::KC_BACK:
if( mPosition != mText.begin() )
{
mPosition = mText.erase( --mPosition );
--mCaret;
}
break;
case OIS::KC_INSERT:
mInsert = ! mInsert;
break;
case OIS::KC_HOME:
mPosition = mText.begin();
mCaret = 0;
break;
case OIS::KC_END:
mPosition = mText.end();
mCaret = (int)mText.length();
break;
case OIS::KC_LEFT:
if( mPosition != mText.begin() )
{
mPosition--;
mCaret--;
}
break;
case OIS::KC_RIGHT:
if( mPosition != mText.end() )
{
mPosition++;
mCaret++;
}
break;
case OIS::KC_DELETE:
if( mPosition != mText.end() )
mPosition = mText.erase( mPosition );
break;
default:
keyUsed = false;
break;
}
}
return keyUsed;
}
{CODE}