1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

detect URLs and show them as hyperlink

This commit is contained in:
krepa098 2014-09-10 16:03:53 +02:00 committed by Tux3 / Mlkj / !Lev.uXFMLA
parent 5aa5e266b2
commit 1b4afcb937
3 changed files with 38 additions and 5 deletions

View File

@ -19,14 +19,21 @@
#include <QAbstractTextDocumentLayout>
#include <QMessageBox>
#include <QScrollBar>
#include <QDesktopServices>
ChatAreaWidget::ChatAreaWidget(QWidget *parent) :
QTextEdit(parent)
QTextBrowser(parent)
{
setReadOnly(true);
viewport()->setCursor(Qt::ArrowCursor);
setContextMenuPolicy(Qt::CustomContextMenu);
setUndoRedoEnabled(false);
setOpenExternalLinks(false);
setOpenLinks(false);
setAcceptRichText(false);
connect(this, &ChatAreaWidget::anchorClicked, this, &ChatAreaWidget::onAnchorClicked);
}
ChatAreaWidget::~ChatAreaWidget()
@ -67,6 +74,11 @@ void ChatAreaWidget::mouseReleaseEvent(QMouseEvent * event)
}
}
void ChatAreaWidget::onAnchorClicked(const QUrl &url)
{
QDesktopServices::openUrl(url);
}
void ChatAreaWidget::insertMessage(ChatAction *msgAction)
{
if (msgAction == nullptr)

View File

@ -17,12 +17,12 @@
#ifndef CHATAREAWIDGET_H
#define CHATAREAWIDGET_H
#include <QTextEdit>
#include <QTextBrowser>
#include <QList>
class ChatAction;
class ChatAreaWidget : public QTextEdit
class ChatAreaWidget : public QTextBrowser
{
Q_OBJECT
public:
@ -36,6 +36,9 @@ signals:
protected:
void mouseReleaseEvent(QMouseEvent * event);
public slots:
void onAnchorClicked(const QUrl& url);
private:
QList<ChatAction*> messages;
bool lockSliderToBottom;

View File

@ -22,7 +22,7 @@
QString ChatAction::toHtmlChars(const QString &str)
{
static QList<QPair<QString, QString>> replaceList = {{"&","&amp;"}, {" ","&nbsp;"}, {">","&gt;"}, {"<","&lt;"}};
static QList<QPair<QString, QString>> replaceList = {{"&","&amp;"}, {">","&gt;"}, {"<","&lt;"}};
QString res = str;
for (auto &it : replaceList)
@ -71,6 +71,24 @@ MessageAction::MessageAction(const QString &author, const QString &message, cons
{
QString message_ = SmileyPack::getInstance().smileyfied(toHtmlChars(message));
// detect urls
QRegExp exp("(www\\.|http[s]?:\\/\\/|ftp:\\/\\/)\\S+");
int offset = 0;
while ((offset = exp.indexIn(message_, offset)) != -1)
{
QString url = exp.cap();
// add scheme if not specified
if (exp.cap(1) == "www.")
url.prepend("http://");
QString htmledUrl = QString("<a href=\"%1\">%1</a>").arg(url);
message_.replace(offset, exp.cap().length(), htmledUrl);
offset += htmledUrl.length();
}
// detect text quotes
QStringList messageLines = message_.split("\n");
message_ = "";
for (QString& s : messageLines)