Jump to content

  • Log In with Google      Sign In   
  • Create Account


GUI/Window message system problem


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 18 May 2011 - 03:03 PM

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 :)

Sponsor:

#2 lpcstr   Members   -  Reputation: 118

Like
1Likes
Like

Posted 18 May 2011 - 04:16 PM

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;
};



#3 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 18 May 2011 - 10:08 PM

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.

#4 Trienco   Crossbones+   -  Reputation: 2050

Like
1Likes
Like

Posted 19 May 2011 - 02:04 AM

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

#5 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 19 May 2011 - 05:25 AM

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.

#6 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 21 May 2011 - 04:18 AM

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 Posted Image

#7 Ron AF Greve   Members   -  Reputation: 512

Like
1Likes
Like

Posted 21 May 2011 - 04:56 AM

(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

#8 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 21 May 2011 - 03:13 PM

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 Posted Image

#9 Ron AF Greve   Members   -  Reputation: 512

Like
1Likes
Like

Posted 21 May 2011 - 04:05 PM

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

#10 simpler   Members   -  Reputation: 912

Like
0Likes
Like

Posted 21 May 2011 - 04:18 PM

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?

#11 Ron AF Greve   Members   -  Reputation: 512

Like
1Likes
Like

Posted 21 May 2011 - 04:38 PM

Well that is actually rather simple for instance a button just creates an event object and passes that to its parent which could handle it or send it to its parent until it hits the root of the hierarchy. Currently it is stored there. So it can be either read by a containing class wich then adds it to the scheduler or I created one big hierarchy (they all derive from a scripting class) and let the non-gui object that created the gui handle them directly.

Although I tested both my scripting and gui I haven't hooked them up yet. But this is how it currently looks when a component sends an event:


class MGUIEventId
{
  private:
    size_t        Hash;
    std::string   Eventname;
    SVRefPtr<VVar> Parameters; // SVRefPtr is my smartptr ( intrusive refcnt ) type

  public:
    MGUIEventId():
      Hash     (       ),
      Eventname(       )
    {
    }

    // Probably should be constant, however it can't really be that way, since it reference counts also inside the variant (mutable would probably do)
    SVRefPtr<VVar> GetParameters() { return Parameters; }

    MGUIEventId( const std::string& Eventname ):
      Eventname( Eventname )
    {
  std::hash<const char*> HashFunction;
  Hash = HashFunction( Eventname.c_str() );
    }

    bool operator< ( const MGUIEventId& GUIEventId ) const
    {
      if( Hash < GUIEventId.Hash ) return true;
      else if( Hash == GUIEventId.Hash )
      {
        return Eventname < GUIEventId.Eventname;
      }
      return false;
    }

    bool operator==( const MGUIEventId& GUIEventId ) const
    {
      return GUIEventId.Hash      == this->Hash      &&
             GUIEventId.Eventname == this->Eventname
             ;
    }

    // ----Inspectors
    const size_t&       GetHash     () const { return Hash     ;}
    const std::string&  GetEventname() const { return Eventname;}

    // ----Mutators
    void SetHash     ( const size_t&        Hash      ) { this->Hash      = Hash     ;}
    void SetEventname( const std::string&   Eventname ) { this->Eventname = Eventname;}

    friend MChannel& operator<<( MChannel& Channel, const MGUIEventId& GUIEventId );
};

class MGUIEvent : public ISerializeScript
{
  private:
    MGUIEventId   GUIEventId;
    CLocation     Location;

  public:
    MGUIEvent():
      GUIEventId(       ),
      Location  (       )
    {
    }

    MGUIEvent( const std::string& Eventname, const CLocation& Location ):
      GUIEventId( Eventname ),
      Location  ( Location   )
    {
    }

    bool operator< ( const MGUIEvent& GUIEvent ) const
    {
      if( GUIEventId < GUIEvent.GUIEventId ) return true;
      else if( GUIEventId == GUIEvent.GUIEventId )
      {
        return Location < GUIEvent.Location;
      }
      return false;
    }

    bool operator==( const MGUIEvent& GUIEvent ) const
    {
      return GUIEvent.GUIEventId == this->GUIEventId &&
             GUIEvent.Location   == this->Location  
             ;
    }

    // ----Inspectors
    const MGUIEventId&  GetGUIEventId() const { return GUIEventId;}
    const CLocation&    GetLocation  () const { return Location  ;}

    // ----Mutators
    void SetGUIEventId( const MGUIEventId&&  GUIEventId ) { this->GUIEventId = GUIEventId;}
    void SetLocation  ( const CLocation&     Location   ) { this->Location   = Location  ;}

    friend MChannel& operator<<( MChannel& Channel, const MGUIEvent& GUIEvent );
};


// ----------------------in MComponent
void  MUIBase::Emit( const MGUIEvent& GUIEvent )

{

 if( Parent )

 {

  Parent->Emit( GUIEvent );

 }





}



void MComponent::Emit( const std::string Eventname, const CLocation& Location )

{

 MUIBase::Emit( MGUIEvent( Name + "::" + Eventname, Location ) );

}

In the root of the hierarchy  I overwirte various methods

void  MWindowGroup::Emit( const MGUIEvent& GUIEvent )
{
        Queue.push_back( GUIEvent );
}

 






edit: Ouch, forgot the most important thing, it needs a array of variants to pass on name-value pairs (the vvar contains a vvar map).
Ron AF Greve




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS