Problem Textbox

Started by
12 comments, last by bobojoga 12 years, 3 months ago
I'm trying to make an insert input so you can type your nickname. I made a box to limit the number of characters but the problem is that you can type unlimitedly and the box won't stop you. I want as soon as the character reach the end of the box I won't let the user type more or push the last characters back, like it would be normally in other games. I hope you understand me smile.gif

34qkc4o.jpg
Advertisement
Like you said, you have added a limit to the number of characters right?

Then, I assume the following possibilities:
1) The max number of characters are less than the width of the box, therefore no adjustment is needed
2) The max number of characters goes beyond the size of the box, then it is needed to bring the text back.

In order to fix number 2, I did something like the following on mine GUI:

class TextBox : public UIElement
{
private:
std::string *text;
std::string *view_text;
int maxChar;
(...)

public:
void EnterText(char c); /*Adds or removes a character from the string text*/
void UpdateText(); /*Updates the string that is being viewed (view_text)*/
void Render(...); /*Renders the box + the view_text string*/
(...)
}

void TextBox::UpdateText()
{
int max = (this->width / CHAR_WIDTH); /*Calculates how many characters can be viewed on the box*/
int i = text->size - max; /*Calculates the first character from the string to be printed*/

if(i < 0)
i = 0;
else
this->view_text->assign(this->text, i, max);

/*Reallocates the surface that will have the text blitted*/
SDL_FreeSurface(srf_Text);
srf_Text = TTF_RenderText_Solid(view->text, color, ...);
}

void TextBox::Render(...)
{
(...)
DrawImage(srf_Text, srf_Screen, ...);
}


It is something like that... you just have to calculate the first character position to be drawn, and the last will be always (textbox->width / char_width) where char_width is the width of your font character.
Programming is an art. Game programming is a masterpiece!
Define a fixed size for the username. When the user is entering text, simply drop characters when the text is at its greatest length. You should make a little beep sound or give some kind of visual feedback that a limit is reached.

Doing what kuramayoko10 suggests, where you keep the additional characters in the buffer but only render the ones that fix, is brittle because it is all too easy to save or send the longer username. Plus you do not want your display logic being responsible for maintaining such an invariant.

If you're using a fixed width font, then you could probably set 20 characters as your max size. If you're using a variable width font, you might need to cut it down a bit (e.g. 15 characters). If you find that this is too small for the kinds of user names you wish to support, consider making the text smaller.

Don't forget it is becoming the standard to use the user's email address as their primary login name. Their "username" is more of a nickname/ anonymity token.
Thanks you for helping me. I have another problem here, could you help me? The thing is that when I draw a text, after something like 4 min the text just disappears. It's really weird. Any ideas?
Sounds like a bug. Have you broken into your application using a debugger when this is happening?

We're not psychic unfortunately, we cannot debug code we cannot see =]
Here is code:
´bool drawText(int red, int green, int blue, int alpha, string text, string filenamefont, string align, int size, int x, int y)
{
SDLCFont = TTF_OpenFont(filenamefont.c_str(), size);
if (!SDLCFont == NULL)
{
if (red > 255) { red = 255; }
if (green > 255) { green = 255; }
if (blue > 255) { blue = 255; }
if (alpha > 255) { alpha = 255; }
SDL_Color scolors;
SDL_Rect offset;
int width = 0;
int height = 0;
scolors.r = red;
scolors.g = green;
scolors.b = blue;
if (TTF_SizeText(SDLCFont, text.c_str(), &width, &height) == 0)
{
if (align == "left") { offset.x = x-width; }
else if (align == "center") { offset.x = x-width/2; }
else if (align == "right") { offset.x = x; }
offset.y = y;
SDLMessages = TTF_RenderText_Blended( SDLCFont, text.c_str(), scolors );
//SDL_SetAlpha(SDLMessages, SDL_SRCALPHA, alpha);
if ( SDL_BlitSurface(SDLMessages, NULL, SDLFunctionsScreenGame, &offset) )
{
//SDL_Flip(SDLMessages);
return true;
}
}
}
else
{
cout << "Error TTF: " << TTF_GetError() << endl;
return false;
}
TTF_CloseFont(SDLCFont);
return false;
}


when I got an error with the last code, I created my own class for it:
cpp

#include "include.h"

using namespace std;

SDL_Surface *TTFScreenGame = NULL;

void onTextStart(SDL_Surface* SceenGame)
{
TTFScreenGame = SceenGame;
}

Text::Text(string filename, int size)
{
TTF_Init();
ttffont = TTF_OpenFont(filename.c_str(), size);
if (!filename.length() == 0 && size)
{
ifstream CheckFile(filename);
if ( CheckFile.is_open() )
{
ttffont = TTF_OpenFont(filename.c_str(), size);
if (!ttffont == NULL)
{
cout << "Loaded TTF: \"" << filename << "\"" << endl;
ttfloaded = true;
}
else
{
cout << "Error: " << TTF_GetError() << endl;
ttfloaded = false;
}
CheckFile.close();
}
else
{
cout << "Error: Can't find \"" << filename << "\" file." << endl;
ttfloaded = false;
}
}
else
{
cout << "Error: You did not enter filename and/or size" << endl;
ttfloaded = false;
}
}

Text::~Text()
{
delete ttffont;
delete messages;
ttffont = NULL;
messages = NULL;
TTF_CloseFont(ttffont);
SDL_FreeSurface(messages);
}

void Text::Render(int red, int green, int blue, int alpha, string text, string align, int size, int x, int y)
{
if (ttfloaded == false) { return; }
if (red > 255) { red = 255; }
if (green > 255) { green = 255; }
if (blue > 255) { blue = 255; }
if (alpha > 255) { alpha = 255; }
SDL_Color scolors;
SDL_Rect offset;
int width = 0;
int height = 0;
scolors.r = red;
scolors.g = green;
scolors.b = blue;
if (TTF_SizeText(ttffont, text.c_str(), &width, &height) == 0)
{
if (align == "left") { offset.x = x-width; }
else if (align == "center") { offset.x = x-width/2; }
else if (align == "right") { offset.x = x; }
offset.y = y;
messages = TTF_RenderText_Blended(ttffont, text.c_str(), scolors );
SDL_SetAlpha(Messages, SDL_SRCALPHA, alpha);
SDL_BlitSurface(messages, NULL, TTFScreenGame, &offset);
}
}

int Text::GetFontWidth(string text)
{
int width = 0;
int height = 0;
if (TTF_SizeText(ttffont, text.c_str(), &width, &height) == 0)
{
return width;
}
return 0;
}


h
#ifndef TEXT_H
#define TEXT_H

#include "include.h"

using namespace std;

void onTextStart(SDL_Surface* SDLTTFScreeGame);

class Text
{
private:
SDL_Surface *messages;
TTF_Font *ttffont;
bool ttfloaded;

public:
Text(string, int);
~Text();
void Render(int, int, int, int, string, string, int, int, int);
int GetFontWidth(string);
};

#endif
Well, it would appear you're leaking memory like a sieve. It is not correct to call delete on something you did not new. Most of your functions leak some memory.

A better way to handle this is to split the responsibilities into different classes.

Here is a simple example I threw together. I contains little error handling, but it does at least check for errors. To use something like this you'll have to decide how you want to handle errors. Some people prefer to throw exceptions, others to mark the object as invalid somehow and to test the object before using it.

The code uses an approach to resource management called RAII: Resource Acquisition is Initialisation.

[Caveat: I haven't compiled nor tested this code.]

Text.hpp

#include <string>
#include "SDL.h"
#include "SDL_ttf.h"

// Usually in a separate utility header
class noncopyable
{
protected:
noncopyable() {}
private:
// Deliberately private and unimplemented!
noncopyable(const noncopyable &);
noncopyable &operator=(const noncopyable &);
};

class Font : noncopyable
{
public:
Font(const std::string &font, int size);

~Font();

SDL_Surface *renderText(const std::string &text, const SDL_Color &colour) const;
bool sizeText(const std::string &text, int &width, int &height) const;

private:
TTF_Font *font;
};

class Text : noncopyable
{
public:
enum Alignment
{
Left, Right, Centre
};

Text(Font *font);
~Text();

void setText(const std::string &text);
void setAlignment(Alignment alignment);
void setColour(int r, int g, int b);

void draw(SDL_Surface *screen, int x, int y);

private:
Font *font;
SDL_Surface *message;
Alignment alignment;
SDL_Color colour;
std::string string;
};

#endif


Text.cpp

#include "text.hpp"


Font::Font(const std::string &filename, int size)
{
font = TTF_OpenFont(filename.c_str(), size);
if(!font)
{
// Error handling
}
}

Font::~Font()
{
TTF_CloseFont(font);
}

SDL_Surface *Font::renderText(const std::string &text, const SDL_Color &colour) const
{
SDL_Surface *result = TTF_RenderText_Blended(font, text.c_str(), colour);
if(result == NULL)
{
// Error handling
}
return result;
}

bool Font::sizeText(const std::string &text, int &width, int &height) const
{
int result = TTF_SizeText(font, text.c_str(), &width, &height);
return (result == 0);
}

Text::Text(Font *font)
:
font(font),
message(0),
alignment(alignment)
{
if(font == NULL)
{
// Error handling
}
colour.r = 0;
colour.g = 0;
colour.b = 0;
}

Text::~Text()
{
if(message)
{
SDL_FreeSurface(message);
}
}

Uint8 sanitiseColour(int component)
{
if(component < 0)
{
return 0;
}
else if(component > 0xff)
{
return 0xff;
}
return component;
}

void Text::setColour(int r, int g, int b)
{
colour.r = sanitiseColour(r);
colour.g = sanitiseColour(g);
colour.b = sanitiseColour(b);
}

void Text::setText(const std::string &text)
{
if(string == text)
{
return;
}
string = text;

SDL_Surface *temp = font->renderText(string, colour);
if(temp)
{
std::swap(temp, message);
SDL_FreeSurface(temp);
}
else
{
// Error handling
}
}

void Text::setAlignment(Alignment alignment)
{
this->alignment = alignment;
}

void Text::draw(SDL_Surface *screen, int x, int y)
{
if(!message)
{
return;
}

int width = 0;
int height = 0;
bool result = font->sizeText(string, width, height);
if(!result)
{
// Error handling...
}
SDL_Rect destination = { x, y };
switch(alignment)
{
case Left:
destination.x = x - width;
break;
case Right:
destination.x = x - width / 2;
break;
case Centre:
destination.x = x;
break;
default:
// Error handling...
}

if(SDL_BlitSurface(message, NULL, screen, &destination) < 0)
{
// Error handling
}
}



What a sample program might look like:

#include <sstream>

#include "SDL.h"
#include "text.hpp"

int main( int argc, char* args[] )
{
if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
{
return 1;
}

std::atexit(&SDL_Quit);

if( TTF_Init() < 0)
{
return 1;
}

std::atexit(&TTF_Quit);

SDL_Surface *screen = SDL_SetVideoMode( 800, 600, 0, SDL_SWSURFACE);
if(!screen)
{
return 1;
}

Font font("somefont.ttf", 16);
Text text(&font);

text.setColour(0xff, 0x00, 0x00);
text.setAlignment(Text::Alignment::Centre);
text.setText("FPS: ?");

int frames = 0;
Uint32 previousTime = SDL_GetTicks();

bool running = true;
while(running)
{
SDL_Event event;
while( SDL_PollEvent(&event) )
{
if( event.type == SDL_QUIT )
{
running = false;
}
}

++frames;
Uint32 now = SDL_GetTicks();
if(now - previousTime > 1000)
{
std::stringstream stream;
stream << "FPS: " << frames;
text.setText(stream.str().c_str());
frames = 0;
previousTime = now;
}

text.draw(screen, screen->w / 2, screen->h / 2);

if( SDL_Flip( screen ) < 0 )
{
return 1;
}
}

return 0;
}

There are some other things in there you should research. For example, the noncopyable class prevents errors such as if you were to try the following code:

Font font2 = font;

Without the noncopyable type, the above code would compile and would cause an error during shutdown.

There is also the neat error handling trick in Text::setText(). A naive implementation would be:

SDL_FreeSurface(message);
SDL_Surface *message = font->renderText(string, colour);

This code has two issues. The minor issue is that if the call to renderText returns NULL then we end up having a blank string. This may or may not be desirable, as opposed to keeping a stale string. A more important point is that if renderText() were to throw an exception*, then the Text instance might be left with it's message pointer invalid.

Instead, we try the risky operation first, and store it in a temporary location. If the operation is successful, we then apply it safely to the object, and finally we deallocate the old resources.

[hr]

* Simple example of how this might happen. IIRC, SDL_TTF doesn't like empty strings. Someone might solve this by writing:

void Text::setText(const std::string &text)
{
if(text.empty())
{
text = " ";
}
// ...
}

Whoops, we might have triggered an allocation, which can fail and result in std::bad_alloc being thrown.
Thanks for helping, it is working now, I tested my game for an hour. There is a bug in your alignment, it's an easy-to-fix bug. One more thing, can I add a setFont function?

There is a bug in your alignment, it's an easy-to-fix bug.
[/quote]
As warned, I didn't test the code.


One more thing, can I add a setFont function?
[/quote]
No.

Of course you can, if you want. I didn't deal with ownership in that program, but one option would be to use std::shared_ptr<> to hold the Font instance.

Thanks for helping, it is working now, I tested my game for an hour. There is a bug in your alignment, it's an easy-to-fix bug. One more thing, can I add a setFont function?

So, what was the bug that you fixed?

This topic is closed to new replies.

Advertisement