diff --git a/.gitignore b/.gitignore index 5f9e6bb054ddefa475dfbdfa13f31d3f03ac4c3c..455118128af154fb9cf7d1e453650dc93e141ef7 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,10 @@ target_wrapper.* # QtCreator CMake CMakeLists.txt.user* -.idea -__pycache__ -bitXiaoSha/data/ +.idea +__pycache__ +bitXiaoSha/data/ +Client/debug/ +Server/debug/ +*.json +.vscode/ diff --git a/Client/Client.pro b/Client/Client.pro index d91d79529b82a06f2af8febabc9b53b0e765eb8d..9b1851d5650ec659626c3a4338ad40c4480f6aad 100644 --- a/Client/Client.pro +++ b/Client/Client.pro @@ -21,13 +21,14 @@ SOURCES += \ Session/onlinesession.cpp \ clientdatacenter.cpp \ clientmain.cpp \ + codeeditor.cpp \ databaseoperation.cpp \ - highlighter.cpp \ kuang.cpp \ main.cpp \ mainwindow.cpp \ message.cpp \ messagemodel.cpp \ + myhighlighter.cpp \ userlogin.cpp \ usermodel.cpp \ userregister.cpp \ @@ -39,9 +40,10 @@ HEADERS += \ Session/onlinesession.h \ clientdatacenter.h \ clientmain.h \ + codeeditor.h \ databaseoperation.h \ - userregister.cpp \ - highlighter.h \ + myhighlighter.h \ + typedef.h \ kuang.h \ ltest.h \ mainwindow.h \ @@ -66,6 +68,4 @@ else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ - rsc.qrc \ - rsc.qrc \ system.qrc diff --git a/Client/Session/onlinesession.cpp b/Client/Session/onlinesession.cpp index 3ee1e234d024e8be121ff7da4ed194ae8c377ad8..4c7246fa0b2a321b9e4f744fc6e16bae1c05f5db 100644 --- a/Client/Session/onlinesession.cpp +++ b/Client/Session/onlinesession.cpp @@ -10,7 +10,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) { id = json["SessionID"].toInt(); loadUsersFromJson(json); - qDebug() << "debug" ; Profile = json["Profile"].toObject(); if ((getSessionType() == SessionType::GROUP && json["SessionType"] == "GROUP") || (getSessionType() == SessionType::FRIEND && json["SessionType"] == "FRIEND") ) @@ -24,7 +23,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) } else { qDebug() << "load error" ; - throw "load error"; } latest = Profile["LatestMessageID"].toInt(); } @@ -39,7 +37,6 @@ void OnlineSession::loadUsersFromJson(const QJsonObject& json) { QJsonArray userlist = json["Members"].toArray(); - if (userlist.size() < 2) { qDebug() << "Value Error"; throw "userlist 至少需要两个 user 元素"; } for (int i = 0; i < userlist.size(); i++) { QString usrname = userlist.at(i).toObject()["Username"].toString(); members.append(usrname); @@ -52,14 +49,14 @@ QJsonObject OnlineSession::generateJsonFromData() const { ret["MsgType"] = "SessionData"; ret["SessionID"] = id; ret["SessionType"] = getSessionType() == SessionType::GROUP ? "GROUP" : "FRIEND"; - ret["Profile"] = Profile; QJsonArray userlist; for (int i = 0; i < members.size(); i++) { QJsonObject tmp; - tmp["username"] = members.at(i); + tmp["Username"] = members.at(i); userlist.append(tmp); } ret["Members"] = userlist; - ret["LatestMessageID"] = latest; + Profile["LatestMessageID"] = latest; + ret["Profile"] = Profile; return ret; } diff --git a/Client/clientdatacenter.cpp b/Client/clientdatacenter.cpp index 62f8f1a6b4bf3cff1b2316d99054055c575b33cb..0c6a5049534f5636f3c31d8a20b856c842db3849 100644 --- a/Client/clientdatacenter.cpp +++ b/Client/clientdatacenter.cpp @@ -18,7 +18,7 @@ void ClientDataCenter::GetSessionMessage(){ int SessionID = Kuang::KuangChosenNow->SessionID; if(hasSession(SessionID)){ OnlineSession &temp = getSession(Kuang::KuangChosenNow->SessionID); - for(int i = 0;i < temp.getLatestMessageID();i++){ + for(int i = 1;i <= temp.getLatestMessageID();i++){ if(hasMessage(SessionID,i)){ QJsonObject tem = getMessage(SessionID,i).generateJsonOutput(); emit addsessionmessage(tem); @@ -48,10 +48,14 @@ void ClientDataCenter::registerMessage(OnlineMessage *msg) { } void ClientDataCenter::RegisterSession(QJsonObject data){ + if(!hasSession(data["SessionID"].toInt())){ + OnlineSession *temp = new OnlineSession(data); registerSession(temp); +// qDebug() << data["SessionType"].toString() << "\n"; if(data["SessionType"].toString()=="FRIEND"){ + emit FriendSessionDataReceived(data); } if(data["SessionType"].toString()=="GROUP"){ @@ -64,7 +68,8 @@ void ClientDataCenter::RegisterMessage(QJsonObject data){ if(!hasMessage(data["SessionID"].toInt(),data["MessageID"].toInt())){ OnlineMessage *temp = new OnlineMessage(data); registerMessage(temp); - getSession(data["SessionID"].toInt()).getLatestMessageID()++; + getSession(data["SessionID"].toInt()).getLatestMessageID() = data["MessageID"].toInt(); + emit sessionorderchange(data); } } diff --git a/Client/clientdatacenter.h b/Client/clientdatacenter.h index 8e8f6cbb0aa3a1f239aebbabbe24df3af857ac95..c423fcec92c02a37508297c22aa0b075349cbb56 100644 --- a/Client/clientdatacenter.h +++ b/Client/clientdatacenter.h @@ -41,6 +41,7 @@ signals: void addsessionmessage(QJsonObject data); void FriendSessionDataReceived(QJsonObject data); void GroupSessionDataReceived(QJsonObject data); + void sessionorderchange(QJsonObject data); public slots: void clean(); diff --git a/Client/clientmain.cpp b/Client/clientmain.cpp index 46fd4d8383bc58cd81b9fbdb6a4b9ebbb20ee4a7..086f3d36afd49a2880665082b19c0bff48c81c25 100644 --- a/Client/clientmain.cpp +++ b/Client/clientmain.cpp @@ -1,6 +1,8 @@ #include "clientmain.h" #include +#include #include +#include ClientMain::ClientMain(QString IPAddress, int portOpen, QObject *parent) : QObject(parent), ipAdd(IPAddress), port(portOpen) @@ -33,6 +35,19 @@ void ClientMain::createmainwindow(QJsonObject data){ //send按钮点击后发送该消息到服务器 connect(main,&MainWindow::SendMessageToServer,this,&ClientMain::MessageFromMainwindow); + + //搜索按钮点击后发送消息到server + connect(main,&MainWindow::SendSearchInfo,this,&ClientMain::SendSearchInfoToSever); + connect(this,&ClientMain::SearchInfoReceived,main,&MainWindow::dealsearchinfo); + connect(main,&MainWindow::SendNewFriendInfo1,this,&ClientMain::SendNewFriendInfoToSever); + connect(main,&MainWindow::sendnewgroup,this,&ClientMain::send); + connect(&datacenter,&ClientDataCenter::sessionorderchange,main,&MainWindow::Sessionorderchange); +} + +void ClientMain::SendNewFriendInfoToSever(Kuang *This){ + Kuang::KuangChosenNow = nullptr; + QJsonObject data = {{"MsgType","AddFriendRequest"}, {"FromUsername", main->username}, {"ToUsername", This->USERNAME}}; + send(data); } void ClientMain::MessageFromMainwindow(const QString &sendername,const QString &text){ @@ -76,11 +91,7 @@ void ClientMain::connectToServer() { socket->connectToHost (QHostAddress(ipAdd), port); } -void ClientMain::receiveMessage() -{ - QByteArray arr = socket->readAll (); - QJsonDocument doc = QJsonDocument::fromJson(arr); - QJsonObject data = doc.object(); +void ClientMain::processMethod(QJsonObject data) { if(data["MsgType"].toString()=="UserData"){ emit UserDataReceived(data); } @@ -96,7 +107,33 @@ void ClientMain::receiveMessage() if(data["MsgType"].toString()=="SessionData"){ emit AddSessionToDatabase(data); } + if(data["MsgType"].toString()=="SearchInfo"){ + emit SearchInfoReceived(data); + } +} +void ClientMain::SendSearchInfoToSever(QString msg){ + QJsonObject data = {{"MsgType","Search"}}; + data["SearchInfo"] = msg; + send(data); +} + +void ClientMain::receiveMessage() +{ + QByteArray arr = socket->readAll (); + QJsonDocument doc = QJsonDocument::fromJson(arr); + QJsonObject data = doc.object(); + qDebug() << "Received from server: " << data; + if(!data.contains("MsgType")) return; + if (data["MsgType"].toString() == "JsonArray") { + auto array = data["MsgList"].toArray(); + for (int i = 0; i < array.size(); i++) { + processMethod(array[i].toObject()); + } + } + else { + processMethod(data); + } } void ClientMain::operator()() { diff --git a/Client/clientmain.h b/Client/clientmain.h index 58388ced2a56cd987cb41c5c35450fa99b9e96fc..f5b9126d94682de534a61842077942e81c1eb0a4 100644 --- a/Client/clientmain.h +++ b/Client/clientmain.h @@ -26,9 +26,13 @@ public: //接收并打印的槽函数 void receiveMessage(); + void processMethod(QJsonObject data); bool isConnected() { return is_connected; } void createmainwindow(QJsonObject data); void MessageFromMainwindow(const QString & sendername, const QString &text); + void receiveJsonObject(QJsonObject); + void SendSearchInfoToSever(QString msg); + void SendNewFriendInfoToSever(Kuang* This); signals: void serverConnected(); @@ -38,6 +42,7 @@ signals: void SessionMessageReceived(QJsonObject data); void RegistConfirmReceived(QJsonObject data); void AddSessionToDatabase(QJsonObject data); + void SearchInfoReceived(QJsonObject data); private: ClientMain(QString IPAddress, int portOpen, QObject *parent = nullptr); diff --git a/Client/codeeditor.cpp b/Client/codeeditor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50a5f19953c2926b31ee256f711b232a738b1df0 --- /dev/null +++ b/Client/codeeditor.cpp @@ -0,0 +1,111 @@ +#include "codeeditor.h" +#include + +CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent) +{ + lineNumberArea = new LineNumberArea(this); + + connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); + connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); + + updateLineNumberAreaWidth(0); + setMode(BROWSE); +} +int CodeEditor::lineNumberAreaWidth() +{ + int digits = 1; + int max = qMax(1, blockCount()); + while (max >= 10) { + max /= 10; + ++digits; + } + + int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; + + return space; +} + +void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) +{ + setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); +} + +void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) +{ + if (dy) + lineNumberArea->scroll(0, dy); + else + lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); + + if (rect.contains(viewport()->rect())) + updateLineNumberAreaWidth(0); +} + +void CodeEditor::resizeEvent(QResizeEvent *e) +{ + QPlainTextEdit::resizeEvent(e); + + QRect cr = contentsRect(); + lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); +} +void CodeEditor::highlightCurrentLine() +{ + QList extraSelections; + + if (!isReadOnly()) { + QTextEdit::ExtraSelection selection; + + QColor lineColor = QColor(Qt::yellow).lighter(160); + + selection.format.setBackground(lineColor); + selection.format.setProperty(QTextFormat::FullWidthSelection, true); + //selection.cursor = textCursor(); + //selection.cursor.clearSelection(); + extraSelections.append(selection); + } + + setExtraSelections(extraSelections); +} + +void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) +{ + QPainter painter(lineNumberArea); + painter.fillRect(event->rect(), Qt::lightGray); + + + QTextBlock block = firstVisibleBlock(); + int blockNumber = block.blockNumber(); + int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); + int bottom = top + (int) blockBoundingRect(block).height(); + + while (block.isValid() && top <= event->rect().bottom()) { + if (block.isVisible() && bottom >= event->rect().top()) { + QString number = QString::number(blockNumber + 1); + painter.setPen(Qt::black); + painter.drawText(-2, top, lineNumberArea->width(), fontMetrics().height(), + Qt::AlignRight, number); + } + + block = block.next(); + top = bottom; + bottom = top + (int) blockBoundingRect(block).height(); + ++blockNumber; + } +} +void CodeEditor::setMode(editorMode mode) +{ + if(mode == BROWSE) + { + this->setReadOnly(true); + this->setStyleSheet("background:#f2f2f3;"); + this->setFont(QFont("Cascadia Code Light")); + highlightCurrentLine(); + } + else if(mode == EDIT) + { + this->setReadOnly(false); + this->setStyleSheet("background:#ffffff;"); + highlightCurrentLine(); + } +} diff --git a/Client/codeeditor.h b/Client/codeeditor.h new file mode 100644 index 0000000000000000000000000000000000000000..c6cf84e1e65392f882d1a98af0a760842afeeef9 --- /dev/null +++ b/Client/codeeditor.h @@ -0,0 +1,57 @@ +#ifndef CODEEDITOR_H +#define CODEEDITOR_H +#include +#include + +#include +#include +#include +#include +#include +#include +class LineNumberArea; + +class CodeEditor : public QPlainTextEdit +{ + Q_OBJECT + +public: + CodeEditor(QWidget *parent = 0); + void setMode(editorMode mode); + void lineNumberAreaPaintEvent(QPaintEvent *event); + int lineNumberAreaWidth(); + +protected: + void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; + +private slots: + void updateLineNumberAreaWidth(int newBlockCount); + void highlightCurrentLine(); + void updateLineNumberArea(const QRect &, int); + +private: + QWidget *lineNumberArea; +}; + + +class LineNumberArea : public QWidget +{ +public: + LineNumberArea(CodeEditor *editor) : QWidget(editor) { + codeEditor = editor; + } + + QSize sizeHint() const Q_DECL_OVERRIDE { + return QSize(codeEditor->lineNumberAreaWidth(), 0); + } + +protected: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE { + codeEditor->lineNumberAreaPaintEvent(event); + } + +private: + CodeEditor *codeEditor; +}; + +#endif // CODEEDITOR_H diff --git a/Client/databaseoperation.cpp b/Client/databaseoperation.cpp index 8cc1ba375cfb5007daaddbec5eac17a996cd91aa..1699d1639fcca2ea87f9c299f0033506b64c4517 100644 --- a/Client/databaseoperation.cpp +++ b/Client/databaseoperation.cpp @@ -3,19 +3,24 @@ #include #include #include +#include #include "databaseoperation.h" -QString json2str(QJsonObject json) { - return QString(QJsonDocument(json).toJson()); +QJsonObject str2json(const QString jsonString) +{ + QTextCodec *tc = QTextCodec::codecForName("UTF-8"); + QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8().data()); + if (jsonDocument.isNull()){ + qDebug() << "Error Parsing Str to Json"; + } + QJsonObject jsonObject = jsonDocument.object(); + return jsonObject; } -QJsonObject str2json(QString str) { - QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8().data()); - if (jsonDoc.isNull()) { - qDebug() << "read json obj from str failed: str = " << str.toLocal8Bit().data(); - } - return jsonDoc.object(); + +QString json2str(QJsonObject json) { + return QString(QJsonDocument(json).toJson(QJsonDocument::Compact)); } DatabaseOperation::DatabaseOperation(QObject *parent) : QObject(parent) @@ -103,7 +108,6 @@ QList DatabaseOperation::findAllSessions() { int sessionId = query.value(0).toInt(); QJsonObject json = query.value(1).toJsonObject(); QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; - QList members = queryMembersBySession(sessionId); OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); @@ -134,36 +138,29 @@ QList DatabaseOperation::findAllMessages() { //往User表中插入数据 -bool DatabaseOperation::insertUser(const char* username, const char* nickname, const char* password, const char* profile){ +bool DatabaseOperation::insertUser(QString username, QString nickname, QString password, QJsonObject profile){ QSqlQuery query; -// QString insert_sql = "insert into User(Username, Nickname, Password, Profile) values (?, ?, ?, ?)"; - QString insert_sql = QString("INSERT INTO User(Username, Nickname, Password, Profile) VALUES ('%1', '%2', '%3', '%4')") - .arg(username).arg(nickname).arg(password).arg(profile); - qDebug() << insert_sql; -// query.prepare(insert_sql); -// query.addBindValue(username); -// query.addBindValue(nickname); -// query.addBindValue(password); -// query.addBindValue(profile); + QString insert_sql = "INSERT INTO User(Username, Nickname, Password, Profile) VALUES (?, ?, ?, ?)"; + query.prepare(insert_sql); + query.addBindValue(username); + query.addBindValue(nickname); + query.addBindValue(password); + query.addBindValue(json2str(profile)); if (! query.exec(insert_sql) ) { qDebug() << query.lastError(); return false; } - ClientDataCenter::Singleton().registerUser(new OnlineUserModel( - QString(username), QString(nickname), str2json(QString(profile)) )); + ClientDataCenter::Singleton().registerUser(new OnlineUserModel(username, nickname, profile)); return true; } bool DatabaseOperation::insertUser(const OnlineUserModel &user, const QString &password) { - return insertUser(user.getUsername().toUtf8().data(), - user.getNickname().toUtf8().data(), - password.toUtf8().data(), - json2str(user.getProfile()).toUtf8().data()); + return insertUser(user.getUsername(), user.getNickname(), password, user.getProfile()); } -int DatabaseOperation::getTableCount(const char * tableName) const { +int DatabaseOperation::getTableCount(QString tableName) const { QSqlQuery query; QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName); query.addBindValue(tableName); @@ -176,14 +173,14 @@ int DatabaseOperation::getTableCount(const char * tableName) const { } //往 Session 表中插入数据 -int DatabaseOperation::insertSessionBasicInfo(const char* SessionType, const char* profile) { +int DatabaseOperation::insertSessionBasicInfo(QString SessionType, QJsonObject profile) { QSqlQuery query; QString insert_sql = "insert into Session(SessionID, SessionType, Profile) values(?, ?, ?)"; query.prepare(insert_sql); int sessionId = getTableCount("Session") + 1; query.addBindValue(sessionId); query.addBindValue(SessionType); - query.addBindValue(profile); + query.addBindValue(json2str(profile)); if (!query.exec()) { qDebug() << query.lastError(); return -1; @@ -191,7 +188,7 @@ int DatabaseOperation::insertSessionBasicInfo(const char* SessionType, const cha return sessionId; } -bool DatabaseOperation::insertMember(int sessionID, const char * user){ +bool DatabaseOperation::insertMember(int sessionID, QString user){ QSqlQuery query; QString insert_sql = "insert into IsMember values(?, ?)"; query.prepare(insert_sql); @@ -205,7 +202,7 @@ bool DatabaseOperation::insertMember(int sessionID, const char * user){ } bool DatabaseOperation::insertMember(int sessionID, const OnlineUserModel &user){ - return insertMember(sessionID, user.getUsername().toUtf8().data()); + return insertMember(sessionID, user.getUsername()); } //通过sessionID查询会议成员 @@ -226,7 +223,7 @@ QList DatabaseOperation::queryMembersBySession(int sessionID){ } //查询用户所拥有的session -QList DatabaseOperation::querySessionsByMember(const char * username){ +QList DatabaseOperation::querySessionsByMember(QString username){ QList member_List; QSqlQuery query; QString query_sql = "SELECT SessionId, Username FROM IsMember WHERE username = (?)"; @@ -260,7 +257,7 @@ bool DatabaseOperation::attemptLogIn(QString username, QString password) const { return false; } -int DatabaseOperation::insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile) { +int DatabaseOperation::insertNewMessage(int SessionId, QString senderUsername, QString MessageText, QJsonObject profile) { QSqlQuery query; QString sql = "select count (*) from Message WHERE SessionId = ?"; query.prepare(sql); @@ -278,7 +275,7 @@ int DatabaseOperation::insertNewMessage(int SessionId, const char *senderUsernam query.addBindValue(msgId); query.addBindValue(senderUsername); query.addBindValue(MessageText); - query.addBindValue(profile); + query.addBindValue(json2str(profile)); if (!query.exec()) { qDebug() << "insertNewMessage : " << query.lastError(); return -1; @@ -314,7 +311,7 @@ OnlineUserModel & ClientDataCenter::getUser(QString username) { } OnlineMessage & ClientDataCenter::getMessage(int SessionId, int MessageId) { - if (_getMessage(SessionId, MessageId)) throw "Not exist"; + if (_getMessage(SessionId, MessageId) == nullptr) throw "Not exist"; return *messages[{SessionId, MessageId}]; } @@ -336,8 +333,8 @@ OnlineSession* ClientDataCenter::_getSession(int SessionId) { } OnlineMessage* ClientDataCenter::_getMessage(int SessionId, int MessageId) { - if (messages.contains({SessionId, MessageId})) - return messages[{SessionId, MessageId}]; + if (messages.contains(QPair({SessionId, MessageId}))) + return messages[QPair({SessionId, MessageId})]; return nullptr; } diff --git a/Client/databaseoperation.h b/Client/databaseoperation.h index 8635e182499a2c0cff8f5cb4d186a82fb0ea38b1..3bd535e6f7ededa044bec817fdc783898a732b82 100644 --- a/Client/databaseoperation.h +++ b/Client/databaseoperation.h @@ -26,22 +26,22 @@ public: void startDatabaseConnection(QString dbfilename); bool isDBExist(QString str) const; void closeDB(); - int getTableCount(const char * tableName) const; + int getTableCount(QString tableName) const; QList findAllUsers(); QList findAllSessions(); QList findAllMessages(); - bool insertUser(const char * username, const char * nickname, const char * password, const char * profile); + bool insertUser(QString username, QString nickname, QString password, QJsonObject profile); bool insertUser(const OnlineUserModel &user, const QString &password); // 返回SessionID - int insertSessionBasicInfo(const char * sessionType, const char * profile); + int insertSessionBasicInfo(QString sessionType, QJsonObject profile); bool isRunning() const { return status == Status::Running; } bool insertMember(int sessionID, const OnlineUserModel& user); - bool insertMember(int sessionID, const char * user); - int insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile); + bool insertMember(int sessionID, QString user); + int insertNewMessage(int SessionId, QString senderUsername, QString MessageText, QJsonObject profile); QList queryMembersBySession(int sessionID); - QList querySessionsByMember(const char * username); + QList querySessionsByMember(QString username); QList getMessageListBySessionID(int SessionId) const; OnlineMessage * findMessage(int sessionId, int MessageId); diff --git a/Client/highlighter.h b/Client/highlighter.h deleted file mode 100644 index 493e59dd42389aa9b41f900a07eab081ebaae352..0000000000000000000000000000000000000000 --- a/Client/highlighter.h +++ /dev/null @@ -1,45 +0,0 @@ - -#ifndef HIGHLIGHTER_H -#define HIGHLIGHTER_H - -#include -#include -#include - -QT_BEGIN_NAMESPACE -class QTextDocument; -QT_END_NAMESPACE - -//! [0] -class Highlighter : public QSyntaxHighlighter //继承QSyntaxHightliaghter -{ - Q_OBJECT - -public: - Highlighter(QTextDocument *parent = 0);//构造函数传一个 QTextDocument 对象 给父类 - -protected: - void highlightBlock(const QString &text) override;//重写父类这个函数 自动调用 - -private: - - struct HighlightingRule//语法规则结构体,包含正则表达式模式串和匹配的样式 - { - QRegularExpression pattern; - QTextCharFormat format; - }; - QVector highlightingRules;//规则的集合,可以定义多个高亮规则 - - QRegularExpression commentStartExpression; //注释的高亮,使用highliangBlock()匹配,下文提到 - QRegularExpression commentEndExpression; - - QTextCharFormat keywordFormat;//高亮样式,关键词,一下顾名思义 - QTextCharFormat classFormat; - QTextCharFormat singleLineCommentFormat; - QTextCharFormat multiLineCommentFormat; - QTextCharFormat quotationFormat; - QTextCharFormat functionFormat; -}; -//! [0] - -#endif // HIGHLIGHTER_H diff --git a/Client/kuang.cpp b/Client/kuang.cpp index 2fa6da3d7b30d0184e49ee280cefbdc6cde31f84..40563194d26dd2db36034980d17e4919fc2d8d2d 100644 --- a/Client/kuang.cpp +++ b/Client/kuang.cpp @@ -2,6 +2,36 @@ #include "ui_kuang.h" #include #include +#include +#include "clientdatacenter.h" +#include + +QPixmap Kuang::PaintHead(const QChar &name) +{ + QSize size(50,50); //指定图片大小; + QImage image(size,QImage::Format_ARGB32); + //以ARGB32格式构造一个QImage + //image.fill(qRgba(0,0,0,100));//填充图片背景,0-255为透明度 + image.fill(qRgba(52,73,94,255)); + QPainter painter(&image); //为这个QImage构造一个QPainter + painter.setCompositionMode(QPainter::CompositionMode_SourceOut); + //设置画刷的组合模式CompositionMode_SourceOut这个模式为目标图像在上。 + //改变组合模式和上面的填充方式可以画出透明的图片。 + + //改变画笔和字体 + QPen pen = painter.pen(); + pen.setColor(QColor(255,255,255,255)); + QFont font = painter.font(); + font.setFamily("Microsoft YaHei"); + font.setBold(true);//加粗 + font.setPixelSize(25);//改变字体大小 + + painter.setPen(pen); + painter.setFont(font); + painter.drawText(image.rect(),Qt::AlignCenter, name); + //将Hello写在Image的中心ui + return QPixmap::fromImage(image); +} Kuang::Kuang(QWidget *parent) : QWidget(parent), @@ -15,14 +45,21 @@ Kuang::Kuang(const QString &username,QJsonObject data,QWidget *parent): QWidget(parent), ui(new Ui::Kuang){ ui->setupUi(this); + ui->lblNewMessage->hide(); QJsonArray temp = data["Members"].toArray(); SessionID = data["SessionID"].toInt(); if(temp[0].toObject()["Username"].toString()==username){ - ui->name->setText(temp[1].toObject()["Username"].toString()); + USERNAME = temp[1].toObject()["Username"].toString(); + ui->name->setText(USERNAME); } else { - ui->name->setText(temp[0].toObject()["Username"].toString()); + USERNAME = temp[0].toObject()["Username"].toString(); + ui->name->setText(USERNAME); } + + IsChosen = false; + ui->profile->setPixmap(PaintHead(USERNAME[0])); + } // GROUP @@ -30,15 +67,44 @@ Kuang::Kuang(QJsonObject data,QWidget *parent): QWidget(parent), ui(new Ui::Kuang){ ui->setupUi(this); + ui->lblNewMessage->hide(); SessionID = data["SessionID"].toInt(); - ui->name->setText(data["Profile"].toObject()["SessionName"].toString()); + IsChosen = false; + USERNAME = data["Profile"].toObject()["SessionName"].toString(); + ui->name->setText(USERNAME); + ui->profile->setPixmap(PaintHead(USERNAME[0])); +} + +void Kuang::Showreddot(){ + ui->lblNewMessage->show(); +} + +void Kuang::Hidereddot(){ + ui->lblNewMessage->hide(); } + +Kuang::Kuang(QString UserName,QString NikeName,QWidget *parent): + QWidget(parent), + ui(new Ui::Kuang){ + ui->setupUi(this); + ui->lblNewMessage->hide(); + SessionID = 0; + IsChosen = false; + USERNAME = UserName; + ui->name->setText(UserName); + ui->profile->setPixmap(PaintHead(USERNAME[0])); +} + Kuang* Kuang::KuangChosenNow = nullptr; + +bool Kuang::IsShow = true; + void Kuang::mousePressEvent(QMouseEvent *ev){ +// qDebug() << "Mouse Pressed" << ClientDataCenter::Singleton().getSession(SessionID).getLatestMessageID(); if(ev->button()==Qt::LeftButton){ if(!KuangChosenNow || KuangChosenNow != this){ - emit KuangChosenChanged(); KuangChosenNow = this; + emit KuangChosenChanged(this); } } } diff --git a/Client/kuang.h b/Client/kuang.h index 2b7fb1253a0f0ca3f15ef8bee3c70b3a7dc7941a..b768d02185173098de5759092570fa1b1d3d4f95 100644 --- a/Client/kuang.h +++ b/Client/kuang.h @@ -19,13 +19,21 @@ public: explicit Kuang(QWidget *parent = nullptr); Kuang(const QString &username,QJsonObject data,QWidget *parent = nullptr); Kuang(QJsonObject data,QWidget *parent = nullptr); + Kuang(QString UserName,QString NikeName,QWidget *parent = nullptr); + void Showreddot(); + void Hidereddot(); virtual void mousePressEvent(QMouseEvent *ev); + QPixmap PaintHead(const QChar &name); ~Kuang(); int SessionID; + bool IsChosen = false; + QString USERNAME; static Kuang *KuangChosenNow; + static bool IsShow; signals: - void KuangChosenChanged(); + void KuangChosenChanged(Kuang *This); + private: Ui::Kuang *ui; }; diff --git a/Client/kuang.ui b/Client/kuang.ui index 113ff0c5d708ecb554c98dbf63464f40af349e23..58fe85c4d99caaaea35a8e4703c2466fa8597298 100644 --- a/Client/kuang.ui +++ b/Client/kuang.ui @@ -6,46 +6,162 @@ 0 0 - 200 - 75 + 253 + 70 + + + 253 + 70 + + + + + 253 + 70 + + + + ArrowCursor + + + Qt::ClickFocus + Form + + false + + + QWidget::hover +{ + background-color::rgb(200,198,198); +} + - 10 - 15 + 20 + 10 50 50 + + QLabel +{ + background-color:transparent; +} + - QFrame::Box + QFrame::NoFrame profile + + true + - 70 - 20 - 121 - 41 + 80 + 10 + 161 + 30 + + + 161 + 30 + + + + + Microsoft YaHei + 14 + + + + QLabel +{ + background-color:transparent; +} + - QFrame::Box + QFrame::NoFrame name + + + + 0 + 0 + 253 + 70 + + + + + 253 + 16777215 + + + + QLabel::hover +{ + background-color:rgb(198,198,198); +} + + + + + + + + + 199 + 29 + 41 + 41 + + + + + 3 + 3 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dotRed.png + + + true + + + label + profile + name + lblNewMessage - + + + diff --git a/Client/main.cpp b/Client/main.cpp index fde944759c4098da325ced3e8e0e50571e66e0a7..025e70ff1948ff52df3258b8cc7b41fbec94e867 100644 --- a/Client/main.cpp +++ b/Client/main.cpp @@ -11,6 +11,7 @@ #include #include + const QString filename = QDir::currentPath() + "/settings.json"; QJsonObject readSettings() { @@ -25,12 +26,19 @@ QJsonObject readSettings() { return QJsonObject(); } +#define DEBUG + int main(int argc, char *argv[]) { QApplication a(argc, argv); +#ifndef DEBUG auto settings = readSettings(); QString ip = settings.contains("Server IP") ? settings["Server IP"].toString() : "127.0.0.1"; int port = settings.contains("Port") ? settings["Port"].toInt() : 8888; +#else + QString ip = "127.0.0.1"; + int port = 8888; +#endif qDebug() << "IP = " << ip << ", port = " << port; ClientMain & client = ClientMain::Singleton(ip, port); diff --git a/Client/mainwindow.cpp b/Client/mainwindow.cpp index c9106a1324be4b2e2660c9ac5abd6597d0817119..8c90ebcd8b66b846cd76a0ab9f85adedda2cfa01 100644 --- a/Client/mainwindow.cpp +++ b/Client/mainwindow.cpp @@ -2,10 +2,12 @@ #include "ui_mainwindow.h" #include "kuang.h" #include "clientdatacenter.h" - +#include #include #include #include +#include +#include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), @@ -13,34 +15,39 @@ MainWindow::MainWindow(QWidget *parent) : { ui->setupUi(this); ui->tabWidget->setAttribute(Qt::WA_StyledBackground); - qApp->installEventFilter(this); //为所有控件添加事件过滤器 - - QToolButton *btn = new QToolButton; - btn->setIcon(QPixmap(":/img/system/img/LittlePink.svg")); - btn->setFixedSize(190, 100); - btn->setIconSize(QSize(50, 50)); - btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn->setText("小粉"); - btn->setAutoRaise(true); - ui->lyFrd->addWidget(btn); - - QToolButton *btn2 = new QToolButton; - btn2->setIcon(QPixmap(":/img/system/img/LittleRed.svg")); - btn2->setIconSize(QSize(190, 100)); - btn2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn2->setText("小红"); - btn2->setAutoRaise(true); - ui->lyFrd->addWidget(btn2); - - QToolButton *btn3 = new QToolButton; - btn3->setIcon(QPixmap(":/img/system/img/LittleBlack.svg")); - btn3->setIconSize(QSize(190, 100)); - btn3->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn3->setText("小黑"); - btn3->setAutoRaise(true); - ui->lyFrd->addWidget(btn3); - - ui->lyFrd->addStretch(); + + QJsonObject data = {{ "MsgType", "SessionData" }, {"SessionID", 1}, {"SessionType", "FRIEND"} }; + QJsonArray members; + members.append(QJsonObject{{"Username", "小蓝"}}); + members.append(QJsonObject{{"Username", "xxx"}}); + data["Members"]=members; + Kuang *k = new Kuang("小蓝", data, this); + friendlayout = new QVBoxLayout(ui->frd); + friendlayout->setContentsMargins(0,0,0,0); + friendlayout->addWidget(k); + + QToolButton* btnSearch = new QToolButton; + btnSearch->setCursor(Qt::PointingHandCursor);//如果不设置鼠标样式,鼠标移动到按钮上依旧显示为编辑框的鼠标样式 + btnSearch->setIcon(QPixmap(":/img/system/img/search.png")); + btnSearch->setIconSize(QSize(20,20)); + btnSearch->setStyleSheet("QToolButton{border:none;}"); + QWidgetAction* action = new QWidgetAction(ui->search); + action->setDefaultWidget(btnSearch); + ui->search->addAction(action, QLineEdit::TrailingPosition); + + ui->widget_2->hide(); + lblBackground = new QLabel(ui->widget_3); + lblBackground->setPixmap(QPixmap(":/img/system/img/bicBackground.png")); + lblBackground->setGeometry((this->width() - 323)/ 2 - 100, this->height() / 2 - 200, 250, 250); + lblWelcome = new QLabel(ui->widget_3); + lblWelcome->setText("Hello, Coder!"); + QFont fontWelcome("Verdana", 37, 90); + lblWelcome->setFont(fontWelcome); + lblWelcome->setStyleSheet("color:rgb(144,224,239);"); + lblWelcome->setGeometry((this->width() - 323)/ 2 - 200, this->height() / 2 + 50, 500, 100); +// ui->widget_2->show(); +// lblBackground->hide(); +// lblWelcome->hide(); } MainWindow::~MainWindow() @@ -55,6 +62,8 @@ void MainWindow::dealMessage(Message *messageW, QListWidgetItem *item, QString t item->setSizeHint(size); //设置item基本规格 同widget messageW->setTextContent(text, time, size, type); //设置message基本内容 ui->listWidget->setItemWidget(item, messageW); //将message的内容 在给定的 item中显示 + + ui->listWidget->setCurrentRow(ui->listWidget->count()-1); } void MainWindow::dealMessageTime(QString curMsgTime) @@ -87,35 +96,15 @@ void MainWindow::on_btnSend_clicked() { QString msg = ui->textEdit->toPlainText(); //返回文字 ui->textEdit->setText(""); //清空 - QString time = QString::number(QDateTime::currentDateTime().toTime_t()); //获取当前时间并转为时间戳 - - dealMessageTime(time); //用于处理时间 - Message *messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem *item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userMe); emit SendMessageToServer(username, msg); - - //test 用例 - if(ui->listWidget->count()%2) { - bool isSending = true; - if(isSending) { - dealMessageTime(time); - - Message* messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem* item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userMe); - } - } else { - if(msg != "") { - dealMessageTime(time); - - Message* messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem* item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userOther); - } + QList owners, repos, commits; + int git_mentions = captureGitRepo(msg, owners, repos, commits); + for (int i = 0; i < git_mentions; i++) { + msg = generateGitMessage(owners[i], repos[i], commits[i]); + emit SendMessageToServer(username, msg); } - ui->listWidget->setCurrentRow(ui->listWidget->count()-1); + ui->listWidget->setCurrentRow(ui->listWidget->count()-1);//保持在最新的Item } void MainWindow::resizeEvent(QResizeEvent *event) @@ -127,9 +116,12 @@ void MainWindow::resizeEvent(QResizeEvent *event) dealMessage(messageW, item, messageW->text(), messageW->time(), messageW->userType()); } + + lblBackground->setGeometry((this->width() - 323)/ 2 - 100, this->height() / 2 - 200, 250, 250); + lblWelcome->setGeometry((this->width() - 323)/ 2 - 200, this->height() / 2 + 50, 500, 100); } //bool MainWindow::eventFilter(QObject *watched, QEvent *event) { - +//用于光标焦点改变 // if(event->type() == QEvent::MouseButtonPress && watched != ui->nickNameShow) // { // ui->nickNameShow->clearFocus(); @@ -147,41 +139,206 @@ MainWindow::MainWindow(QJsonObject data,QWidget *parent): ui->tabWidget->setAttribute(Qt::WA_StyledBackground); friendlayout = new QVBoxLayout(ui->frd); grouplayout = new QVBoxLayout(ui->group); + friendlayout->setContentsMargins(0,0,0,0); + grouplayout->setContentsMargins(0,0,0,0); + searchlayout = new QVBoxLayout(ui->searchkuang); + newgrouplayout = new QVBoxLayout(ui->newgroup); + newgroupviewlayout = new QVBoxLayout(ui->newgroupview); + setup(data); + friendlayout->addStretch(); + grouplayout->addStretch(); + ui->widget_2->hide(); + lblBackground = new QLabel(ui->widget_3); + lblBackground->setPixmap(QPixmap(":/img/system/img/bicBackground.png")); + lblBackground->setGeometry((this->width() - 323)/ 2 - 100, this->height() / 2 - 200, 250, 250); + lblWelcome = new QLabel(ui->widget_3); + lblWelcome->setText("Hello, Coder!"); + QFont fontWelcome("Verdana", 33, 90); + lblWelcome->setFont(fontWelcome); + lblWelcome->setStyleSheet("color:rgb(1, 73, 124);"); + lblWelcome->setGeometry((this->width() - 323)/ 2 - 200, this->height() / 2 + 50, 500, 100); +} + +void MainWindow::setup(QJsonObject data) { ui->userNameShow->setText(data["Username"].toString()); username = data["Username"].toString(); ui->nickNameShow->setText(data["Nickname"].toString()); + //搜索框按钮 + QToolButton* btnSearch = new QToolButton; + btnSearch->setCursor(Qt::PointingHandCursor);//如果不设置鼠标样式,鼠标移动到按钮上依旧显示为编辑框的鼠标样式 + btnSearch->setIcon(QPixmap(":/img/system/img/search.png")); + btnSearch->setIconSize(QSize(20,20)); + btnSearch->setStyleSheet("QToolButton{border:none;}"); + QWidgetAction* action = new QWidgetAction(ui->search); + action->setDefaultWidget(btnSearch); + ui->search->addAction(action, QLineEdit::TrailingPosition); + connect(btnSearch,&QToolButton::clicked,[=](){ + QString msg = ui->search->text(); + emit SendSearchInfo(msg); + }); +} + +void MainWindow::dealsearchinfo(QJsonObject data){ + QJsonArray arr = data["SearchInfo"].toArray(); + QString UserName,NickName; + int n = kuangstore.size(),i; + for(i=0;iremoveWidget(kuangstore[i]); + delete kuangstore[i]; + } + kuangstore = {}; + n = arr.size(); + for(i=0;iaddWidget(k); + } +} +void MainWindow::SendNewFriendInfo(Kuang *This){ + int j,n1 = friendsession.size(); + if(This->USERNAME == username){ + QMessageBox::information(this,"提示","不能添加自己为好友"); + return; + } + for(j=0;j < n1;j++){ + if(friendsession[j]->USERNAME == This->USERNAME){ + QMessageBox::information(this,"提示",friendsession[j]->USERNAME + "已经是您的好友了"); + return; + } + } + if(This->IsChosen){ + QMessageBox::information(this,"提示","请勿重复发送好友请求"); + } + else { + QMessageBox::information(this,"提示","添加好友信息已发送"); + This->IsChosen = true; + emit SendNewFriendInfo1(This); + } +} + +void MainWindow::showreddot(Kuang *This){ + This->Showreddot(); +} + +void MainWindow::hidereddot(Kuang *This){ + This->Hidereddot(); +} + +void MainWindow::Sessionorderchange(QJsonObject data){ + int ID = data["SessionID"].toInt(),i,n; + n = friendsession.size(); + for(i=0;iSessionID == ID){ + friendlayout->removeWidget(friendsession[i]); + friendlayout->insertWidget(0,friendsession[i]); + if(data["SenderName"].toString()!=username){ + showreddot(friendsession[i]); + } + return; + } + } + n = groupsession.size(); + for(i=0;iSessionID == ID){ + grouplayout->removeWidget(groupsession[i]); + grouplayout->insertWidget(0,groupsession[i]); + if(data["SenderName"].toString()!=username){ + showreddot(groupsession[i]); + } + return; + } + } } void MainWindow::FriendSessionAdd(QJsonObject data){ + QLayoutItem * lastItem = friendlayout->itemAt(friendlayout->count() - 1); // 头像弹簧 + friendlayout->removeItem(lastItem); Kuang *k = new Kuang(username,data,this); friendlayout->addWidget(k); + friendsession.append(k); connect(k,&Kuang::KuangChosenChanged,this,&MainWindow::clearlistview); + Kuang *t = new Kuang(username,data,this); + newgrouplayout->addWidget(t); + kuanggroupstore.append(t); + connect(t,&Kuang::KuangChosenChanged,this,&MainWindow::groupchanged); + friendlayout->addStretch(); +} + +void MainWindow::groupchanged(Kuang *This){ + Kuang::KuangChosenNow = nullptr; + if(This->IsChosen == true){ + newgroupviewlayout->removeWidget(This); + newgrouplayout->addWidget(This); + This->IsChosen = false; + } + else{ + newgrouplayout->removeWidget(This); + newgroupviewlayout->addWidget(This); + This->IsChosen = true; + } } void MainWindow::GroupSessionAdd(QJsonObject data){ + QLayoutItem * lastItem = grouplayout->itemAt(grouplayout->count() - 1); // 头像弹簧 + grouplayout->removeItem(lastItem); Kuang *k = new Kuang(data,this); grouplayout->addWidget(k); + groupsession.append(k); connect(k,&Kuang::KuangChosenChanged,this,&MainWindow::clearlistview); + grouplayout->addStretch(); } -void MainWindow::clearlistview(){ +void MainWindow::clearlistview(Kuang *This){ ui->listWidget->clear(); + if(Kuang::IsShow){ + Kuang::IsShow = false; + ui->widget_2->show(); + lblBackground->hide(); + lblWelcome->hide(); + } + ui->lblUsername->setText(This->USERNAME); + hidereddot(This); emit updatelistview(); } void MainWindow::AddMessagetoListview(QJsonObject data){ if(Kuang::KuangChosenNow && data["SessionID"].toInt()==Kuang::KuangChosenNow->SessionID){ + hidereddot(Kuang::KuangChosenNow); QString time = QString::number(QDateTime::currentDateTime().toTime_t()); dealMessageTime(time); //用于处理时间 - Message *messageW = new Message(ui->listWidget->parentWidget()); QListWidgetItem *item = new QListWidgetItem(ui->listWidget); QString msg = data["Body"].toObject()["Text"].toString(); if(data["SenderName"].toString() == username){ + Message *messageW = new Message(username,ui->listWidget->parentWidget()); dealMessage(messageW, item, msg, time, Message::userMe); } else{ + Message *messageW = new Message(data["SenderName"].toString(),ui->listWidget->parentWidget()); dealMessage(messageW, item, msg, time, Message::userOther); } } } + +void MainWindow::on_sendgroup_clicked() +{ + QString msg = ui->lineEdit->text(); + if(msg.size()==0){ + QMessageBox::information(this,"提示","请为您的群聊设置一个昵称"); + return; + } + QJsonArray temp; + int i, n = kuanggroupstore.size(); + for(i=0;iIsChosen){ + temp.append(QJsonObject({{"username", kuanggroupstore[i]->USERNAME}})); + } + } + temp.append(QJsonObject({{"username", username}})); + QJsonObject data = {{"MsgType","NewGroup"},{"SessionName",msg}}; + data["Members"] = temp; + emit sendnewgroup(data); +} diff --git a/Client/mainwindow.h b/Client/mainwindow.h index 1df99c6e46b1e8d30939c6b5d8118b975e5404eb..f39d5c167599416c5e46a9d445761f3acf5438e4 100644 --- a/Client/mainwindow.h +++ b/Client/mainwindow.h @@ -10,6 +10,7 @@ #include #include #include +#include #include "message.h" namespace Ui { @@ -24,24 +25,46 @@ public: explicit MainWindow(QWidget *parent = nullptr); MainWindow(QJsonObject data,QWidget *parent = nullptr); ~MainWindow(); + void setup(QJsonObject data); void FriendSessionAdd(QJsonObject data); void GroupSessionAdd(QJsonObject data); QVBoxLayout *friendlayout; QVBoxLayout *grouplayout; + QLabel *lblBackground; + QLabel *lblWelcome; + QVBoxLayout *searchlayout; + QVBoxLayout *newgrouplayout; + QVBoxLayout *newgroupviewlayout; QString username; - + QVectorkuangstore,kuanggroupstore,friendsession,groupsession; //处理信息 void dealMessage(Message *messageW, QListWidgetItem *item, QString text, QString time, Message::UserType type); + //处理搜索框好友显示 + void dealNewFriend(QString text); //处理时间 void dealMessageTime(QString curMsgTime); void AddMessagetoListview(QJsonObject data); - void clearlistview(); + void clearlistview(Kuang *This); + void dealsearchinfo(QJsonObject data); + void groupchanged(Kuang *This); + void Sessionorderchange(QJsonObject data); + void SendNewFriendInfo(Kuang *This); + void showreddot(Kuang *This); + void hidereddot(Kuang *This); + signals: + void SendNewFriendInfo1(Kuang *This); void updatelistview(); void SendMessageToServer(const QString &sendername,const QString &text); bool eventFilter(QObject *watched, QEvent *event); + void SendSearchInfo(QString msg); + void sendnewgroup(QJsonObject data); + + private slots: void on_btnSend_clicked(); + void on_sendgroup_clicked(); + protected: //重生事件 调整聊天框大小 void resizeEvent(QResizeEvent *event); diff --git a/Client/mainwindow.ui b/Client/mainwindow.ui index d1d49c3949952f32864f65dfd64fd05aa046a7bf..341ce491ec5d7e15cd30ccdd75ccfb3958991abd 100644 --- a/Client/mainwindow.ui +++ b/Client/mainwindow.ui @@ -1,1014 +1,1273 @@ - - - MainWindow - - - - 0 - 0 - 899 - 642 - - - - BICQ - - - - :/img/system/img/bicq.png:/img/system/img/bicq.png - - - 1.000000000000000 - - - QMainWindow -{ - border-radius: 8px; -} - - - - 100 - 100 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - true - - - QTabWidget{ - background-color:rgb(46,46,46); -} -QTabBar::tab -{ - background-color:rgb(46,46,46); - width:70px; - height:70px; -} - -QTabBar::tab:hover -{ - background-color:rgb(20,33,61); -} - - - - QTabWidget::West - - - QTabWidget::Rounded - - - 3 - - - - 30 - 30 - - - - Qt::ElideNone - - - false - - - false - - - false - - - false - - - - - :/img/system/img/personalOff.png - :/img/system/img/personalOn.png - - - - - - - 个人信息 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 700 - 600 - - - - - - 300 - 240 - 231 - 40 - - - - - Microsoft YaHei - 10 - false - - - - QLabel{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} - - - QFrame::NoFrame - - - Little_Blue - - - - - - 300 - 300 - 311 - 40 - - - - - Microsoft YaHei - 15 - 75 - true - - - - color: rgb(55, 63, 85); - - - QFrame::NoFrame - - - nick name: - - - - - - 300 - 180 - 241 - 40 - - - - - Microsoft YaHei - 15 - 75 - false - true - - - - color: rgb(55, 63, 85); - - - QFrame::NoFrame - - - user name: - - - Qt::AutoText - - - false - - - false - - - - - - 110 - 240 - 120 - 120 - - - - - - - :/img/system/img/LittleBlue.svg - - - true - - - Qt::AlignCenter - - - - - true - - - - 300 - 350 - 231 - 40 - - - - - Microsoft YaHei - 10 - - - - Qt::ClickFocus - - - 输入昵称 - - - - - - - - - QLineEdit -{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} -QLineEdit::hover -{ - border:2px solid rgb(142,202,230); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} -QLineEdit::focus -{ - border:2px solid rgb(18,150,219); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} - - - 昵称 - - - false - - - - - - - - - - :/system/system/img/message.png - :/img/system/img/messageOff.png - :/img/system/img/messageOn.png:/system/system/img/message.png - - - - - - 聊天 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 570 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 253 - 0 - - - - - 253 - 16777215 - - - - - Microsoft YaHei - 10 - - - - QToolBox { - background:rgb(240,240,240); -} - -QToolBox::tab { - background:rgb(245,245,245); - color:rgb(0,0,0); - border:1px solid black; - border-radius:5px; -} -QToolBox::tab::hover{ - background:rgb(255,255,255); - color:rgb(18,150,219); - border:1px solid black; - border-radius:5px; -} - - - 1 - - - 1 - - - - - 0 - 0 - 100 - 30 - - - - - Microsoft YaHei - 20 - - - - > top session - - - - - - 0 - 0 - 253 - 540 - - - - > friend - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - 0 - 0 - 100 - 30 - - - - > group - - - - - - - - - 0 - 0 - - - - - 370 - 350 - - - - QListWidget -{ -background-color: rgb(245, 245, 245); -color:rgb(51,51,51); -border: 1px solid rgb(245, 245, 245); -outline:0px;} -QListWidget::Item{background-color: rgb(245, 245, 245);} -QListWidget::Item:hover{background-color: rgb(245, 245, 245); } -QListWidget::item:selected{ - background-color: rgb(245, 245, 245); - color:black; - border: 1px solid rgb(245, 245, 245); -} -QListWidget::item:selected:!active{border: 1px solid rgb(245, 245, 245); background-color: rgb(245, 245, 245); color:rgb(51,51,51); } - - - QFrame::NoFrame - - - Qt::ScrollBarAsNeeded - - - Qt::ScrollBarAlwaysOff - - - - - - - - 370 - 30 - - - - - 16777215 - 30 - - - - QFrame::NoFrame - - - QFrame::Plain - - - - - 40 - 0 - 40 - 30 - - - - background-color: rgb(255, 255, 255); - - - - - - - :/img/system/img/git.png:/img/system/img/git.png - - - - 30 - 30 - - - - false - - - true - - - - - - 0 - 0 - 40 - 30 - - - - background-color: rgb(255, 255, 255); - - - - - - - :/img/system/img/face.png:/img/system/img/face.png - - - - 25 - 25 - - - - true - - - false - - - false - - - false - - - true - - - - - - - - - 370 - 150 - - - - - 16777215 - 150 - - - - - Microsoft YaHei - 20 - - - - Qt::ClickFocus - - - QFrame::NoFrame - - - QFrame::Plain - - - - - - - - 0 - 40 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - send - - - Backspace - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - - - - - - - - - :/system/system/img/searchOff.png - :/img/system/img/searchOff.png - :/img/system/img/searchOn.png:/system/system/img/searchOff.png - - - - - - 添加好友/群聊 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - :/img/system/img/search.png:/img/system/img/search.png - - - - 50 - 50 - - - - false - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 500 - 40 - - - - - Microsoft YaHei - 10 - - - - Qt::ClickFocus - - - QLineEdit -{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} -QLineEdit::hover -{ - border:2px solid rgb(142,202,230); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} -QLineEdit::focus -{ - border:2px solid rgb(18,150,219); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} - - - - - - 用户名或昵称或群聊ID - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - - :/system/system/img/addOff.png - :/img/system/img/addOff.png - :/img/system/img/addOn.png:/system/system/img/addOff.png - - - - - - 创建群聊 - - - - - - :/img/system/img/gitOff.png - :/img/system/img/gitOn.png - - - - - - - Git - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - - - Widget - QWidget -
widget.h
- 1 -
-
- - - - -
+ + + MainWindow + + + + 0 + 0 + 899 + 698 + + + + BICQ-Nano + + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + 1.000000000000000 + + + + + + + 100 + 100 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + ArrowCursor + + + false + + + QTabWidget{ + background-color:rgb(1,73,124); +} +QTabBar::tab +{ + background-color:rgb(1,73,124); + width:70px; + height:70px; +} + +QTabBar::tab:hover +{ + background-color:rgb(20,33,61); +} + + + + QTabWidget::West + + + QTabWidget::Rounded + + + 0 + + + + 30 + 30 + + + + Qt::ElideNone + + + false + + + false + + + false + + + false + + + + ArrowCursor + + + + :/img/system/img/personalOff.png + :/img/system/img/test.png + + + + + + + 个人信息 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 700 + 600 + + + + + + 300 + 240 + 231 + 40 + + + + + Microsoft YaHei + 10 + false + + + + QLabel{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QFrame::NoFrame + + + Little_Blue + + + + + + 300 + 300 + 311 + 40 + + + + + Microsoft YaHei + 15 + 75 + true + + + + color: rgb(55, 63, 85); + + + QFrame::NoFrame + + + Nickname: + + + + + + 300 + 180 + 241 + 40 + + + + + Microsoft YaHei + 15 + 75 + false + true + + + + color: rgb(55, 63, 85); + + + QFrame::NoFrame + + + Username: + + + Qt::AutoText + + + false + + + false + + + + + + 110 + 240 + 120 + 120 + + + + + + + :/img/system/img/LittleBlue.svg + + + true + + + Qt::AlignCenter + + + + + true + + + + 300 + 350 + 231 + 40 + + + + + Microsoft YaHei + 10 + + + + Qt::ClickFocus + + + 输入昵称 + + + + + + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + 昵称 + + + false + + + + + + + + + ArrowCursor + + + + :/system/system/img/message.png + :/img/system/img/messageOff.png + :/img/system/img/messageOnFinal.png:/system/system/img/message.png + + + + + + 聊天 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 253 + 0 + + + + + 253 + 16777215 + + + + + Microsoft YaHei + 10 + + + + QToolBox { + background:rgb(240,240,240); +} + +QToolBox::tab { + background:rgb(235,235,235); + color:rgb(0,0,0); +} +QToolBox::tab::hover{ + background:rgb(255,255,255); + color:rgb(18,150,219); +} + + + 0 + + + 0 + + + + + 0 + 0 + 253 + 599 + + + + + Microsoft YaHei + 20 + + + + > top session + + + + + + 0 + 0 + 100 + 30 + + + + > friend + + + + + + 0 + 0 + 100 + 30 + + + + > group + + + + + + + + + 570 + 0 + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + true + + + + 570 + 0 + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 370 + 30 + + + + + 16777215 + 30 + + + + QFrame +{ + background-color: rgb(255, 255, 255); +} + + + QFrame::NoFrame + + + QFrame::Plain + + + + + 40 + 0 + 40 + 30 + + + + PointingHandCursor + + + background-color: rgb(255, 255, 255); + + + + + + + :/img/system/img/git.png:/img/system/img/git.png + + + + 30 + 30 + + + + false + + + true + + + + + + 0 + 0 + 40 + 30 + + + + PointingHandCursor + + + background-color: rgb(255, 255, 255); + + + + + + + :/img/system/img/face.png:/img/system/img/face.png + + + + 25 + 25 + + + + false + + + false + + + false + + + false + + + true + + + + + + + + + 0 + 40 + + + + QWidget +{ + background-color: rgb(255, 255, 255); +} + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 93 + 30 + + + + + 93 + 30 + + + + + Microsoft YaHei + 10 + + + + PointingHandCursor + + + color: rgb(96,96,96); + + + send + + + Backspace + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + + + + 0 + 0 + + + + + 370 + 350 + + + + + 16777215 + 1000 + + + + QListWidget +{ +background-color: rgb(245, 245, 245); +color:rgb(51,51,51); +border: 1px solid rgb(245, 245, 245); +outline:0px;} +QListWidget::Item{background-color: rgb(245, 245, 245);} +QListWidget::Item:hover{background-color: rgb(245, 245, 245); } +QListWidget::item:selected{ + background-color: rgb(245, 245, 245); + color:black; + border: 1px solid rgb(245, 245, 245); +} +QListWidget::item:selected:!active{border: 1px solid rgb(245, 245, 245); background-color: rgb(245, 245, 245); color:rgb(51,51,51); } + + + QFrame::NoFrame + + + Qt::ScrollBarAsNeeded + + + Qt::ScrollBarAlwaysOff + + + + + + + + 370 + 150 + + + + + 16777215 + 150 + + + + + Microsoft YaHei + 14 + + + + Qt::ClickFocus + + + QFrame::NoFrame + + + QFrame::Plain + + + + + + + + 0 + 50 + + + + + Microsoft YaHei + 16 + + + + QLabel +{ + background:rgb(235,235,235); +} + + + + + + + + + + + + + + + + + + :/system/system/img/searchOff.png + :/img/system/img/searchOff.png + :/img/system/img/searchOnFinal.png:/system/system/img/searchOff.png + + + + + + 添加好友/群聊 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 700 + 500 + + + + + + 100 + 127 + 501 + 331 + + + + +QToolBox +{ + background:rgb(240,240,240); +} + +QToolBox::tab +{ + background:rgb(245,245,245); + color:rgb(0,0,0); + border:1px solid black; + border-radius:9px; +} + + + 0 + + + + + 0 + 0 + 501 + 302 + + + + background-color: transparent; + + + + + + + + + + 100 + 110 + 500 + 40 + + + + + 500 + 40 + + + + + Microsoft YaHei + 10 + + + + Qt::ClickFocus + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} + + + + + + 用户名或昵称 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + :/system/system/img/addOff.png + :/img/system/img/addOff.png + :/img/system/img/addOnFinal.png:/system/system/img/addOff.png + + + + + + 创建群聊 + + + + + 0 + 90 + 400 + 611 + + + + QToolBox { + background:rgb(240,240,240); +} + +QToolBox::tab { + background:rgb(235,235,235); + color:rgb(0,0,0); +} +QToolBox::tab::hover{ + background:rgb(255,255,255); + color:rgb(18,150,219); +} + + + 0 + + + + + 0 + 0 + 400 + 582 + + + + 好友 列表 + + + + + + + 430 + 90 + 400 + 611 + + + + QToolBox { + background:rgb(240,240,240); +} + +QToolBox::tab { + background:rgb(235,235,235); + color:rgb(0,0,0); +} +QToolBox::tab::hover{ + background:rgb(255,255,255); + color:rgb(18,150,219); +} + + + 0 + + + + + 0 + 0 + 400 + 582 + + + + 已选中的 好友 + + + + + + + 20 + 20 + 491 + 41 + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + + + + + + + 540 + 20 + 191 + 41 + + + + + Microsoft YaHei + + + + QPushButton{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(1,73,124); +} +QPushButton::hover{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} + + + 创建群聊 + + + + + + + :/img/system/img/gitOff.png + :/img/system/img/gitOnFinal.png + + + + + + + Git + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + Widget + QWidget +
widget.h
+ 1 +
+
+ + + + +
diff --git a/Client/message.cpp b/Client/message.cpp index 060b2f9ef4f4f88fd0522bb081c902f07d66d162..4ddb63f496eba19307b7836b5e7cfa1982fee28b 100644 --- a/Client/message.cpp +++ b/Client/message.cpp @@ -5,10 +5,43 @@ Message::Message(QWidget *parent) : QWidget(parent) { //设置字体 + QFont textFont("MicrosoftYaHei", 12); this->setFont(textFont); //缓冲按钮暂定 } +Message::Message(QString messagename,QWidget *parent): QWidget(parent) +{ + QFont textFont("MicrosoftYaHei", 12); + this->setFont(textFont); + MessageName = messagename; +} +QPixmap Message::paintHead(const QChar &name) +{ + QSize size(50,50); //指定图片大小; + QImage image(size,QImage::Format_ARGB32); + //以ARGB32格式构造一个QImage + //image.fill(qRgba(0,0,0,100));//填充图片背景,0-255为透明度 + image.fill(qRgba(52,73,94,255)); + QPainter painter(&image); //为这个QImage构造一个QPainter + painter.setCompositionMode(QPainter::CompositionMode_SourceOut); + //设置画刷的组合模式CompositionMode_SourceOut这个模式为目标图像在上。 + //改变组合模式和上面的填充方式可以画出透明的图片。 + + //改变画笔和字体 + QPen pen = painter.pen(); + pen.setColor(QColor(255,255,255,255)); + QFont font = painter.font(); + font.setFamily("Microsoft YaHei"); + font.setBold(true);//加粗 + font.setPixelSize(25);//改变字体大小 + + painter.setPen(pen); + painter.setFont(font); + painter.drawText(image.rect(),Qt::AlignCenter, name); + //将Hello写在Image的中心ui + return QPixmap::fromImage(image); +} void Message::setTextContent(QString text, QString time, QSize size, UserType type) { m_msg = text; @@ -18,8 +51,8 @@ void Message::setTextContent(QString text, QString time, QSize size, UserType ty m_wholeSize = size; //自定义头像 next - m_meRightIcon = QPixmap(":/img/system/img/LittleBlue.svg"); - m_otherLeftIcon = QPixmap(":/img/system/img/LittlePink.svg"); + m_meRightIcon = paintHead(MessageName[0]); + m_otherLeftIcon = paintHead(MessageName[0]); //需增加名称显示 next } QSize Message::setSize(QString str) @@ -166,13 +199,7 @@ void Message::paintEvent(QPaintEvent *event) painter.drawText(m_textLeftRect, m_msg,option);//写文本 } else if(m_userType == UserType::userMe) { // 自己 //头像 - - painter.drawPixmap(m_iconRightRect, m_meRightIcon); - qDebug() << "this->width()" << this->width(); - qDebug() << "x" << m_iconRightRect.x(); - qDebug() << "this->width()" << this->width(); - //框 QColor col_Kuang(75,164,242); painter.setBrush(QBrush(col_Kuang)); diff --git a/Client/message.h b/Client/message.h index 90a6b8625eff1671cc5d62d87429e06dfe1d9b05..662b402690bbaa7157f769a9c7d7ef073fcb0fb6 100644 --- a/Client/message.h +++ b/Client/message.h @@ -8,6 +8,7 @@ class Message : public QWidget Q_OBJECT public: explicit Message(QWidget *parent = nullptr); + Message(QString messagename,QWidget *parent = nullptr); //发送者类别 enum UserType @@ -25,6 +26,8 @@ public: QSize getStringSize(QString str); //画图事件 void paintEvent(QPaintEvent *event); + //制作头像 + QPixmap paintHead(const QChar &name); inline UserType userType() { @@ -38,6 +41,7 @@ public: { return m_time; } + QString MessageName; private: UserType m_userType; diff --git a/Client/messagemodel.cpp b/Client/messagemodel.cpp index cfbc0aeeca72b472d19039502e80b9c331f13e9f..d9b62b3a4bc6ef2f3cc6204783fb34728ac6c24c 100644 --- a/Client/messagemodel.cpp +++ b/Client/messagemodel.cpp @@ -32,7 +32,7 @@ OnlineMessage::OnlineMessage(QJsonObject json, MessageModel * parent) : { messageID = json["MessageID"].toInt(); sessionID = json["SessionID"].toInt(); - senderUsername = json["SenderUsername"].toString(); + senderUsername = json["SenderName"].toString(); QJsonObject body = json["Body"].toObject(); text = body["Text"].toString(); diff --git a/Client/highlighter.cpp b/Client/myhighlighter.cpp similarity index 39% rename from Client/highlighter.cpp rename to Client/myhighlighter.cpp index bcdd88121f8f04b9b7e6524b62435aa90ebf3293..6a997a954a2dee07ad7957fc355f7aa894aadd60 100644 --- a/Client/highlighter.cpp +++ b/Client/myhighlighter.cpp @@ -1,14 +1,13 @@ -#include "highlighter.h" +#include "myhighlighter.h" -//! [0] -Highlighter::Highlighter(QTextDocument *parent) +MyHighLighter::MyHighLighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; - keywordFormat.setForeground(Qt::red);//设定关键词的高亮样式 + keywordFormat.setForeground(Qt::darkBlue); keywordFormat.setFontWeight(QFont::Bold); - QStringList keywordPatterns; //关键词集合,关键都以正则表达式表示 下面的可以改为我们想要的关键词 + QStringList keywordPatterns; keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b" << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b" @@ -18,91 +17,75 @@ Highlighter::Highlighter(QTextDocument *parent) << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b" << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b" << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b" - << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bbool\\b" - << "\\bdef\\b"<< "\\binclude\\b"<< "\\bself\\b"<< "\\btype\\b" - << "\\bimport\\b"<< "\\bfrom\\b"<< "\\bbreak\\b"<< "\\band\\b"<< "\\bor\\b" - << "\\bif\\b"<< "\\btry\\b"<< "\\bexcept\\b"<< "\\bNone\\b"<< "\\bwith\\b" - << "\\bencoding\\b"<< "\\breturn\\b"<< "\\bnot\\b"<< "\\belif\\b"<< "\\belse\\b"; + << "\\bvoid\\b" << "\\bvolatile\\b" <<"\\bdef\\b" + << "\\binclude\\b" << "\\breturn\\b" <<"\\bbreak\\b" + << "\\bcontinue\\b" << "\\bif\\b" <<"\\belse\\b" + << "\\belif\\b" << "\\band\\b" <<"\\bTrue\\b" + << "\\bself\\b" << "\\bnn\\b" <<"\\bimport\\b" + << "\\bin\\b" << "\\bfor\\b" <<"\\bis\\b"; foreach (const QString &pattern, keywordPatterns) { - rule.pattern = QRegularExpression(pattern); + rule.pattern = QRegExp(pattern); rule.format = keywordFormat; highlightingRules.append(rule); -//! [0] //! [1] } -//! [1] - -//! [2] - classFormat.setFontWeight(QFont::Bold);//添加Qt的类到高亮规则中 + classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(Qt::darkMagenta); - rule.pattern = QRegularExpression("\\bQ[A-Za-z]+\\b"); + rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b"); rule.format = classFormat; highlightingRules.append(rule); -//! [2] -//! [3] - singleLineCommentFormat.setForeground(Qt::darkBlue);//单行注释 - rule.pattern = QRegularExpression("//[^\n]*"); + singleLineCommentFormat.setForeground(Qt::red); + rule.pattern = QRegExp("//[^\n]*"); rule.format = singleLineCommentFormat; highlightingRules.append(rule); - multiLineCommentFormat.setForeground(Qt::darkBlue);//多行注释,只设定了样式,具体匹配在highlightBlock中设置 -//! [3] + multiLineCommentFormat.setForeground(Qt::red); -//! [4] - quotationFormat.setForeground(Qt::darkGreen);//字符串 - rule.pattern = QRegularExpression("\".*\""); + quotationFormat.setForeground(Qt::darkGreen); + rule.pattern = QRegExp("\".*\""); rule.format = quotationFormat; highlightingRules.append(rule); -//! [4] -//! [5] - functionFormat.setFontItalic(true);//函数 + functionFormat.setFontItalic(true); functionFormat.setForeground(Qt::blue); - rule.pattern = QRegularExpression("\\b[A-Za-z0-9_]+(?=\\()"); + rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); rule.format = functionFormat; highlightingRules.append(rule); -//! [5] -//! [6] - commentStartExpression = QRegularExpression("/\\*");//多行注释的匹配正则表达式 - commentEndExpression = QRegularExpression("\\*/"); + commentStartExpression = QRegExp("/\\*"); + commentEndExpression = QRegExp("\\*/"); } -//! [6] -//! [7] -void Highlighter::highlightBlock(const QString &text)//应用高亮规则,也用于区块的高亮,比如多行注释 +void MyHighLighter::highlightBlock(const QString &text) { - foreach (const HighlightingRule &rule, highlightingRules) {//文本采用高亮规则 - QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); - while (matchIterator.hasNext()) { - QRegularExpressionMatch match = matchIterator.next(); - setFormat(match.capturedStart(), match.capturedLength(), rule.format); + foreach (const HighlightingRule &rule, highlightingRules) { + QRegExp expression(rule.pattern); + int index = expression.indexIn(text); + while (index >= 0) { + int length = expression.matchedLength(); + setFormat(index, length, rule.format); + index = expression.indexIn(text, index + length); } } -//! [7] //! [8] - setCurrentBlockState(0); //以下是多行注释的匹配 -//! [8] -//! [9] + setCurrentBlockState(0); + int startIndex = 0; if (previousBlockState() != 1) - startIndex = text.indexOf(commentStartExpression); + startIndex = commentStartExpression.indexIn(text); + -//! [9] //! [10] while (startIndex >= 0) { -//! [10] //! [11] - QRegularExpressionMatch match = commentEndExpression.match(text, startIndex); - int endIndex = match.capturedStart(); - int commentLength = 0; + int endIndex = commentEndExpression.indexIn(text, startIndex); + int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex - + match.capturedLength(); + + commentEndExpression.matchedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); - startIndex = text.indexOf(commentStartExpression, startIndex + commentLength); + startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); } } -//! [11] diff --git a/Client/myhighlighter.h b/Client/myhighlighter.h new file mode 100644 index 0000000000000000000000000000000000000000..edd2c7acff24ab2f830b9302588bb1a715834025 --- /dev/null +++ b/Client/myhighlighter.h @@ -0,0 +1,36 @@ +#ifndef MYHIGHLIGHTER_H +#define MYHIGHLIGHTER_H +#include +#include +#include +class MyHighLighter : public QSyntaxHighlighter +{ + Q_OBJECT + +public: + MyHighLighter(QTextDocument *parent = 0); + +protected: + void highlightBlock(const QString &text) Q_DECL_OVERRIDE; + +private: + struct HighlightingRule + { + QRegExp pattern; + QTextCharFormat format; + }; + QVector highlightingRules; + + QRegExp commentStartExpression; + QRegExp commentEndExpression; + + QTextCharFormat keywordFormat; + QTextCharFormat classFormat; + QTextCharFormat singleLineKey; + QTextCharFormat singleLineValue; + QTextCharFormat singleLineCommentFormat; + QTextCharFormat multiLineCommentFormat; + QTextCharFormat quotationFormat; + QTextCharFormat functionFormat; +}; +#endif // MYHIGHLIGHTER_H diff --git a/Client/system.qrc b/Client/system.qrc index b861af6d26168169658b0e2c62183dd77fcab72b..80295a032644f73e8dabf728163e7dfd7391705d 100644 --- a/Client/system.qrc +++ b/Client/system.qrc @@ -21,5 +21,17 @@ system/img/LittleBlack.svg system/img/LittlePink.svg system/img/LittleRed.svg + system/img/bicqWhite.png + system/img/gitWhite.png + system/img/test.png + system/img/bicqBlue.png + system/img/bicqGreen.png + system/img/dot.png + system/img/addOnFinal.png + system/img/gitOnFinal.png + system/img/messageOnFinal.png + system/img/searchOnFinal.png + system/img/bicBackground.png + system/img/dotRed.png diff --git a/Client/system/img/addOnFinal.png b/Client/system/img/addOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..cc83baf29100e997df66e5120b5b52891d3d3f6d Binary files /dev/null and b/Client/system/img/addOnFinal.png differ diff --git a/Client/system/img/bicBackground.png b/Client/system/img/bicBackground.png new file mode 100644 index 0000000000000000000000000000000000000000..0a5042d3cd24b647498414151e5d028733faf12a Binary files /dev/null and b/Client/system/img/bicBackground.png differ diff --git a/Client/system/img/bicqBlue.png b/Client/system/img/bicqBlue.png new file mode 100644 index 0000000000000000000000000000000000000000..9ce6ec252f5827ebb95597ff3eaeda6f75dbbad4 Binary files /dev/null and b/Client/system/img/bicqBlue.png differ diff --git a/Client/system/img/bicqGreen.png b/Client/system/img/bicqGreen.png new file mode 100644 index 0000000000000000000000000000000000000000..b397cf3973590bbbf4db818ab89ac263718e64f4 Binary files /dev/null and b/Client/system/img/bicqGreen.png differ diff --git a/Client/system/img/bicqWhite.png b/Client/system/img/bicqWhite.png new file mode 100644 index 0000000000000000000000000000000000000000..e789c8fab18531e15d1586f8abccfe855c5d71c9 Binary files /dev/null and b/Client/system/img/bicqWhite.png differ diff --git a/Client/system/img/dot.png b/Client/system/img/dot.png new file mode 100644 index 0000000000000000000000000000000000000000..b68fe73d89f5c3f6b59139dde5f56e047c195fe5 Binary files /dev/null and b/Client/system/img/dot.png differ diff --git a/Client/system/img/dotRed.png b/Client/system/img/dotRed.png new file mode 100644 index 0000000000000000000000000000000000000000..19140bf2326b318db3cd69d33db528a1cd1f25e7 Binary files /dev/null and b/Client/system/img/dotRed.png differ diff --git a/Client/system/img/gitOnFinal.png b/Client/system/img/gitOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..19befd4892b87be487f278b5384884d2000086cc Binary files /dev/null and b/Client/system/img/gitOnFinal.png differ diff --git a/Client/system/img/gitWhite.png b/Client/system/img/gitWhite.png new file mode 100644 index 0000000000000000000000000000000000000000..e0851f766146608826f56de946a62fe43c053c25 Binary files /dev/null and b/Client/system/img/gitWhite.png differ diff --git a/Client/system/img/messageOnFinal.png b/Client/system/img/messageOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..6915ce31f1f304421d841dda5dc5dedeb02c1a41 Binary files /dev/null and b/Client/system/img/messageOnFinal.png differ diff --git a/Client/system/img/searchOnFinal.png b/Client/system/img/searchOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..c0318459e7a69404a89f2ed137e0ebb78c8d73ed Binary files /dev/null and b/Client/system/img/searchOnFinal.png differ diff --git a/Client/system/img/test.png b/Client/system/img/test.png new file mode 100644 index 0000000000000000000000000000000000000000..560ecc55412835dd6a3142ed498017745391552f Binary files /dev/null and b/Client/system/img/test.png differ diff --git a/Client/typedef.h b/Client/typedef.h new file mode 100644 index 0000000000000000000000000000000000000000..499a81de8b6ce134d796e5ac8edf652ecfe7b9b6 --- /dev/null +++ b/Client/typedef.h @@ -0,0 +1,10 @@ +#ifndef TYPEDEF_H +#define TYPEDEF_H + +typedef enum{ + BROWSE, + EDIT, +}editorMode; + + +#endif // TYPEDEF_H diff --git a/Client/userlogin.cpp b/Client/userlogin.cpp index ceb6ff0839336960c2933ee5837de1942de3e243..5af3f157e66985ed7543708ebeec478a3144632f 100644 --- a/Client/userlogin.cpp +++ b/Client/userlogin.cpp @@ -21,15 +21,24 @@ UserLogin::UserLogin(QWidget *parent) //点击注册跳转到注册页面 connect(ui->btnRegister,&QPushButton::clicked,[=](){ this->hide(); - emit registerButtonClicked(); }); - +//#define UIDEBUG +#ifndef UIDEBUG //点击登录发送登录信息 connect(ui->btnLogIn,&QPushButton::clicked,[=](){ QJsonObject login = { {"MsgType","LogIn"},{"Username",ui->lineEditUserName->text()},{"Password",ui->lineEditPassword->text()}}; emit sendlogindata(login); }); +#else + //调试入口 + connect(ui->btnLogIn, &QPushButton::clicked,[=](){ + MainWindow *main = new MainWindow(); + main->show(); + }); +#endif + + // main = new MainWindow(this); } void UserLogin::loginconfirm(QJsonObject data){ @@ -47,3 +56,8 @@ UserLogin::~UserLogin() delete ui; } + +void UserLogin::on_lineEditPassword_returnPressed() +{ + emit ui->btnLogIn->clicked(); +} diff --git a/Client/userlogin.h b/Client/userlogin.h index fd5a40e495470199b0bceb78143b7503f42a5fba..301ede389ee31c40f189e53df593de8d6e25b158 100644 --- a/Client/userlogin.h +++ b/Client/userlogin.h @@ -24,6 +24,10 @@ signals: void registerButtonClicked(); void sendlogindata(QJsonObject data); void createMainWindow(QJsonObject data); +private slots: + + void on_lineEditPassword_returnPressed(); + private: Ui::UserLogin *ui; }; diff --git a/Client/userlogin.ui b/Client/userlogin.ui index 7131e2e7f85e765bf0f682e5d4193e801b028675..611017fbd1e81489314ceef79bc66c73bbc68d05 100644 --- a/Client/userlogin.ui +++ b/Client/userlogin.ui @@ -6,250 +6,340 @@ 0 0 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - UserLogin + BICQ-Nano - - - - - - - - - - - QLineEdit::Password - - - - - - - 用户名 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 密码 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 10 - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 登录 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 注册 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + + + + background-color: rgb(255, 255, 255); + + + + + 165 + 50 + 100 + 100 + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + + + + :/img/system/img/bicq.png + + + true + + + + + + 25 + 610 + 381 + 50 + + + + + Microsoft YaHei + 10 + false + false + + + + PointingHandCursor + + + QPushButton{ + color: rgb(0,0,0); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(255,255,255); +} +QPushButton::hover{ + color: rgb(0,0,0); + border:3px solid rgb(1,73,124); + border-radius: 10px; +} + + + + Don't have an acount? Register for FREE. + + + false + + + false + + + false + + + + + + 15 + 240 + 400 + 331 + + + + QWidget{ + + border-radius: 20px; + background-color:rgb(246,248,250); +} + + + + + 20 + 30 + 141 + 31 + + + + + Microsoft YaHei + 13 + + + + Username + + + + + + 20 + 70 + 360 + 50 + + + + + 0 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + + + + 20 + 140 + 111 + 37 + + + + + Microsoft YaHei + 13 + + + + Password + + + + + + 20 + 180 + 360 + 50 + + + + + 0 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + + + + 20 + 250 + 360 + 53 + + + + + 0 + 53 + + + + + Microsoft YaHei + 16 + + + + PointingHandCursor + + + QPushButton{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(1,73,124); +} +QPushButton::hover{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} + + + Sign In + + + + 20 + 20 + + + + + + + + 110 + 170 + 211 + 51 + + + + + Microsoft YaHei + 16 + + + + QLabel +{ + color: rgb(18,150,219); +} + + + Sign In to Nano + + - + + + diff --git a/Client/usermodel.h b/Client/usermodel.h index ccb7ab9ce1a89949e47833aae52e30afa3012b77..91b28302a7faadfd2e9b6fdc5d952b5d58a2047d 100644 --- a/Client/usermodel.h +++ b/Client/usermodel.h @@ -31,7 +31,7 @@ public: OfflineUserModel(QString Username, QObject *parent = nullptr); Type getType() const { return Type::Offline; } void setNickname(QString nname) { nickname = nname; } - void setSigniture(QString sig) { profile["Signiture"] = sig; } + void setSigniture(QString sig) { profile["signiture"] = sig; } QJsonObject generateUserModelJson() const; @@ -49,7 +49,7 @@ public: OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent = nullptr); Type getType() const { return Type::Online; } const QString& getNickname() const { return nickname; } - const QString getSigniture() const { return profile["Signiture"].toString(); } + const QString getSigniture() const { return profile["signiture"].toString(); } QJsonObject generateUserModelJson() const; signals: diff --git a/Client/userregister.cpp b/Client/userregister.cpp index 00314df5fd56ea898c7aa4e2da2edf6ad0004ad8..c3ba291cc9406758778cb53281d85e7a370a1d83 100644 --- a/Client/userregister.cpp +++ b/Client/userregister.cpp @@ -1,59 +1,67 @@ -#include "userregister.h" -#include "ui_userregister.h" -#include -#include -#include -#include -#include - - -UserRegister::UserRegister(QWidget *parent) : - QWidget(parent), - ui(new Ui::UserRegister) -{ - ui->setupUi(this); - connect(ui->btnRegister,&QPushButton::clicked,[=](){ - bool islegal = true; - QJsonObject registration_info; - QString s = ui->lERgUserName->text(), s1; - if(s.size()==0){ - QMessageBox::critical(this,"Error!","用户名不能为空"); - islegal = false; - } - s = ui->lERgPassword1->text(); - s1 = ui->lERgPassword2->text(); - if((s.size()==0 || s1.size()==0) && islegal){ - QMessageBox::critical(this,"Error!","密码不能为空"); - islegal = false; - } - if(s != s1 && islegal){ - QMessageBox::critical(this,"Error!","两次输入的密码不一致"); - islegal = false; - } - if(islegal){ - //发送注册信息 - registration_info.insert("Username",ui->lERgUserName->text()); - registration_info.insert("Nickname",ui->lERgNickName->text()); - registration_info.insert("Password",ui->lERgPassword1->text()); - registration_info.insert("MsgType","Regist"); - sendregistdata(registration_info); - } - }); -} - -void UserRegister::registconfirm(QJsonObject data){ - bool legal = data["IsLegal"].toBool(); - if(legal){ - QMessageBox::information(this,"提示","注册成功"); - emit UserRegister::registfinished(); - this->close(); - } - else{ - QMessageBox::critical(this,"Error!","用户名已存在"); - } -} - -UserRegister::~UserRegister() -{ - delete ui; -} +#include "userregister.h" +#include "ui_userregister.h" +#include +#include +#include +#include +#include + + +UserRegister::UserRegister(QWidget *parent) : + QWidget(parent), + ui(new Ui::UserRegister) +{ + ui->setupUi(this); + connect(ui->btnRegister,&QPushButton::clicked,[=](){ + bool islegal = true; + QJsonObject registration_info; + QString s = ui->lERgUserName->text(), s1; + if(s.size()==0){ + QMessageBox::critical(this,"Error!","用户名不能为空"); + islegal = false; + } + s = ui->lERgPassword1->text(); + s1 = ui->lERgPassword2->text(); + if((s.size()==0 || s1.size()==0) && islegal){ + QMessageBox::critical(this,"Error!","密码不能为空"); + islegal = false; + } + if(ui->lERgNickName->text().size()==0 && islegal){ + QMessageBox::information(this,"提示","请设置您的昵称"); + islegal = false; + } + if(s != s1 && islegal){ + QMessageBox::critical(this,"Error!","两次输入的密码不一致"); + islegal = false; + } + if(islegal){ + //发送注册信息 + registration_info.insert("Username",ui->lERgUserName->text()); + registration_info.insert("Nickname",ui->lERgNickName->text()); + registration_info.insert("Password",ui->lERgPassword1->text()); + registration_info.insert("MsgType","Regist"); + sendregistdata(registration_info); + } + }); +} + +void UserRegister::registconfirm(QJsonObject data){ + bool legal = data["IsLegal"].toBool(); + if(legal){ + QMessageBox::information(this,"提示","注册成功"); + emit UserRegister::registfinished(); + this->close(); + } + else{ + QMessageBox::critical(this,"Error!","用户名已存在"); + } +} + +UserRegister::~UserRegister() +{ + delete ui; +} + +void UserRegister::on_lERgPassword1_returnPressed() { + emit ui->btnRegister->clicked(); +} diff --git a/Client/userregister.h b/Client/userregister.h index 7159159c357800a0ba688bdaba37f5017bd72346..aef5d07cc15ba4ad9120cb3cc13e82f935eca88b 100644 --- a/Client/userregister.h +++ b/Client/userregister.h @@ -21,6 +21,10 @@ public: signals: void registfinished(); void sendregistdata(QJsonObject data); +private slots: + + void on_lERgPassword1_returnPressed(); + private: Ui::UserRegister *ui; }; diff --git a/Client/userregister.ui b/Client/userregister.ui index 4e1ef100d14c5702c2cafe0599f2a6ac1ad1b392..865dd7ac0a76371abcc65d339f21ffb5bddca756 100644 --- a/Client/userregister.ui +++ b/Client/userregister.ui @@ -6,95 +6,493 @@ 0 0 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - Form + BICQ-Nano + + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + - 90 - 70 - 226 - 128 + 15 + 210 + 400 + 391 - - - - - 用户名 - - - - - - - - - - 昵称 - - - - - - - QLineEdit::Password - - - - - - - 密码 - - - - - - - - - - 确认密码 - - - - - - - + + QWidget{ + + border-radius: 20px; + background-color:rgb(246,248,250); +} + + + + + 20 + 5 + 121 + 31 + + + + + Microsoft YaHei + 13 + + + + Username + + + + + + 20 + 40 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + + + + 20 + 90 + 161 + 31 + + + + + Microsoft YaHei + 13 + + + + Nickname + + + + + + 20 + 130 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Normal + + + + + + 20 + 200 + 131 + 31 + + + + + Microsoft YaHei + 13 + + + + Password + + + + + + 20 + 240 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + + + + 20 + 310 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + Confirm Password + + - 170 - 220 - 84 - 24 + 25 + 630 + 381 + 50 + + + + + Microsoft YaHei + 16 + + + + PointingHandCursor + + + QPushButton{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(1,73,124); +} +QPushButton::hover{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} + + + Sign Up + + + + + + 50 + 60 + 100 + 100 - 注册 + + + + :/img/system/img/LittleBlue.svg + + + true + + + + + + 160 + 50 + 231 + 51 + + + + + Microsoft YaHei + 16 + + + + QLabel +{ + color: rgb(18,150,219); +} + + + Sign Up to + + + + + + 163 + 103 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 174 + 96 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 150 + 106 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 303 + 46 + 101 + 51 + + + + + Microsoft YaHei + 20 + 75 + true + + + + QLabel +{ + color: rgb(18,150,219); +} + + + Nano - + + + diff --git a/Client/widget.cpp b/Client/widget.cpp index 75a737c1e8c53ec30b2f6373738e55a55a665428..c927150f8e56bf8aacf246e14479f2bd68ec47eb 100644 --- a/Client/widget.cpp +++ b/Client/widget.cpp @@ -1,19 +1,25 @@ #include "widget.h" #include "ui_widget.h" -#include "highlighter.h" #include #include #include #include #include #include +#include +#include "myhighlighter.h" +#include "codeeditor.h" +#include "typedef.h" +#include Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); - + configEditor = new CodeEditor(); + configEditor->setMode(BROWSE); + ui->gridLayout_3->addWidget(configEditor); connect (ui->listWidget, &QListWidget::itemDoubleClicked, this, &Widget::showContents); } @@ -26,7 +32,7 @@ Widget::~Widget() void Widget::on_pushButton_clicked() { - QByteArray file = get(ui->lineEdit->text ()); + QByteArray file = get("https://gitee.com/api/v5/repos/" + this->ui->lineEdit->text() + "/" + this->ui->lineEdit_2->text() + "/git/trees/master"); QJsonDocument newjson = QJsonDocument::fromJson(file); QJsonObject jsonObject = newjson.object (); @@ -37,7 +43,7 @@ void Widget::on_pushButton_clicked() { QJsonArray array = arrayValue.toArray(); length = array.size (); - for(int i=0;itext ()) { QByteArray content = get(icon["url"].toString ()); QJsonDocument newjson = QJsonDocument::fromJson(content); QJsonObject jsonObject = newjson.object (); - ui->textEdit->setText ( QByteArray::fromBase64(jsonObject["content"].toString ().toUtf8 ())); - Highlighter * h = new Highlighter(ui->textEdit->document ()); + configEditor->setPlainText(QByteArray::fromBase64(jsonObject["content"].toString ().toUtf8 ()).data ()); + //ui->gridLayout->addWidget(configEditor); + QString text = "def hhh()"; + MyHighLighter *highlighter = new MyHighLighter(configEditor->document()); + + //Highlighter * h = new Highlighter(ui->textEdit->document ()); + } } @@ -75,3 +87,62 @@ void Widget::showContents(QListWidgetItem * nowItem) // git commit try at: https://gitee.com/api/v5/repos/jasonliu233/gitstudy/commits/master // git tree at: https://gitee.com/api/v5/repos/jasonliu233/zhishigongcheng/git/trees/master +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits) { + QRegExp reg("@\\[((?:[^ ,\\,])+),[ ]*((?:[^ ,\\,])+)(?:,[ ]*((?:[^ ,\\,])*))?\\]"); + int pos = 0, initial = authors.size(); + while ((pos = reg.indexIn(raw, pos)) != -1) { + authors.append(reg.cap(1)); + repos.append(reg.cap(2)); + commits.append(reg.cap(3) == "" ? "master" : reg.cap(3)); + pos += reg.matchedLength(); + } + return authors.size() - initial; +} + +QByteArray get(const QString &str_url){ + const QUrl url = QUrl::fromUserInput(str_url); + QNetworkRequest qnr(url); + QNetworkAccessManager qnam; + QNetworkReply *reply = qnam.get(qnr); + QEventLoop eventloop; + QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit); + eventloop.exec(QEventLoop::ExcludeUserInputEvents); + QByteArray reply_data = reply->readAll(); + reply->deleteLater(); + reply = nullptr; + return reply_data; +} + +QString generateGitMessage(QString owner, QString repo, QString sha) { + QString url = "https://gitee.com/api/v5/repos/"+owner+"/"+repo+"/"+"commits"+"/"+sha; + + QByteArray file = get(url); + + QJsonDocument newjson = QJsonDocument::fromJson(file); + QJsonObject jsonObject = newjson.object (); + + QString output; + QString msg = jsonObject["commit"].toObject ()["message"].toString (); + QString author = jsonObject["commit"].toObject ()["author"].toObject ()["name"].toString (); + QString commitInformation = "提交信息 git@gitee:" + owner + "/" + repo + "\n" + msg+"by "+author + "\n"; + + output.append (commitInformation); + QJsonArray fileList = jsonObject["files"].toArray (); + for(int i=0;i #include #include +#include + QT_BEGIN_NAMESPACE namespace Ui { class Widget; } @@ -42,5 +44,10 @@ private slots: private: Ui::Widget *ui; QJsonValue arrayValue; + CodeEditor *configEditor; }; + + +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits); +QString generateGitMessage(QString owner, QString repo, QString sha); #endif // WIDGET_H diff --git a/Client/widget.ui b/Client/widget.ui index 0ea2faa3d57551204036f9e444f1a25b2c3140a9..9613d09c320990752c733a91e57dc5f7e076359b 100644 --- a/Client/widget.ui +++ b/Client/widget.ui @@ -107,17 +107,28 @@ QLineEdit::focus 80 + + PointingHandCursor + - background-color: rgb(46,46,46); + QPushButton{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(22,138,173); +} +QPushButton::hover{ + + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} - - :/img/system/img/gitBtnOff.png - :/img/system/img/gitBtnOn.png - + + :/img/system/img/gitWhite.png:/img/system/img/gitWhite.png @@ -214,22 +225,6 @@ border-style: solid; - - - - - Microsoft Yi Baiti - 12 - - - - background-color: rgb(245, 245, 245); - - - QFrame::NoFrame - - - @@ -279,8 +274,17 @@ border-style: solid; + + + + 0 + + + - + + + diff --git a/Database_Lyh/Database_Lyh.pro b/Database_Lyh/Database_Lyh.pro deleted file mode 100644 index eb7a5ba37e7786a47cf9faa00f449545f77b74f4..0000000000000000000000000000000000000000 --- a/Database_Lyh/Database_Lyh.pro +++ /dev/null @@ -1,31 +0,0 @@ -QT += core gui sql - -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets - -CONFIG += c++11 - -# The following define makes your compiler emit warnings if you use -# any Qt feature that has been marked deprecated (the exact warnings -# depend on your compiler). Please consult the documentation of the -# deprecated API in order to know how to port your code away from it. -DEFINES += QT_DEPRECATED_WARNINGS - -# You can also make your code fail to compile if it uses deprecated APIs. -# In order to do so, uncomment the following line. -# You can also select to disable deprecated APIs only up to a certain version of Qt. -#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - -SOURCES += \ - main.cpp \ - widget.cpp - -HEADERS += \ - widget.h - -FORMS += \ - widget.ui - -# Default rules for deployment. -qnx: target.path = /tmp/$${TARGET}/bin -else: unix:!android: target.path = /opt/$${TARGET}/bin -!isEmpty(target.path): INSTALLS += target diff --git a/Database_Lyh/main.cpp b/Database_Lyh/main.cpp deleted file mode 100644 index e57e09ca21147eeccd4fff1bea4273e8d8a46b28..0000000000000000000000000000000000000000 --- a/Database_Lyh/main.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "widget.h" - -#include -#include -#include -#include -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - Widget w; - w.show(); - return a.exec(); -} diff --git a/Database_Lyh/widget.cpp b/Database_Lyh/widget.cpp deleted file mode 100644 index e32fbbb5f2e18cea962668e11882bfda951f548d..0000000000000000000000000000000000000000 --- a/Database_Lyh/widget.cpp +++ /dev/null @@ -1,166 +0,0 @@ -#include "widget.h" -#include "ui_widget.h" -#include -#include -#include -#include -#include -#include - -Widget::Widget(QWidget *parent) - : QWidget(parent) - , ui(new Ui::Widget) -{ - ui->setupUi(this); - createDB(); - createTable (); - insertData_User("124","Li","123456","..."); - insertData_User("123","Wang","123456","..."); - insertData_Dialog("friend","..."); - insertData_Message(1,"123","123to124","..."); - insertData_Message(1,"124","124to123","..."); - insertData_Member(1,"123"); - insertData_Member(2,"124"); -// insertData_Alldialog("123",1); -// insertData_Alldialog("124",1); - queryTable(); - database.close(); -} - -Widget::~Widget() -{ - delete ui; -} - - -//创建数据库 -void Widget::createDB(){ - - if (QSqlDatabase::contains("qt_sql_default_connection")) - { - database = QSqlDatabase::database("qt_sql_default_connection"); - } - else - { - database = QSqlDatabase::addDatabase("QSQLITE"); - database.setDatabaseName("MyDataBase.db"); - } - //建立连接 - if (!database.open()) - { - qDebug() << "Error: Failed to connect database." << database.lastError(); - } - else - { - qDebug() <<"数据库链接成功"; - } -} - - -//创建表格 -void Widget::createTable (void) { - // 构建创建数据表sql语句的字符串 - //先有成员、然后会话,然后才有消息 - //用户表 - QString userstr ("CREATE TABLE User(username TEXT PRIMARY KEY NOT NULL, nickname TEXT NOT NULL, password TEXT NOT NULL, profile TEXT NOT NULL)"); - //消息表 - QString messagestr ("CREATE TABLE Message(messageID INT PRIMARY KEY NOT NULL, sessionID INT NOT NULL, senderUsername TEXT NOT NULL, messageText TEXT NOT NULL, profile TEXT NOT NULL, foreign KEY (senderUsername) references User(username), foreign KEY (sessionID) references Dialog(sessionID))"); - //会话表 - QString dialoguestr ("CREATE TABLE Dialog(sessionID INT PRIMARY KEY NOT NULL, SessionType TEXT NOT NULL, profile TEXT NOT NULL)"); - //会话中成员表 - QString memberstr ("CREATE TABLE Member(sessionID INT NOT NULL, username TEXT NOT NULL)");//, primary key(sessionID,username), foreign KEY (sessionID) references Dialog(sessionID), foreign KEY (username) references User(username) - //用户所拥有的会话表 - //QString alldialogstr ("CREATE TABLE Alldialog(username TEXT NOT NULL, sessionID INT NOT NULL)");//, primary key(username,sessionID), foreign KEY (sessionID) references Dialog(sessionID), foreign KEY (username) references User(username) - // 执行sql语句 - QSqlQuery *query; - query = new QSqlQuery(); - query->exec (userstr); - query->exec (messagestr); - query->exec (dialoguestr); - query->exec (memberstr); - //query->exec (alldialogstr); -} - - -//查询所有User表中的数据 -void Widget::queryTable (void) { - QSqlQuery sqlQuery; - sqlQuery.exec("SELECT * FROM User"); - if(!sqlQuery.exec()) - { - qDebug() << "Error: Fail to query table. " << sqlQuery.lastError(); - } - else - { - while(sqlQuery.next()) - { - QString username = sqlQuery.value(0).toString(); - QString nickname = sqlQuery.value(1).toString(); - QString password = sqlQuery.value(2).toString(); - QString profile = sqlQuery.value(3).toString(); - qDebug()<prepare(insert_sql); - query->addBindValue(username); - query->addBindValue(nickname); - query->addBindValue(password); - query->addBindValue(profile); - query->exec(); -} -//往message表中插入数据 -void Widget::insertData_Message(int sessionID, const char* senderUsername, const char* messageText,const char* profile){ - QSqlQuery *query; - query = new QSqlQuery(); - QString insert_sql = "insert into Message values (?, ?, ?, ?, ?)"; - query->prepare(insert_sql); - query->addBindValue(++maxMessage); - query->addBindValue(sessionID); - query->addBindValue(senderUsername); - query->addBindValue(messageText); - query->addBindValue(profile); - query->exec(); -} -//往Dialog表中插入数据 -void Widget::insertData_Dialog(const char* SessionType, const char* profile){ - QSqlQuery *query; - query = new QSqlQuery(); - QString insert_sql = "insert into Dialog values(?, ?, ?)"; - query->prepare(insert_sql); - query->addBindValue(++maxDioalog); - query->addBindValue(SessionType); - query->addBindValue(profile); - query->exec(); -} -//记录一个会议的参加人员 -void Widget::insertData_Member(int sessionID, const char* username){ - QSqlQuery *query; - query = new QSqlQuery(); - QString insert_sql = "insert into Member values(?, ?)"; - query->prepare(insert_sql); - query->addBindValue(sessionID); - query->addBindValue(username); - if(!query->exec()){ - qDebug()<<"query error: "<lastError(); - } -} -//记录一人参加的会议 -//void Widget::insertData_Alldialog (const char* username, int sessionID){ -// QSqlQuery *query; -// query = new QSqlQuery(); -// QString insert_sql = "insert into Alldialog values(?, ?)"; -// query->addBindValue(username); -// query->addBindValue(sessionID); -// if(!query->exec()){ -// qDebug()<<"query error: "<lastError(); -// } -//} - diff --git a/Database_Lyh/widget.h b/Database_Lyh/widget.h deleted file mode 100644 index 99a4ee789c1ea2462015031e946f9bfa32754413..0000000000000000000000000000000000000000 --- a/Database_Lyh/widget.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE -namespace Ui { class Widget; } -QT_END_NAMESPACE - -class Widget : public QWidget -{ - Q_OBJECT - -public: - Widget(QWidget *parent = nullptr); - ~Widget(); -private: - QSqlDatabase database;// 建立QT程序和数据的连接 - QSqlQueryModel model; // 保存和遍历查询结果 - int maxMessage=0; - int maxDioalog=0; -private: - void createDB (void);//创建数据库 - void createTable (void);//创建数据表 -public: - void queryTable (void);//查询数据 - void insertData_User (const char* username,const char* nickname,const char* password,const char* profile);//往User中插入数据 - void insertData_Message (int sessionID, const char* senderUsername, const char* messageText,const char* profile); - void insertData_Dialog (const char* SessionType, const char* profile); - void insertData_Member (int sessionID, const char* username); - //void insertData_Alldialog (const char* username, int sessionID); -private: - Ui::Widget *ui; -}; -#endif // WIDGET_H diff --git a/Database_Lyh/widget.ui b/Database_Lyh/widget.ui deleted file mode 100644 index c3fa28a3218bd25cc6bdae9e09c8e49ae36da0a2..0000000000000000000000000000000000000000 --- a/Database_Lyh/widget.ui +++ /dev/null @@ -1,19 +0,0 @@ - - - Widget - - - - 0 - 0 - 800 - 600 - - - - Widget - - - - - diff --git a/README.md b/README.md index 0d2acb40a07fa75cbe5ccae2c26ed5953387b688..b9b0ee00b4d23728f09a2fe830754afce95c51d3 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,26 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework 1. 类名、文件名使用大驼峰命名法,函数名使用小驼峰命名法 2. 仓库在 master 和 Develop 分支上设置了保护,一般工作在feature分支上,如果是可以独立开发的模块,强烈建议单独拉一条新分支出来。每个 working state 会合并到 Develop 分支,release 版本合并到 master 分支 +```json +{ + "MsgType": "JsonArray", + "MsgList": [ + { ... }, + { ... }, + { ... }, + ] +} + +``` +### 加好友 +```json +{ + "MsgType": "AddFriendRequest", + "FromUsername": "...", + "ToUsername": "..." +} +``` + ### 注册信息 ``` json @@ -48,7 +68,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework } } ``` - ``` json { "MsgType": "LogInConfirm", @@ -56,6 +75,38 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework } } ``` +### 搜索消息 + + ``` json + { + "MsgType": "Search", + "SearchInfo": "..." + } + ``` + + ``` json + { + "MsgType": "SearchInfo", + "SearchInfo": [ + { "UserName": "...", "NickName": "..." }, + { "UserName": "...", "NickName": "..." }, + ... + { "UserName": "...", "NickName": "..." } + ] + } + ``` +### 新建群组消息 + ``` json + { + "MsgType": "NewGroup", + "SessionName":"..." + "Members": [ + { "username": "..." }, + { "username": "..." }, + { "username": "..." }, + ], + } + ``` ### 登录后服务端行为 首先发送 LogInConfirm @@ -67,12 +118,8 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework ``` json { "MsgType": "MessageSyncCode", - "Sessions": [ - { "SessionID": 1, "Latest Message ID": 123 }, - { "SessionID": ..., "Latest Message ID": ... }, - ... - { "SessionID": ..., "Latest Message ID": ... } - ] + "SessionID": 1, + "Latest Message ID": 123 } ``` @@ -86,7 +133,7 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "Username": "...", "Nickname": "...", "Profile" : { - "Signiture" : "...", + "signiture" : "...", "..." : "...", } } @@ -100,13 +147,11 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "MsgType": "SessionData", "SessionID": 111, "SessionType": "FRIEND", - "Latest Message ID":123 "Members": [ { "Username": "..." }, { "Username": "..." }, ], "Profile": [ - "CreatedTime": "yyyy-mm-dd", "LatestMessageID": ..., ] } @@ -126,7 +171,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework ], "Profile": { "SessionName": "...", - "CreatedTime": "yyyy-mm-dd", "LatestMessageID": ..., } } @@ -153,8 +197,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "Body": { "Text": "...", "Profile": { - "hasMentionInfo": false, - "ReadMark": true / false, "...": "...", } } @@ -163,23 +205,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework - 注:客户端向服务器发送时没有 "MessageID" -消息版本列表 -``` json -{ - "MsgType": "MessageVersion", - "Data": [ - { - "SessionID": ..., - "LatestMessageID": ... - }, - { - "SessionID": ..., - "LatestMessageID": ... - }, - ... - ] -} -``` #### 软件架构 软件架构说明 diff --git a/Server/Session/abstractsession.h b/Server/Session/abstractsession.h index 6decd30fa45bf3c9e476bd12f0a8f5ba6ce8b62a..e2d4672d125f5f06fd284ff5c87152c4ee062468 100644 --- a/Server/Session/abstractsession.h +++ b/Server/Session/abstractsession.h @@ -21,6 +21,7 @@ public: } int getMemberCount() const { return members.size(); } + const UserContainer & getMembers() { return members; } protected: UserContainer members; diff --git a/Server/Session/onlinesession.cpp b/Server/Session/onlinesession.cpp index 10aa549b250e439e43296a03b0bf2a0e7dd33be3..4b6595ba588e0029fac21f4ae8cc676f294ec899 100644 --- a/Server/Session/onlinesession.cpp +++ b/Server/Session/onlinesession.cpp @@ -1,8 +1,7 @@ #include "onlinesession.h" #include -OnlineSession::OnlineSession(QJsonObject &json, AbstractSession * parent) : - QObject(parent) +OnlineSession::OnlineSession(QJsonObject &json) { loadDataFromJson(json); } @@ -11,7 +10,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) { id = json["SessionID"].toInt(); loadUsersFromJson(json); - qDebug() << "debug" ; Profile = json["Profile"].toObject(); if ((getSessionType() == SessionType::GROUP && json["SessionType"] == "GROUP") || (getSessionType() == SessionType::FRIEND && json["SessionType"] == "FRIEND") ) @@ -25,8 +23,8 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) } else { qDebug() << "load error" ; - throw "load error"; } + latest = Profile["LatestMessageID"].toInt(); } const QString& OnlineSession::getSessionName() const { @@ -52,11 +50,13 @@ QJsonObject OnlineSession::generateJsonFromData() const { ret["MsgType"] = "SessionData"; ret["SessionID"] = id; ret["SessionType"] = getSessionType() == SessionType::GROUP ? "GROUP" : "FRIEND"; + Profile["LatestMessageID"] = latest; ret["Profile"] = Profile; + QJsonArray userlist; for (int i = 0; i < members.size(); i++) { QJsonObject tmp; - tmp["username"] = members.at(i); + tmp["Username"] = members.at(i); userlist.append(tmp); } ret["Members"] = userlist; diff --git a/Server/Session/onlinesession.h b/Server/Session/onlinesession.h index 5a37a8c4c7436ae6611ee20b742c9389561ab567..c091639f1267fadc5c77c24d07246ae796c2dc07 100644 --- a/Server/Session/onlinesession.h +++ b/Server/Session/onlinesession.h @@ -9,18 +9,21 @@ class OnlineSession: public AbstractSession Q_OBJECT public: - OnlineSession(QJsonObject &json, AbstractSession * parent = nullptr); + OnlineSession(QJsonObject &json); OnlineSession(int sessionID, QString sessionName, QJsonObject profile, UserContainer Users) { id = sessionID, SessionName = sessionName, Profile = profile, members = Users; + latest = profile["LatestMessageID"].toInt(); } int getSessionID() const { return id; } const QString& getSessionName() const; + int & getLatestMessageID() { return latest; } const QJsonObject& getProfile() const { return Profile; } QJsonObject generateJsonFromData() const; + void addMember(OnlineUserModel * user) { members.append(user->getUsername()); } private: - int id; + int id, latest; QString SessionName; QJsonObject Profile; diff --git a/Server/databaseoperation.cpp b/Server/databaseoperation.cpp index 6e48e953aef8e6e357206544301353393df938b0..7778289e015aa1c5ceb8612abf4e2c12c4ac822d 100644 --- a/Server/databaseoperation.cpp +++ b/Server/databaseoperation.cpp @@ -1,396 +1,429 @@ -#include -#include -#include -#include -#include - -#include "databaseoperation.h" - -QString json2str(QJsonObject json) { - return QString(QJsonDocument(json).toJson()); -} - -QJsonObject str2json(QString str) { - QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8().data()); - if (jsonDoc.isNull()) { - qDebug() << "read json obj from str failed: str = " << str.toLocal8Bit().data(); - } - return jsonDoc.object(); -} - -DatabaseOperation::DatabaseOperation(QObject *parent) : QObject(parent) -{ - status = Status::Stop; -} - -void DatabaseOperation::startDatabaseConnection(QString dbfilename) { - if (status != Status::Stop) { - qDebug() << "db server already running..."; - throw "Already running error"; - } - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); - db.setDatabaseName(dbfilename); //如果本目录下没有该文件,则会在本目录下生成,否则连接该文件 - if (!db.open()) { - qDebug() << db.lastError().text(); - throw "Database Error"; - } - status = Status::Running; - createTables(); - findAllUsers(); - findAllSessions(); - findAllMessages(); - emit signal_DB_ready(); -} - -void DatabaseOperation::executeSqlStatement(QString str) { - QSqlQuery query (str); - if (!query.isActive()) { - qDebug() << query.lastError(); - } -} - -void DatabaseOperation::createTables() { - executeSqlStatement("CREATE TABLE User(Username TEXT PRIMARY KEY, Nickname TEXT NOT NULL, Password TEXT NOT NULL, Profile TEXT)"); - executeSqlStatement("CREATE TABLE Session(SessionID INT PRIMARY KEY, SessionType TEXT NOT NULL, Profile TEXT)"); - executeSqlStatement("CREATE TABLE Message(SessionID INT NOT NULL, MessageID INT NOT NULL, SenderUsername TEXT NOT NULL, MessageText TEXT NOT NULL, Profile TEXT, PRIMARY KEY(SessionID, MessageID), FOREIGN KEY(SessionID) REFERENCES Session(SessionID), FOREIGN KEY(SenderUserName) REFERENCES User(Username))"); - executeSqlStatement("CREATE TABLE IsMember(SessionID INT NOT NULL, Username TEXT NOT NULL, PRIMARY KEY (Username, SessionID), FOREIGN KEY (Username) REFERENCES User(username), FOREIGN KEY (SessionID) REFERENCES Session(SessionID))"); -} - -bool DatabaseOperation::isDBExist(QString dbfilename) const { - QFileInfo file(dbfilename); - return file.exists(); -} - -void DatabaseOperation::closeDB() { - if (status != Status::Running) throw "already closed"; - database.close(); - - status = Status::Stop; - emit signal_DBstop(); -} - -QList DatabaseOperation::findAllUsers() { - QList ret; - QSqlQuery sqlQuery; - sqlQuery.exec("SELECT Username, Nickname, Password, Profile FROM User"); - if(!sqlQuery.exec()) { - qDebug() << "Error: Fail to query table. " << sqlQuery.lastError(); - throw "DB read error"; - } - else { - auto & dcenter = ServerDataCenter::Singleton(); - while(sqlQuery.next()) { - QString username = sqlQuery.value(0).toString(); - QString nickname = sqlQuery.value(1).toString(); - QString profile = sqlQuery.value(3).toString(); - auto newuser = new OnlineUserModel(username, nickname, str2json(profile)); - dcenter.registerUser(newuser); - ret.append(newuser); - } - } - return ret; -} - -QList DatabaseOperation::findAllSessions() { - QList ret; - QSqlQuery query; - if (!query.exec("SELECT SessionID, Profile FROM Session")) { - qDebug() << "findAllSessions: " << query.lastError(); - throw "DB read error"; - } - auto & dcenter = ServerDataCenter::Singleton(); - while (query.next()) { - int sessionId = query.value(0).toInt(); - QJsonObject json = query.value(1).toJsonObject(); - QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; - - QList members = queryMembersBySession(sessionId); - - OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); - ret.append(session); - dcenter.registerSession(session); - } - return ret; -} - -QList DatabaseOperation::findAllMessages() { - QList ret; - QSqlQuery query; - if (!query.exec("SELECT SessionID, MessageID, senderUsername, MessageText, Profile FROM messages")) { - while (query.next()) { - int sessionID = query.value(0).toInt(); - int msgId = query.value(1).toInt(); - QString sender = query.value(2).toString(); - QString text = query.value(3).toString(); - QJsonObject profile = query.value(4).toJsonObject(); - - auto * msg = new OnlineMessage(msgId, sessionID, sender, text, profile); - ret.append(msg); - ServerDataCenter::Singleton().registerMessage(msg); - } - } - return ret; -} - - -//往User表中插入数据 -bool DatabaseOperation::insertUser(const char* username, const char* nickname, const char* password, const char* profile){ - QSqlQuery query; -// QString insert_sql = "insert into User(Username, Nickname, Password, Profile) values (?, ?, ?, ?)"; - QString insert_sql = QString("INSERT INTO User(Username, Nickname, Password, Profile) VALUES ('%1', '%2', '%3', '%4')") - .arg(username).arg(nickname).arg(password).arg(profile); - qDebug() << insert_sql; -// query.prepare(insert_sql); -// query.addBindValue(username); -// query.addBindValue(nickname); -// query.addBindValue(password); -// query.addBindValue(profile); - if (! query.exec(insert_sql) ) { - qDebug() << query.lastError(); - return false; - } - ServerDataCenter::Singleton().registerUser(new OnlineUserModel( - QString(username), QString(nickname), str2json(QString(profile)) )); - return true; -} - -bool DatabaseOperation::insertUser(const OnlineUserModel &user, const QString &password) { - return insertUser(user.getUsername().toUtf8().data(), - user.getNickname().toUtf8().data(), - password.toUtf8().data(), - json2str(user.getProfile()).toUtf8().data()); -} - - - -int DatabaseOperation::getTableCount(const char * tableName) const { - QSqlQuery query; - QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName); - query.addBindValue(tableName); - if (!query.exec(sql)) { - qDebug() << query.lastError(); - return -1; - } - if (!query.next()) return -1; - return query.value(0).toInt(); -} - -//往 Session 表中插入数据 -int DatabaseOperation::insertSessionBasicInfo(const char* SessionType, const char* profile) { - QSqlQuery query; - QString insert_sql = "insert into Session(SessionID, SessionType, Profile) values(?, ?, ?)"; - query.prepare(insert_sql); - int sessionId = getTableCount("Session") + 1; - query.addBindValue(sessionId); - query.addBindValue(SessionType); - query.addBindValue(profile); - if (!query.exec()) { - qDebug() << query.lastError(); - return -1; - } - return sessionId; -} - -bool DatabaseOperation::insertMember(int sessionID, const char * user){ - QSqlQuery query; - QString insert_sql = "insert into IsMember values(?, ?)"; - query.prepare(insert_sql); - query.addBindValue(sessionID); - query.addBindValue(user); - if(!query.exec()){ - qDebug()<<"query error: "< DatabaseOperation::queryMembersBySession(int sessionID){ - QList member_List; - QSqlQuery query; - QString query_sql = "SELECT SessionID, Username FROM IsMember WHERE sessionID = (?)"; - query.prepare(query_sql); - query.addBindValue(sessionID); - if (! query.exec()) { - qDebug() << "error occurred in queryMembersBySession, " << query.lastError(); - return member_List; - } - while(query.next()){ - member_List.append(query.value(1).toString()); - } - return member_List; -} - -//查询用户所拥有的session -QList DatabaseOperation::querySessionsByMember(const char * username){ - QList member_List; - QSqlQuery query; - QString query_sql = "SELECT SessionId, Username FROM IsMember WHERE username = (?)"; - query.prepare(query_sql); - query.addBindValue(username); - query.exec(); - while(query.next()){ - member_List.append(query.value(0).toInt()); - } - return member_List; -} - -bool DatabaseOperation::attemptLogIn(QString username, QString password) const { - //用户名检测 - QSqlQuery query(database); - query.prepare("select username, password from User where username=?"); - query.addBindValue(username); - bool ok = query.exec(); - if(!ok){ - qDebug() << "Fail query register username" << query.lastError(); - return false; - } - if(query.next()){ - //密码检测 - if (query.value(1).toString() == password) - return true; - qDebug() << "password incorrect"; - return false; - } - qDebug() << "Username not found"; - return false; -} - -int DatabaseOperation::insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile) { - QSqlQuery query; - QString sql = "select count (*) from Message WHERE SessionId = ?"; - query.prepare(sql); - query.addBindValue(SessionId); - if (!query.exec() || !query.next()) { - qDebug() << "Error Occurred when querying Message Number" << query.lastError(); - return -1; - } - int msgId = query.value(0).toInt() + 1; - qDebug() << "Current MsgId for sessionId = " << msgId; - - sql = "insert into Message(SessionID, MessageID, SenderUsername, MessageText, Profile) VALUES (?, ?, ?, ?, ?)"; - query.prepare(sql); - query.addBindValue(SessionId); - query.addBindValue(msgId); - query.addBindValue(senderUsername); - query.addBindValue(MessageText); - query.addBindValue(profile); - if (!query.exec()) { - qDebug() << "insertNewMessage : " << query.lastError(); - return -1; - } - return msgId; -} - -QList DatabaseOperation::getMessageListBySessionID(int SessionId) const { - QList ret; - QSqlQuery query; - QString sql = "SELECT MessageID, SenderUsername, MessageText, Profile FROM Message WHERE SessionID = ?"; - query.prepare(sql); - query.addBindValue(SessionId); - if (!query.exec()) { - qDebug() << "getMessageListBySessionID: " << query.lastError(); - throw query.lastError(); - } - while(query.next()) { - int msgId = query.value(0).toInt(); - QString senderUsername = query.value(1).toString(); - QString messageText = query.value(2).toString(); - QJsonObject profile = query.value(3).toJsonObject(); - auto * msg = new OnlineMessage(msgId, SessionId, senderUsername, messageText, profile); - ret.append(msgId); - ServerDataCenter::Singleton().registerMessage(msg); - } - return ret; -} - -OnlineUserModel & ServerDataCenter::getUser(QString username) { - if (_getUser(username) == nullptr) throw "Not exist"; - return *users[username]; -} - -OnlineMessage & ServerDataCenter::getMessage(int SessionId, int MessageId) { - if (_getMessage(SessionId, MessageId)) throw "Not exist"; - return *messages[{SessionId, MessageId}]; -} - -OnlineSession & ServerDataCenter::getSession(int SessionId) { - if (_getSession(SessionId) == nullptr) throw "Not exist"; - return *sessions[SessionId]; -} - -OnlineUserModel* ServerDataCenter::_getUser(QString username) { - if (users.contains(username)) - return users[username]; - return nullptr; -} - -OnlineSession* ServerDataCenter::_getSession(int SessionId) { - if (sessions.contains(SessionId)) - return sessions[SessionId]; - return nullptr; -} - -OnlineMessage* ServerDataCenter::_getMessage(int SessionId, int MessageId) { - if (messages.contains({SessionId, MessageId})) - return messages[{SessionId, MessageId}]; - return nullptr; -} - -OnlineUserModel * DatabaseOperation::findUser(QString username) { - QSqlQuery query; - QString sql = "SELECT Username, Nickname, Profile FROM User WHERE Username = " + username; - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findUser: " << query.lastError(); - return nullptr; - } - OnlineUserModel * ret = new OnlineUserModel(query.value(0).toString(), - query.value(1).toString(), - query.value(2).toJsonObject()); - ServerDataCenter::Singleton().registerUser(ret); - return ret; -} - -OnlineSession * DatabaseOperation::findSession(int sessionID) { - QSqlQuery query; - QString sql = "SELECT Profile FROM Session WHERE SessionID = " + QString::number(sessionID); - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findSession: " << query.lastError(); - return nullptr; - } - - auto json = query.value(0).toJsonObject(); - QString SessionName = json.contains("SessionName") ? - json["SessionName"].toString() : "None"; - - OnlineSession * ret = new OnlineSession(sessionID, SessionName, json, - queryMembersBySession(sessionID)); - ServerDataCenter::Singleton().registerSession(ret); - return ret; -} - -OnlineMessage * DatabaseOperation::findMessage(int sessionId, int MessageId) { - QSqlQuery query; - QString sql = "SELECT SenderUsername, MessageText, Profile FROM Message WHERE SessionID = " + - QString::number(sessionId) + " and MessageID = " + QString::number(MessageId); - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findMessage: " << query.lastError(); - return nullptr; - } - - QString sender = query.value(0).toString(); - QString text = query.value(1).toString(); - QJsonObject json = query.value(2).toJsonObject(); - OnlineMessage * ret = new OnlineMessage(MessageId, sessionId, sender, text, json); - ServerDataCenter::Singleton().registerMessage(ret); - return ret; -} - -ServerDataCenter::ServerDataCenter(QObject *parent) : QObject(parent) -{ - connect(&DatabaseOperation::Singleton(), &DatabaseOperation::signal_DBstop, this, &ServerDataCenter::clean); -} +#include +#include +#include +#include +#include + +#include "databaseoperation.h" + +QString json2str(QJsonObject json) { + return QString(QJsonDocument(json).toJson()); +} + +QJsonObject str2json(QString str) { + QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8().data()); + if (jsonDoc.isNull()) { + qDebug() << "read json obj from str failed: str = " << str.toLocal8Bit().data(); + } + return jsonDoc.object(); +} + +DatabaseOperation::DatabaseOperation(QObject *parent) : QObject(parent) +{ + status = Status::Stop; +} + +void DatabaseOperation::startDatabaseConnection(QString dbfilename) { + if (status != Status::Stop) { + qDebug() << "db server already running..."; + throw "Already running error"; + } + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(dbfilename); //如果本目录下没有该文件,则会在本目录下生成,否则连接该文件 + if (!db.open()) { + qDebug() << db.lastError().text(); + throw "Database Error"; + } + status = Status::Running; + createTables(); + findAllUsers(); + findAllSessions(); + findAllMessages(); + emit signal_DB_ready(); +} + +void DatabaseOperation::executeSqlStatement(QString str) { + QSqlQuery query (str); + if (!query.isActive()) { + qDebug() << query.lastError(); + } +} + +void DatabaseOperation::createTables() { + executeSqlStatement("CREATE TABLE User(Username TEXT PRIMARY KEY, Nickname TEXT NOT NULL, Password TEXT NOT NULL, Profile TEXT)"); + executeSqlStatement("CREATE TABLE Session(SessionID INT PRIMARY KEY, SessionType TEXT NOT NULL, Profile TEXT)"); + executeSqlStatement("CREATE TABLE Message(SessionID INT NOT NULL, MessageID INT NOT NULL, SenderUsername TEXT NOT NULL, MessageText TEXT NOT NULL, Profile TEXT, PRIMARY KEY(SessionID, MessageID), FOREIGN KEY(SessionID) REFERENCES Session(SessionID), FOREIGN KEY(SenderUserName) REFERENCES User(Username))"); + executeSqlStatement("CREATE TABLE IsMember(SessionID INT NOT NULL, Username TEXT NOT NULL, PRIMARY KEY (Username, SessionID), FOREIGN KEY (Username) REFERENCES User(username), FOREIGN KEY (SessionID) REFERENCES Session(SessionID))"); +} + +bool DatabaseOperation::isDBExist(QString dbfilename) const { + QFileInfo file(dbfilename); + return file.exists(); +} + +void DatabaseOperation::closeDB() { + if (status != Status::Running) throw "already closed"; + database.close(); + + status = Status::Stop; + emit signal_DBstop(); +} + +QList DatabaseOperation::findAllUsers() { + QList ret; + QSqlQuery sqlQuery; + sqlQuery.exec("SELECT Username, Nickname, Password, Profile FROM User"); + if(!sqlQuery.exec()) { + qDebug() << "Error: Fail to query table. " << sqlQuery.lastError(); + throw "DB read error"; + } + else { + auto & dcenter = ServerDataCenter::Singleton(); + while(sqlQuery.next()) { + QString username = sqlQuery.value(0).toString(); + QString nickname = sqlQuery.value(1).toString(); + QString profile = sqlQuery.value(3).toString(); + auto newuser = new OnlineUserModel(username, nickname, str2json(profile)); + dcenter.registerUser(newuser); + ret.append(newuser); + } + } + return ret; +} + +QList DatabaseOperation::findAllSessions() { + QList ret; + QSqlQuery query; + if (!query.exec("SELECT SessionID, Profile FROM Session")) { + qDebug() << "findAllSessions: " << query.lastError(); + throw "DB read error"; + } + auto & dcenter = ServerDataCenter::Singleton(); + while (query.next()) { + int sessionId = query.value(0).toInt(); + QJsonObject json = query.value(1).toJsonObject(); + QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; + + QList members = queryMembersBySession(sessionId); + + OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); + ret.append(session); + dcenter.registerSession(session); + } + return ret; +} + +QList DatabaseOperation::findAllMessages() { + QList ret; + QSqlQuery query; + if (query.exec("SELECT SessionID, MessageID, senderUsername, MessageText, Profile FROM Message")) { + while (query.next()) { + int sessionID = query.value(0).toInt(); + int msgId = query.value(1).toInt(); + QString sender = query.value(2).toString(); + QString text = query.value(3).toString(); + QJsonObject profile = query.value(4).toJsonObject(); + + auto * msg = new OnlineMessage(msgId, sessionID, sender, text, profile); + ret.append(msg); + ServerDataCenter::Singleton().registerMessage(msg); + } + } + return ret; +} + + +//往User表中插入数据 +bool DatabaseOperation::insertUser(QString username, QString nickname, QString password, QJsonObject profile){ + QSqlQuery query; + QString insert_sql = "INSERT INTO User(Username, Nickname, Password, Profile) VALUES (?, ?, ?, ?)"; + query.prepare(insert_sql); + query.addBindValue(username); + query.addBindValue(nickname); + query.addBindValue(password); + query.addBindValue(profile); + if (! query.exec() ) { + qDebug() << query.lastError(); + return false; + } + ServerDataCenter::Singleton().registerUser(new OnlineUserModel(username, nickname, profile)); + return true; +} + +bool DatabaseOperation::insertUser(const OnlineUserModel &user, const QString &password) { + return insertUser(user.getUsername(), user.getNickname(), password, user.getProfile()); +} + + + +int DatabaseOperation::getTableCount(QString tableName) const { + QSqlQuery query; + QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName); + query.addBindValue(tableName); + if (!query.exec(sql)) { + qDebug() << query.lastError(); + return -1; + } + if (!query.next()) return -1; + return query.value(0).toInt(); +} + +//往 Session 表中插入数据 +int DatabaseOperation::insertSessionBasicInfo(QString SessionType, QJsonObject profile) { + QSqlQuery query; + QString insert_sql = "insert into Session(SessionID, SessionType, Profile) values(?, ?, ?)"; + query.prepare(insert_sql); + int sessionId = getTableCount("Session") + 1; + query.addBindValue(sessionId); + query.addBindValue(SessionType); + query.addBindValue(profile); + if (!query.exec()) { + qDebug() << query.lastError(); + return -1; + } + QString sessionName = profile.contains("SessionName") ? profile["SessionName"].toString() : "None"; + OnlineSession * session = new OnlineSession(sessionId, sessionName, profile, QList()); + auto & dcenter = ServerDataCenter::Singleton(); + dcenter.registerSession(session); + return sessionId; +} + +bool DatabaseOperation::insertMember(int sessionID, QString user){ + QSqlQuery query; + QString insert_sql = "insert into IsMember values(?, ?)"; + query.prepare(insert_sql); + query.addBindValue(sessionID); + query.addBindValue(user); + if(!query.exec()){ + qDebug()<<"query error: "< DatabaseOperation::queryMembersBySession(int sessionID){ + QList member_List; + QSqlQuery query; + QString query_sql = "SELECT SessionID, Username FROM IsMember WHERE sessionID = (?)"; + query.prepare(query_sql); + query.addBindValue(sessionID); + if (! query.exec()) { + qDebug() << "error occurred in queryMembersBySession, " << query.lastError(); + return member_List; + } + while(query.next()){ + member_List.append(query.value(1).toString()); + } + return member_List; +} + +//查询用户所拥有的session +QList DatabaseOperation::querySessionsByMember(QString username){ + QList member_List; + QSqlQuery query; + QString query_sql = "SELECT SessionId, Username FROM IsMember WHERE username = (?)"; + query.prepare(query_sql); + query.addBindValue(username); + query.exec(); + while(query.next()){ + member_List.append(query.value(0).toInt()); + } + return member_List; +} + +//查询会话的所有历史消息 +QList DatabaseOperation::queryMessageBySession(int sessionID) { + QList ret; + QSqlQuery query; + QString sql = "SELECT MessageID FROM Message WHERE SessionID = (?)"; + query.prepare(sql); query.addBindValue(sessionID); + if (!query.exec()) { + qDebug() << "queryMessageBySession: " << query.lastError(); + return ret; + } + while (query.next()) { + ret.append(query.value(0).toInt()); + } + return ret; +} + + +bool DatabaseOperation::attemptLogIn(QString username, QString password) const { + //用户名检测 + QSqlQuery query(database); + query.prepare("select username, password from User where username=?"); + query.addBindValue(username); + bool ok = query.exec(); + if(!ok){ + qDebug() << "Fail query register username" << query.lastError(); + return false; + } + if(query.next()){ + //密码检测 + if (query.value(1).toString() == password) + return true; + qDebug() << "password incorrect"; + return false; + } + qDebug() << "Username not found"; + return false; +} + +int DatabaseOperation::insertNewMessage(int SessionId, QString senderUsername, QString MessageText, QJsonObject profile) { + QSqlQuery query; + QString sql = "select count (*) from Message WHERE SessionId = ?"; + query.prepare(sql); + query.addBindValue(SessionId); + if (!query.exec() || !query.next()) { + qDebug() << "Error Occurred when querying Message Number" << query.lastError(); + return -1; + } + int msgId = query.value(0).toInt() + 1; + qDebug() << "Current MsgId for sessionId = " << msgId; + + sql = "insert into Message(SessionID, MessageID, SenderUsername, MessageText, Profile) VALUES (?, ?, ?, ?, ?)"; + query.prepare(sql); + query.addBindValue(SessionId); + query.addBindValue(msgId); + query.addBindValue(senderUsername); + query.addBindValue(MessageText); + query.addBindValue(profile); + if (!query.exec()) { + qDebug() << "insertNewMessage : " << query.lastError(); + return -1; + } + return msgId; +} + +QList DatabaseOperation::getMessageListBySessionID(int SessionId) const { + QList ret; + QSqlQuery query; + QString sql = "SELECT MessageID, SenderUsername, MessageText, Profile FROM Message WHERE SessionID = ?"; + query.prepare(sql); + query.addBindValue(SessionId); + if (!query.exec()) { + qDebug() << "getMessageListBySessionID: " << query.lastError(); + throw query.lastError(); + } + while(query.next()) { + int msgId = query.value(0).toInt(); + QString senderUsername = query.value(1).toString(); + QString messageText = query.value(2).toString(); + QJsonObject profile = query.value(3).toJsonObject(); + auto * msg = new OnlineMessage(msgId, SessionId, senderUsername, messageText, profile); + ret.append(msgId); + ServerDataCenter::Singleton().registerMessage(msg); + } + return ret; +} + +OnlineUserModel & ServerDataCenter::getUser(QString username) { + if (_getUser(username) == nullptr) throw "Not exist"; + return *users[username]; +} + +OnlineMessage & ServerDataCenter::getMessage(int SessionId, int MessageId) { + if (_getMessage(SessionId, MessageId) == nullptr) throw "Not exist"; + return *messages[{SessionId, MessageId}]; +} + +OnlineSession & ServerDataCenter::getSession(int SessionId) { + if (_getSession(SessionId) == nullptr) throw "Not exist"; + return *sessions[SessionId]; +} + +OnlineUserModel* ServerDataCenter::_getUser(QString username) { + if (users.contains(username)) + return users[username]; + return nullptr; +} + +OnlineSession* ServerDataCenter::_getSession(int SessionId) { + if (sessions.contains(SessionId)) + return sessions[SessionId]; + return nullptr; +} + +OnlineMessage* ServerDataCenter::_getMessage(int SessionId, int MessageId) { + OnlineMessage * ret = nullptr; + if (messages.contains(QPair({SessionId, MessageId}))) + ret = messages[QPair({SessionId, MessageId})]; + return ret; +} + +OnlineUserModel * DatabaseOperation::findUser(QString username) { + QSqlQuery query; + QString sql = "SELECT Username, Nickname, Profile FROM User WHERE Username = " + username; + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findUser: " << query.lastError(); + return nullptr; + } + OnlineUserModel * ret = new OnlineUserModel(query.value(0).toString(), + query.value(1).toString(), + query.value(2).toJsonObject()); + ServerDataCenter::Singleton().registerUser(ret); + return ret; +} + +OnlineSession * DatabaseOperation::findSession(int sessionID) { + QSqlQuery query; + QString sql = "SELECT Profile FROM Session WHERE SessionID = " + QString::number(sessionID); + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findSession: " << query.lastError(); + return nullptr; + } + + auto json = query.value(0).toJsonObject(); + QString SessionName = json.contains("SessionName") ? + json["SessionName"].toString() : "None"; + + OnlineSession * ret = new OnlineSession(sessionID, SessionName, json, + queryMembersBySession(sessionID)); + ServerDataCenter::Singleton().registerSession(ret); + return ret; +} + +OnlineMessage * DatabaseOperation::findMessage(int sessionId, int MessageId) { + QSqlQuery query; + QString sql = "SELECT SenderUsername, MessageText, Profile FROM Message WHERE SessionID = " + + QString::number(sessionId) + " and MessageID = " + QString::number(MessageId); + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findMessage: " << query.lastError(); + return nullptr; + } + + QString sender = query.value(0).toString(); + QString text = query.value(1).toString(); + QJsonObject json = query.value(2).toJsonObject(); + OnlineMessage * ret = new OnlineMessage(MessageId, sessionId, sender, text, json); + ServerDataCenter::Singleton().registerMessage(ret); + return ret; +} + +ServerDataCenter::ServerDataCenter(QObject *parent) : QObject(parent) +{ + connect(&DatabaseOperation::Singleton(), &DatabaseOperation::signal_DBstop, this, &ServerDataCenter::clean); +} + +QList DatabaseOperation::findFriend(QString name){ + QSqlQuery query; + QList result; + QString sql = "SELECT Username FROM User WHERE Username LIKE '%"+name+"%' or Nickname LIKE '%"+name+"%'"; + query.prepare(sql); + if (!query.exec()){ + qDebug() << query.lastError(); + } + else{ + while(query.next()){ + result.append(query.value(0).toString()); + } + } + return result; +} diff --git a/Server/databaseoperation.h b/Server/databaseoperation.h index 9b90e3e7ed79780bca3e995b3a505dc29b7015cd..016734dc05ecca2cf24946deea1eda7d3d313f21 100644 --- a/Server/databaseoperation.h +++ b/Server/databaseoperation.h @@ -26,27 +26,29 @@ public: void startDatabaseConnection(QString dbfilename); bool isDBExist(QString str) const; void closeDB(); - int getTableCount(const char * tableName) const; + int getTableCount(QString tableName) const; QList findAllUsers(); QList findAllSessions(); QList findAllMessages(); - bool insertUser(const char * username, const char * nickname, const char * password, const char * profile); + bool insertUser(QString username, QString nickname, QString password, QJsonObject profile); bool insertUser(const OnlineUserModel &user, const QString &password); // 返回SessionID - int insertSessionBasicInfo(const char * sessionType, const char * profile); + int insertSessionBasicInfo(QString sessionType, QJsonObject profile); bool isRunning() const { return status == Status::Running; } bool insertMember(int sessionID, const OnlineUserModel& user); - bool insertMember(int sessionID, const char * user); - int insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile); + bool insertMember(int sessionID, QString user); + int insertNewMessage(int SessionId, QString senderUsername, QString MessageText, QJsonObject profile); QList queryMembersBySession(int sessionID); - QList querySessionsByMember(const char * username); + QList querySessionsByMember(QString username); + QList queryMessageBySession(int sessionID); QList getMessageListBySessionID(int SessionId) const; OnlineMessage * findMessage(int sessionId, int MessageId); OnlineSession * findSession(int sessionID); OnlineUserModel * findUser(QString username); + QList findFriend(QString name); bool attemptLogIn(QString username, QString password) const; diff --git a/Server/handlesignal.h b/Server/handlesignal.h index 111256e98177cf04ec4aa995b84c0f4a5b51b476..6e1db5aa480ab139327486baa54ad6c37836b2a4 100644 --- a/Server/handlesignal.h +++ b/Server/handlesignal.h @@ -13,6 +13,7 @@ public: signals: void sendSignal(int); + }; #endif // HANDLESIGNAL_H diff --git a/Server/messagemodel.cpp b/Server/messagemodel.cpp index 8e4695ce4b5fae191ceb1f4c0bf3d1ec1d4765f9..9472682771279ff255412481e46e040896d58645 100644 --- a/Server/messagemodel.cpp +++ b/Server/messagemodel.cpp @@ -32,7 +32,7 @@ OnlineMessage::OnlineMessage(QJsonObject json, MessageModel * parent) : { messageID = json["MessageID"].toInt(); sessionID = json["SessionID"].toInt(); - senderUsername = json["SenderUsername"].toString(); + senderUsername = json["SenderName"].toString(); QJsonObject body = json["Body"].toObject(); text = body["Text"].toString(); @@ -48,3 +48,12 @@ OnlineMessage::OnlineMessage(int MessageID, int SessionID, QString sender, QStri profile = Profile; this->setParent(parent); } + +QJsonObject OnlineMessage::generateJsonOutput() const { + QJsonObject ret = {{ "MsgType", "SessionMessage" }}; + ret["SessionID"] = sessionID; + ret["MessageID"] = messageID; + ret["SenderName"] = senderUsername; + ret["Body"] = QJsonObject({{"Text", text}, {"Profile", QJsonObject()}}); + return ret; +} diff --git a/Server/messagemodel.h b/Server/messagemodel.h index 9b68c6276d3263c83067731efce6f9289e66a955..d7559ab63f08948b1606ff9502b890a5b59234a1 100644 --- a/Server/messagemodel.h +++ b/Server/messagemodel.h @@ -24,7 +24,6 @@ public: enum class Type { Offline, Online }; virtual Type getType() const { return Type::Offline; } - QJsonObject generateJsonOutput() const; signals: @@ -44,6 +43,7 @@ public: explicit OnlineMessage(QJsonObject json, MessageModel * parent = nullptr); explicit OnlineMessage(int MessageID, int SessionID, QString sender, QString text, QJsonObject Profile, MessageModel * parent = nullptr); int getMessageID() const override { return messageID; } + QJsonObject generateJsonOutput() const; private: int messageID; }; diff --git a/Server/operations.cpp b/Server/operations.cpp index 1b878eceb3a4f376742532ecd74b0e74a3fac7bb..2ad08ee4e3c55fda1e54400fd73913a8cb60458a 100644 --- a/Server/operations.cpp +++ b/Server/operations.cpp @@ -2,21 +2,14 @@ #include "serverdatacenter.h" #include "databaseoperation.h" -Operations::Operations(QObject *parent) : QObject(parent) -{ +Operations::Operations(QObject *parent) : QObject(parent) { } - - - - ServerDataCenter& dcenter = ServerDataCenter::Singleton(); using resp = QList; using Json = QJsonObject; - - resp Operations::loginResponse(QJsonObject json) { DatabaseOperation & db = DatabaseOperation::Singleton(); QString username = json["Username"].toString(); @@ -28,6 +21,7 @@ resp Operations::loginResponse(QJsonObject json) { } response["IsLegal"] = true; response["Username"] = username; + auto & user = dcenter.getUser(username); response["Nickname"] = user.getNickname(); response["Profile"] = user.getProfile(); @@ -35,13 +29,24 @@ resp Operations::loginResponse(QJsonObject json) { auto sessionlist = db.querySessionsByMember(username.toUtf8().data()); for (int i = 0; i < sessionlist.size(); i++) { - auto userlist = db.queryMembersBySession(sessionlist.at(i)); + int ssid = sessionlist.at(i); + auto userlist = db.queryMembersBySession(ssid); for (int j = 0; j < userlist.size(); j++) { auto cur = userlist.at(j); if (cur == username) continue; auto & curuser = dcenter.getUser(cur); ret.append(curuser.generateUserModelJson()); + + } + ret.append(dcenter.getSession(ssid).generateJsonFromData()); + auto msglist = db.queryMessageBySession(sessionlist.at(i)); + for (int j = 0; j < msglist.size(); j++) { + try{ + ret.append(dcenter.getMessage(ssid, msglist[j]).generateJsonOutput()); + } catch (...) { + qDebug() << "fatal error"; + } } ret.append(dcenter.getSession(sessionlist.at(i)).generateJsonFromData()); } @@ -55,13 +60,89 @@ resp Operations::registerResponse(QJsonObject json) { Json head = {{"MsgType", "RegistConfirm"}, {"IsLegal", false}}; if (dcenter.hasUser(json["Username"].toString())) return {head}; - char * username = json["Username"].toString().toUtf8().data(); - Q_ASSERT(username == json["Username"].toString()); - char * nickname = json["Nickname"].toString().toUtf8().data(); - char * password = json["Password"].toString().toUtf8().data(); + QString username = json["Username"].toString(); + qDebug() << "Registering User into DB, username = " << username; + QString nickname = json["Nickname"].toString(); + QString password = json["Password"].toString(); - if (!db.insertUser(username, nickname, password, "{ \"Signiture\": \"None\"}")) + if (!db.insertUser(username, nickname, password, QJsonObject({{"Signiture", "None"}}))) return {head}; + qDebug() << "Register: Success"; head["IsLegal"] = true; return {head}; } + +resp Operations::newMessageResponse(QJsonObject json) { + DatabaseOperation & db = DatabaseOperation::Singleton(); + int sessionID = json["SessionID"].toInt(); + QString senderUsername = json["SenderName"].toString(); + auto json1 = json["Body"].toObject(); + QString text = json1["Text"].toString(); + bool mention = json1["Profile"].toObject()["hasMentionInfo"].toBool(); + if (mention) { + throw "Not Implemented"; + } + int msgID = db.insertNewMessage(sessionID, senderUsername, text, json["Profile"].toObject()); + json["MessageID"] = msgID; + emit newMessage(sessionID, json); + + return resp(); +} + +resp Operations::addFriendResponse(QJsonObject json) { + DatabaseOperation & db = DatabaseOperation::Singleton(); + QString from = json["FromUsername"].toString(), to = json["ToUsername"].toString(); + OnlineUserModel & fromUser = dcenter.getUser(from), &toUser = dcenter.getUser(to); + + auto sessionlist = db.querySessionsByMember(from.toUtf8().data()); + for (int i = 0; i < sessionlist.size(); i++) { + auto & session = dcenter.getSession(sessionlist[i]); + auto & members = session.getMembers(); + for (int j = 0; j < members.size(); j++) { + if (members[j] == to && session.getSessionType() == AbstractSession::SessionType::FRIEND) + return resp(); + } + } + + int id = db.insertSessionBasicInfo("FRIEND", QJsonObject({{"LatestMessageID", 0}, {"SessionName", "None"}})); + db.insertMember(id, fromUser); + db.insertMember(id, toUser); + + auto response = dcenter.getSession(id).generateJsonFromData(); + + emit newMessage(id, response); + return resp(); +} + +resp Operations::searchResponse(QJsonObject json) { + DatabaseOperation & db = DatabaseOperation::Singleton(); + ServerDataCenter & dcenter = ServerDataCenter::Singleton(); + QString queryStr = json["SearchInfo"].toString(); + + QList result = db.findFriend(queryStr); + QJsonObject response = {{ "MsgType", "SearchInfo" }}; + QJsonArray array; + for (int i = 0; i < result.size(); i++) { + array.append(QJsonObject({{"Username", result[i]}, + {"Nickname", dcenter.getUser(result[i]).getNickname()}})); + } + response["SearchInfo"] = array; + return {response}; +} + +resp Operations::createGroupResponse(QJsonObject json) { + DatabaseOperation & db = DatabaseOperation::Singleton(); + ServerDataCenter & dcenter = ServerDataCenter::Singleton(); + + QString sessionName = json["SessionName"].toString(); + QJsonArray array = json["Members"].toArray(); + int id = db.insertSessionBasicInfo("GROUP", QJsonObject({{"LatestMessageID", 0}, {"SessionName", sessionName}})); + for (int i = 0; i < array.size(); i++) { + QString username = array[i].toObject()["username"].toString(); + db.insertMember(id, dcenter.getUser(username)); + } + + QJsonObject response = dcenter.getSession(id).generateJsonFromData(); + emit newMessage(id, response); + return resp(); +} diff --git a/Server/operations.h b/Server/operations.h index fc1e3723f1e345d281131f9275eb8ba6d4c4f6d7..1c7e489f9147487aaaa20a22b41550480f881aaf 100644 --- a/Server/operations.h +++ b/Server/operations.h @@ -21,13 +21,17 @@ public: QList request(QJsonObject json); signals: + void newMessage(int sessionId, QJsonObject msg); + public: explicit Operations(QObject *parent = nullptr); QList registerResponse(QJsonObject json); QList loginResponse(QJsonObject json); QList newMessageResponse(QJsonObject json); - + QList addFriendResponse(QJsonObject json); + QList searchResponse(QJsonObject json); + QList createGroupResponse(QJsonObject json); }; #endif // OPERATIONS_H diff --git a/Server/serverdatacenter.cpp b/Server/serverdatacenter.cpp index 20076d6374fb164e63a52abd7556a96592a8e36c..358360b71bfc131908eb38d7538e5f839ec5b16a 100644 --- a/Server/serverdatacenter.cpp +++ b/Server/serverdatacenter.cpp @@ -28,7 +28,6 @@ void ServerDataCenter::registerMessage(OnlineMessage *msg) { messages[{msg->getSessionID(), msg->getMessageID()}] = msg; msg->setParent(this); registeredObjects.append(msg); - qDebug() << "### ServerDataCenter Down"; } diff --git a/Server/sever.cpp b/Server/sever.cpp index 943d40a6feb626c35acc6cb2cba4c44f9ac769f9..9574002e6fabcfdaa98e235f8f50dec8ec3b6799 100644 --- a/Server/sever.cpp +++ b/Server/sever.cpp @@ -6,6 +6,7 @@ #include #include"databaseoperation.h" + Sever::Sever(QObject *parent) : QTcpServer (parent) { @@ -30,9 +31,13 @@ void Sever::incomingConnection(qintptr handle) newHandle->aaa(handle); }); + connect(socket,&QTcpSocket::disconnected,[=](){ + emit offLine (handle); + }); + emit sendChannel (handle); - emit linkMsg (socket->peerAddress ().toString ()+"上线了", 2); //2表示在登录框中显示 + emit linkMsg (socket->peerAddress ().toString ()+"连接成功!"); //2表示在登录框中显示 } @@ -57,6 +62,7 @@ void Sever::receiveMessage(int handle) QByteArray receiveMes = it.value ()->readAll (); QJsonDocument receJson = QJsonDocument::fromJson (receiveMes); QJsonObject recejson = receJson.object (); + qDebug() << "Received Message from " << handle << ": " << recejson; if(!recejson.contains ("MsgType")) { qDebug()<<"receive message is not json!"; @@ -67,17 +73,59 @@ void Sever::receiveMessage(int handle) auto returnList = QList(); auto &op = Operations::Singleton (); + if(method == "login") { - returnList = op.loginResponse (recejson); + //首次收到登陆信息 + messageSender = recejson["Username"].toString(); + QMap >::iterator it1 = userToHandle.begin(); + int flag=0; + while(it1!=userToHandle.end ()) + { + if(it1.key ()==messageSender)//并非首次登陆 + { + it1.value ().append (handle); + emit linkMsg (messageSender+" "+QString::number (it1.value ().size ())+" "+"登陆了!"); + qDebug()<< it1.value ().size (); + flag=1; + break; + } + it1++; + } + if(flag==0)//首次登陆 + { + QList ll; + ll.append (handle); + userToHandle.insert (messageSender,ll); + emit linkMsg (messageSender+" 1 "+"登陆了!"); + } + returnList = op.loginResponse (recejson); + emit sendMsg (returnList, handle); } else if (method == "regist") { returnList = op.registerResponse(recejson); + emit sendMsg (returnList, handle); } else if (method == "info") { - qDebug() << recejson["Message"].toString(); - emit linkMsg(recejson["Message"].toString(), 1); + + emit linkMsg(recejson["Message"].toString()); + } - qDebug() << returnList; - emit sendMsg (returnList, handle); //1表示在文本框中显示 + else if(method == "sessionmessage"){ + op.newMessageResponse (recejson); + //同时触发信号,到widget + } + else if (method == "search") { + returnList = op.searchResponse(recejson); + emit sendMsg(returnList, handle); + } + else if (method == "addfriendrequest") { + op.addFriendResponse(recejson); + } + else if (method == "newgroup") { + op.createGroupResponse(recejson); + } + + qDebug() << "Server ReturnList: " << returnList; + } diff --git a/Server/sever.h b/Server/sever.h index 2c6d4689b9f77840f47c96eb1378ec2ab7432b18..bde4efd02bf0cde0d1c635bb237b005cbd57a8c9 100644 --- a/Server/sever.h +++ b/Server/sever.h @@ -12,21 +12,29 @@ class Sever : public QTcpServer public: explicit Sever(QObject *parent = nullptr); + //handle索引的socket QMap clientMap; + //username索引的handle,实现了一对多 + QMap> userToHandle; + private: QTcpSocket *sock; void incomingConnection(qintptr handle); void receiveMessage(qintptr); + QString messageSender = ""; public slots: void setIP(QString); + signals: - void linkMsg(QString, int); - void sendMsg(QList, int);//将tcp_server收到的信息作为信号发送给mianwindow + void linkMsg(QString); + void sendMsg(QList, int);//将tcp_server收到的信息作为信号发送给 MainWindow void ready_Read(qintptr); void sendChannel(int); + void offLine(int); + }; #endif // SEVER_H diff --git a/Server/testcases.cpp b/Server/testcases.cpp index ff2a6a38902ed3e759d100e2edf86edfb42742c4..983f5ece8205f7619d102e7a467f6af469098f56 100644 --- a/Server/testcases.cpp +++ b/Server/testcases.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "databaseoperation.h" #include "serverdatacenter.h" @@ -88,7 +89,7 @@ ENDSUITE(SessionTest) TESTSUITE(UserTest) CASE(OfflineUserGenerateJsonObject) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); @@ -96,17 +97,17 @@ CASE(OfflineUserGenerateJsonObject) { assertEqual(json["Nickname"].toString(), "nicknameA"); auto profile = json["Profile"].toObject(); - assertEqual(profile["Signiture"].toString(), "None"); + assertEqual(profile["signiture"].toString(), "None"); } CASE(NewOnlineUser_ReadJson_LoadProfile) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); - OnlineUserModel newuser(json, &obj); + OnlineUserModel newuser(json); assertEqual(newuser.getType(), UserModel::Type::Online); assertEqual(newuser.getUsername(), "userA"); @@ -130,17 +131,17 @@ CASE(CanGetSingleton) { } CASE(getOnlineUserFromUsername) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); - OnlineUserModel newuser(json, &obj); + OnlineUserModel newuser(json); - OfflineUserModel userB("userB", &obj); + OfflineUserModel userB("userB"); userB.setNickname("nicknameA"); userB.setSigniture("None"); json = userB.generateUserModelJson(); - OnlineUserModel newuserB(json, &obj); + OnlineUserModel newuserB(json); auto& dcenter = ServerDataCenter::Singleton(); dcenter.registerUser(& newuser); @@ -164,17 +165,17 @@ TESTSUITE(MessageTest) CASE(NewMessage_GeneratedBy_UserAndSessionObject) { - OfflineUserModel userA("userA", &obj); + OfflineUserModel userA("userA"); userA.setNickname("nicknameA"); userA.setSigniture("None"); auto json = userA.generateUserModelJson(); - OnlineUserModel userA_online(json, &obj); + OnlineUserModel userA_online(json); - OfflineUserModel userB("userB", &obj); + OfflineUserModel userB("userB"); userB.setNickname("nicknameA"); userB.setSigniture("None"); json = userB.generateUserModelJson(); - OnlineUserModel userB_online(json, &obj); + OnlineUserModel userB_online(json); ServerDataCenter & dcenter = ServerDataCenter::Singleton(); dcenter.registerUser(&userA_online); @@ -197,7 +198,7 @@ CASE(NewMessage_GeneratedBy_UserAndSessionObject) testlog("Constructed mock users and session."); - MessageModel msg(userA_online, session, "a->b text", QJsonObject(), &obj); + MessageModel msg(userA_online, session, "a->b text", QJsonObject()); testlog("Generated offline message"); assertEqual(msg.getType(), MessageModel::Type::Offline); @@ -230,11 +231,11 @@ CASE(CanCreateNewDB) { } void insertUser() { - db.insertUser("xiaoming","XiaoMing", "xiaoming123", "{\"Signiture\":\"nop\"}"); - db.insertUser("xxx", "XXX", "xXxXx", "{ \"Signiture\": \"yyy\"}"); - db.insertUser("wuzirui", "wuzirui", "1234", "{ \"Signiture\": \"cai\"}"); - db.insertUser("usera", "UserA", "AAAA", "{ \"Signiture\": \"B -1\"}"); - db.insertUser("userB", "bibibi", "bbbb", "{ \"Signiture\": \"A+1\"}"); +// db.insertUser("xiaoming","XiaoMing", "xiaoming123", "{\"signiture\":\"nop\"}"); +// db.insertUser("xxx", "XXX", "xXxXx", "{ \"signiture\": \"yyy\"}"); +// db.insertUser("wuzirui", "wuzirui", "1234", "{ \"signiture\": \"cai\"}"); +// db.insertUser("usera", "UserA", "AAAA", "{ \"signiture\": \"B -1\"}"); +// db.insertUser("userB", "bibibi", "bbbb", "{ \"signiture\": \"A+1\"}"); } void checkInsertedUser() { @@ -248,61 +249,61 @@ void checkInsertedUser() { } void insertSession() { - int startId = db.getTableCount("Session"); - assertEqual(startId, 0); - int newId = db.insertSessionBasicInfo("FRIEND", "{}"); - assertEqual(newId, startId + 1); - assertEqual(newId, db.getTableCount("Session")); - - db.insertMember(newId, "wuzirui"); - db.insertMember(newId, "xiaoming"); - assertEqual(2, db.getTableCount("IsMember"), - "Expected 2, got " << db.getTableCount("IsMember")); - auto list = db.queryMembersBySession(newId); - assertEqual(list.size(), 2); - assertEqual(list.at(0), "wuzirui"); - assertEqual(list.at(1), "xiaoming"); - assertEqual(db.getTableCount("Session"), 1, db.getTableCount("Session")); - - int newerId = db.insertSessionBasicInfo("GROUP", "{}"); - assertEqual(newerId, newId + 1); - db.insertMember(newerId, "usera"); - db.insertMember(newerId, "userB"); - db.insertMember(newerId, "xxx"); - db.insertMember(newerId, "wuzirui"); - assertEqual(6, db.getTableCount("IsMember"), db.getTableCount("IsMember")); - list = db.queryMembersBySession(newerId); - assertEqual(list.size(), 4, list.size()); - assertEqual(list.at(0), "usera", list.at(0).toUtf8().data()); - assertEqual(list.at(1), "userB", list.at(1).toUtf8().data()); - assertEqual(list.at(2), "xxx", list.at(2).toUtf8().data()); - assertEqual(list.at(3), "wuzirui", list.at(3).toUtf8().data()); - - auto sslist = db.querySessionsByMember("wuzirui"); - assertEqual(sslist.size(), 2); - assertEqual(sslist.at(0), newId, sslist.at(0)); - assertEqual(sslist.at(1), newerId, sslist.at(1)); +// int startId = db.getTableCount("Session"); +// assertEqual(startId, 0); +// int newId = db.insertSessionBasicInfo("FRIEND", "{}"); +// assertEqual(newId, startId + 1); +// assertEqual(newId, db.getTableCount("Session")); + +// db.insertMember(newId, "wuzirui"); +// db.insertMember(newId, "xiaoming"); +// assertEqual(2, db.getTableCount("IsMember"), +// "Expected 2, got " << db.getTableCount("IsMember")); +// auto list = db.queryMembersBySession(newId); +// assertEqual(list.size(), 2); +// assertEqual(list.at(0), "wuzirui"); +// assertEqual(list.at(1), "xiaoming"); +// assertEqual(db.getTableCount("Session"), 1, db.getTableCount("Session")); + +// int newerId = db.insertSessionBasicInfo("GROUP", "{}"); +// assertEqual(newerId, newId + 1); +// db.insertMember(newerId, "usera"); +// db.insertMember(newerId, "userB"); +// db.insertMember(newerId, "xxx"); +// db.insertMember(newerId, "wuzirui"); +// assertEqual(6, db.getTableCount("IsMember"), db.getTableCount("IsMember")); +// list = db.queryMembersBySession(newerId); +// assertEqual(list.size(), 4, list.size()); +// assertEqual(list.at(0), "usera", list.at(0).toUtf8().data()); +// assertEqual(list.at(1), "userB", list.at(1).toUtf8().data()); +// assertEqual(list.at(2), "xxx", list.at(2).toUtf8().data()); +// assertEqual(list.at(3), "wuzirui", list.at(3).toUtf8().data()); + +// auto sslist = db.querySessionsByMember("wuzirui"); +// assertEqual(sslist.size(), 2); +// assertEqual(sslist.at(0), newId, sslist.at(0)); +// assertEqual(sslist.at(1), newerId, sslist.at(1)); } void insertMessage() { - int currentTextNum = db.getTableCount("Message"); - assertEqual(currentTextNum, 0); - auto list = db.getMessageListBySessionID(2); - int currentTextId = list.size(); - assertEqual(currentTextId, 0); - db.insertNewMessage(db.getTableCount("Session"), - "wuzirui", ("This is a text, rand = %d" - + QString::number(rand())).toUtf8().data(), - "{\"hasMentionedInfo\": \"false\"}"); - assertEqual(db.getTableCount("Message"), - currentTextNum + 1, - db.getTableCount("Message") - << " != " << currentTextNum + 1); - db.insertNewMessage(1, "xiaoming", "fixed text", "{}"); - db.insertNewMessage(2, "wuzirui", "fixed text 2", "{}"); - testlog("Inserted 3 messages"); - list = db.getMessageListBySessionID(2); - assertEqual(2, list.size(), "a = " << 2 << ", b = " << list.size()); +// int currentTextNum = db.getTableCount("Message"); +// assertEqual(currentTextNum, 0); +// auto list = db.getMessageListBySessionID(2); +// int currentTextId = list.size(); +// assertEqual(currentTextId, 0); +// db.insertNewMessage(db.getTableCount("Session"), +// "wuzirui", ("This is a text, rand = %d" +// + QString::number(rand())).toUtf8().data(), +// "{\"hasMentionedInfo\": \"false\"}"); +// assertEqual(db.getTableCount("Message"), +// currentTextNum + 1, +// db.getTableCount("Message") +// << " != " << currentTextNum + 1); +// db.insertNewMessage(1, "xiaoming", "fixed text", "{}"); +// db.insertNewMessage(2, "wuzirui", "fixed text 2", "{}"); +// testlog("Inserted 3 messages"); +// list = db.getMessageListBySessionID(2); +// assertEqual(2, list.size(), "a = " << 2 << ", b = " << list.size()); } @@ -410,8 +411,6 @@ CASE(MessageForwardTest) { json["Body"] = body; // auto response = op.newMessageResponse(json); - - } void execute() { @@ -423,3 +422,34 @@ void execute() { } ENDSUITE(Functional) + +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits) { + QRegExp reg("@\\[((?:[^ ,\\,])+),[ ]*((?:[^ ,\\,])+)(?:,[ ]*((?:[^ ,\\,])*))?\\]"); + int pos = 0, initial = authors.size(); + while ((pos = reg.indexIn(raw, pos)) != -1) { + authors.append(reg.cap(1)); + repos.append(reg.cap(2)); + commits.append(reg.cap(3) == "" ? "master" : reg.cap(3)); + pos += reg.matchedLength(); + } + return authors.size() - initial; +} + +TESTSUITE(reg) + +CASE(REG_Repo) { + QList authors, repos, commits; + int ret = captureGitRepo("a message with a gitee @[jasonliu233,zhishigongcheng, master] repo", authors, repos, commits); + assertEqual(ret, 1, ret); + testlog("Pattern recognized: author = %s, repo = %s, commit = %s", authors[0].toUtf8().data(), + repos[0].toUtf8().data(), commits[0].toUtf8().data()); + assertEqual(authors[0], "jasonliu233"); + assertEqual(repos[0], "zhishigongcheng"); + assertEqual(commits[0], "master"); +} + + +void execute() override { + EXE(REG_Repo) +} +ENDSUITE(reg) diff --git a/Server/usermodel.cpp b/Server/usermodel.cpp index bf3f1543dd1aed49e2a84877e8eadf21a0f14fe7..0286b012ab29699b69067342745270b77d8923a7 100644 --- a/Server/usermodel.cpp +++ b/Server/usermodel.cpp @@ -1,17 +1,17 @@ #include "usermodel.h" -UserModel::UserModel(QObject *parent) : QObject(parent) +UserModel::UserModel() { - + profile["signiture"] = "Nop"; } -OfflineUserModel::OfflineUserModel(QString Username, QObject *parent) :QObject (parent) +OfflineUserModel::OfflineUserModel(QString Username) { username = Username; } -OnlineUserModel::OnlineUserModel(QJsonObject &json, QObject *parent) : QObject (parent) +OnlineUserModel::OnlineUserModel(QJsonObject &json) { loadBasicInfoFromJson(json); } @@ -23,8 +23,7 @@ void OnlineUserModel::loadBasicInfoFromJson(QJsonObject &json) { } -OnlineUserModel::OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent) : - UserModel(parent) +OnlineUserModel::OnlineUserModel(QString usrname, QString nick, QJsonObject json) { username = usrname; nickname = nick; @@ -43,6 +42,7 @@ QJsonObject OnlineUserModel::generateUserModelJson() const { QJsonObject OfflineUserModel::generateUserModelJson() const { QJsonObject json; + json["MsgType"] = "UserData"; json["Username"] = username; json["Nickname"] = nickname; json["Profile"] = profile; diff --git a/Server/usermodel.h b/Server/usermodel.h index ccb7ab9ce1a89949e47833aae52e30afa3012b77..1295d5dc6c55a956de6b215c68ec6a82f2adc874 100644 --- a/Server/usermodel.h +++ b/Server/usermodel.h @@ -10,7 +10,7 @@ class UserModel : virtual public QObject { Q_OBJECT public: - UserModel(QObject *parent = nullptr); + UserModel(); enum class Type { Offline, Online, None}; virtual Type getType() const { return Type::None; } const QString& getUsername() const { return username; } @@ -24,14 +24,14 @@ protected: QJsonObject profile; }; -class OfflineUserModel : virtual public UserModel, virtual public QObject +class OfflineUserModel : public UserModel { Q_OBJECT public: - OfflineUserModel(QString Username, QObject *parent = nullptr); + OfflineUserModel(QString Username); Type getType() const { return Type::Offline; } void setNickname(QString nname) { nickname = nname; } - void setSigniture(QString sig) { profile["Signiture"] = sig; } + void setSigniture(QString sig) { profile["signiture"] = sig; } QJsonObject generateUserModelJson() const; @@ -41,15 +41,15 @@ signals: }; -class OnlineUserModel : virtual public UserModel, virtual public QObject +class OnlineUserModel : public UserModel { Q_OBJECT public: - OnlineUserModel(QJsonObject &json, QObject *parent = nullptr); - OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent = nullptr); + OnlineUserModel(QJsonObject &json); + OnlineUserModel(QString usrname, QString nick, QJsonObject json); Type getType() const { return Type::Online; } const QString& getNickname() const { return nickname; } - const QString getSigniture() const { return profile["Signiture"].toString(); } + const QString getSigniture() const { return profile["signiture"].toString(); } QJsonObject generateUserModelJson() const; signals: diff --git a/Server/widget.cpp b/Server/widget.cpp index c8dafd47394642c21c4adde15b459f1eead29aea..f145ac6da3fd2e5ad5ff54000ee5542aefb694c2 100644 --- a/Server/widget.cpp +++ b/Server/widget.cpp @@ -14,6 +14,8 @@ Widget::Widget(QWidget *parent) //widget接受来自server的信息,并进行打印 connect(&sever, &Sever::linkMsg,this, &Widget::printLink); connect(&sever, &Sever::sendMsg,this, &Widget::printMsg); + connect(&sever, &Sever::offLine,this,&Widget::setOffline); + //socket首次连接之后设置handle connect(&sever, &Sever::sendChannel,this,&Widget::setChannel); @@ -21,59 +23,62 @@ Widget::Widget(QWidget *parent) connect(this,&Widget::pushIP,&sever, &Sever::setIP); connect(&(DatabaseOperation::Singleton()), &DatabaseOperation::signal_DB_ready, this, &Widget::load_Users); + + connect(&(Operations::Singleton ()),&Operations::newMessage,this, &Widget::getMessageTargetandContent); + } Widget::~Widget() { + DatabaseOperation::Singleton().closeDB(); delete ui; - - } -void Widget::printLink(QString str, int type) +void Widget::printLink(QString str) { - if(type==1) - { - ui->listWidget->addItem (str); - ui->listWidget->setCurrentRow (ui->listWidget->count ()-1); - } - else - { - ui->listWidget_2->addItem (str); - ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); - } - + ui->listWidget_2->addItem (str); + ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); } void Widget::printMsg(QList list, int handle) { + //针对于regist、login、search请求仅回发单个socket qDebug() << "in printMsg!"; - for(int i=0;iwrite(send2.data ()); + array.append(list[i]); } + Package["MsgList"] = array; + + QJsonDocument send1 = QJsonDocument(Package); + QByteArray send2 = send1.toJson (); + + sever.clientMap[handle]->write(send2); + + } void Widget::on_btnSend_clicked() { - //发送功能实现,点对点 - int channelName = ui->comboBox->currentText ().toUInt (); - QByteArray sendText = ui->teSend->toPlainText ().toUtf8 (); - //通过handle键取到值 - sever.clientMap[channelName]->write (sendText); + qDebug() << "not implemented Widget::on_btnSend_clicked"; +// //发送功能实现,点对点 +// int channelName = ui->comboBox->currentText ().toUInt (); +// QByteArray sendText = ui->teSend->toPlainText ().toUtf8 (); +// //通过handle键取到值 +// sever.clientMap[channelName]->write (sendText); } void Widget::on_btnRadio_clicked() { - //广播功能实现,点对多点 - QMap::iterator it; - for ( it = sever.clientMap.begin(); it != sever.clientMap.end(); ++it ) - { - it.value ()->write (ui->teSend->toPlainText ().toUtf8 ()); - } + qDebug() << "not implemented Widget::on_btnRadio_clicked"; +// //广播功能实现,点对多点 +// QMap::iterator it; +// for ( it = sever.clientMap.begin(); it != sever.clientMap.end(); ++it ) +// { +// it.value ()->write (ui->teSend->toPlainText ().toUtf8 ()); +// } } void Widget::setChannel(int channel) @@ -94,6 +99,26 @@ void Widget::on_btnSetServer_clicked() } +void Widget::setOffline(int handle) +{ + //下线功能,非常重要!!! + int index = ui->comboBox->findText(QString::number (handle)); + if(index != -1 ) + ui->comboBox->setItemText (index, "disconnected."); + QString str = sever.clientMap[handle]->peerAddress ().toString ()+"断开连接!"; + ui->listWidget_2->addItem (str); + ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); + + sever.clientMap.remove (handle); + //删除usertohandle的表格 + for(QMap >::iterator it1 = sever.userToHandle.begin();it1!=sever.userToHandle.end ();it1++) + { + it1.value ().removeAll (handle); + + } + qDebug() << sever.userToHandle; + +} void Widget::load_Users() { auto& db = DatabaseOperation::Singleton(); auto list = db.findAllUsers(); @@ -101,3 +126,32 @@ void Widget::load_Users() { this->ui->userWidgets->addItem(list[i]->getNickname() + " @" + list[i]->getUsername()); } } + +void Widget::getMessageTargetandContent(int sessionID, QJsonObject msg) +{ + + auto& db = DatabaseOperation::Singleton(); + QList sessionList = db.queryMembersBySession (sessionID); + + QJsonDocument send1 = QJsonDocument(msg); + QByteArray send2 = send1.toJson (); + + //所有会话中的成员 + for(int i=0;i>::iterator it1 = sever.userToHandle.begin();it1!=sever.userToHandle.end ();it1++) { + if(it1.key ()==sessionList[i]) { + qDebug()<< "找到相同user名"; + if(it1.value ().size ()==0) + break;//当前成员没有终端登陆 + for(int j=0;jwrite (send2.data ()); + + } + break; + } + } + } + + +} diff --git a/Server/widget.h b/Server/widget.h index 9e5dc9895c6a214d65e39b144defab6108581a49..8cb6b522cf17dd59c0221ac224fd9b5aa5c9dddc 100644 --- a/Server/widget.h +++ b/Server/widget.h @@ -19,8 +19,8 @@ public: private slots: // void on_pushButton_3_clicked() {} - void printLink(QString, int); //收到由server发来窗口的信号,并且打印到文本框 - void printMsg(QList,int); + void printLink(QString); //收到由server发来窗口的信号,并且打印到文本框 + void printMsg(QList, int); void on_btnSend_clicked(); @@ -30,8 +30,10 @@ private slots: void on_btnSetServer_clicked(); + void setOffline(int); void load_Users(); + void getMessageTargetandContent(int, QJsonObject); signals: diff --git a/Server/widget.ui b/Server/widget.ui index c9d3bec88f8616507c3536b69aa11a7340e47559..a3870c7da275cda661bc3593eb5c9fa5a1879618 100644 --- a/Server/widget.ui +++ b/Server/widget.ui @@ -169,7 +169,7 @@ p, li { white-space: pre-wrap; } 770 640 401 - 251 + 221 diff --git a/gitTreeFunction/gitTreeFunction.pro b/gitTreeFunction/gitTreeFunction.pro deleted file mode 100644 index b695efb6826519086829e7609a364b4a071f96ac..0000000000000000000000000000000000000000 --- a/gitTreeFunction/gitTreeFunction.pro +++ /dev/null @@ -1,31 +0,0 @@ -QT += core gui network - -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets - -CONFIG += c++11 - -# The following define makes your compiler emit warnings if you use -# any Qt feature that has been marked deprecated (the exact warnings -# depend on your compiler). Please consult the documentation of the -# deprecated API in order to know how to port your code away from it. -DEFINES += QT_DEPRECATED_WARNINGS - -# You can also make your code fail to compile if it uses deprecated APIs. -# In order to do so, uncomment the following line. -# You can also select to disable deprecated APIs only up to a certain version of Qt. -#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - -SOURCES += \ - main.cpp \ - widget.cpp - -HEADERS += \ - widget.h - -FORMS += \ - widget.ui - -# Default rules for deployment. -qnx: target.path = /tmp/$${TARGET}/bin -else: unix:!android: target.path = /opt/$${TARGET}/bin -!isEmpty(target.path): INSTALLS += target diff --git a/gitTreeFunction/main.cpp b/gitTreeFunction/main.cpp deleted file mode 100644 index b0a4ec26478f6b9aba3e1747ec464ea0c26dd5b9..0000000000000000000000000000000000000000 --- a/gitTreeFunction/main.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "widget.h" - -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - Widget w; - w.show(); - return a.exec(); -} diff --git a/gitTreeFunction/widget.cpp b/gitTreeFunction/widget.cpp deleted file mode 100644 index 92ea075d467e3dc1a07f8901cefd0f86e31831d4..0000000000000000000000000000000000000000 --- a/gitTreeFunction/widget.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "widget.h" -#include "ui_widget.h" -#include -#include -#include -#include -#include -#include - -Widget::Widget(QWidget *parent) - : QWidget(parent) - , ui(new Ui::Widget) -{ - ui->setupUi(this); - - connect (ui->listWidget, &QListWidget::itemDoubleClicked, this, &Widget::showContents); -} - -Widget::~Widget() -{ - delete ui; - -} - - -void Widget::on_pushButton_clicked() -{ - QByteArray file = get(ui->lineEdit->text ()); - - QJsonDocument newjson = QJsonDocument::fromJson(file); - QJsonObject jsonObject = newjson.object (); - - arrayValue = jsonObject.value(QStringLiteral("tree")); - int length = 0; - if(arrayValue.isArray ()) - { - QJsonArray array = arrayValue.toArray(); - length = array.size (); - for(int i=0;ilistWidget->addItem (icon["path"].toString ()); - } - } - -} - -void Widget::showContents(QListWidgetItem * nowItem) -{ - - - if(arrayValue.isArray ()) - { - QJsonArray array = arrayValue.toArray(); - for(int i=0;itext ()) - { - QByteArray content = get(icon["url"].toString ()); - QJsonDocument newjson = QJsonDocument::fromJson(content); - QJsonObject jsonObject = newjson.object (); - ui->textEdit->setText ( QByteArray::fromBase64(jsonObject["content"].toString ().toUtf8 ())); - - } - - } - } -} - -// git commit try at: https://gitee.com/api/v5/repos/jasonliu233/gitstudy/commits/master -// git tree at: https://gitee.com/api/v5/repos/jasonliu233/zhishigongcheng/git/trees/master - diff --git a/gitTreeFunction/widget.h b/gitTreeFunction/widget.h deleted file mode 100644 index bc327382bfef6e1cf07702ce6f4975b17634c97f..0000000000000000000000000000000000000000 --- a/gitTreeFunction/widget.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE -namespace Ui { class Widget; } -QT_END_NAMESPACE - -class Widget : public QWidget -{ - Q_OBJECT - -public: - Widget(QWidget *parent = nullptr); - ~Widget(); - QByteArray get(const QString &str_url){ - - const QUrl url = QUrl::fromUserInput(str_url); - QNetworkRequest qnr(url); - QNetworkAccessManager qnam; - QNetworkReply *reply = qnam.get(qnr); - QEventLoop eventloop; - QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit); - eventloop.exec(QEventLoop::ExcludeUserInputEvents); - QByteArray reply_data = reply->readAll(); - reply->deleteLater(); - reply = nullptr; - return reply_data; - } - - -private slots: - void on_pushButton_clicked(); - void showContents(QListWidgetItem*); - -private: - Ui::Widget *ui; - QJsonValue arrayValue; -}; -#endif // WIDGET_H diff --git a/gitTreeFunction/widget.ui b/gitTreeFunction/widget.ui deleted file mode 100644 index fe2c8385505f5ba8d77bb902c663ae5a4a981a3b..0000000000000000000000000000000000000000 --- a/gitTreeFunction/widget.ui +++ /dev/null @@ -1,101 +0,0 @@ - - - Widget - - - - 0 - 0 - 1200 - 900 - - - - Widget - - - - - 120 - 20 - 921 - 61 - - - - - - - 1060 - 20 - 111 - 61 - - - - get! - - - - - - 20 - 20 - 91 - 51 - - - - URL - - - - - - 30 - 140 - 361 - 741 - - - - - - - 30 - 90 - 131 - 51 - - - - filename - - - - - - 440 - 140 - 741 - 741 - - - - - - - 440 - 80 - 181 - 61 - - - - content - - - - - - diff --git a/git_try_0827/git_try_0827.pro b/git_try_0827/git_try_0827.pro deleted file mode 100644 index b695efb6826519086829e7609a364b4a071f96ac..0000000000000000000000000000000000000000 --- a/git_try_0827/git_try_0827.pro +++ /dev/null @@ -1,31 +0,0 @@ -QT += core gui network - -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets - -CONFIG += c++11 - -# The following define makes your compiler emit warnings if you use -# any Qt feature that has been marked deprecated (the exact warnings -# depend on your compiler). Please consult the documentation of the -# deprecated API in order to know how to port your code away from it. -DEFINES += QT_DEPRECATED_WARNINGS - -# You can also make your code fail to compile if it uses deprecated APIs. -# In order to do so, uncomment the following line. -# You can also select to disable deprecated APIs only up to a certain version of Qt. -#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - -SOURCES += \ - main.cpp \ - widget.cpp - -HEADERS += \ - widget.h - -FORMS += \ - widget.ui - -# Default rules for deployment. -qnx: target.path = /tmp/$${TARGET}/bin -else: unix:!android: target.path = /opt/$${TARGET}/bin -!isEmpty(target.path): INSTALLS += target diff --git a/git_try_0827/main.cpp b/git_try_0827/main.cpp deleted file mode 100644 index b0a4ec26478f6b9aba3e1747ec464ea0c26dd5b9..0000000000000000000000000000000000000000 --- a/git_try_0827/main.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "widget.h" - -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - Widget w; - w.show(); - return a.exec(); -} diff --git a/git_try_0827/widget.cpp b/git_try_0827/widget.cpp deleted file mode 100644 index 63b8f3513e019244c9fff21b6aac64a4f5575a27..0000000000000000000000000000000000000000 --- a/git_try_0827/widget.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "widget.h" -#include "ui_widget.h" -#include -#include - -Widget::Widget(QWidget *parent) - : QWidget(parent) - , ui(new Ui::Widget) -{ - ui->setupUi(this); -} - -Widget::~Widget() -{ - delete ui; -} - - -void Widget::on_btnGet_clicked() -{ - QByteArray file = get(ui->lineEdit->text ()); - ui->textEdit->setText (file); - - QJsonDocument newjson = QJsonDocument::fromJson(file); - QJsonObject jsonObject = newjson.object (); - qDebug() << jsonObject["commit"].toObject ()["message"]; - -} diff --git a/git_try_0827/widget.h b/git_try_0827/widget.h deleted file mode 100644 index 31fa66c1b02b4e5bb9634ca26efb986725619158..0000000000000000000000000000000000000000 --- a/git_try_0827/widget.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE -namespace Ui { class Widget; } -QT_END_NAMESPACE - -class Widget : public QWidget -{ - Q_OBJECT - -public: - Widget(QWidget *parent = nullptr); - ~Widget(); - QByteArray get(const QString &str_url){ - - const QUrl url = QUrl::fromUserInput(str_url); - QNetworkRequest qnr(url); - QNetworkAccessManager qnam; - QNetworkReply *reply = qnam.get(qnr); - QEventLoop eventloop; - QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit); - eventloop.exec(QEventLoop::ExcludeUserInputEvents); - QByteArray reply_data = reply->readAll(); - reply->deleteLater(); - reply = nullptr; - return reply_data; - } - -private slots: - void on_btnGet_clicked(); - -private: - Ui::Widget *ui; -}; -#endif // WIDGET_H diff --git a/git_try_0827/widget.ui b/git_try_0827/widget.ui deleted file mode 100644 index 43a5c186e46a3de24824f746fa72ca24a5d38622..0000000000000000000000000000000000000000 --- a/git_try_0827/widget.ui +++ /dev/null @@ -1,78 +0,0 @@ - - - Widget - - - - 0 - 0 - 1200 - 900 - - - - Widget - - - - - 110 - 30 - 951 - 71 - - - - - - - 40 - 20 - 151 - 81 - - - - URL - - - - - - 1080 - 30 - 111 - 71 - - - - get! - - - - - - 30 - 170 - 1151 - 701 - - - - - - - 40 - 110 - 171 - 61 - - - - JSON file - - - - - - diff --git a/tcpsever/handlesignal.cpp b/tcpsever/handlesignal.cpp deleted file mode 100644 index bba8f07993e75cfabd4558d01903b0b3034b5aec..0000000000000000000000000000000000000000 --- a/tcpsever/handlesignal.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "handlesignal.h" - -handleSignal::handleSignal(QObject *parent) : QObject(parent) -{ - -} - -handleSignal::handleSignal(int handle) -{ - emit handleSignal::sendSignal (handle); -} - -void handleSignal::aaa(int handle) -{ - emit handleSignal::sendSignal (handle); -} diff --git a/tcpsever/handlesignal.h b/tcpsever/handlesignal.h deleted file mode 100644 index 111256e98177cf04ec4aa995b84c0f4a5b51b476..0000000000000000000000000000000000000000 --- a/tcpsever/handlesignal.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef HANDLESIGNAL_H -#define HANDLESIGNAL_H - -#include - -class handleSignal : public QObject -{ - Q_OBJECT -public: - explicit handleSignal(QObject *parent = nullptr); - handleSignal(int); - void aaa(int); - -signals: - void sendSignal(int); -}; - -#endif // HANDLESIGNAL_H diff --git a/tcpsever/main.cpp b/tcpsever/main.cpp deleted file mode 100644 index c3efeb46c6278c0805a7e7764d78bd6bf01eea76..0000000000000000000000000000000000000000 --- a/tcpsever/main.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "widget.h" - -#include - -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - Widget w; - w.show(); - return a.exec(); -} diff --git a/tcpsever/sever.cpp b/tcpsever/sever.cpp deleted file mode 100644 index 1a2edab368b15aff135286fae8d9aa39ccb8ff13..0000000000000000000000000000000000000000 --- a/tcpsever/sever.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "sever.h" -#include -#include"handlesignal.h" - -Sever::Sever(QObject *parent) : QTcpServer (parent) -{ - - //开启端口服务 - - listen(QHostAddress("172.20.10.8") ,8888); -} - -void Sever::incomingConnection(qintptr handle) -{ - - qDebug()<<"产生了新连接!!!"; - //重写产生新连接 - QTcpSocket *socket = new QTcpSocket(this); - socket->setSocketDescriptor (handle); - qDebug()<< handle; - - - clientMap.insert (handle,socket); - - handleSignal *newHandle = new handleSignal(handle); - - connect(newHandle, &handleSignal::sendSignal, this,&Sever::receiveMessage); - connect (socket, &QTcpSocket::readyRead, [=](){ - newHandle->aaa(handle); - }); - - - emit sendChannel (handle); - - emit sendMsg (socket->peerAddress ().toString ()+"上线了", 2); -} - - -void Sever::receiveMessage(int handle) -{ - qDebug()<<"in receive message!"; - - QMap::iterator it = clientMap.find (handle); - QString receiveMes = it.value ()->readAll ().data (); - - emit sendMsg (receiveMes, 1); -} diff --git a/tcpsever/sever.h b/tcpsever/sever.h deleted file mode 100644 index 2685d239aa90531098947c7ee4cac5b5cfc5b8e6..0000000000000000000000000000000000000000 --- a/tcpsever/sever.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef SEVER_H -#define SEVER_H - -#include -#include -#include -#include -class Sever : public QTcpServer -{ - Q_OBJECT -public: - explicit Sever(QObject *parent = nullptr); - - QMap clientMap; - -private: - QTcpSocket *sock; - void incomingConnection(qintptr handle); - void receiveMessage(qintptr); - - -signals: - void sendMsg(QString, int); //将tcp_server收到的信息作为信号发送给mianwindow - void ready_Read(qintptr); - void sendChannel(int); -}; - -#endif // SEVER_H diff --git a/tcpsever/tcpsever.pro b/tcpsever/tcpsever.pro deleted file mode 100644 index fbf370b68503d6dc7906bdb8194e6d36bdb106e7..0000000000000000000000000000000000000000 --- a/tcpsever/tcpsever.pro +++ /dev/null @@ -1,28 +0,0 @@ -QT += core gui network - -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets - -CONFIG += c++11 - -# You can make your code fail to compile if it uses deprecated APIs. -# In order to do so, uncomment the following line. -#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - -SOURCES += \ - handlesignal.cpp \ - main.cpp \ - sever.cpp \ - widget.cpp - -HEADERS += \ - handlesignal.h \ - sever.h \ - widget.h - -FORMS += \ - widget.ui - -# Default rules for deployment. -qnx: target.path = /tmp/$${TARGET}/bin -else: unix:!android: target.path = /opt/$${TARGET}/bin -!isEmpty(target.path): INSTALLS += target diff --git a/tcpsever/widget.cpp b/tcpsever/widget.cpp deleted file mode 100644 index 1b17214da31b8b73a2ee548fc72f3fb8758ef0cf..0000000000000000000000000000000000000000 --- a/tcpsever/widget.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "widget.h" -#include "ui_widget.h" - -Widget::Widget(QWidget *parent) - : QWidget(parent) - , ui(new Ui::Widget) -{ - ui->setupUi(this); - - connect(&sever, &Sever::sendMsg,this, &Widget::printMes); - connect(&sever, &Sever::sendChannel,this,&Widget::setChannel); - -} - -Widget::~Widget() -{ - delete ui; - - -} - -void Widget::printMes(QString str, int type) -{ - if(type==1) - { - ui->listWidget->addItem (str); - ui->listWidget->setCurrentRow (ui->listWidget->count ()-1); - } - else - { - ui->listWidget_2->addItem (str); - ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); - } - -} - -void Widget::on_btnSend_clicked() -{ - int channelName = ui->comboBox->currentText ().toUInt (); - QByteArray sendText = ui->teSend->toPlainText ().toUtf8 (); - - sever.clientMap[channelName]->write (sendText); -} - -void Widget::on_btnRadio_clicked() -{ - QMap::iterator it; - for ( it = sever.clientMap.begin(); it != sever.clientMap.end(); ++it ) - { - it.value ()->write (ui->teSend->toPlainText ().toUtf8 ()); - } -} - -void Widget::setChannel(int channel) -{ - qDebug()<<"setcha"; - if(ui->comboBox->findText(QString::number (channel)) == -1) - qDebug()<comboBox->addItem (QString::number (channel)); -} - - diff --git a/tcpsever/widget.h b/tcpsever/widget.h deleted file mode 100644 index d9851125200d9f74caa3aae48e0b8f01d523bab5..0000000000000000000000000000000000000000 --- a/tcpsever/widget.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include "sever.h" - -QT_BEGIN_NAMESPACE -namespace Ui { class Widget; } -QT_END_NAMESPACE - -class Widget : public QWidget -{ - Q_OBJECT - -public: - Widget(QWidget *parent = nullptr); - ~Widget(); - -private slots: - void on_pushButton_3_clicked(); - void printMes(QString, int); //收到由server发来窗口的信号,并且打印到文本框 - - void on_btnSend_clicked(); - - void on_btnRadio_clicked(); - - void setChannel(int); - - void on_btnSetServer_clicked(); - -private: - Ui::Widget *ui; - Sever sever; //实例化一个sever对象 -}; -#endif // WIDGET_H diff --git a/tcpsever/widget.ui b/tcpsever/widget.ui deleted file mode 100644 index c6d03914c01637543305447c934e039acf8b850d..0000000000000000000000000000000000000000 --- a/tcpsever/widget.ui +++ /dev/null @@ -1,169 +0,0 @@ - - - Widget - - - - 0 - 0 - 1200 - 900 - - - - Widget - - - - - 1040 - 40 - 121 - 61 - - - - 开启端口 - - - - - - 30 - 30 - 631 - 71 - - - - 请输入本机ip地址 - - - - - - 700 - 30 - 311 - 71 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'SimSun'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'SimSun';">8888</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'SimSun';"><br /></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'SimSun';"><br /></p></body></html> - - - - - - 40 - 580 - 541 - 281 - - - - - - - 610 - 610 - 131 - 81 - - - - 广播 - - - - - - 610 - 750 - 131 - 81 - - - - 发送 - - - - - - 770 - 170 - 401 - 691 - - - - - - - 40 - 170 - 671 - 311 - - - - - - - 780 - 110 - 101 - 41 - - - - 接收 - - - - - - 60 - 510 - 291 - 41 - - - - 发送(选择客户端) - - - - - - 350 - 500 - 381 - 71 - - - - - - - 60 - 120 - 161 - 41 - - - - 上线信息 - - - - - -