-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget.cpp
More file actions
410 lines (366 loc) · 12.9 KB
/
widget.cpp
File metadata and controls
410 lines (366 loc) · 12.9 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
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ui->label->setText(" SoftwareTesting 2016 ");
this->resize(850,550);
ui->textEdit->setFocusPolicy(Qt::StrongFocus);
ui->textBrowser->setFocusPolicy(Qt::NoFocus);
ui->textEdit->setFocus();
ui->textEdit->installEventFilter(this);
udpSocket = new QUdpSocket(this);
port = 45454;
udpSocket->bind(port,QUdpSocket::ShareAddress
| QUdpSocket::ReuseAddressHint);
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));
sendMessage(NewParticipant);
server = new TcpServer(this);
connect(server,SIGNAL(sendFileName(QString)),this,SLOT(sentFileName(QString)));
connect(ui->textEdit,SIGNAL(currentCharFormatChanged(QTextCharFormat)),this,SLOT(currentFormatChanged(const QTextCharFormat)));
}
void Widget::currentFormatChanged(const QTextCharFormat &format)
{//当编辑器的字体格式改变时,我们让部件状态也随之改变
ui->fontComboBox->setCurrentFont(format.font());
if(format.fontPointSize()<9) //如果字体大小出错,因为我们最小的字体为9
ui->fontsizecomboBox->setCurrentIndex(3); //即显示12
else ui->fontsizecomboBox->setCurrentIndex(
ui->fontsizecomboBox->findText(QString::number(format.fontPointSize())));
ui->textbold->setChecked(format.font().bold());
ui->textitalic->setChecked(format.font().italic());
ui->textUnderline->setChecked(format.font().underline());
color = format.foreground().color();
}
void Widget::processPendingDatagrams() //接收数据UDP
{
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(),datagram.size());
QDataStream in(&datagram,QIODevice::ReadOnly);
int messageType;
in >> messageType;
QString userName,localHostName,ipAddress,message;
QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
switch(messageType)
{
case Message:
{
in >>userName >>localHostName >>ipAddress >>message;
ui->textBrowser->setTextColor(Qt::blue);
ui->textBrowser->setCurrentFont(QFont("Times New Roman",12));
ui->textBrowser->append("[ " +userName+" ] "+ time);
ui->textBrowser->append(message);
break;
}
case NewParticipant:
{
in >>userName >>localHostName >>ipAddress;
newParticipant(userName,localHostName,ipAddress);
break;
}
case ParticipantLeft:
{
in >>userName >>localHostName;
participantLeft(userName,localHostName,time);
break;
}
case FileName:
{
in >>userName >>localHostName >> ipAddress;
QString clientAddress,fileName;
in >> clientAddress >> fileName;
hasPendingFile(userName,ipAddress,clientAddress,fileName);
break;
}
case Refuse:
{
in >> userName >> localHostName;
QString serverAddress;
in >> serverAddress;
QString ipAddress = getIP();
if(ipAddress == serverAddress)
{
server->refused();
}
break;
}
}
}
}
//处理新用户加入
void Widget::newParticipant(QString userName,QString localHostName,QString ipAddress)
{
//查看是否已有此用户
bool bb = ui->tableWidget->findItems(localHostName,Qt::MatchExactly).isEmpty();
if(bb)//如果没有,则添加
{
//向QTableWidget中插入项--这里是以列的形式插入的
QTableWidgetItem *user = new QTableWidgetItem(userName);
QTableWidgetItem *host = new QTableWidgetItem(localHostName);
QTableWidgetItem *ip = new QTableWidgetItem(ipAddress);
ui->tableWidget->insertRow(0);//插入一行
ui->tableWidget->setItem(0,0,user);//设置行中列的项内容
ui->tableWidget->setItem(0,1,host);
ui->tableWidget->setItem(0,2,ip);
//设置显示窗口--更新
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
ui->textBrowser->append(tr("%1 is online!").arg(userName));
ui->onlineUser->setText(tr(" OnlineUsers:%1").arg(ui->tableWidget->rowCount()));
sendMessage(NewParticipant);//发送新用户加入消息
}
}
//处理用户离开
void Widget::participantLeft(QString userName,QString localHostName,QString time)
{
//获取当前用户所在行位置
int rowNum = ui->tableWidget->findItems(localHostName,Qt::MatchExactly).first()->row();
ui->tableWidget->removeRow(rowNum); //移除行
//更新显示窗口
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
ui->textBrowser->append(tr("%1 quit at %2 !").arg(userName).arg(time));
ui->onlineUser->setText(tr(" OnlineUsers:%1").arg(ui->tableWidget->rowCount()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange: //如果语言更改
ui->retranslateUi(this); //重新载入语言
break;
default:
break;
}
}
QString Widget::getIP() //获取ip地址
{
QList<QHostAddress> list = QNetworkInterface::allAddresses();//返回主机上发现的所有IP地址。
foreach (QHostAddress address, list)
{
if(address.protocol() == QAbstractSocket::IPv4Protocol) //我们使用IPv4地址
return address.toString(); //以字符串返回IPv4地址
}
return 0;
}
void Widget::sendMessage(MessageType type, QString serverAddress) //发送信息
{
QByteArray data;
QDataStream out(&data,QIODevice::WriteOnly);
QString localHostName = QHostInfo::localHostName();
QString address = getIP();
out << type << getUserName() << localHostName;
switch(type)
{
case ParticipantLeft:
{
break;
}
case NewParticipant:
{
out << address;
break;
}
case Message :
{
if(ui->textEdit->toPlainText() == "")
{
QMessageBox::warning(0,tr("Warning"),tr("Content sends can't be null!!"),QMessageBox::Ok);
return;
}
out << address << getMessage();
//设置滚动条滚到最下面
ui->textBrowser->verticalScrollBar()->setValue(ui->textBrowser->verticalScrollBar()->maximum());
break;
}
case FileName:
{
int row = ui->tableWidget->currentRow();
QString clientAddress = ui->tableWidget->item(row,2)->text();
out << address << clientAddress << fileName;
break;
}
case Refuse:
{
out << serverAddress;
break;
}
}
//udp传输数据
udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port);
}
QString Widget::getUserName() //获取用户名
{
QStringList envVariables;
envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
<< "HOSTNAME.*" << "DOMAINNAME.*";
//这里获取登陆用户的系统信息--使用的是电脑系统信息
QStringList environment = QProcess::systemEnvironment();
foreach (QString string, envVariables)
{
int index = environment.indexOf(QRegExp(string));//使用正则表达式进行匹配环境信息(以上各种信息中的一个)
if (index != -1)
{
QStringList stringList = environment.at(index).split('=');//将匹配的内容分割成两部分(一部分为名称,一部分为名称对应的值)
if (stringList.size() == 2)//确定分割后只含有名称和名称对应的值
{
return stringList.at(1);//首先匹配的是USERNAME.*,也只返回这个对应的用户名
break;
}
}
}
return " ";
}
QString Widget::getMessage() //获得要发送的信息
{
QString msg = ui->textEdit->toHtml();//将文本转换为html富文本进行传输
ui->textEdit->clear();
ui->textEdit->setFocus();
return msg;
}
void Widget::closeEvent(QCloseEvent *)
{
sendMessage(ParticipantLeft);//向其他未离开用户->发送用户离开消息
}
void Widget::sentFileName(QString fileName)
{
this->fileName = fileName;
sendMessage(FileName);
}
void Widget::hasPendingFile(QString userName,QString serverAddress, //接收文件
QString clientAddress,QString fileName)
{
QString ipAddress = getIP();
if(ipAddress == clientAddress)
{
int btn = QMessageBox::information(this,tr("Recieve file"),
tr("from%1(%2) de file:%3,recieve or not?")
.arg(userName).arg(serverAddress).arg(fileName),
QMessageBox::Yes,QMessageBox::No);
if(btn == QMessageBox::Yes)
{
QString name = QFileDialog::getSaveFileName(0,tr("save file"),fileName);
if(!name.isEmpty())
{
//建立Tcp连接传输文件
TcpClient *client = new TcpClient(this);
client->setFileName(name);
client->setHostAddress(QHostAddress(serverAddress));
client->show();
}
}
else{
sendMessage(Refuse,serverAddress);//拒绝接收
}
}
}
void Widget::on_send_clicked()//发送
{
sendMessage(Message);
}
void Widget::on_sendfile_clicked()
{
if(ui->tableWidget->selectedItems().isEmpty())
{
QMessageBox::warning(0,tr("Choose user"),tr("Please choose from the userlist first!"),QMessageBox::Ok);
return;
}
server->show();
server->initServer();
}
void Widget::on_close_clicked()//关闭
{
this->close();
}
//事件过滤---在消息编辑框内检测Enter按钮事件
bool Widget::eventFilter(QObject *target, QEvent *event)
{
if(target == ui->textEdit)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if(k->key() == Qt::Key_Return)
{
on_send_clicked();
return true;
}
}
}
return QWidget::eventFilter(target,event);//一直进行检测!
}
void Widget::on_fontComboBox_currentFontChanged(QFont f)//字体设置
{
ui->textEdit->setCurrentFont(f);
ui->textEdit->setFocus();
}
void Widget::on_fontsizecomboBox_currentIndexChanged(QString size)//字体大小设置
{
ui->textEdit->setFontPointSize(size.toDouble());
ui->textEdit->setFocus();
}
void Widget::on_textbold_clicked(bool checked)//字体粗细设置
{
if(checked)
ui->textEdit->setFontWeight(QFont::Bold);
else
ui->textEdit->setFontWeight(QFont::Normal);
ui->textEdit->setFocus();
}
void Widget::on_textitalic_clicked(bool checked)//字体斜体设置
{
ui->textEdit->setFontItalic(checked);
ui->textEdit->setFocus();
}
void Widget::on_textUnderline_clicked(bool checked)//字体下划线设置
{
ui->textEdit->setFontUnderline(checked);
ui->textEdit->setFocus();
}
void Widget::on_textcolor_clicked()//字体颜色设置
{
color = QColorDialog::getColor(color,this);
if(color.isValid())
{
ui->textEdit->setTextColor(color);
ui->textEdit->setFocus();
}
}
void Widget::on_save_clicked()//保存聊天记录
{
if(ui->textBrowser->document()->isEmpty())
QMessageBox::warning(0,tr("Warning"),tr("Chat record is null to save!"),QMessageBox::Ok);
else
{
//获得文件名
QString fileName = QFileDialog::getSaveFileName(this,tr("save the chat record"),tr("chat record"),tr("text(*.txt);;All File(*.*)"));
if(!fileName.isEmpty())
saveFile(fileName);
}
}
bool Widget::saveFile(const QString &fileName)//保存文件
{
QFile file(fileName);
if(!file.open(QFile::WriteOnly | QFile::Text))
{
QMessageBox::warning(this,tr("save file"),
tr("can not save file %1:\n %2").arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream out(&file);
out << ui->textBrowser->toPlainText();
return true;
}
void Widget::on_clear_clicked()//清空聊天记录
{
ui->textBrowser->clear();
}