-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
532 lines (450 loc) · 17.7 KB
/
mainwindow.cpp
File metadata and controls
532 lines (450 loc) · 17.7 KB
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Client.h"
#include "Logger.h"
#include <QDateTime>
#include <QScrollBar>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, isConnected(false)
, isAdmin(false)
{
ui->setupUi(this);
InitLogger("client", "client.log");
spdlog::set_level(spdlog::level::warn);
connect(ui->pbConnect, &QPushButton::clicked, this, &MainWindow::on_pbConnect_clicked);
// connect(ui->pbRegister, &QPushButton::clicked, this, &MainWindow::on_pbRegister_clicked);
connect(ui->pbSend, &QPushButton::clicked, this, &MainWindow::on_pbSend_clicked);
connect(ui->pbDisconnect, &QPushButton::clicked, this, &MainWindow::on_pbDisconnect_clicked);
connect(ui->pbLogout, &QPushButton::clicked, this, &MainWindow::on_pbLogout_clicked);
connect(ui->leInput, &QLineEdit::returnPressed, this, &MainWindow::on_leInput_returnPressed);
connect(ui->pbClearLog, &QPushButton::clicked, this, &MainWindow::on_pbClearLog_clicked);
connect(ui->cbUsers, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::onCurrentUserChanged);
appendLog("客户端已启动");
}
MainWindow::~MainWindow()
{
for (Client* c : clients) {
c->Disconnect();
}
clients.clear();
ShutdownLogger();
delete ui;
}
Client* MainWindow::getOrCreateClient(const QString& username)
{
if (clients.contains(username))
return clients.value(username);
Client* c = new Client(this);
connect(c, &Client::connected, this, &MainWindow::onConnected, Qt::UniqueConnection);
connect(c, &Client::disconnected, this, &MainWindow::onDisconnected, Qt::UniqueConnection);
connect(c, &Client::authSuccess, this, &MainWindow::onAuthSuccess, Qt::UniqueConnection);
connect(c, &Client::authFailed, this, &MainWindow::onAuthFailed, Qt::UniqueConnection);
connect(c, &Client::registerResult, this, &MainWindow::onRegisterResult, Qt::UniqueConnection);
connect(c, &Client::publicMessage, this, &MainWindow::onPublicMessage, Qt::UniqueConnection);
connect(c, &Client::privateMessage, this, &MainWindow::onPrivateMessage, Qt::UniqueConnection);
connect(c, &Client::systemMessage, this, &MainWindow::onSystemMessage, Qt::UniqueConnection);
connect(c, &Client::errorOccurred, this, &MainWindow::onError, Qt::UniqueConnection);
connect(c, &Client::kickReceived, this, &MainWindow::onKickReceived, Qt::UniqueConnection);
connect(c, &Client::echoResponse, this, &MainWindow::onEchoResponse, Qt::UniqueConnection);
clients[username] = c;
return c;
}
void MainWindow::removeClient(const QString& username)
{
if (!clients.contains(username))
return;
Client* c = clients.take(username);
disconnect(c, nullptr, this, nullptr);
c->Disconnect();
c->deleteLater();
int idx = ui->cbUsers->findData(username);
if (idx >= 0)
ui->cbUsers->removeItem(idx);
if (currentUsername == username) {
currentUsername.clear();
isAdmin = false;
updateCurrentUserState();
}
}
void MainWindow::on_pbConnect_clicked()
{
QString host = ui->leIP->text().trimmed();
QString portStr = ui->lePort->text().trimmed();
if (host.isEmpty()) {
QMessageBox::warning(this, "输入错误", "请输入服务器 IP 地址");
return;
}
bool ok = false;
uint16_t port = portStr.toUShort(&ok);
if (!ok || port == 0) {
QMessageBox::warning(this, "输入错误", "端口号无效(1-65535)");
return;
}
ui->pbConnect->setEnabled(false);
ui->pbConnect->setText("连接中...");
ui->statusbar->showMessage("正在连接...");
QApplication::processEvents();
for (Client* c : clients) {
disconnect(c, nullptr, this, nullptr);
c->Disconnect();
c->deleteLater();
}
clients.clear();
ui->cbUsers->clear();
currentUsername.clear();
isAdmin = false;
Client* c = new Client(this);
connect(c, &Client::connected, this, &MainWindow::onConnected, Qt::UniqueConnection);
connect(c, &Client::disconnected, this, &MainWindow::onDisconnected, Qt::UniqueConnection);
connect(c, &Client::authSuccess, this, &MainWindow::onAuthSuccess, Qt::UniqueConnection);
connect(c, &Client::authFailed, this, &MainWindow::onAuthFailed, Qt::UniqueConnection);
connect(c, &Client::registerResult, this, &MainWindow::onRegisterResult, Qt::UniqueConnection);
connect(c, &Client::publicMessage, this, &MainWindow::onPublicMessage, Qt::UniqueConnection);
connect(c, &Client::privateMessage, this, &MainWindow::onPrivateMessage, Qt::UniqueConnection);
connect(c, &Client::systemMessage, this, &MainWindow::onSystemMessage, Qt::UniqueConnection);
connect(c, &Client::errorOccurred, this, &MainWindow::onError, Qt::UniqueConnection);
connect(c, &Client::kickReceived, this, &MainWindow::onKickReceived, Qt::UniqueConnection);
connect(c, &Client::echoResponse, this, &MainWindow::onEchoResponse, Qt::UniqueConnection);
clients["__connection__"] = c;
c->ConnectAsync(host.toStdString(), port);
appendLog(QString("正在连接 %1:%2...").arg(host).arg(port));
}
void MainWindow::onConnected()
{
isConnected = true;
ui->pbConnect->setText("已连接");
ui->statusbar->showMessage("已连接到服务器");
setConnectedUI(true);
appendLog("已成功连接到服务器");
appendSystem("已成功连接到服务器,请登录或注册");
}
void MainWindow::onDisconnected()
{
// 获取是哪个 Client 触发了断开信号
Client* c = qobject_cast<Client*>(sender());
if (!c) return;
// 找到这个 Client 对应的用户名
QString disconnectedUser = clients.key(c);
if (disconnectedUser == "__connection__") {
// 如果只是后台未登录的临时连接断了(例如输错IP导致连不上)
appendLog("后台空闲连接断开");
clients.remove("__connection__");
c->deleteLater();
ui->pbLogin->setText("登录");
ui->pbLogin->setEnabled(true);
ui->pbRegister->setText("注册");
ui->pbRegister->setEnabled(true);
}
else if (!disconnectedUser.isEmpty()) {
// 如果是一个已经登录的用户断开了
appendLog(QString("用户 [%1] 的连接已断开").arg(disconnectedUser));
appendSystem(QString("用户 [%1] 已断开服务器连接").arg(disconnectedUser));
// 安全移除
removeClient(disconnectedUser);
}
// 只有当所有的客户端(包括占位符和已登录用户)全部清空时,才重置全局UI
if (clients.isEmpty()) {
ui->statusbar->showMessage("所有连接已断开");
setConnectedUI(false);
setAuthenticatedUI(false, false);
isConnected = false;
}
}
void MainWindow::on_pbLogin_clicked()
{
QString username = ui->leUsername->text().trimmed();
QString password = ui->lePassword->text();
if (username.isEmpty() || password.isEmpty()) {
QMessageBox::warning(this, "输入错误", "用户名和密码不能为空");
return;
}
if (clients.contains(username) && clients.value(username)->IsAuthenticated()) {
QMessageBox::warning(this, "登录错误", "该用户已登录,请从下拉框切换");
return;
}
Client* c = clients.value("__connection__");
// 情况 A:如果有现成的空闲连接,直接使用
if (c) {
c->LoginAsync(username.toStdString(), password.toStdString());
appendLog(QString("发送登录请求,用户名: %1").arg(username));
}
// 情况 B:没有空闲连接,动态创建并等待连接成功后登录
else {
QString host = ui->leIP->text().trimmed();
uint16_t port = ui->lePort->text().toUShort();
c = getOrCreateClient("__connection__");
connect(c, &Client::connected, this, [c, username, password, this]() {
c->LoginAsync(username.toStdString(), password.toStdString());
appendLog(QString("发送登录请求,用户名: %1").arg(username));
}, Qt::SingleShotConnection);
appendLog(QString("正在为新账号动态建立连接..."));
c->ConnectAsync(host.toStdString(), port);
return;
}
}
void MainWindow::onAuthSuccess(const QString& username, bool isAdmin_)
{
if (clients.contains("__connection__")) {
Client* c = clients.take("__connection__");
clients[username] = c;
}
int idx = ui->cbUsers->findData(username);
if (idx < 0) {
ui->cbUsers->addItem(username, username);
idx = ui->cbUsers->count() - 1;
}
ui->cbUsers->setCurrentIndex(idx);
if (currentUsername.isEmpty()) {
currentUsername = username;
isAdmin = isAdmin_;
}
ui->pbLogin->setText("登录");
ui->pbLogin->setEnabled(true);
ui->lePassword->clear();
appendLog(QString("用户 %1 登录成功,管理员: %2").arg(username).arg(isAdmin_ ? "是" : "否"));
appendSystem(QString("用户 %1 登录成功%2").arg(username).arg(isAdmin_ ? " [管理员]" : ""));
updateCurrentUserState();
}
void MainWindow::onAuthFailed(const QString& reason)
{
appendLog(QString("登录失败: %1").arg(reason));
ui->pbLogin->setText("登录");
ui->pbLogin->setEnabled(true);
setConnectedUI(isConnected);
QMessageBox::critical(this, "登录失败", reason);
}
void MainWindow::on_pbRegister_clicked()
{
QString username = ui->leUsername->text().trimmed();
QString password = ui->lePassword->text();
if (username.isEmpty() || password.isEmpty()) {
QMessageBox::warning(this, "输入错误", "用户名和密码不能为空");
return;
}
if (username.length() < 3 || username.length() > 20) {
QMessageBox::warning(this, "输入错误", "用户名长度需在 3-20 位之间");
return;
}
if (password.length() < 6) {
QMessageBox::warning(this, "输入错误", "密码长度至少 6 位");
return;
}
ui->pbRegister->setEnabled(false);
ui->pbRegister->setText("注册中...");
Client* c = clients.value("__connection__");
// 情况 A:有现成的空闲连接
if (c) {
c->RegisterAsync(username.toStdString(), password.toStdString());
appendLog(QString("发送注册请求,用户名: %1").arg(username));
}
// 情况 B:无空闲连接,新建并挂载异步事件
else {
QString host = ui->leIP->text().trimmed();
uint16_t port = ui->lePort->text().toUShort();
c = getOrCreateClient("__connection__");
connect(c, &Client::connected, this, [c, username, password, this]() {
c->RegisterAsync(username.toStdString(), password.toStdString());
appendLog(QString("发送注册请求,用户名: %1").arg(username));
}, Qt::SingleShotConnection);
appendLog(QString("正在为注册请求建立连接..."));
c->ConnectAsync(host.toStdString(), port);
return;
}
}
void MainWindow::onRegisterResult(bool ok, const QString& message)
{
ui->pbRegister->setText("注册");
ui->pbRegister->setEnabled(true);
if (ok) {
appendLog(QString("注册成功: %1").arg(message));
QMessageBox::information(this, "注册成功", message);
} else {
appendLog(QString("注册失败: %1").arg(message));
QMessageBox::critical(this, "注册失败", message);
}
}
void MainWindow::on_pbSend_clicked()
{
QString text = ui->leInput->text();
if (text.isEmpty()) return;
Client* c = clients.value(currentUsername);
if (!c || !c->IsAuthenticated()) return;
QString target = ui->lePrivateTarget->text().trimmed();
if (target.isEmpty()) {
appendLog(QString("[%1] 发送公聊消息: %2").arg(currentUsername).arg(text));
c->SendPublicMessageAsync(text.toStdString());
} else {
appendLog(QString("[%1] 发送私聊消息 to %2: %3").arg(currentUsername).arg(target).arg(text));
c->SendPrivateMessageAsync(target.toStdString(), text.toStdString());
}
ui->leInput->clear();
}
void MainWindow::on_leInput_returnPressed()
{
on_pbSend_clicked();
}
void MainWindow::on_pbDisconnect_clicked()
{
appendLog("用户主动断开所有连接");
for (Client* c : clients) {
disconnect(c, nullptr, this, nullptr);
c->Disconnect();
c->deleteLater();
}
clients.clear();
ui->cbUsers->clear();
currentUsername.clear();
isAdmin = false;
isConnected = false;
ui->pbConnect->setText("连接");
ui->pbConnect->setEnabled(true);
setConnectedUI(false);
}
void MainWindow::on_pbLogout_clicked()
{
if (currentUsername.isEmpty()) return;
QString u = currentUsername;
appendLog(QString("注销用户: %1").arg(u));
removeClient(u);
}
void MainWindow::onCurrentUserChanged(int index)
{
Q_UNUSED(index);
updateCurrentUserState();
}
void MainWindow::updateCurrentUserState()
{
QString u = ui->cbUsers->currentData().toString();
currentUsername = u;
Client* c = clients.value(u);
bool authed = c && c->IsAuthenticated();
bool admin = c && c->IsAdmin();
isAdmin = admin;
setAuthenticatedUI(authed, admin);
}
void MainWindow::onPublicMessage(const QString& sender, const QString& content, const QString& timestamp)
{
appendLog(QString("[%1] %2: %3").arg(timestamp).arg(sender).arg(content));
bool isSelf = (sender == currentUsername);
QString color = isSelf ? "#1565C0" : "#2E7D32";
QString prefix = isSelf ? "" : QString("[%1] ").arg(sender);
appendMessage(QString(
R"(<table width="100%" cellpadding="0" cellspacing="0"><tr>)"
R"(<td style="color:%1;font-weight:bold;">%2%3</td>)"
R"(<td align="right" style="color:#9E9E9E;font-size:11px;">%4</td>)"
R"(</tr></table>)"
R"(<div style="color:#333;margin:2px 0 6px 0;">%5</div>)"
).arg(color).arg(prefix).arg(isSelf ? "我" : sender).arg(timestamp).arg(content.toHtmlEscaped()));
}
void MainWindow::onPrivateMessage(const QString& sender, const QString& content, const QString& timestamp)
{
appendLog(QString("[%1] [私聊] %2: %3").arg(timestamp).arg(sender).arg(content));
QString html = QString(
"<div style='color:#6A1B9A;font-weight:bold;'>[私聊] %1</div>"
"<div style='color:#555;margin:2px 0 6px 0;'>%2</div>"
"<div style='color:#9E9E9E;font-size:11px;'>%3</div>"
).arg(sender.toHtmlEscaped()).arg(content.toHtmlEscaped()).arg(timestamp);
appendMessage(html);
}
void MainWindow::onSystemMessage(const QString& message)
{
appendSystem(message);
}
void MainWindow::onError(const QString& error)
{
appendLog(QString("[错误] %1").arg(error));
appendSystem(QString("[错误] %1").arg(error));
}
void MainWindow::onKickReceived(const QString& reason)
{
appendLog(QString("[被踢出] %1").arg(reason));
QMessageBox::warning(this, "被踢出", reason);
if (!currentUsername.isEmpty()) {
removeClient(currentUsername);
} else {
isAdmin = false;
setAuthenticatedUI(false, false);
}
appendSystem(QString("[被踢出] %1").arg(reason));
}
void MainWindow::onEchoResponse(const QString& content)
{
appendSystem(QString("[Echo] %1").arg(content.toHtmlEscaped()));
}
void MainWindow::setConnectedUI(bool connected)
{
ui->leIP->setEnabled(!connected);
ui->lePort->setEnabled(!connected);
ui->pbConnect->setEnabled(!connected);
ui->pbConnect->setText(connected ? "已连接" : "连接");
ui->leUsername->setEnabled(connected);
ui->lePassword->setEnabled(connected);
ui->pbLogin->setEnabled(connected);
ui->pbRegister->setEnabled(connected);
if (!connected) {
ui->pbDisconnect->setEnabled(false);
ui->leInput->setEnabled(false);
ui->pbSend->setEnabled(false);
ui->lePrivateTarget->setEnabled(false);
ui->pbLogout->setEnabled(false);
ui->cbUsers->setEnabled(false);
}
}
void MainWindow::setAuthenticatedUI(bool authenticated, bool isAdmin_)
{
Q_UNUSED(isAdmin_);
ui->leInput->setEnabled(authenticated);
ui->pbSend->setEnabled(authenticated);
ui->lePrivateTarget->setEnabled(authenticated);
ui->pbDisconnect->setEnabled(isConnected);
ui->pbLogout->setEnabled(authenticated && !currentUsername.isEmpty());
ui->cbUsers->setEnabled(true);
if (authenticated) {
ui->leInput->setFocus();
}
}
void MainWindow::appendMessage(const QString& html)
{
QTextCursor cursor(ui->teMessages->document());
cursor.movePosition(QTextCursor::End);
cursor.insertHtml(html + "<hr style='margin:4px 0;border:none;border-top:1px solid #E0E0E0;'>");
ui->teMessages->verticalScrollBar()->setValue(ui->teMessages->verticalScrollBar()->maximum());
}
void MainWindow::appendSystem(const QString& msg)
{
QTextCursor cursor(ui->teMessages->document());
cursor.movePosition(QTextCursor::End);
QString timeStr = QDateTime::currentDateTime().toString("hh:mm:ss");
cursor.insertHtml(QString(
R"(<div style="color:#FF6F00;font-size:12px;">[%1] )"
).arg(timeStr));
cursor.insertText(msg + "\n");
ui->teMessages->verticalScrollBar()->setValue(ui->teMessages->verticalScrollBar()->maximum());
}
void MainWindow::appendLog(const QString& msg)
{
QString timeStr = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
QTextCursor cursor(ui->teLog->document());
cursor.movePosition(QTextCursor::End);
cursor.insertHtml(QString("<span style=\"color:#9E9E9E;\">[%1]</span> ")
.arg(timeStr));
cursor.insertText(msg + "\n");
ui->teLog->verticalScrollBar()->setValue(ui->teLog->verticalScrollBar()->maximum());
}
void MainWindow::on_pbClearLog_clicked()
{
ui->teLog->clear();
}
void MainWindow::setControlsEnabled(bool enabled)
{
Q_UNUSED(enabled);
}
void MainWindow::resetAllControls()
{
isConnected = false;
isAdmin = false;
currentUsername.clear();
}