File: SimpleChatWidget.C

package info (click to toggle)
witty 3.1.2-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 45,512 kB
  • ctags: 35,832
  • sloc: cpp: 69,469; ansic: 66,945; xml: 4,383; sh: 594; perl: 108; makefile: 106
file content (310 lines) | stat: -rw-r--r-- 8,892 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
 * Copyright (C) 2008 Emweb bvba, Heverlee, Belgium.
 *
 * See the LICENSE file for terms of use.
 */

#include "SimpleChatWidget.h"
#include "SimpleChatServer.h"

#include <Wt/WApplication>
#include <Wt/WContainerWidget>
#include <Wt/WEnvironment>
#include <Wt/WHBoxLayout>
#include <Wt/WVBoxLayout>
#include <Wt/WLabel>
#include <Wt/WLineEdit>
#include <Wt/WText>
#include <Wt/WTextArea>
#include <Wt/WPushButton>
#include <Wt/WCheckBox>

#include <iostream>

using namespace Wt;

SimpleChatWidget::SimpleChatWidget(SimpleChatServer& server,
				   Wt::WContainerWidget *parent)
  : WContainerWidget(parent),
    server_(server),
    app_(WApplication::instance()),
    messageReceived_("sounds/message_received.mp3")
{
  user_ = server_.suggestGuest();
  letLogin();

  // this widget supports server-side updates its processChatEvent()
  // method is connected to a slot that is triggered from outside this
  // session's event loop (usually because another user enters text).
  app_->enableUpdates();
}

SimpleChatWidget::~SimpleChatWidget()
{
  logout();
}

void SimpleChatWidget::letLogin()
{
  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);
  userNameEdit_->setFocus();

  WPushButton *b = new WPushButton("Login");
  hLayout->addWidget(b, 0, AlignMiddle);
  hLayout->addStretch(1);

  b->clicked().connect(SLOT(this, SimpleChatWidget::login));
  userNameEdit_->enterPressed().connect(SLOT(this, SimpleChatWidget::login));

  vLayout->addWidget(statusMsg_ = new WText());
  statusMsg_->setTextFormat(PlainText);
}

void SimpleChatWidget::login()
{
  WString name = WWebWidget::escapeText(userNameEdit_->text());

  if (!startChat(name))
    statusMsg_->setText("Sorry, name '" + name + "' is already taken.");
}

void SimpleChatWidget::logout()
{
  if (eventConnection_.connected()) {
    eventConnection_.disconnect(); // do not listen for more events
    server_.logout(user_);

    letLogin();
  }
}

bool SimpleChatWidget::startChat(const WString& user)
{
  if (server_.login(user)) {
    eventConnection_
      = server_.chatEvent().connect(SLOT(this,
				       SimpleChatWidget::processChatEvent));
    user_ = user;    

    clear();

    /*
     * Create a vertical layout, which will hold 3 rows,
     * organized like this:
     *
     * WVBoxLayout
     * --------------------------------------------
     * | nested WHBoxLayout (vertical stretch=1)  |
     * |                              |           |
     * |  messages                    | userslist |
     * |   (horizontal stretch=1)     |           |
     * |                              |           |
     * --------------------------------------------
     * | message edit area                        |
     * --------------------------------------------
     * | WHBoxLayout                              |
     * | send | logout |       stretch = 1        |
     * --------------------------------------------
     */
    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_ = new WContainerWidget(), 1);
    messages_->setStyleClass("chat-msgs");
    // Display scroll bars if contents overflows
    messages_->setOverflow(WContainerWidget::OverflowAuto);

    // Add another widget to hirozontal layout with stretch = 0
    hLayout->addWidget(userList_ = new WContainerWidget());
    userList_->setStyleClass("chat-users");
    userList_->setOverflow(WContainerWidget::OverflowAuto);

    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_ = new WTextArea());
    messageEdit_->setStyleClass("chat-noedit");
    messageEdit_->setRows(2);
    messageEdit_->setFocus();

    // Create a horizontal layout for the buttons.
    hLayout = new WHBoxLayout();

    // Add button to horizontal layout with stretch = 0
    hLayout->addWidget(sendButton_ = new WPushButton("Send"));
    WPushButton *b;

    // Add button to horizontal layout with stretch = 0
    hLayout->addWidget(b = new WPushButton("Logout"));

    // Add stretching spacer to horizontal layout
    hLayout->addStretch(1);

    // Add nested layout to vertical layout with stretch = 0
    vLayout->addLayout(hLayout);

    setLayout(vLayout);

    /*
     * 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.
    clearInput_.setJavaScript
      ("function(o, e) {"
       "" + messageEdit_->jsRef() + ".value='';"
       "}");

    // Bind the C++ and JavaScript event handlers.
    sendButton_->clicked().connect(SLOT(this, SimpleChatWidget::send));
    messageEdit_->enterPressed().connect(SLOT(this, SimpleChatWidget::send));
    sendButton_->clicked().connect(clearInput_);
    messageEdit_->enterPressed().connect(clearInput_);

    // Prevent the enter from generating a new line, which is its
    // default function
    messageEdit_->enterPressed().setPreventDefault(true);

    b->clicked().connect(SLOT(this, SimpleChatWidget::logout));

    WText *msg = new WText
      ("<div><span class='chat-info'>You are joining the conversation as "
       + user_ + "</span></div>", messages_);
    msg->setStyleClass("chat-msg");

    updateUsers();
    
    return true;
  } else
    return false;
}

void SimpleChatWidget::send()
{
  if (!messageEdit_->text().empty()) {
    server_.sendMessage(user_, messageEdit_->text());
    if (!WApplication::instance()->environment().ajax())
      messageEdit_->setText(WString::Empty);
  }

  messageEdit_->setFocus();
}

void SimpleChatWidget::updateUsers()
{
  userList_->clear();

  SimpleChatServer::UserSet users = server_.users();

  UserMap oldUsers = users_;
  users_.clear();

  for (SimpleChatServer::UserSet::iterator i = users.begin();
       i != users.end(); ++i) {
    WCheckBox *w = new WCheckBox(*i, userList_);
    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();
    w->changed().connect(SLOT(this, SimpleChatWidget::updateUser));

    if (*i == user_)
      w->setStyleClass("chat-self");
  }
}

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

void SimpleChatWidget::processChatEvent(const ChatEvent& event)
{
  /*
   * This is where the "server-push" happens. This method is called
   * when a new event or message needs to be notified to the user. In
   * general, it is called from another session.
   */

  /*
   * First, take the lock to safely manipulate the UI outside of the
   * normal event loop, by having exclusive access to the session.
   */
  WApplication::UpdateLock lock = app_->getUpdateLock();

  /*
   * 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
   */
  bool needPush = false;

  /*
   * If it is not a normal message, also update the user list.
   */
  if (event.type() != ChatEvent::Message) {
    needPush = true;
    updateUsers();
  }

  bool display = event.type() != ChatEvent::Message
    || (users_.find(event.user()) != users_.end() && users_[event.user()]);

  if (display) {
    needPush = true;

    WText *w = new WText(event.formattedHTML(user_), messages_);
    w->setInline(false);
    w->setStyleClass("chat-msg");

    /*
     * Leave not 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_.play();
  }

  if (needPush)
    app_->triggerUpdate();
}