GUI/Window message system problem

Started by
9 comments, last by Ron AF Greve 12 years, 11 months ago
I've written my own window controls, so far I have textboxes, inputboxes, dropboxes, buttons, checkboxes and listboxes. I've got a base class called Window that all other window controls inherit from. I also have a class called WindowHandler that has a list of all windows and make sure that they get drawn and fed with user input. It has been working great and still does but my system has a big flaw; all windows have a value of the type string.


class Window
{
public:
...
void setValue(string value);
string getValue(void);
private:
string mValue; // every windows value
};



mValue can for example be the text in a inputbox, the value of a checkbox or the marked line in a listbox. That does for example mean that the value of a checkbox is either "true" or "false", and an example showing how ugly this is could look like this:


bool soundOn(void)
{
if(mSoundCheckBox.getValue() == "true")
return true;
else if(mSoundCheckBox.getValue() == "false")
return false;
}


Maybe even uglier than this is the way I get the int value from an InputBox;


int platformX = atoi(mInputX.c_str());


So I'm looking for a better way to do this and I was quite happy yesterday when I came up with the idea of using templates. The idea is to store the value as a generic type so it can be whatever it should be. For an inputbox it could be a float or int or string and for a checkbox a bool and for a slidebar int or float. That would allow me to do this instead of the above;



bool soundOn(void)
{
return mSoundCheckBox.getValue(); // mValue is declared as a bool
}


Some code showing how I think;


template<class T>

class Window
{
public:
...
void setValue(T value);
T getValue(void);
private:
T mValue; // every windows value
};


Creation of a InputBox:

InputBox<int> inputBox = new InputBox(mWindowHandler, 500, 500, 100, 20);


It feels like a smart way to do it but ofcourse I encounter problems.. To start with the vector inside WindowHandler doesn't seem able to do what I want:


class WindowHandler
{
...
private:
template<class T>
vector<Window<T>> mWindowList; // compiler crashes
}


I'm not going to show any more code, because I'm starting to feel like there are much better ways to do what I want in. What I'm looking for is basicly a generic way to store different types of values inside different window types. I also need a way to send data with different types in a messaging system.

I'd love to read your opinion about how this should be done.

Cheers,
simpler :)
Advertisement
Why do your controls rely on a single generic value? What if a control requires more than one value?

A check box may want to have a text value at the same time as having a bool state.


class TextBox : public Window
{
public:
const std::string& getText() const;
void setText(const std::string& str);
private:
std::string mText;
};

class CheckBox : public Window
{
public:
const std::string& getText() const;
void setText(const std::string& str);

bool getValue() const;
void setText(bool value);

private:
std::string mText;
bool mValue;
};

Yes ofcourse a lot of windows will have more members than just one. But the idea with mValue is that that's the value that the user can get. In your case with the checkbox the only value that the user is interested in is the bool mValue, to see if it's checked or not. Hope you understand what I mean.

Yes ofcourse a lot of windows will have more members than just one. But the idea with mValue is that that's the value that the user can get. In your case with the checkbox the only value that the user is interested in is the bool mValue, to see if it's checked or not. Hope you understand what I mean.


The user will want to work with Gui elements in a way that makes sense for this element, not through some over-generic base class interface. You put stuff in there that they share, but dont dump some "most generic type"-thing in there and force every derived element to put up with it no matter how much or little sense it might make. Look at existing libraries. Does Qt, wx or any other common lib force you to work with buttons and lists as if they were windows?
f@dzhttp://festini.device-zero.de
Yeah you are right. I will make each type of gui element to have their own appropriate type of value. However, how should I do with inputboxes? Some should store strings and others numbers. Is it best for them to store a generic value or should I store all values as strings and then use something like boost::lexical_cast in the getValue() function.

The InputBox constructor would take a enum argument which decides what type it should return in getValue().

Also, how should I make a message system that can send different types of data? If a checkbox gets presses it should send it's bool vale to messageHandler(), and a inputbox would send it's string or int value.
After a lot of headaches I've finally got it to work close to the way I wanted. All windows now have a appropriate value, and it works great but I want to ask you about the way I handled InputBoxes. An InputBox can currently have three values: string, int and float. First I thought about having a generic value member so it would look like this:


template <class T>
class InputBox : public Window
{
public:
InputBox(....);
...
T getValue(void) {
return mValue;
}
void setValue(T value) {
mValue = value;
}
private:
T mValue;
};


But that led to some code that I didn't like.


InputBox<int> inputBox(500, 500, 50, 50, "bkgd.bmp"); // <int> :/
inputBox.setValue(345);

int value = inputBox.getValue<int>(); // i believe the <int> is ugly and makes up a bad user interface


So instead of that I decided that every InputBox should store the value as a string, and then cast it to the right value when it's going to get returned. Like this:



class InputBox : public Window
{
public:
InputBox(....);
...
void setValue(string value);
void setValue(int value);
void setValue(float value);

int getInt(void);
float getFloat(void);
string getString(void);
private:
string mValue;
};




void InputBox::setValue(string value)
{
mValue = value;
}

void InputBox::setValue(int value)
{
mValue = boost::lexical_cast<string>(value);
}

void InputBox::setValue(float value)
{
mValue = boost::lexical_cast<string>(value);
}

int InputBox::getInt(void)
{
return boost::lexical_cast<int>(mValue);
}

float InputBox::getFloat(void)
{
return boost::lexical_cast<float>(mValue);
}

string InputBox::getString(void)
{
return mValue;
}


That makes the interface look like this:


InputBox inputBox(500, 500, 50, 50, "bkgd.bmp");
inputBox.setValue(512);

int value = inputBox.getInt();


Which in my opinion feels a lot better, but please tell me what you think and if there are even better ways!
I also plan on doing the same thing with windows messages, that the message store the value as a string and then you call getInt() or getString() depending on what you want.

I'd love some feedback and thoughts smile.gif
(I am also working on my gui system and haven't got everything working yet)

I think there are two ways you can do things.

1. Have a nice clean design. Every control that contains other controls knows their exact type. That means every control, that can contain other controls, needs a container for that control. For instance if I have a panel that can contain anything I need a container for buttons, one for input boxes another one for sliders etc. Every time you invent another control go over all your code to add it everywhere. Clean, correct but it will be lots of work.

2. Just call everything a component. (or window or whatever). Actually this is what you do (and what I do in my gui-system). My gui system however uses messages with an map of my own variant type (map<string, VVar>). So for instance my button would set the following values

<"name", "component name">

<"event", "component name_LButtonDown">

<"X", mouseXPos>

etc.

And then would send it to its parent which send it to its parent and so forth until it reaches the top of the chain. There it would lookup the event name in the current object to see if there is a handler with that name and call that and passing the parameters to the function. When no function is found nothing happens when it does find a function it will compile it (I wrote my compiler using a hand written front end and LLVM as backend). Variables in the function first resolves to locally declared variables (the fastest) then it will look in the map of passed in variables and lastly it will go back to the object it is running on (this is the slowest since it has to look up every time it accesses the variable since it might have been created during execution).



I haven't yet thought how to get the text from my text control. But I think I could just send the control a message that would ask it to either send the text in response. The map-variant type makes it generic very flexible but also a bit slower (but this is GUI stuff so I don't think that would be a problem).

As a side note, the way you have various methods to convert a string to float, int etc. is exactly how I implemented my XML file reader. Since the nodes themselves are always strings. this was the easiest way to keep a generic XML reader that I can use for any file by only changing the tags.


edit: Fixed some typos
Ron AF Greve
Thanks for a great reply Ron AF Greve!

Can you tell me how you store different types in a map? I've never used maps before but from what I found it seems impossible to store a generic type, but if you got a work-around please tell me :)

I have now added and completed the window messaging system, it might not be the best way but it works fine. Looking like this:



class WindowMessage
{
public:
WindowMessage(string data);
WindowMessage(int data);
WindowMessage(float data);
WindowMessage(bool data);
~WindowMessage();

int getInt(void);
float getFloat(void);
string getString(void);
bool getBool(void);

private:
string mData;
};





WindowMessage::WindowMessage(string data)
{
mData = boost::lexical_cast<string>(data);
}

WindowMessage::WindowMessage(int data)
{
mData = boost::lexical_cast<string>(data);
}

WindowMessage::WindowMessage(float data)
{
mData = boost::lexical_cast<string>(data);
}

WindowMessage::WindowMessage(bool data)
{
if(data)
mData = "true";
else
mData = "false";
}

WindowMessage::~WindowMessage()
{
// dtor
}

std::string WindowMessage::getString(void)
{
return mData;
}

int WindowMessage::getInt(void)
{
return boost::lexical_cast<int>(mData);
}

float WindowMessage::getFloat(void)
{
return boost::lexical_cast<float>(mData);
}

bool WindowMessage::getBool(void)
{
if(mData == "true")
return true;
else
return false;
}



And the message handler function which each window control gets connected to by a boost::function member uses the messages like this:

bool Editor::messageHandler(WindowID id, WindowMessage msg)
{
switch(id) { case INPUT_X_VALUE:
mActiveObject->setX(msg.getInt());
break;
}


I'm quite pleased with this, but I'm sure that your way with using maps is better. If anyone got an even better way of doing this, please share it rolleyes.gif
You're right you can't store more than one type in a map. But there is no need to since you store a pair of variants. One variant is the name, the key or the 'identifier' however you want to view it. The oter is the value so
map<*Variant, *Variant, comparator> Name2Value;




(Copy and paste of my code ) this is main part of my vairant class

class VVar : public ISerialize
{
public:
typedef enum { eNull = 0, eLong = 1, eDouble = 2, eString = 3, eMap = 4, eSRefPtr = 5, eWRefPtr = 6, eKey = 7, eAddress = 8, eInvalid = 254, eLastType } eType_t;





//__declspec(align(64))
union
{
Int64 Null; // Needed to keep scripting stuff logical (every type has a field so give one to eNull too)
Int64 Long;
double Double;
VVarString *VarString;
VVarMap *VarMap;
char SRefPtr [ sizeof( SVRefPtr<ISerialize> ) ];
char WRefPtr [ sizeof( WVRefPtr<ISerialize> ) ];
char KeyStroke[ sizeof( MKey ) ];
VVar *Var;
};
UInt16 Type;



So it just remembers the type in the int Type and all possiblle types are in a union.I created a special Varmap but it is just that I tried to opitimize things a bit a regual map would do too.
In the end it will always use the size of the largest type. The RefPtrs are smart pointers to an object. So it can store int's, double, longs, and maps of variants (i.e. recursively)

Note that if you store stl strings, maps or actually any object (like the MKey object in my example) you have to understand that the array of chars only reserve bytes. The object itself still has to be creaed in that space.

So you need to create it in that location, you also need to make sure the alignment is right. Best is to make sure it is aligned on a 64 boundary.


Example creating the MKey object in the union:
For instance from my VVar deserialization code



if( Archive.IsReading() )
{
CleanUp();
}

Archive.Serialize( Type );
switch( Type )
{
case eKey:
if( Archive.IsReading() )
{
new( this->KeyStroke ) MKey; // <----- In place new
}
reinterpret_cast<MKey *>( KeyStroke )->Serialize( Archive );
break;




So you could keep it simple (from the top of my head, this might contain errors and typos):



// check your compiler to make sure the union is on 64 bbyte boundary (so put char type behind it for one thing)
class CVariant

{
public:

typedef enum { eInt, eDouble, eObject, eString, eLastType } eType_t;
private:
union

{

int Int;
double Double;
void *Object;

char String[ sizeof( std::string) ]

};
char Type;

}


// Creaet variant with string inside
CVariant::CVariant( const std::string& String )

{
new ( this->String ) std::string( String );

Type = eString;
}

CVariant::~CVaraint()

{
switch( Type )

{

case eNull:

break;

case eString:
delete String;
break;
}

CVariant operator+( const CVariant& Variant )

{
switch ( Type )

{
case eString:
switch( Variant.Type )

{
case eInt:
stringstream Stream;

Stream << reinterpret_cast<std::string>( *String ) << Variant.Int;

return Variant( Stream.Str() );
break;
}
break;
}
}


Just begin simple with a int and double and one operator. Once you can add different types together like VarResult = Var1 + Var2 it will be fun to extent.


BTW: In my own code I use jump tables not switches in the operators. Saves expensive conditional jumps but makes it more complex. I created another program to create all combinations between types for all operators.
Ron AF Greve
Wow, thanks! You're way truly is a lot more advanced than mine. How Does it look when you use your messaging system, I mean, how does the interface look?

This topic is closed to new replies.

Advertisement