-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
482 lines (380 loc) · 13 KB
/
mainwindow.cpp
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#include "mainwindow.h"
#include <QtDebug>
#include <QPair>
#include <QDir>
#include <QRegExp>
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
// initialisation lists look ugly
// Windgets
messages_widget = new QTextEdit(this);
input_line = new QLineEdit(this);
user_list_widget = new QListWidget(this);
send_button = new QPushButton(tr("Send"), this);
// Objects
socket = new QUdpSocket(this);
hello_timer = new QTimer(this);
keepalive_timer = new QTimer(this);
deliver_timer = new QTimer(this);
send_timer = new QTimer(this);
send_timer->setSingleShot(true);
// Layout-related
QGridLayout *layout = new QGridLayout(this);
layout->addWidget(messages_widget, 0, 0);
layout->addWidget(user_list_widget, 0, 1);
layout->addWidget(input_line, 1, 0);
layout->addWidget(send_button, 1, 1);
layout->setColumnStretch(0, 2); // 2 : 1
layout->setColumnStretch(1, 1);
// Tweaking widgets
setWindowTitle(tr("Network peer-to-peer chat"));
input_line->setFocus();
messages_widget->setReadOnly(true);
// User information and network routines
my_nickname = askUserForNickname();
socket->bind(PORT, QUdpSocket::ShareAddress);
/*QList<QHostAddress> addr = QNetworkInterface::allAddresses();
qDebug() << "Avaliable network interfaces:";
foreach (QHostAddress a, addr)
{
qDebug() << a.toString();
}
if ( addr.size() < 3 )
{
addSystemMessageToWidget(tr("Network interface wasn\'t found!"));
my_address = QHostAddress::LocalHost;
}
else
{
// KOSTYL
my_address = addr[ 2 ];
addSystemMessageToWidget(tr("Hello ") + my_nickname + ", your network "
"address is " + my_address.toString());
}*/
my_address = QHostAddress::LocalHost;
// Connecting everything
connect(send_button, SIGNAL(clicked()), this, SLOT(sendButtonPressed()));
connect(send_timer, SIGNAL(timeout()), this, SLOT(sendTimerExpired()));
connect(hello_timer, SIGNAL(timeout()), this, SLOT(sendHello()));
connect(keepalive_timer, SIGNAL(timeout()), this, SLOT(sendKeepalive()));
connect(deliver_timer, SIGNAL(timeout()), this, SLOT(delieverMessages()));
connect(socket, SIGNAL(readyRead()), this, SLOT(handleSocketMessage()));
// Starting up
hello_timer->start(HELLO_INTERVAL);
sendHello();
keepalive_timer->start(KEEPALIVE_INTERVAL);
deliver_timer->start(DELIEVER_INTERVAL);
updateUserListWidget();
qDebug() << "Constructor execution finished";
}
MainWindow::~MainWindow()
{
sendQuit();
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return )
{
if ( send_button->isEnabled() )
sendButtonPressed();
}
else
QWidget::keyPressEvent(event);
}
QString MainWindow::askUserForNickname()
{
QString nickname;
QRegExp regexp("[^A-Z][^a-z][^0-9][^-_.]");
forever
{
nickname = QInputDialog::getText(
this,
tr("Select your nickname"),
tr("Enter your nickname:"),
QLineEdit::Normal,
QDir::home().dirName()
);
if ( regexp.indexIn(nickname) != -1 )
{
QMessageBox::warning(
this,
tr("Select your nickname"),
tr("Nickname is invalid!")
);
}
else
break;
}
return nickname;
}
void MainWindow::addSystemMessageToWidget(QString message)
{
messages_widget->append("<b><font color=\"red\">" + message + "<\font><\b>\n");
}
void MainWindow::addMessageToWidget(QString author, QString message)
{
messages_widget->append("<b>" + author + ": </b> <i><font color=\"blue\">" + message + "</font></i>\n");
}
void MainWindow::addPeerToList(QString nickname, QHostAddress address)
{
qDebug() << "Trying to add new peer to list: "
<< nickname
<< address.toString();
if ( nickname == my_nickname && my_address == QHostAddress::LocalHost )
{
qDebug() << " Now I know my IP address: " << address;
my_address = address;
}
foreach (Peer *p, peer_list)
if ( address == p->getAddress() )
{
qDebug() << " Already know that buddy";
if ( nickname != p->getNickname() )
{
qDebug() << " But now he has new nickname!"
<< "Probably disconnected and reconnected "
"without sending QUIT.";
p->setNickname(nickname);
}
return;
}
Peer *newcomer = new Peer(nickname, address, this);
peer_list.push_back(newcomer);
connect(newcomer, SIGNAL(peerDied(QHostAddress)), this, SLOT(removePeerFromList(QHostAddress)));
qDebug() << "Added successfully";
user_list_widget->addItem(newcomer->getFormattedString());
addSystemMessageToWidget( tr("%1 connected").arg( newcomer->getFormattedString() ) );
}
void MainWindow::keepPeerAlive(QHostAddress peer_address)
{
foreach (Peer *p, peer_list)
if (p->getAddress() == peer_address)
{
qDebug() << p->getNickname()
<< p->getAddress().toString() << "kept alive";
p->resetKeepaliveTimer();
return;
}
}
bool MainWindow::addToChatHistory(time_t time, QString author, QString msg)
{
for (int i = chat_history.size() - 1; i >= 0 && chat_history[i].first >= time; --i)
if ( chat_history[i].first == time && chat_history[i].second == author )
return false;
qDebug() << "Added message to history: " << time << author;
chat_history.push_back( qMakePair(time, author) );
addMessageToWidget(author, msg);
return true;
}
void MainWindow::updateUserListWidget()
{
user_list_widget->clear();
foreach (Peer *p, peer_list)
{
user_list_widget->addItem( p->getFormattedString() );
}
qDebug() << "User list widget updated";
}
void MainWindow::removePeerFromList(QHostAddress peer_address)
{
for (int i = 0; i < peer_list.size(); ++i)
if (peer_list[i]->getAddress() == peer_address)
{
Peer *p = peer_list[i];
qDebug() << p->getFormattedString() << "removed from list";
peer_list.removeAt(i);
addSystemMessageToWidget( tr("%1 left").arg( p->getFormattedString() ) );
updateUserListWidget();
p->deleteLater();
return;
}
}
void MainWindow::sendButtonPressed()
{
QString msg_text = input_line->text();
input_line->clear();
input_line->setFocus();
time_t t = time(NULL);
addToChatHistory(t, my_nickname, msg_text);
Message message(t, my_nickname, my_address, msg_text);
undelivered_messages.push_back(message);
delieverMessages();
// Artifically block sendButton for SEND_INTERVAL milliseconds
send_button->setEnabled(false);
send_timer->start(SEND_INTERVAL);
}
void MainWindow::sendTimerExpired()
{
send_button->setEnabled(true);
}
void MainWindow::handleSocketMessage()
{
QHostAddress sender_address;
QStringList list;
{
quint16 sender_port;
QByteArray datagram;
datagram.resize( socket->pendingDatagramSize() );
socket->readDatagram(datagram.data(), datagram.size(), &sender_address, &sender_port);
QString text = QString(datagram.data());
text.remove(text.size() - 2, 2); // Remove \r\n
list = text.split(' ');
qDebug() << "Datagram arrived: " << text;
}
QString cmd = list[0];
list.removeAt(0);
if ( cmd == "HELLO" )
{
QString sender_nickname = list[0];
if ( sender_address != my_address )
{
sendResponse(sender_address);
addPeerToList(sender_nickname, sender_address);
updateUserListWidget();
sendJoin(sender_nickname, sender_address);
}
}
else if ( cmd == "RESPONSE" )
{
hello_timer->stop();
addPeerToList(list[0], sender_address);
for (int i = 1; i < list.size(); i += 2)
addPeerToList(list[i + 1], QHostAddress(list[i]));
updateUserListWidget();
}
else if ( cmd == "MESSAGE" )
{
if ( sender_address != my_address )
{
QHostAddress author_address( list[0] );
QString author_nickname( list[1] );
time_t time( list[2].toULongLong() );
QString msg = list[3];
for (int i = 4; i < list.size(); ++i)
msg += " " + list[i];
if ( addToChatHistory(time, author_nickname, msg) )
{
Message message(time, author_nickname, author_address, msg);
undelivered_messages.push_back(message);
delieverMessages();
}
// Sending accept back
sendAccepted(sender_address, author_nickname, time);
}
}
else if ( cmd == "ACCEPTED" )
{
QString nickname = list[0];
time_t time = list[1].toULongLong();
delieverConfirmed(nickname, time);
}
else if ( cmd == "JOIN" )
{
QHostAddress newcomer_addr = QHostAddress(list[0]);
addPeerToList(list[1], newcomer_addr);
updateUserListWidget();
}
else if ( cmd == "QUIT" )
{
QHostAddress leaver_addr = QHostAddress(list[0]);
removePeerFromList(leaver_addr);
}
else if ( cmd == "GET" )
{
sendResponse(sender_address);
}
else if ( cmd == "KEEPALIVE" )
{
keepPeerAlive(sender_address);
}
}
void MainWindow::sendString(QString what, QHostAddress where)
{
QByteArray datagram;
datagram.append(what);
datagram.append("\r\n");
socket->writeDatagram(datagram.data(), datagram.size(), where, PORT);
qDebug() << " Send string: " << what
<< "to " << ( (where != QHostAddress::Broadcast) ? where.toString() : "BROADCAST" );
}
void MainWindow::sendToEverybody(QString what)
{
qDebug() << "Sending to " << peer_list.size()
<< " peers in peer list: " << what;
foreach (Peer *p, peer_list)
{
sendString(what, p->getAddress());
}
}
void MainWindow::sendHello()
{
qDebug() << "Sending HELLO";
sendString("HELLO " + my_nickname, QHostAddress::Broadcast);
}
QString MainWindow::responseString()
{
QString msg = "RESPONSE " + my_nickname;
foreach (Peer *p, peer_list)
{
msg += " " + p->getAddress().toString() +
" " + p->getNickname();
}
return msg;
}
void MainWindow::sendResponse(QHostAddress to_whom)
{
qDebug() << "Sending RESPONSE to " << to_whom.toString();
sendString(responseString(), to_whom);
}
void MainWindow::sendJoin(QString newcomer_nickname, QHostAddress newcomer_address)
{
sendToEverybody("JOIN " + newcomer_address.toString() + " " + newcomer_nickname);
}
void MainWindow::sendMessage(time_t time, QString msg)
{
sendToEverybody("MESSAGE " + my_address.toString() + " " + my_nickname + " " +
QString::number(time) + " " + msg);
}
void MainWindow::sendMessage(Message msg)
{
sendToEverybody("MESSAGE " + msg.getAuthorAddress().toString() + " " + msg.getAuthorNickname() +
" " + QString::number(msg.getTime()) + " " + msg.getMsg());
}
void MainWindow::sendAccepted(QHostAddress to_whom, QString nickname, time_t time)
{
sendString("ACCEPTED " + nickname + " " + QString::number(time), to_whom);
}
void MainWindow::sendKeepalive()
{
qDebug() << "Requesting peers to keep me alive";
sendToEverybody("KEEPALIVE");
}
void MainWindow::sendQuit()
{
qDebug() << "I am disconnecting, so I request peers to remove "
"me from their peer lists";
sendToEverybody("QUIT " + my_address.toString());
}
void MainWindow::delieverMessages()
{
qDebug() << "Sending " << undelivered_messages.size() << " undelievered messages";
foreach (Message msg, undelivered_messages)
{
sendMessage(msg);
}
}
void MainWindow::delieverConfirmed(QString nickname, time_t time)
{
qDebug() << "Trying to match confirmation for ("
<< nickname << ", " << time << ")...";
for (int i = 0; i < undelivered_messages.size(); ++i)
if ( undelivered_messages[i].getAuthorNickname() == nickname &&
undelivered_messages[i].getTime() == time )
{
qDebug() << "Delivery of message (" << nickname << ", "
<< time << ") is confirmed!";
undelivered_messages.removeAt(i);
return;
}
}