Simple replacements for Qt 6

QStringRef -> QStringView
QTextCursor constructor accepts a QTextDocument only
Some headers are moved, so paths are removed
QMatrix -> QTransform
Methods returning qsizetype are wrapped to int()s to allow compiler to deduce the type
This commit is contained in:
Ilya Fedin 2021-10-19 16:10:47 +04:00 committed by John Preston
parent 1651470638
commit 8e5d35229a
19 changed files with 122 additions and 121 deletions

View file

@ -80,13 +80,13 @@ bool UrlClickHandler::IsSuspicious(const QString &url) {
if (!match1.hasMatch()) { if (!match1.hasMatch()) {
return false; return false;
} }
const auto domain = match1.capturedRef(3); const auto domain = match1.capturedView(3);
static const auto Check2 = QRegularExpression("^(.*)\\.[a-zA-Z]+$"); static const auto Check2 = QRegularExpression("^(.*)\\.[a-zA-Z]+$");
const auto match2 = Check2.match(domain); const auto match2 = Check2.match(domain);
if (!match2.hasMatch()) { if (!match2.hasMatch()) {
return false; return false;
} }
const auto part = match2.capturedRef(1); const auto part = match2.capturedView(1);
static const auto Check3 = QRegularExpression("[^a-zA-Z0-9\\.\\-]"); static const auto Check3 = QRegularExpression("[^a-zA-Z0-9\\.\\-]");
return Check3.match(part).hasMatch(); return Check3.match(part).hasMatch();
} }
@ -100,11 +100,11 @@ QString UrlClickHandler::ShowEncoded(const QString &url) {
"^(https?://)?([^/#\\:]+)([/#\\:]|$)", "^(https?://)?([^/#\\:]+)([/#\\:]|$)",
QRegularExpression::CaseInsensitiveOption); QRegularExpression::CaseInsensitiveOption);
if (const auto match1 = Check1.match(url); match1.hasMatch()) { if (const auto match1 = Check1.match(url); match1.hasMatch()) {
const auto domain = match1.captured(1).append(match1.capturedRef(2)); const auto domain = match1.captured(1).append(match1.capturedView(2));
if (const auto u = QUrl(domain); u.isValid()) { if (const auto u = QUrl(domain); u.isValid()) {
return QString( return QString(
).append(QString::fromUtf8(u.toEncoded()) ).append(QString::fromUtf8(u.toEncoded())
).append(url.midRef(match1.capturedEnd(2))); ).append(QStringView(url).mid(match1.capturedEnd(2)));
} }
} }
return url; return url;

View file

@ -62,7 +62,7 @@ void NumbersAnimation::realSetText(QString text, int value) {
} }
auto oldSize = _digits.size(); auto oldSize = _digits.size();
auto animating = false; auto animating = false;
for (auto i = 0, size = _digits.size(); i != size; ++i) { for (auto i = 0, size = int(_digits.size()); i != size; ++i) {
auto &digit = _digits[i]; auto &digit = _digits[i];
digit.from = digit.to; digit.from = digit.to;
digit.fromWidth = digit.toWidth; digit.fromWidth = digit.toWidth;

View file

@ -118,7 +118,7 @@ private:
[[nodiscard]] inline EmojiPtr FromUrl(const QString &url) { [[nodiscard]] inline EmojiPtr FromUrl(const QString &url) {
auto start = qstr("emoji://e."); auto start = qstr("emoji://e.");
if (url.startsWith(start)) { if (url.startsWith(start)) {
return internal::ByIndex(url.midRef(start.size()).toInt()); // skip emoji://e. return internal::ByIndex(QStringView(url).mid(start.size()).toInt()); // skip emoji://e.
} }
return nullptr; return nullptr;
} }

View file

@ -15,7 +15,7 @@
#include <QtGui/QWindow> #include <QtGui/QWindow>
#include <QtGui/QOpenGLContext> #include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLFunctions> #include <QtGui/QOpenGLFunctions>
#include <QtWidgets/QOpenGLWidget> #include <QOpenGLWidget>
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include <QtGui/QGuiApplication> #include <QtGui/QGuiApplication>

View file

@ -9,8 +9,8 @@
#include "ui/gl/gl_math.h" #include "ui/gl/gl_math.h"
#include "ui/style/style_core.h" #include "ui/style/style_core.h"
#include <QtGui/QOpenGLBuffer> #include <QOpenGLBuffer>
#include <QtGui/QOpenGLShaderProgram> #include <QOpenGLShaderProgram>
class QOpenGLFunctions; class QOpenGLFunctions;

View file

@ -7,7 +7,7 @@
#pragma once #pragma once
#include <QtCore/QString> #include <QtCore/QString>
#include <QtGui/QOpenGLShader> #include <QOpenGLShader>
class OpenGLShaderProgram; class OpenGLShaderProgram;

View file

@ -13,7 +13,7 @@
#include <QtGui/QOpenGLContext> #include <QtGui/QOpenGLContext>
#include <QtGui/QWindow> #include <QtGui/QWindow>
#include <QtGui/QPaintEngine> #include <QtGui/QPaintEngine>
#include <QtWidgets/QOpenGLWidget> #include <QOpenGLWidget>
namespace Ui::GL { namespace Ui::GL {
namespace { namespace {

View file

@ -84,7 +84,7 @@ RadialBlob::RadialBlob(int n, float minScale, float minSpeed, float maxSpeed)
void RadialBlob::paint(Painter &p, const QBrush &brush, float outerScale) { void RadialBlob::paint(Painter &p, const QBrush &brush, float outerScale) {
auto path = QPainterPath(); auto path = QPainterPath();
auto m = QMatrix(); auto m = QTransform();
const auto scale = (_minScale + (1. - _minScale) * _scale) * outerScale; const auto scale = (_minScale + (1. - _minScale) * _scale) * outerScale;
if (scale == 0.) { if (scale == 0.) {

View file

@ -434,20 +434,18 @@ bool TranslucentWindowsSupported(QPoint globalPosition) {
if (::Platform::IsX11()) { if (::Platform::IsX11()) {
if (const auto native = QGuiApplication::platformNativeInterface()) { if (const auto native = QGuiApplication::platformNativeInterface()) {
if (const auto desktop = QApplication::desktop()) { if (const auto screen = base::QScreenNearestTo(globalPosition)) {
if (const auto screen = base::QScreenNearestTo(globalPosition)) { if (native->nativeResourceForScreen(QByteArray("compositingEnabled"), screen)) {
if (native->nativeResourceForScreen(QByteArray("compositingEnabled"), screen)) { return true;
return true;
}
const auto index = QGuiApplication::screens().indexOf(screen);
static auto WarnedAbout = base::flat_set<int>();
if (!WarnedAbout.contains(index)) {
WarnedAbout.emplace(index);
LOG(("WARNING: Compositing is disabled for screen index %1 (for position %2,%3)").arg(index).arg(globalPosition.x()).arg(globalPosition.y()));
}
} else {
LOG(("WARNING: Could not get screen for position %1,%2").arg(globalPosition.x()).arg(globalPosition.y()));
} }
const auto index = QGuiApplication::screens().indexOf(screen);
static auto WarnedAbout = base::flat_set<int>();
if (!WarnedAbout.contains(index)) {
WarnedAbout.emplace(index);
LOG(("WARNING: Compositing is disabled for screen index %1 (for position %2,%3)").arg(index).arg(globalPosition.x()).arg(globalPosition.y()));
}
} else {
LOG(("WARNING: Could not get screen for position %1,%2").arg(globalPosition.x()).arg(globalPosition.y()));
} }
} }
} }

View file

@ -15,7 +15,7 @@
#include <QtCore/QAbstractNativeEventFilter> #include <QtCore/QAbstractNativeEventFilter>
#include <QtGui/QWindow> #include <QtGui/QWindow>
#include <QtGui/QtEvents> #include <QtGui/QtEvents>
#include <QtWidgets/QOpenGLWidget> #include <QOpenGLWidget>
#include <Cocoa/Cocoa.h> #include <Cocoa/Cocoa.h>
@interface WindowObserver : NSObject { @interface WindowObserver : NSObject {

View file

@ -14,7 +14,9 @@
#include "base/platform/base_platform_info.h" #include "base/platform/base_platform_info.h"
#include <private/qfontengine_p.h> #include <private/qfontengine_p.h>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <private/qharfbuzz_p.h> #include <private/qharfbuzz_p.h>
#endif // Qt < 6.0.0
namespace Ui { namespace Ui {
namespace Text { namespace Text {
@ -161,7 +163,7 @@ QString textcmdStartLink(const QString &url) {
QString result; QString result;
result.reserve(url.size() + 4); result.reserve(url.size() + 4);
return result.append(TextCommand).append(QChar(TextCommandLinkText)).append(QChar(url.size())).append(url).append(TextCommand); return result.append(TextCommand).append(QChar(TextCommandLinkText)).append(QChar(int(url.size()))).append(url).append(TextCommand);
} }
QString textcmdStopLink() { QString textcmdStopLink() {
@ -2056,10 +2058,21 @@ private:
auto analysis = _parAnalysis.data() + (_localFrom - _parStart); auto analysis = _parAnalysis.data() + (_localFrom - _parStart);
{ {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QUnicodeTools::ScriptItemArray scriptItems;
QUnicodeTools::initScripts(_e->layoutData->string, &scriptItems);
for (int i = 0; i < scriptItems.length(); ++i) {
const auto &item = scriptItems.at(i);
int end = i < scriptItems.length() - 1 ? scriptItems.at(i + 1).position : length;
for (int j = item.position; j < end; ++j)
analysis[j].script = item.script;
}
#else // Qt >= 6.0.0
QVarLengthArray<uchar> scripts(length); QVarLengthArray<uchar> scripts(length);
QUnicodeTools::initScripts(string, length, scripts.data()); QUnicodeTools::initScripts(string, length, scripts.data());
for (int i = 0; i < length; ++i) for (int i = 0; i < length; ++i)
analysis[i].script = scripts.at(i); analysis[i].script = scripts.at(i);
#endif // Qt < 6.0.0
} }
blockIndex = _lineStartBlock; blockIndex = _lineStartBlock;
@ -2080,7 +2093,9 @@ private:
} else { } else {
analysis->flags = QScriptAnalysis::None; analysis->flags = QScriptAnalysis::None;
} }
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
analysis->script = hbscript_to_script(script_to_hbscript(analysis->script)); // retain the old behavior analysis->script = hbscript_to_script(script_to_hbscript(analysis->script)); // retain the old behavior
#endif // Qt < 6.0.0
++start; ++start;
++analysis; ++analysis;
} }
@ -3149,7 +3164,7 @@ void String::enumerateText(TextSelection selection, AppendPartCallback appendPar
auto rangeFrom = qMax(selection.from, lnkFrom); auto rangeFrom = qMax(selection.from, lnkFrom);
auto rangeTo = qMin(selection.to, blockFrom); auto rangeTo = qMin(selection.to, blockFrom);
if (rangeTo > rangeFrom) { // handle click handler if (rangeTo > rangeFrom) { // handle click handler
QStringRef r = _text.midRef(rangeFrom, rangeTo - rangeFrom); const auto r = QStringView(_text).mid(rangeFrom, rangeTo - rangeFrom);
if (lnkFrom != rangeFrom || blockFrom != rangeTo) { if (lnkFrom != rangeFrom || blockFrom != rangeTo) {
// Ignore links that are partially copied. // Ignore links that are partially copied.
clickHandlerFinishCallback(r, nullptr); clickHandlerFinishCallback(r, nullptr);
@ -3180,7 +3195,7 @@ void String::enumerateText(TextSelection selection, AppendPartCallback appendPar
auto rangeFrom = qMax(selection.from, blockFrom); auto rangeFrom = qMax(selection.from, blockFrom);
auto rangeTo = qMin(selection.to, uint16(blockFrom + countBlockLength(i, e))); auto rangeTo = qMin(selection.to, uint16(blockFrom + countBlockLength(i, e)));
if (rangeTo > rangeFrom) { if (rangeTo > rangeFrom) {
appendPartCallback(_text.midRef(rangeFrom, rangeTo - rangeFrom)); appendPartCallback(QStringView(_text).mid(rangeFrom, rangeTo - rangeFrom));
} }
} }
} }
@ -3243,7 +3258,7 @@ TextForMimeData String::toText(
insertEntity({ insertEntity({
tracker.type, tracker.type,
tracker.start, tracker.start,
result.rich.text.size() - tracker.start }); int(result.rich.text.size()) - tracker.start });
} else if ((newFlags & flag) && !(oldFlags & flag)) { } else if ((newFlags & flag) && !(oldFlags & flag)) {
tracker.start = result.rich.text.size(); tracker.start = result.rich.text.size();
} }
@ -3253,7 +3268,7 @@ TextForMimeData String::toText(
linkStart = result.rich.text.size(); linkStart = result.rich.text.size();
}; };
const auto clickHandlerFinishCallback = [&]( const auto clickHandlerFinishCallback = [&](
const QStringRef &inText, QStringView inText,
const ClickHandlerPtr &handler) { const ClickHandlerPtr &handler) {
if (!handler || (!composeExpanded && !composeEntities)) { if (!handler || (!composeExpanded && !composeEntities)) {
return; return;
@ -3262,7 +3277,7 @@ TextForMimeData String::toText(
const auto plainUrl = (entity.type == EntityType::Url) const auto plainUrl = (entity.type == EntityType::Url)
|| (entity.type == EntityType::Email); || (entity.type == EntityType::Email);
const auto full = plainUrl const auto full = plainUrl
? entity.data.midRef(0, entity.data.size()) ? QStringView(entity.data).mid(0, entity.data.size())
: inText; : inText;
const auto customTextLink = (entity.type == EntityType::CustomUrl); const auto customTextLink = (entity.type == EntityType::CustomUrl);
const auto internalLink = customTextLink const auto internalLink = customTextLink
@ -3280,11 +3295,11 @@ TextForMimeData String::toText(
insertEntity({ insertEntity({
entity.type, entity.type,
linkStart, linkStart,
(result.rich.text.size() - linkStart), int(result.rich.text.size() - linkStart),
plainUrl ? QString() : entity.data }); plainUrl ? QString() : entity.data });
} }
}; };
const auto appendPartCallback = [&](const QStringRef &part) { const auto appendPartCallback = [&](QStringView part) {
result.rich.text += part; result.rich.text += part;
if (composeExpanded) { if (composeExpanded) {
result.expanded += part; result.expanded += part;

View file

@ -1156,13 +1156,13 @@ const QRegularExpression &RegExpWordSplit() {
for (const auto &entity : urls) { for (const auto &entity : urls) {
const auto till = entity.offset() + entity.length(); const auto till = entity.offset() + entity.length();
if (till > offset) { if (till > offset) {
result.append(original.midRef(offset, till - offset)); result.append(QStringView(original).mid(offset, till - offset));
} }
result.append(qstr(" (")).append(entity.data()).append(')'); result.append(qstr(" (")).append(entity.data()).append(')');
offset = till; offset = till;
} }
if (original.size() > offset) { if (original.size() > offset) {
result.append(original.midRef(offset)); result.append(QStringView(original).mid(offset));
} }
return result; return result;
} }
@ -1619,10 +1619,10 @@ void ParseEntities(TextWithEntities &result, int32 flags, bool rich) {
auto mentionIgnore = false; auto mentionIgnore = false;
if (mHashtag.hasMatch()) { if (mHashtag.hasMatch()) {
if (!mHashtag.capturedRef(1).isEmpty()) { if (!mHashtag.capturedView(1).isEmpty()) {
++hashtagStart; ++hashtagStart;
} }
if (!mHashtag.capturedRef(2).isEmpty()) { if (!mHashtag.capturedView(2).isEmpty()) {
--hashtagEnd; --hashtagEnd;
} }
if (RegExpHashtagExclude().match( if (RegExpHashtagExclude().match(
@ -1633,10 +1633,10 @@ void ParseEntities(TextWithEntities &result, int32 flags, bool rich) {
} }
} }
while (mMention.hasMatch()) { while (mMention.hasMatch()) {
if (!mMention.capturedRef(1).isEmpty()) { if (!mMention.capturedView(1).isEmpty()) {
++mentionStart; ++mentionStart;
} }
if (!mMention.capturedRef(2).isEmpty()) { if (!mMention.capturedView(2).isEmpty()) {
--mentionEnd; --mentionEnd;
} }
if (!(start + mentionStart + 1)->isLetter() || !(start + mentionEnd - 1)->isLetterOrNumber()) { if (!(start + mentionStart + 1)->isLetter() || !(start + mentionEnd - 1)->isLetterOrNumber()) {
@ -1657,10 +1657,10 @@ void ParseEntities(TextWithEntities &result, int32 flags, bool rich) {
} }
} }
if (mBotCommand.hasMatch()) { if (mBotCommand.hasMatch()) {
if (!mBotCommand.capturedRef(1).isEmpty()) { if (!mBotCommand.capturedView(1).isEmpty()) {
++botCommandStart; ++botCommandStart;
} }
if (!mBotCommand.capturedRef(3).isEmpty()) { if (!mBotCommand.capturedView(3).isEmpty()) {
--botCommandEnd; --botCommandEnd;
} }
} }
@ -2019,16 +2019,16 @@ QString TagsTextMimeType() {
return QString::fromLatin1("application/x-td-field-text"); return QString::fromLatin1("application/x-td-field-text");
} }
bool IsMentionLink(const QStringRef &link) { bool IsMentionLink(QStringView link) {
return link.startsWith(kMentionTagStart); return link.startsWith(kMentionTagStart);
} }
[[nodiscard]] bool IsSeparateTag(const QStringRef &tag) { [[nodiscard]] bool IsSeparateTag(QStringView tag) {
return (tag == Ui::InputField::kTagCode) return (tag == Ui::InputField::kTagCode)
|| (tag == Ui::InputField::kTagPre); || (tag == Ui::InputField::kTagPre);
} }
QString JoinTag(const QVector<QStringRef> &list) { QString JoinTag(const QVector<QStringView> &list) {
if (list.isEmpty()) { if (list.isEmpty()) {
return QString(); return QString();
} }
@ -2039,7 +2039,7 @@ QString JoinTag(const QVector<QStringRef> &list) {
auto result = QString(); auto result = QString();
result.reserve(length); result.reserve(length);
result.append(list.front()); result.append(list.front());
for (auto i = 1, count = list.size(); i != count; ++i) { for (auto i = 1, count = int(list.size()); i != count; ++i) {
if (!IsSeparateTag(list[i])) { if (!IsSeparateTag(list[i])) {
result.append('|').append(list[i]); result.append('|').append(list[i]);
} }
@ -2051,8 +2051,8 @@ QString TagWithRemoved(const QString &tag, const QString &removed) {
if (tag == removed) { if (tag == removed) {
return QString(); return QString();
} }
auto list = tag.splitRef('|'); auto list = QStringView(tag).split('|');
list.erase(ranges::remove(list, removed.midRef(0)), list.end()); list.erase(ranges::remove(list, QStringView(removed).mid(0)), list.end());
return JoinTag(list); return JoinTag(list);
} }
@ -2060,8 +2060,8 @@ QString TagWithAdded(const QString &tag, const QString &added) {
if (tag.isEmpty() || tag == added) { if (tag.isEmpty() || tag == added) {
return added; return added;
} }
auto list = tag.splitRef('|'); auto list = QStringView(tag).split('|');
const auto ref = added.midRef(0); const auto ref = QStringView(added).mid(0);
if (list.contains(ref)) { if (list.contains(ref)) {
return tag; return tag;
} }
@ -2156,7 +2156,7 @@ EntitiesInText ConvertTextTagsToEntities(const TextWithTags::Tags &tags) {
if (IsMentionLink(nextState.link)) { if (IsMentionLink(nextState.link)) {
const auto match = qthelp::regex_match( const auto match = qthelp::regex_match(
"^(\\d+\\.\\d+)(/|$)", "^(\\d+\\.\\d+)(/|$)",
nextState.link.midRef(kMentionTagStart.size())); QStringView(nextState.link).mid(kMentionTagStart.size()));
if (match) { if (match) {
openType(EntityType::MentionName, match->captured(1)); openType(EntityType::MentionName, match->captured(1));
} }
@ -2173,7 +2173,7 @@ EntitiesInText ConvertTextTagsToEntities(const TextWithTags::Tags &tags) {
}; };
const auto stateForTag = [&](const QString &tag) { const auto stateForTag = [&](const QString &tag) {
auto result = State(); auto result = State();
const auto list = tag.splitRef('|'); const auto list = QStringView(tag).split('|');
for (const auto &single : list) { for (const auto &single : list) {
if (single == Ui::InputField::kTagBold) { if (single == Ui::InputField::kTagBold) {
result.set(EntityType::Bold); result.set(EntityType::Bold);

View file

@ -360,17 +360,9 @@ void ApplyServerCleaning(TextWithEntities &result);
inline const auto kMentionTagStart = qstr("mention://user."); inline const auto kMentionTagStart = qstr("mention://user.");
[[nodiscard]] bool IsMentionLink(const QStringRef &link); [[nodiscard]] bool IsMentionLink(QStringView link);
[[nodiscard]] inline bool IsMentionLink(const QString &link) { [[nodiscard]] bool IsSeparateTag(QStringView tag);
return IsMentionLink(link.midRef(0)); [[nodiscard]] QString JoinTag(const QVector<QStringView> &list);
}
[[nodiscard]] bool IsSeparateTag(const QStringRef &tag);
[[nodiscard]] inline bool IsSeparateTag(const QString &tag) {
return IsSeparateTag(tag.midRef(0));
}
[[nodiscard]] QString JoinTag(const QVector<QStringRef> &list);
[[nodiscard]] QString TagWithRemoved( [[nodiscard]] QString TagWithRemoved(
const QString &tag, const QString &tag,
const QString &removed); const QString &removed);

View file

@ -19,7 +19,7 @@ TextWithEntities WithSingleEntity(
EntityType type, EntityType type,
const QString &data = QString()) { const QString &data = QString()) {
auto result = TextWithEntities{ text }; auto result = TextWithEntities{ text };
result.entities.push_back({ type, 0, text.size(), data }); result.entities.push_back({ type, 0, int(text.size()), data });
return result; return result;
} }
@ -49,25 +49,25 @@ TextWithEntities RichLangValue(const QString &text) {
while (offset < text.size()) { while (offset < text.size()) {
const auto m = kStart.match(text, offset); const auto m = kStart.match(text, offset);
if (!m.hasMatch()) { if (!m.hasMatch()) {
result.text.append(text.midRef(offset)); result.text.append(QStringView(text).mid(offset));
break; break;
} }
const auto position = m.capturedStart(); const auto position = m.capturedStart();
const auto from = m.capturedEnd(); const auto from = m.capturedEnd();
const auto tag = m.capturedRef(); const auto tag = m.capturedView();
const auto till = text.indexOf(tag, from + 1); const auto till = text.indexOf(tag, from + 1);
if (till <= from) { if (till <= from) {
offset = from; offset = from;
continue; continue;
} }
if (position > offset) { if (position > offset) {
result.text.append(text.midRef(offset, position - offset)); result.text.append(QStringView(text).mid(offset, position - offset));
} }
const auto type = (tag == qstr("__")) const auto type = (tag == qstr("__"))
? EntityType::Italic ? EntityType::Italic
: EntityType::Bold; : EntityType::Bold;
result.entities.push_back({ type, result.text.size(), till - from }); result.entities.push_back({ type, int(result.text.size()), int(till - from) });
result.text.append(text.midRef(from, till - from)); result.text.append(QStringView(text).mid(from, till - from));
offset = till + tag.size(); offset = till + tag.size();
} }
return result; return result;

View file

@ -99,7 +99,7 @@ bool IsNewline(QChar ch) {
return (kNewlineChars.indexOf(ch) >= 0); return (kNewlineChars.indexOf(ch) >= 0);
} }
[[nodiscard]] bool IsValidMarkdownLink(const QStringRef &link) { [[nodiscard]] bool IsValidMarkdownLink(QStringView link) {
return (link.indexOf('.') >= 0) || (link.indexOf(':') >= 0); return (link.indexOf('.') >= 0) || (link.indexOf(':') >= 0);
} }
@ -124,21 +124,21 @@ bool IsNewline(QChar ch) {
return QString(); return QString();
} }
auto found = false; auto found = false;
for (const auto &single : existing.id.splitRef('|')) { for (const auto &single : QStringView(existing.id).split('|')) {
const auto normalized = (single == kTagPre.midRef(0)) const auto normalized = (single == QStringView(kTagPre).mid(0))
? kTagCode.midRef(0) ? QStringView(kTagCode).mid(0)
: single; : single;
if (checkingLink && IsValidMarkdownLink(single)) { if (checkingLink && IsValidMarkdownLink(single)) {
if (resultLink.isEmpty()) { if (resultLink.isEmpty()) {
resultLink = single.toString(); resultLink = single.toString();
found = true; found = true;
break; break;
} else if (resultLink.midRef(0) == single) { } else if (QStringView(resultLink).mid(0) == single) {
found = true; found = true;
break; break;
} }
return QString(); return QString();
} else if (!checkingLink && tag.midRef(0) == normalized) { } else if (!checkingLink && QStringView(tag).mid(0) == normalized) {
found = true; found = true;
break; break;
} }
@ -683,7 +683,8 @@ void RemoveDocumentTags(
not_null<QTextDocument*> document, not_null<QTextDocument*> document,
int from, int from,
int end) { int end) {
auto cursor = QTextCursor(document->docHandle(), from); auto cursor = QTextCursor(document);
cursor.setPosition(from);
cursor.setPosition(end, QTextCursor::KeepAnchor); cursor.setPosition(end, QTextCursor::KeepAnchor);
auto format = QTextCharFormat(); auto format = QTextCharFormat();
@ -700,7 +701,7 @@ QTextCharFormat PrepareTagFormat(
auto result = QTextCharFormat(); auto result = QTextCharFormat();
auto font = st.font; auto font = st.font;
auto color = std::optional<style::color>(); auto color = std::optional<style::color>();
const auto applyOne = [&](const QStringRef &tag) { const auto applyOne = [&](QStringView tag) {
if (IsValidMarkdownLink(tag)) { if (IsValidMarkdownLink(tag)) {
color = st::defaultTextPalette.linkFg; color = st::defaultTextPalette.linkFg;
} else if (tag == kTagBold) { } else if (tag == kTagBold) {
@ -716,7 +717,7 @@ QTextCharFormat PrepareTagFormat(
font = font->monospace(); font = font->monospace();
} }
}; };
for (const auto &tag : tag.splitRef('|')) { for (const auto &tag : QStringView(tag).split('|')) {
applyOne(tag); applyOne(tag);
} }
result.setFont(font); result.setFont(font);
@ -760,7 +761,7 @@ int ProcessInsertedTags(
applyNoTagFrom, applyNoTagFrom,
tagFrom); tagFrom);
} }
QTextCursor c(document->docHandle(), 0); QTextCursor c(document);
c.setPosition(tagFrom); c.setPosition(tagFrom);
c.setPosition(tagTo, QTextCursor::KeepAnchor); c.setPosition(tagTo, QTextCursor::KeepAnchor);
@ -1444,7 +1445,7 @@ void InputField::setExtendedContextMenu(
value value
) | rpl::start_with_next([=](auto pair) { ) | rpl::start_with_next([=](auto pair) {
auto &[menu, e] = pair; auto &[menu, e] = pair;
contextMenuEventInner(&e, std::move(menu)); contextMenuEventInner(e.get(), std::move(menu));
}, lifetime()); }, lifetime());
} }
@ -1493,14 +1494,14 @@ void InputField::setMaxLength(int length) {
if (_maxLength > 0) { if (_maxLength > 0) {
const auto document = _inner->document(); const auto document = _inner->document();
_correcting = true; _correcting = true;
QTextCursor(document->docHandle(), 0).joinPreviousEditBlock(); QTextCursor(document).joinPreviousEditBlock();
const auto guard = gsl::finally([&] { const auto guard = gsl::finally([&] {
_correcting = false; _correcting = false;
QTextCursor(document->docHandle(), 0).endEditBlock(); QTextCursor(document).endEditBlock();
handleContentsChanged(); handleContentsChanged();
}); });
auto cursor = QTextCursor(document->docHandle(), 0); auto cursor = QTextCursor(document);
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
chopByMaxLength(0, cursor.position()); chopByMaxLength(0, cursor.position());
} }
@ -2188,9 +2189,8 @@ void InputField::processFormatting(int insertPosition, int insertEnd) {
if (action.type != ActionType::Invalid) { if (action.type != ActionType::Invalid) {
PrepareFormattingOptimization(document); PrepareFormattingOptimization(document);
auto cursor = QTextCursor( auto cursor = QTextCursor(document);
document->docHandle(), cursor.setPosition(action.intervalStart);
action.intervalStart);
cursor.setPosition(action.intervalEnd, QTextCursor::KeepAnchor); cursor.setPosition(action.intervalEnd, QTextCursor::KeepAnchor);
if (action.type == ActionType::InsertEmoji) { if (action.type == ActionType::InsertEmoji) {
InsertEmojiAtCursor(cursor, action.emoji); InsertEmojiAtCursor(cursor, action.emoji);
@ -2258,7 +2258,7 @@ void InputField::onDocumentContentsChange(
// Qt bug workaround https://bugreports.qt.io/browse/QTBUG-49062 // Qt bug workaround https://bugreports.qt.io/browse/QTBUG-49062
if (!position) { if (!position) {
auto cursor = QTextCursor(document->docHandle(), 0); auto cursor = QTextCursor(document);
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
if (position + charsAdded > cursor.position()) { if (position + charsAdded > cursor.position()) {
const auto delta = position + charsAdded - cursor.position(); const auto delta = position + charsAdded - cursor.position();
@ -2277,10 +2277,10 @@ void InputField::onDocumentContentsChange(
: charsAdded; : charsAdded;
_correcting = true; _correcting = true;
QTextCursor(document->docHandle(), 0).joinPreviousEditBlock(); QTextCursor(document).joinPreviousEditBlock();
const auto guard = gsl::finally([&] { const auto guard = gsl::finally([&] {
_correcting = false; _correcting = false;
QTextCursor(document->docHandle(), 0).endEditBlock(); QTextCursor(document).endEditBlock();
handleContentsChanged(); handleContentsChanged();
const auto added = charsAdded - _emojiSurrogateAmount; const auto added = charsAdded - _emojiSurrogateAmount;
_documentContentsChanges.fire({position, charsRemoved, added}); _documentContentsChanges.fire({position, charsRemoved, added});
@ -2313,7 +2313,7 @@ void InputField::chopByMaxLength(int insertPosition, int insertLength) {
return; return;
} }
auto cursor = QTextCursor(document()->docHandle(), 0); auto cursor = QTextCursor(document());
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
const auto fullSize = cursor.position(); const auto fullSize = cursor.position();
const auto toRemove = fullSize - _maxLength; const auto toRemove = fullSize - _maxLength;
@ -2508,7 +2508,7 @@ void InputField::setTextWithTags(
_realInsertPosition = 0; _realInsertPosition = 0;
_realCharsAdded = textWithTags.text.size(); _realCharsAdded = textWithTags.text.size();
const auto document = _inner->document(); const auto document = _inner->document();
auto cursor = QTextCursor(document->docHandle(), 0); auto cursor = QTextCursor(document);
if (historyAction == HistoryAction::Clear) { if (historyAction == HistoryAction::Clear) {
document->setUndoRedoEnabled(false); document->setUndoRedoEnabled(false);
cursor.beginEditBlock(); cursor.beginEditBlock();
@ -2565,7 +2565,7 @@ TextWithTags InputField::getTextWithAppliedMarkdown() const {
auto from = 0; auto from = 0;
const auto addOriginalTextUpTill = [&](int offset) { const auto addOriginalTextUpTill = [&](int offset) {
if (offset > from) { if (offset > from) {
result.text.append(originalText.midRef(from, offset - from)); result.text.append(QStringView(originalText).mid(from, offset - from));
} }
}; };
auto link = links.begin(); auto link = links.begin();
@ -2621,7 +2621,7 @@ TextWithTags InputField::getTextWithAppliedMarkdown() const {
int(result.text.size()), int(result.text.size()),
entityLength, entityLength,
tag.tag }); tag.tag });
result.text.append(originalText.midRef( result.text.append(QStringView(originalText).mid(
entityStart, entityStart,
entityLength)); entityLength));
} }
@ -2896,7 +2896,8 @@ auto InputField::selectionEditLinkData(EditLinkSelection selection) const
}; };
const auto stateTagHasLink = [&](const State &state) { const auto stateTagHasLink = [&](const State &state) {
const auto tag = stateTag(state); const auto tag = stateTag(state);
return (tag == link) || tag.splitRef('|').contains(link.midRef(0)); return (tag == link) || QStringView(tag).split('|').contains(
QStringView(link).mid(0));
}; };
const auto stateStart = [&](const State &state) { const auto stateStart = [&](const State &state) {
return state.i.fragment().position(); return state.i.fragment().position();
@ -3104,9 +3105,9 @@ void InputField::commitInstantReplacement(
const auto currentTag = cursor.charFormat().property( const auto currentTag = cursor.charFormat().property(
kTagProperty kTagProperty
).toString(); ).toString();
const auto currentTags = currentTag.splitRef('|'); const auto currentTags = QStringView(currentTag).split('|');
if (currentTags.contains(kTagPre.midRef(0)) if (currentTags.contains(QStringView(kTagPre).mid(0))
|| currentTags.contains(kTagCode.midRef(0))) { || currentTags.contains(QStringView(kTagCode).mid(0))) {
return; return;
} }
} }
@ -3141,7 +3142,7 @@ bool InputField::commitMarkdownReplacement(
const QString &tag, const QString &tag,
const QString &edge) { const QString &edge) {
const auto end = [&] { const auto end = [&] {
auto cursor = QTextCursor(document()->docHandle(), 0); auto cursor = QTextCursor(document());
cursor.movePosition(QTextCursor::End); cursor.movePosition(QTextCursor::End);
return cursor.position(); return cursor.position();
}(); }();
@ -3155,7 +3156,7 @@ bool InputField::commitMarkdownReplacement(
const auto extended = getTextWithTagsPart( const auto extended = getTextWithTagsPart(
from - extendLeft, from - extendLeft,
till + extendRight).text; till + extendRight).text;
const auto outer = extended.midRef( const auto outer = QStringView(extended).mid(
extendLeft, extendLeft,
extended.size() - extendLeft - extendRight); extended.size() - extendLeft - extendRight);
if ((outer.size() <= 2 * edge.size()) if ((outer.size() <= 2 * edge.size())
@ -3251,8 +3252,7 @@ void InputField::addMarkdownTag(
int till, int till,
const QString &tag) { const QString &tag) {
const auto current = getTextWithTagsPart(from, till); const auto current = getTextWithTagsPart(from, till);
const auto currentLength = current.text.size(); const auto currentLength = int(current.text.size());
const auto tagRef = tag.midRef(0);
// #TODO Trim inserted tag, so that all newlines are left outside. // #TODO Trim inserted tag, so that all newlines are left outside.
auto tags = TagList(); auto tags = TagList();
@ -3290,7 +3290,6 @@ void InputField::removeMarkdownTag(
int till, int till,
const QString &tag) { const QString &tag) {
const auto current = getTextWithTagsPart(from, till); const auto current = getTextWithTagsPart(from, till);
const auto tagRef = tag.midRef(0);
auto tags = TagList(); auto tags = TagList();
for (const auto &existing : current.tags) { for (const auto &existing : current.tags) {
@ -3319,7 +3318,7 @@ void InputField::finishMarkdownTagChange(
_inner->setTextCursor(cursor); _inner->setTextCursor(cursor);
} }
bool InputField::IsValidMarkdownLink(const QStringRef &link) { bool InputField::IsValidMarkdownLink(QStringView link) {
return ::Ui::IsValidMarkdownLink(link); return ::Ui::IsValidMarkdownLink(link);
} }
@ -4180,7 +4179,7 @@ void NumberInput::correctValue(
QString newText; QString newText;
newText.reserve(now.size()); newText.reserve(now.size());
auto newPos = nowCursor; auto newPos = nowCursor;
for (auto i = 0, l = now.size(); i < l; ++i) { for (auto i = 0, l = int(now.size()); i < l; ++i) {
if (now.at(i).isDigit()) { if (now.at(i).isDigit()) {
newText.append(now.at(i)); newText.append(now.at(i));
} else if (i < nowCursor) { } else if (i < nowCursor) {
@ -4216,7 +4215,7 @@ void HexInput::correctValue(
QString newText; QString newText;
newText.reserve(now.size()); newText.reserve(now.size());
auto newPos = nowCursor; auto newPos = nowCursor;
for (auto i = 0, l = now.size(); i < l; ++i) { for (auto i = 0, l = int(now.size()); i < l; ++i) {
const auto ch = now[i]; const auto ch = now[i];
if ((ch >= '0' && ch <= '9') if ((ch >= '0' && ch <= '9')
|| (ch >= 'a' && ch <= 'f') || (ch >= 'a' && ch <= 'f')

View file

@ -242,7 +242,7 @@ public:
struct ExtendedContextMenu { struct ExtendedContextMenu {
QMenu *menu = nullptr; QMenu *menu = nullptr;
QContextMenuEvent event; std::shared_ptr<QContextMenuEvent> event;
}; };
void setAdditionalMargin(int margin); void setAdditionalMargin(int margin);
@ -256,10 +256,7 @@ public:
EditLinkSelection selection, EditLinkSelection selection,
const QString &text, const QString &text,
const QString &link); const QString &link);
static bool IsValidMarkdownLink(const QStringRef &link); static bool IsValidMarkdownLink(QStringView link);
static bool IsValidMarkdownLink(const QString &link) {
return IsValidMarkdownLink(link.midRef(0));
}
const QString &getLastText() const { const QString &getLastText() const {
return _lastTextWithTags.text; return _lastTextWithTags.text;

View file

@ -26,7 +26,7 @@ namespace {
} else { } else {
result.entities.append(EntityInText{ result.entities.append(EntityInText{
EntityType::Underline, EntityType::Underline,
result.text.size(), int(result.text.size()),
1 }); 1 });
result.text.append(ch); result.text.append(ch);
} }

View file

@ -6,7 +6,7 @@
// //
#include "ui/widgets/menu/menu_common.h" #include "ui/widgets/menu/menu_common.h"
#include <QtWidgets/QAction> #include <QAction>
namespace Ui::Menu { namespace Ui::Menu {

View file

@ -22,11 +22,11 @@ QTime ValidateTime(const QString &value) {
return QTime(); return QTime();
} }
const auto readInt = [](const QString &value) { const auto readInt = [](const QString &value) {
auto ref = value.midRef(0); auto view = QStringView(value);
while (!ref.isEmpty() && ref.at(0) == '0') { while (!view.isEmpty() && view.at(0) == '0') {
ref = ref.mid(1); view = view.mid(1);
} }
return ref.toInt(); return view.toInt();
}; };
return QTime(readInt(match.captured(1)), readInt(match.captured(2))); return QTime(readInt(match.captured(1)), readInt(match.captured(2)));
} }
@ -78,12 +78,12 @@ private:
std::optional<int> Number(not_null<TimePart*> field) { std::optional<int> Number(not_null<TimePart*> field) {
const auto text = field->getLastText(); const auto text = field->getLastText();
auto ref = text.midRef(0); auto view = QStringView(text);
while (ref.size() > 1 && ref.at(0) == '0') { while (view.size() > 1 && view.at(0) == '0') {
ref = ref.mid(1); view = view.mid(1);
} }
return QRegularExpression("^\\d+$").match(ref).hasMatch() return QRegularExpression("^\\d+$").match(view).hasMatch()
? std::make_optional(ref.toInt()) ? std::make_optional(view.toInt())
: std::nullopt; : std::nullopt;
} }