Wt examples  3.2.1
Public Member Functions | Protected Member Functions | Private Types | Private Member Functions | Private Attributes
SimpleChatWidget Class Reference

A self-contained chat widget. More...

#include <SimpleChatWidget.h>

Inheritance diagram for SimpleChatWidget:
Inheritance graph
[legend]

List of all members.

Public Member Functions

 SimpleChatWidget (SimpleChatServer &server, Wt::WContainerWidget *parent=0)
 Create a chat widget that will connect to the given server.
 ~SimpleChatWidget ()
 Delete a chat widget.
void connect ()
void disconnect ()
void letLogin ()
 Show a simple login screen.
bool startChat (const Wt::WString &user)
 Start a chat for the given user.
void logout ()
SimpleChatServerserver ()
int userCount ()
const Wt::WStringuserName () const
- Public Member Functions inherited from Wt::WContainerWidget
 WContainerWidget (WContainerWidget *parent=0)
 ~WContainerWidget ()
void setLayout (WLayout *layout)
void setLayout (WLayout *layout, WFlags< AlignmentFlag > alignment)
WLayoutlayout ()
virtual void addWidget (WWidget *widget)
virtual void insertBefore (WWidget *widget, WWidget *before)
virtual void insertWidget (int index, WWidget *widget)
virtual void removeWidget (WWidget *widget)
virtual void clear ()
virtual int indexOf (WWidget *widget) const
virtual WWidgetwidget (int index) const
virtual int count () const
void setContentAlignment (WFlags< AlignmentFlag > contentAlignment)
void setPadding (const WLength &padding, WFlags< Side > sides=All)
WLength padding (Side side) const
WFlags< AlignmentFlagcontentAlignment () const
void setOverflow (Overflow overflow, WFlags< Orientation > orientation=(Horizontal|Vertical))
void setList (bool list, bool ordered=false)
bool isList () const
bool isUnorderedList () const
bool isOrderedList () const
EventSignal< WScrollEvent > & scrolled ()
 WInteractWidget (WContainerWidget *parent=0)
EventSignal< WKeyEvent > & keyWentDown ()
EventSignal< WKeyEvent > & keyPressed ()
EventSignal< WKeyEvent > & keyWentUp ()
EventSignalenterPressed ()
EventSignalescapePressed ()
EventSignal< WMouseEvent > & clicked ()
EventSignal< WMouseEvent > & doubleClicked ()
EventSignal< WMouseEvent > & mouseWentDown ()
EventSignal< WMouseEvent > & mouseWentUp ()
EventSignal< WMouseEvent > & mouseWentOut ()
EventSignal< WMouseEvent > & mouseWentOver ()
EventSignal< WMouseEvent > & mouseMoved ()
EventSignal< WMouseEvent > & mouseDragged ()
EventSignal< WMouseEvent > & mouseWheel ()
EventSignal< WTouchEvent > & touchStarted ()
EventSignal< WTouchEvent > & touchEnded ()
EventSignal< WTouchEvent > & touchMoved ()
EventSignal< WGestureEvent > & gestureStarted ()
EventSignal< WGestureEvent > & gestureChanged ()
EventSignal< WGestureEvent > & gestureEnded ()
void setDraggable (const std::string &mimeType, WWidget *dragWidget=0, bool isDragWidgetOnly=false, WObject *sourceWidget=0)
virtual void load ()
virtual bool isEnabled () const
 WWebWidget (WContainerWidget *parent=0)
virtual void setPositionScheme (PositionScheme scheme)
virtual PositionScheme positionScheme () const
virtual void setOffsets (const WLength &offset, WFlags< Side > sides=All)
virtual WLength offset (Side s) const
virtual void resize (const WLength &width, const WLength &height)
virtual WLength width () const
virtual WLength height () const
virtual void setMinimumSize (const WLength &width, const WLength &height)
virtual WLength minimumWidth () const
virtual WLength minimumHeight () const
virtual void setMaximumSize (const WLength &width, const WLength &height)
virtual WLength maximumWidth () const
virtual WLength maximumHeight () const
virtual void setLineHeight (const WLength &height)
virtual WLength lineHeight () const
virtual void setFloatSide (Side s)
virtual Side floatSide () const
virtual void setClearSides (WFlags< Side > sides)
virtual WFlags< SideclearSides () const
virtual void setMargin (const WLength &margin, WFlags< Side > sides=All)
virtual WLength margin (Side side) const
virtual void setHiddenKeepsGeometry (bool enabled)
virtual bool hiddenKeepsGeometry () const
virtual void setHidden (bool hidden, const WAnimation &animation=WAnimation())
virtual bool isHidden () const
virtual bool isVisible () const
virtual void setDisabled (bool disabled)
virtual bool isDisabled () const
virtual void setPopup (bool popup)
virtual bool isPopup () const
virtual void setInline (bool isInline)
virtual bool isInline () const
virtual void setDecorationStyle (const WCssDecorationStyle &style)
virtual WCssDecorationStyledecorationStyle ()
virtual void setStyleClass (const WString &styleClass)
virtual WString styleClass () const
virtual void addStyleClass (const WString &styleClass, bool force=false)
virtual void removeStyleClass (const WString &styleClass, bool force=false)
virtual void setVerticalAlignment (AlignmentFlag alignment, const WLength &length=WLength())
virtual AlignmentFlag verticalAlignment () const
virtual WLength verticalAlignmentLength () const
virtual void setToolTip (const WString &text, TextFormat textFormat=PlainText)
virtual WString toolTip () const
virtual void refresh ()
virtual void setAttributeValue (const std::string &name, const WString &value)
virtual WString attributeValue (const std::string &name) const
virtual void setJavaScriptMember (const std::string &name, const std::string &value)
virtual std::string javaScriptMember (const std::string &name) const
virtual void callJavaScriptMember (const std::string &name, const std::string &args)
virtual bool loaded () const
virtual void setTabIndex (int index)
virtual int tabIndex () const
virtual void setId (const std::string &id)
virtual WWidgetfind (const std::string &name)
virtual void setSelectable (bool selectable)
virtual void doJavaScript (const std::string &javascript)
virtual const std::string id () const
void setLoadLaterWhenInvisible (bool)
const std::vector< WWidget * > & children () const
SignalchildrenChanged ()
bool isRendered () const
virtual ~WWidget ()
WWidgetparent () const
void setWidth (const WLength &width)
void setHeight (const WLength &height)
virtual void positionAt (const WWidget *widget, Orientation orientation=Vertical)
std::string jsRef () const
virtual void acceptDrops (const std::string &mimeType, const WString &hoverStyleClass=WString())
virtual void stopAcceptDrops (const std::string &mimeType)
virtual void htmlText (std::ostream &out)
void hide ()
void animateHide (const WAnimation &animation)
void show ()
void animateShow (const WAnimation &animation)
void enable ()
void disable ()
bool layoutSizeAware () const
 WObject (WObject *parent=0)
virtual ~WObject ()
void setObjectName (const std::string &name)
virtual std::string objectName () const
void resetLearnedSlots ()
void resetLearnedSlot (void(T::*method)())
WStatelessSlot * implementStateless (void(T::*method)())
WStatelessSlot * implementStateless (void(T::*method)(), void(T::*undoMethod)())
WStatelessSlot * implementJavaScript (void(T::*method)(), const std::string &jsCode)
void addChild (WObject *child)

Protected Member Functions

virtual void createLayout (Wt::WWidget *messages, Wt::WWidget *userList, Wt::WWidget *messageEdit, Wt::WWidget *sendButton, Wt::WWidget *logoutButton)
virtual void updateUsers ()
virtual void newMessage ()
virtual void render (Wt::WFlags< Wt::RenderFlag > flags)
bool loggedIn () const
- Protected Member Functions inherited from Wt::WContainerWidget
virtual void propagateSetEnabled (bool enabled)
virtual void enableAjax ()
virtual void removeChild (WObject *child)
void setLayoutSizeAware (bool sizeAware)
virtual void layoutSizeChanged (int width, int height)
 WWidget (WContainerWidget *parent=0)
virtual void dropEvent (WDropEvent dropEvent)
virtual int boxPadding (Orientation orientation) const
virtual int boxBorder (Orientation orientation) const
virtual WStatelessSlot * getStateless (Method method)

Private Types

typedef std::map< Wt::WString,
bool > 
UserMap

Private Member Functions

void login ()
void send ()
void updateUser ()
void processChatEvent (const ChatEvent &event)

Private Attributes

UserMap users_
SimpleChatServerserver_
bool loggedIn_
Wt::JSlot clearInput_
Wt::WString user_
Wt::WLineEdituserNameEdit_
Wt::WTextstatusMsg_
Wt::WContainerWidgetmessages_
Wt::WContainerWidgetmessageEditArea_
Wt::WTextAreamessageEdit_
Wt::WPushButtonsendButton_
Wt::WContainerWidgetuserList_
Wt::WSoundmessageReceived_

Additional Inherited Members

- Public Types inherited from Wt::WContainerWidget
enum  Overflow
- Public Attributes inherited from Wt::WContainerWidget
 OverflowVisible
 OverflowAuto
 OverflowHidden
 OverflowScroll

Detailed Description

A self-contained chat widget.

Definition at line 34 of file SimpleChatWidget.h.


Member Typedef Documentation

typedef std::map<Wt::WString, bool> SimpleChatWidget::UserMap
private

Definition at line 82 of file SimpleChatWidget.h.


Constructor & Destructor Documentation

SimpleChatWidget::SimpleChatWidget ( SimpleChatServer server,
Wt::WContainerWidget parent = 0 
)

Create a chat widget that will connect to the given server.

Definition at line 26 of file SimpleChatWidget.C.

SimpleChatWidget::~SimpleChatWidget ( )

Delete a chat widget.

Definition at line 38 of file SimpleChatWidget.C.


Member Function Documentation

void SimpleChatWidget::connect ( )

Definition at line 45 of file SimpleChatWidget.C.

void SimpleChatWidget::createLayout ( Wt::WWidget messages,
Wt::WWidget userList,
Wt::WWidget messageEdit,
Wt::WWidget sendButton,
Wt::WWidget logoutButton 
)
protectedvirtual

Reimplemented in PopupChatWidget.

Definition at line 108 of file SimpleChatWidget.C.

{
/*
* Create a vertical layout, which will hold 3 rows,
* organized like this:
*
* WVBoxLayout
* --------------------------------------------
* | nested WHBoxLayout (vertical stretch=1) |
* | | |
* | messages | userList |
* | (horizontal stretch=1) | |
* | | |
* --------------------------------------------
* | message edit area |
* --------------------------------------------
* | WHBoxLayout |
* | send | logout |
* --------------------------------------------
*/
WVBoxLayout *vLayout = new WVBoxLayout();
// Create a horizontal layout for the messages | userslist.
WHBoxLayout *hLayout = new WHBoxLayout();
// Add widget to horizontal layout with stretch = 1
hLayout->addWidget(messages, 1);
messages->setStyleClass("chat-msgs");
// Add another widget to horizontal layout with stretch = 0
hLayout->addWidget(userList);
userList->setStyleClass("chat-users");
hLayout->setResizable(0, true);
// Add nested layout to vertical layout with stretch = 1
vLayout->addLayout(hLayout, 1);
// Add widget to vertical layout with stretch = 0
vLayout->addWidget(messageEdit);
messageEdit->setStyleClass("chat-noedit");
// Create a horizontal layout for the buttons.
hLayout = new WHBoxLayout();
// Add button to horizontal layout with stretch = 0
hLayout->addWidget(sendButton);
// Add button to horizontal layout with stretch = 0
hLayout->addWidget(logoutButton);
// Add nested layout to vertical layout with stretch = 0
vLayout->addLayout(hLayout, 0, AlignLeft | AlignTop);
setLayout(vLayout);
}
void SimpleChatWidget::disconnect ( )

Definition at line 52 of file SimpleChatWidget.C.

void SimpleChatWidget::letLogin ( )

Show a simple login screen.

Definition at line 58 of file SimpleChatWidget.C.

{
clear();
WVBoxLayout *vLayout = new WVBoxLayout();
setLayout(vLayout, AlignLeft | AlignTop);
WHBoxLayout *hLayout = new WHBoxLayout();
vLayout->addLayout(hLayout);
hLayout->addWidget(new WLabel("User name:"), 0, AlignMiddle);
hLayout->addWidget(userNameEdit_ = new WLineEdit(user_), 0, AlignMiddle);
WPushButton *b = new WPushButton("Login");
hLayout->addWidget(b, 0, AlignMiddle);
b->clicked().connect(this, &SimpleChatWidget::login);
vLayout->addWidget(statusMsg_ = new WText());
}
bool SimpleChatWidget::loggedIn ( ) const
protected

Definition at line 167 of file SimpleChatWidget.C.

{
return loggedIn_;
}
void SimpleChatWidget::login ( )
private

Definition at line 84 of file SimpleChatWidget.C.

{
if (!loggedIn()) {
messageReceived_ = new WSound("sounds/message_received.mp3");
if (!startChat(name))
statusMsg_->setText("Sorry, name '" + escapeText(name) +
"' is already taken.");
}
}
void SimpleChatWidget::logout ( )

Definition at line 98 of file SimpleChatWidget.C.

{
if (loggedIn()) {
loggedIn_ = false;
}
}
void SimpleChatWidget::newMessage ( )
protectedvirtual

Reimplemented in PopupChatWidget.

Definition at line 310 of file SimpleChatWidget.C.

{ }
void SimpleChatWidget::processChatEvent ( const ChatEvent event)
private

Definition at line 319 of file SimpleChatWidget.C.

{
WApplication *app = WApplication::instance();
/*
* This is where the "server-push" happens. The chat server posts to this
* event from other sessions, see SimpleChatServer::postChatEvent()
*/
/*
* Format and append the line to the conversation.
*
* This is also the step where the automatic XSS filtering will kick in:
* - if another user tried to pass on some JavaScript, it is filtered away.
* - if another user did not provide valid XHTML, the text is automatically
* interpreted as PlainText
*/
/*
* If it is not a plain message, also update the user list.
*/
if (event.type() != ChatEvent::Message) {
if (event.type() == ChatEvent::Rename && event.user() == user_)
user_ = event.data();
}
/*
* Anything else doesn't matter if we are not logged in.
*/
if (!loggedIn()) {
app->triggerUpdate();
return;
}
bool display = event.type() != ChatEvent::Message
|| (users_.find(event.user()) != users_.end() && users_[event.user()]);
if (display) {
WText *w = new WText(messages_);
/*
* If it fails, it is because the content wasn't valid XHTML
*/
if (!w->setText(event.formattedHTML(user_, XHTMLText))) {
w->setText(event.formattedHTML(user_, PlainText));
w->setTextFormat(XHTMLText);
}
w->setInline(false);
w->setStyleClass("chat-msg");
/*
* Leave no more than 100 messages in the back-log
*/
if (messages_->count() > 100)
delete messages_->children()[0];
/*
* Little javascript trick to make sure we scroll along with new content
*/
app->doJavaScript(messages_->jsRef() + ".scrollTop += "
+ messages_->jsRef() + ".scrollHeight;");
/* If this message belongs to another user, play a received sound */
if (event.user() != user_ && messageReceived_)
}
/*
* This is the server push action: we propagate the updated UI to the client,
* (when the event was triggered by another user)
*/
app->triggerUpdate();
}
void SimpleChatWidget::render ( Wt::WFlags< Wt::RenderFlag flags)
protectedvirtual

Definition at line 172 of file SimpleChatWidget.C.

{
if (flags & RenderFull) {
if (loggedIn()) {
/* Handle a page refresh correctly */
messageEdit_->setText(WString::Empty);
doJavaScript("setTimeout(function() { "
+ messages_->jsRef() + ".scrollTop += "
+ messages_->jsRef() + ".scrollHeight;}, 0);");
}
}
}
void SimpleChatWidget::send ( )
private

Definition at line 274 of file SimpleChatWidget.C.

SimpleChatServer& SimpleChatWidget::server ( )
inline

Definition at line 62 of file SimpleChatWidget.h.

{ return server_; }
bool SimpleChatWidget::startChat ( const Wt::WString user)

Start a chat for the given user.

Returns false if the user could not login.

Definition at line 187 of file SimpleChatWidget.C.

{
/*
* When logging in, we pass our processChatEvent method as the function that
* is used to indicate a new chat event for this user.
*/
if (server_.login(user)) {
loggedIn_ = true;
user_ = user;
clear();
// Display scroll bars if contents overflows
messages_->setOverflow(WContainerWidget::OverflowAuto);
userList_->setOverflow(WContainerWidget::OverflowAuto);
sendButton_ = new WPushButton("Send");
WPushButton *logoutButton = new WPushButton("Logout");
/*
* Connect event handlers:
* - click on button
* - enter in text area
*
* We will clear the input field using a small custom client-side
* JavaScript invocation.
*/
// Create a JavaScript 'slot' (JSlot). The JavaScript slot always takes
// 2 arguments: the originator of the event (in our case the
// button or text area), and the JavaScript event object.
("function(o, e) { setTimeout(function() {"
"" + messageEdit_->jsRef() + ".value='';"
"}, 0); }");
// Bind the C++ and JavaScript event handlers.
sendButton_->clicked().connect(messageEdit_, &WLineEdit::setFocus);
messageEdit_->enterPressed().connect(messageEdit_, &WLineEdit::setFocus);
// Prevent the enter from generating a new line, which is its default
// action
logoutButton->clicked().connect(this, &SimpleChatWidget::logout);
WText *msg = new WText
("<div><span class='chat-info'>You are joining as "
+ escapeText(user_) + ".</span></div>",
msg->setStyleClass("chat-msg");
if (!userList_->parent()) {
delete userList_;
userList_ = 0;
}
if (!sendButton_->parent()) {
delete sendButton_;
}
if (!logoutButton->parent())
delete logoutButton;
return true;
} else
return false;
}
void SimpleChatWidget::updateUser ( )
private

Definition at line 313 of file SimpleChatWidget.C.

{
WCheckBox *b = dynamic_cast<WCheckBox *>(sender());
users_[b->text()] = b->isChecked();
}
void SimpleChatWidget::updateUsers ( )
protectedvirtual

Reimplemented in PopupChatWidget.

Definition at line 280 of file SimpleChatWidget.C.

{
if (userList_) {
UserMap oldUsers = users_;
users_.clear();
for (SimpleChatServer::UserSet::iterator i = users.begin();
i != users.end(); ++i) {
w->setInline(false);
UserMap::const_iterator j = oldUsers.find(*i);
if (j != oldUsers.end())
w->setChecked(j->second);
else
w->setChecked(true);
users_[*i] = w->isChecked();
if (*i == user_)
w->setStyleClass("chat-self");
}
}
}
int SimpleChatWidget::userCount ( )
inline

Definition at line 64 of file SimpleChatWidget.h.

{ return users_.size(); }
const Wt::WString& SimpleChatWidget::userName ( ) const
inline

Definition at line 66 of file SimpleChatWidget.h.

{ return user_; }

Member Data Documentation

Wt::JSlot SimpleChatWidget::clearInput_
private

Definition at line 88 of file SimpleChatWidget.h.

bool SimpleChatWidget::loggedIn_
private

Definition at line 86 of file SimpleChatWidget.h.

Wt::WTextArea* SimpleChatWidget::messageEdit_
private

Definition at line 97 of file SimpleChatWidget.h.

Wt::WContainerWidget* SimpleChatWidget::messageEditArea_
private

Definition at line 96 of file SimpleChatWidget.h.

Wt::WSound* SimpleChatWidget::messageReceived_
private

Definition at line 101 of file SimpleChatWidget.h.

Wt::WContainerWidget* SimpleChatWidget::messages_
private

Definition at line 95 of file SimpleChatWidget.h.

Wt::WPushButton* SimpleChatWidget::sendButton_
private

Definition at line 98 of file SimpleChatWidget.h.

SimpleChatServer& SimpleChatWidget::server_
private

Definition at line 85 of file SimpleChatWidget.h.

Wt::WText* SimpleChatWidget::statusMsg_
private

Definition at line 93 of file SimpleChatWidget.h.

Wt::WString SimpleChatWidget::user_
private

Definition at line 90 of file SimpleChatWidget.h.

Wt::WContainerWidget* SimpleChatWidget::userList_
private

Definition at line 99 of file SimpleChatWidget.h.

Wt::WLineEdit* SimpleChatWidget::userNameEdit_
private

Definition at line 92 of file SimpleChatWidget.h.

UserMap SimpleChatWidget::users_
private

Definition at line 83 of file SimpleChatWidget.h.


The documentation for this class was generated from the following files:

Generated on Sun May 27 2012 for the C++ Web Toolkit (Wt) by doxygen 1.8.1