/* This file is part of Telegram Desktop, the official desktop version of Telegram messaging app, see https://telegram.org Telegram Desktop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. In addition, as a special exception, the copyright holders give permission to link the code of portions of this program with the OpenSSL library. Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE Copyright (c) 2014-2016 John Preston, https://desktop.telegram.org */ #include "stdafx.h" #include "historywidget.h" #include "boxes/confirmbox.h" #include "boxes/photosendbox.h" #include "ui/filedialog.h" #include "ui/toast/toast.h" #include "inline_bots/inline_bot_result.h" #include "lang.h" #include "application.h" #include "mainwidget.h" #include "mainwindow.h" #include "passcodewidget.h" #include "mainwindow.h" #include "fileuploader.h" #include "audio.h" #include "localstorage.h" #include "apiwrap.h" #include "window/top_bar_widget.h" #include "playerwidget.h" namespace { QString mimeTagFromTag(const QString &tagId) { if (tagId.startsWith(qstr("mention://"))) { return tagId + ':' + QString::number(MTP::authedId()); } return tagId; } QMimeData *mimeDataFromTextWithEntities(const TextWithEntities &forClipboard) { if (forClipboard.text.isEmpty()) { return nullptr; } auto result = new QMimeData(); result->setText(forClipboard.text); auto tags = textTagsFromEntities(forClipboard.entities); if (!tags.isEmpty()) { for (auto &tag : tags) { tag.id = mimeTagFromTag(tag.id); } result->setData(FlatTextarea::tagsMimeType(), FlatTextarea::serializeTagsList(tags)); } return result; } // For mention tags save and validate userId, ignore tags for different userId. class FieldTagMimeProcessor : public FlatTextarea::TagMimeProcessor { public: QString mimeTagFromTag(const QString &tagId) override { return ::mimeTagFromTag(tagId); } QString tagFromMimeTag(const QString &mimeTag) override { if (mimeTag.startsWith(qstr("mention://"))) { auto match = QRegularExpression(":(\\d+)$").match(mimeTag); if (!match.hasMatch() || match.capturedRef(1).toInt() != MTP::authedId()) { return QString(); } return mimeTag.mid(0, mimeTag.size() - match.capturedLength()); } return mimeTag; } }; } // namespace // flick scroll taken from http://qt-project.org/doc/qt-4.8/demos-embedded-anomaly-src-flickcharm-cpp.html HistoryInner::HistoryInner(HistoryWidget *historyWidget, ScrollArea *scroll, History *history) : TWidget(nullptr) , _peer(history->peer) , _migrated(history->peer->migrateFrom() ? App::history(history->peer->migrateFrom()->id) : nullptr) , _history(history) , _widget(historyWidget) , _scroll(scroll) { connect(App::wnd(), SIGNAL(imageLoaded()), this, SLOT(update())); _touchSelectTimer.setSingleShot(true); connect(&_touchSelectTimer, SIGNAL(timeout()), this, SLOT(onTouchSelect())); setAttribute(Qt::WA_AcceptTouchEvents); connect(&_touchScrollTimer, SIGNAL(timeout()), this, SLOT(onTouchScrollTimer())); _trippleClickTimer.setSingleShot(true); notifyIsBotChanged(); setMouseTracking(true); } void HistoryInner::messagesReceived(PeerData *peer, const QVector &messages, const QVector *collapsed) { if (_history && _history->peer == peer) { _history->addOlderSlice(messages, collapsed); } else if (_migrated && _migrated->peer == peer) { bool newLoaded = (_migrated && _migrated->isEmpty() && !_history->isEmpty()); _migrated->addOlderSlice(messages, collapsed); if (newLoaded) { _migrated->addNewerSlice(QVector(), 0); } } } void HistoryInner::messagesReceivedDown(PeerData *peer, const QVector &messages, const QVector *collapsed) { if (_history && _history->peer == peer) { bool oldLoaded = (_migrated && _history->isEmpty() && !_migrated->isEmpty()); _history->addNewerSlice(messages, collapsed); if (oldLoaded) { _history->addOlderSlice(QVector(), 0); } } else if (_migrated && _migrated->peer == peer) { _migrated->addNewerSlice(messages, collapsed); } } void HistoryInner::repaintItem(const HistoryItem *item) { if (!item || item->detached() || !_history) return; int32 msgy = itemTop(item); if (msgy >= 0) { update(0, msgy, width(), item->height()); } } namespace { // helper binary search for an item in a list that is not completely below the given bottom of the visible area // is applied once for blocks list in a history and once for items list in the found block template int binarySearchBlocksOrItems(const T &list, int bottom) { int start = 0, end = list.size(); while (end - start > 1) { int middle = (start + end) / 2; if (list.at(middle)->y >= bottom) { end = middle; } else { start = middle; } } return start; } } template void HistoryInner::enumerateUserpicsInHistory(History *h, int htop, Method method) { // no displayed messages in this history if (htop < 0 || h->isEmpty() || !h->canHaveFromPhotos() || _visibleAreaBottom <= htop) { return; } // find and remember the bottom of an attached messages pack // -1 means we didn't find an attached to previous message yet int lowestAttachedItemBottom = -1; // binary search for blockIndex of the first block that is not completely below the visible area int blockIndex = binarySearchBlocksOrItems(h->blocks, _visibleAreaBottom - htop); // binary search for itemIndex of the first item that is not completely below the visible area HistoryBlock *block = h->blocks.at(blockIndex); int blocktop = htop + block->y; int itemIndex = binarySearchBlocksOrItems(block->items, _visibleAreaBottom - blocktop); while (true) { while (itemIndex >= 0) { HistoryItem *item = block->items.at(itemIndex--); int itemtop = blocktop + item->y; int itembottom = itemtop + item->height(); // binary search should've skipped all the items that are below the visible area t_assert(itemtop < _visibleAreaBottom); // skip all service messages if (HistoryMessage *message = item->toHistoryMessage()) { if (lowestAttachedItemBottom < 0 && message->isAttachedToPrevious()) { lowestAttachedItemBottom = itembottom - message->marginBottom(); } // draw userpic for all messages that have it and for those who are not showing it // because of their attachment to the previous message if they are top-most visible if (message->displayFromPhoto() || (message->hasFromPhoto() && itemtop <= _visibleAreaTop)) { if (lowestAttachedItemBottom < 0) { lowestAttachedItemBottom = itembottom - message->marginBottom(); } // attach userpic to the top of the visible area with the same margin as it is from the left side int userpicTop = qMax(itemtop + message->marginTop(), _visibleAreaTop + st::msgMargin.left()); // do not let the userpic go below the attached messages pack bottom line userpicTop = qMin(userpicTop, lowestAttachedItemBottom - int(st::msgPhotoSize)); // call the template callback function that was passed // and return if it finished everything it needed if (!method(message, userpicTop)) { return; } } // forget the found bottom of the pack, search for the next one from scratch if (!message->isAttachedToPrevious()) { lowestAttachedItemBottom = -1; } } // skip all the items that are above the visible area if (itemtop <= _visibleAreaTop) { return; } } // skip all the rest blocks that are above the visible area if (blocktop <= _visibleAreaTop) { return; } if (--blockIndex < 0) { return; } else { block = h->blocks.at(blockIndex); blocktop = htop + block->y; itemIndex = block->items.size() - 1; } } } void HistoryInner::paintEvent(QPaintEvent *e) { if (!App::main() || (App::wnd() && App::wnd()->contentOverlapped(this, e))) { return; } if (hasPendingResizedItems()) { return; } Painter p(this); QRect r(e->rect()); bool trivial = (rect() == r); if (!trivial) { p.setClipRect(r); } uint64 ms = getms(); if (!_firstLoading && _botAbout && !_botAbout->info->text.isEmpty() && _botAbout->height > 0) { if (r.y() < _botAbout->rect.y() + _botAbout->rect.height() && r.y() + r.height() > _botAbout->rect.y()) { textstyleSet(&st::inTextStyle); App::roundRect(p, _botAbout->rect, st::msgInBg, MessageInCorners, &st::msgInShadow); p.setFont(st::msgNameFont); p.setPen(st::black); p.drawText(_botAbout->rect.left() + st::msgPadding.left(), _botAbout->rect.top() + st::msgPadding.top() + st::msgNameFont->ascent, lang(lng_bot_description)); _botAbout->info->text.draw(p, _botAbout->rect.left() + st::msgPadding.left(), _botAbout->rect.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip, _botAbout->width); textstyleRestore(); } } else if (_firstLoading || (_history->isEmpty() && (!_migrated || _migrated->isEmpty()))) { QPoint dogPos((width() - st::msgDogImg.pxWidth()) / 2, ((height() - st::msgDogImg.pxHeight()) * 4) / 9); p.drawPixmap(dogPos, *cChatDogImage()); } if (!_firstLoading) { adjustCurrent(r.top()); SelectedItems::const_iterator selEnd = _selected.cend(); bool hasSel = !_selected.isEmpty(); int32 drawToY = r.y() + r.height(); int32 selfromy = itemTop(_dragSelFrom), seltoy = itemTop(_dragSelTo); if (selfromy < 0 || seltoy < 0) { selfromy = seltoy = -1; } else { seltoy += _dragSelTo->height(); } int32 mtop = migratedTop(), htop = historyTop(), hdrawtop = historyDrawTop(); if (mtop >= 0) { int32 iBlock = (_curHistory == _migrated ? _curBlock : (_migrated->blocks.size() - 1)); HistoryBlock *block = _migrated->blocks[iBlock]; int32 iItem = (_curHistory == _migrated ? _curItem : (block->items.size() - 1)); HistoryItem *item = block->items[iItem]; int32 y = mtop + block->y + item->y; p.save(); p.translate(0, y); if (r.y() < y + item->height()) while (y < drawToY) { TextSelection sel; if (y >= selfromy && y < seltoy) { if (_dragSelecting && !item->serviceMsg() && item->id > 0) { sel = FullSelection; } } else if (hasSel) { auto i = _selected.constFind(item); if (i != selEnd) { sel = i.value(); } } item->draw(p, r.translated(0, -y), sel, ms); if (item->hasViews()) { App::main()->scheduleViewIncrement(item); } int32 h = item->height(); p.translate(0, h); y += h; ++iItem; if (iItem == block->items.size()) { iItem = 0; ++iBlock; if (iBlock == _migrated->blocks.size()) { break; } block = _migrated->blocks[iBlock]; } item = block->items[iItem]; } p.restore(); } if (htop >= 0) { int32 iBlock = (_curHistory == _history ? _curBlock : 0); HistoryBlock *block = _history->blocks[iBlock]; int32 iItem = (_curHistory == _history ? _curItem : 0); HistoryItem *item = block->items[iItem]; QRect historyRect = r.intersected(QRect(0, hdrawtop, width(), r.top() + r.height())); int32 y = htop + block->y + item->y; p.save(); p.translate(0, y); while (y < drawToY) { int32 h = item->height(); if (historyRect.y() < y + h && hdrawtop < y + h) { TextSelection sel; if (y >= selfromy && y < seltoy) { if (_dragSelecting && !item->serviceMsg() && item->id > 0) { sel = FullSelection; } } else if (hasSel) { auto i = _selected.constFind(item); if (i != selEnd) { sel = i.value(); } } item->draw(p, historyRect.translated(0, -y), sel, ms); if (item->hasViews()) { App::main()->scheduleViewIncrement(item); } } p.translate(0, h); y += h; ++iItem; if (iItem == block->items.size()) { iItem = 0; ++iBlock; if (iBlock == _history->blocks.size()) { break; } block = _history->blocks[iBlock]; } item = block->items[iItem]; } p.restore(); } if (mtop >= 0 || htop >= 0) { enumerateUserpics([&p, &r](HistoryMessage *message, int userpicTop) -> bool { // stop the enumeration if the userpic is above the painted rect if (userpicTop + st::msgPhotoSize <= r.top()) { return false; } // paint the userpic if it intersects the painted rect if (userpicTop < r.top() + r.height()) { message->from()->paintUserpicLeft(p, st::msgPhotoSize, st::msgMargin.left(), userpicTop, message->history()->width); } return true; }); } } } bool HistoryInner::event(QEvent *e) { if (e->type() == QEvent::TouchBegin || e->type() == QEvent::TouchUpdate || e->type() == QEvent::TouchEnd || e->type() == QEvent::TouchCancel) { QTouchEvent *ev = static_cast(e); if (ev->device()->type() == QTouchDevice::TouchScreen) { touchEvent(ev); return true; } } return QWidget::event(e); } void HistoryInner::onTouchScrollTimer() { uint64 nowTime = getms(); if (_touchScrollState == TouchScrollAcceleration && _touchWaitingAcceleration && (nowTime - _touchAccelerationTime) > 40) { _touchScrollState = TouchScrollManual; touchResetSpeed(); } else if (_touchScrollState == TouchScrollAuto || _touchScrollState == TouchScrollAcceleration) { int32 elapsed = int32(nowTime - _touchTime); QPoint delta = _touchSpeed * elapsed / 1000; bool hasScrolled = _widget->touchScroll(delta); if (_touchSpeed.isNull() || !hasScrolled) { _touchScrollState = TouchScrollManual; _touchScroll = false; _touchScrollTimer.stop(); } else { _touchTime = nowTime; } touchDeaccelerate(elapsed); } } void HistoryInner::touchUpdateSpeed() { const uint64 nowTime = getms(); if (_touchPrevPosValid) { const int elapsed = nowTime - _touchSpeedTime; if (elapsed) { const QPoint newPixelDiff = (_touchPos - _touchPrevPos); const QPoint pixelsPerSecond = newPixelDiff * (1000 / elapsed); // fingers are inacurates, we ignore small changes to avoid stopping the autoscroll because // of a small horizontal offset when scrolling vertically const int newSpeedY = (qAbs(pixelsPerSecond.y()) > FingerAccuracyThreshold) ? pixelsPerSecond.y() : 0; const int newSpeedX = (qAbs(pixelsPerSecond.x()) > FingerAccuracyThreshold) ? pixelsPerSecond.x() : 0; if (_touchScrollState == TouchScrollAuto) { const int oldSpeedY = _touchSpeed.y(); const int oldSpeedX = _touchSpeed.x(); if ((oldSpeedY <= 0 && newSpeedY <= 0) || ((oldSpeedY >= 0 && newSpeedY >= 0) && (oldSpeedX <= 0 && newSpeedX <= 0)) || (oldSpeedX >= 0 && newSpeedX >= 0)) { _touchSpeed.setY(snap((oldSpeedY + (newSpeedY / 4)), -MaxScrollAccelerated, +MaxScrollAccelerated)); _touchSpeed.setX(snap((oldSpeedX + (newSpeedX / 4)), -MaxScrollAccelerated, +MaxScrollAccelerated)); } else { _touchSpeed = QPoint(); } } else { // we average the speed to avoid strange effects with the last delta if (!_touchSpeed.isNull()) { _touchSpeed.setX(snap((_touchSpeed.x() / 4) + (newSpeedX * 3 / 4), -MaxScrollFlick, +MaxScrollFlick)); _touchSpeed.setY(snap((_touchSpeed.y() / 4) + (newSpeedY * 3 / 4), -MaxScrollFlick, +MaxScrollFlick)); } else { _touchSpeed = QPoint(newSpeedX, newSpeedY); } } } } else { _touchPrevPosValid = true; } _touchSpeedTime = nowTime; _touchPrevPos = _touchPos; } void HistoryInner::touchResetSpeed() { _touchSpeed = QPoint(); _touchPrevPosValid = false; } void HistoryInner::touchDeaccelerate(int32 elapsed) { int32 x = _touchSpeed.x(); int32 y = _touchSpeed.y(); _touchSpeed.setX((x == 0) ? x : (x > 0) ? qMax(0, x - elapsed) : qMin(0, x + elapsed)); _touchSpeed.setY((y == 0) ? y : (y > 0) ? qMax(0, y - elapsed) : qMin(0, y + elapsed)); } void HistoryInner::touchEvent(QTouchEvent *e) { const Qt::TouchPointStates &states(e->touchPointStates()); if (e->type() == QEvent::TouchCancel) { // cancel if (!_touchInProgress) return; _touchInProgress = false; _touchSelectTimer.stop(); _touchScroll = _touchSelect = false; _touchScrollState = TouchScrollManual; dragActionCancel(); return; } if (!e->touchPoints().isEmpty()) { _touchPrevPos = _touchPos; _touchPos = e->touchPoints().cbegin()->screenPos().toPoint(); } switch (e->type()) { case QEvent::TouchBegin: if (_menu) { e->accept(); return; // ignore mouse press, that was hiding context menu } if (_touchInProgress) return; if (e->touchPoints().isEmpty()) return; _touchInProgress = true; if (_touchScrollState == TouchScrollAuto) { _touchScrollState = TouchScrollAcceleration; _touchWaitingAcceleration = true; _touchAccelerationTime = getms(); touchUpdateSpeed(); _touchStart = _touchPos; } else { _touchScroll = false; _touchSelectTimer.start(QApplication::startDragTime()); } _touchSelect = false; _touchStart = _touchPrevPos = _touchPos; break; case QEvent::TouchUpdate: if (!_touchInProgress) return; if (_touchSelect) { dragActionUpdate(_touchPos); } else if (!_touchScroll && (_touchPos - _touchStart).manhattanLength() >= QApplication::startDragDistance()) { _touchSelectTimer.stop(); _touchScroll = true; touchUpdateSpeed(); } if (_touchScroll) { if (_touchScrollState == TouchScrollManual) { touchScrollUpdated(_touchPos); } else if (_touchScrollState == TouchScrollAcceleration) { touchUpdateSpeed(); _touchAccelerationTime = getms(); if (_touchSpeed.isNull()) { _touchScrollState = TouchScrollManual; } } } break; case QEvent::TouchEnd: if (!_touchInProgress) return; _touchInProgress = false; if (_touchSelect) { dragActionFinish(_touchPos, Qt::RightButton); QContextMenuEvent contextMenu(QContextMenuEvent::Mouse, mapFromGlobal(_touchPos), _touchPos); showContextMenu(&contextMenu, true); _touchScroll = false; } else if (_touchScroll) { if (_touchScrollState == TouchScrollManual) { _touchScrollState = TouchScrollAuto; _touchPrevPosValid = false; _touchScrollTimer.start(15); _touchTime = getms(); } else if (_touchScrollState == TouchScrollAuto) { _touchScrollState = TouchScrollManual; _touchScroll = false; touchResetSpeed(); } else if (_touchScrollState == TouchScrollAcceleration) { _touchScrollState = TouchScrollAuto; _touchWaitingAcceleration = false; _touchPrevPosValid = false; } } else { // one short tap -- like mouse click dragActionStart(_touchPos); dragActionFinish(_touchPos); } _touchSelectTimer.stop(); _touchSelect = false; break; } } void HistoryInner::mouseMoveEvent(QMouseEvent *e) { if (!(e->buttons() & (Qt::LeftButton | Qt::MiddleButton)) && _dragAction != NoDrag) { mouseReleaseEvent(e); } dragActionUpdate(e->globalPos()); } void HistoryInner::dragActionUpdate(const QPoint &screenPos) { _dragPos = screenPos; onUpdateSelected(); } void HistoryInner::touchScrollUpdated(const QPoint &screenPos) { _touchPos = screenPos; _widget->touchScroll(_touchPos - _touchPrevPos); touchUpdateSpeed(); } QPoint HistoryInner::mapMouseToItem(QPoint p, HistoryItem *item) { int32 msgy = itemTop(item); if (msgy < 0) return QPoint(0, 0); p.setY(p.y() - msgy); return p; } void HistoryInner::mousePressEvent(QMouseEvent *e) { if (_menu) { e->accept(); return; // ignore mouse press, that was hiding context menu } dragActionStart(e->globalPos(), e->button()); } void HistoryInner::dragActionStart(const QPoint &screenPos, Qt::MouseButton button) { dragActionUpdate(screenPos); if (button != Qt::LeftButton) return; ClickHandler::pressed(); if (App::pressedItem() != App::hoveredItem()) { repaintItem(App::pressedItem()); App::pressedItem(App::hoveredItem()); repaintItem(App::pressedItem()); } _dragAction = NoDrag; _dragItem = App::mousedItem(); _dragStartPos = mapMouseToItem(mapFromGlobal(screenPos), _dragItem); _dragWasInactive = App::wnd()->inactivePress(); if (_dragWasInactive) App::wnd()->inactivePress(false); if (ClickHandler::getPressed()) { _dragAction = PrepareDrag; } else if (!_selected.isEmpty()) { if (_selected.cbegin().value() == FullSelection) { if (_selected.constFind(_dragItem) != _selected.cend() && App::hoveredItem()) { _dragAction = PrepareDrag; // start items drag } else if (!_dragWasInactive) { _dragAction = PrepareSelect; // start items select } } } if (_dragAction == NoDrag && _dragItem) { HistoryTextState dragState; if (_trippleClickTimer.isActive() && (screenPos - _trippleClickPoint).manhattanLength() < QApplication::startDragDistance()) { HistoryStateRequest request; request.flags = Text::StateRequest::Flag::LookupSymbol; dragState = _dragItem->getState(_dragStartPos.x(), _dragStartPos.y(), request); if (dragState.cursor == HistoryInTextCursorState) { TextSelection selStatus = { dragState.symbol, dragState.symbol }; if (selStatus != FullSelection && (_selected.isEmpty() || _selected.cbegin().value() != FullSelection)) { if (!_selected.isEmpty()) { repaintItem(_selected.cbegin().key()); _selected.clear(); } _selected.insert(_dragItem, selStatus); _dragSymbol = dragState.symbol; _dragAction = Selecting; _dragSelType = TextSelectParagraphs; dragActionUpdate(_dragPos); _trippleClickTimer.start(QApplication::doubleClickInterval()); } } } else if (App::pressedItem()) { HistoryStateRequest request; request.flags = Text::StateRequest::Flag::LookupSymbol; dragState = _dragItem->getState(_dragStartPos.x(), _dragStartPos.y(), request); } if (_dragSelType != TextSelectParagraphs) { if (App::pressedItem()) { _dragSymbol = dragState.symbol; bool uponSelected = (dragState.cursor == HistoryInTextCursorState); if (uponSelected) { if (_selected.isEmpty() || _selected.cbegin().value() == FullSelection || _selected.cbegin().key() != _dragItem ) { uponSelected = false; } else { uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; if (_dragSymbol < selFrom || _dragSymbol >= selTo) { uponSelected = false; } } } if (uponSelected) { _dragAction = PrepareDrag; // start text drag } else if (!_dragWasInactive) { if (dynamic_cast(App::pressedItem()->getMedia()) || _dragCursorState == HistoryInDateCursorState) { _dragAction = PrepareDrag; // start sticker drag or by-date drag } else { if (dragState.afterSymbol) ++_dragSymbol; TextSelection selStatus = { _dragSymbol, _dragSymbol }; if (selStatus != FullSelection && (_selected.isEmpty() || _selected.cbegin().value() != FullSelection)) { if (!_selected.isEmpty()) { repaintItem(_selected.cbegin().key()); _selected.clear(); } _selected.insert(_dragItem, selStatus); _dragAction = Selecting; repaintItem(_dragItem); } else { _dragAction = PrepareSelect; } } } } else if (!_dragWasInactive) { _dragAction = PrepareSelect; // start items select } } } if (!_dragItem) { _dragAction = NoDrag; } else if (_dragAction == NoDrag) { _dragItem = 0; } } void HistoryInner::dragActionCancel() { _dragItem = 0; _dragAction = NoDrag; _dragStartPos = QPoint(0, 0); _dragSelFrom = _dragSelTo = 0; _wasSelectedText = false; _widget->noSelectingScroll(); } void HistoryInner::onDragExec() { if (_dragAction != Dragging) return; bool uponSelected = false; if (_dragItem) { if (!_selected.isEmpty() && _selected.cbegin().value() == FullSelection) { uponSelected = _selected.contains(_dragItem); } else { HistoryStateRequest request; request.flags |= Text::StateRequest::Flag::LookupSymbol; auto dragState = _dragItem->getState(_dragStartPos.x(), _dragStartPos.y(), request); uponSelected = (dragState.cursor == HistoryInTextCursorState); if (uponSelected) { if (_selected.isEmpty() || _selected.cbegin().value() == FullSelection || _selected.cbegin().key() != _dragItem ) { uponSelected = false; } else { uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; if (dragState.symbol < selFrom || dragState.symbol >= selTo) { uponSelected = false; } } } } } ClickHandlerPtr pressedHandler = ClickHandler::getPressed(); TextWithEntities sel; QList urls; if (uponSelected) { sel = getSelectedText(); } else if (pressedHandler) { sel = { pressedHandler->dragText(), EntitiesInText() }; //if (!sel.isEmpty() && sel.at(0) != '/' && sel.at(0) != '@' && sel.at(0) != '#') { // urls.push_back(QUrl::fromEncoded(sel.toUtf8())); // Google Chrome crashes in Mac OS X O_o //} } if (auto mimeData = mimeDataFromTextWithEntities(sel)) { updateDragSelection(0, 0, false); _widget->noSelectingScroll(); QDrag *drag = new QDrag(App::wnd()); if (!urls.isEmpty()) mimeData->setUrls(urls); if (uponSelected && !_selected.isEmpty() && _selected.cbegin().value() == FullSelection && !Adaptive::OneColumn()) { mimeData->setData(qsl("application/x-td-forward-selected"), "1"); } drag->setMimeData(mimeData); drag->exec(Qt::CopyAction); if (App::main()) App::main()->updateAfterDrag(); return; } else { QString forwardMimeType; HistoryMedia *pressedMedia = nullptr; if (HistoryItem *pressedItem = App::pressedItem()) { pressedMedia = pressedItem->getMedia(); if (_dragCursorState == HistoryInDateCursorState || (pressedMedia && pressedMedia->dragItem())) { forwardMimeType = qsl("application/x-td-forward-pressed"); } } if (HistoryItem *pressedLnkItem = App::pressedLinkItem()) { if ((pressedMedia = pressedLnkItem->getMedia())) { if (forwardMimeType.isEmpty() && pressedMedia->dragItemByHandler(pressedHandler)) { forwardMimeType = qsl("application/x-td-forward-pressed-link"); } } } if (!forwardMimeType.isEmpty()) { QDrag *drag = new QDrag(App::wnd()); QMimeData *mimeData = new QMimeData(); mimeData->setData(forwardMimeType, "1"); if (DocumentData *document = (pressedMedia ? pressedMedia->getDocument() : nullptr)) { QString filepath = document->filepath(DocumentData::FilePathResolveChecked); if (!filepath.isEmpty()) { QList urls; urls.push_back(QUrl::fromLocalFile(filepath)); mimeData->setUrls(urls); } } drag->setMimeData(mimeData); drag->exec(Qt::CopyAction); if (App::main()) App::main()->updateAfterDrag(); return; } } } void HistoryInner::itemRemoved(HistoryItem *item) { SelectedItems::iterator i = _selected.find(item); if (i != _selected.cend()) { _selected.erase(i); _widget->updateTopBarSelection(); } if (_dragItem == item) { dragActionCancel(); } if (_dragSelFrom == item || _dragSelTo == item) { _dragSelFrom = 0; _dragSelTo = 0; update(); } onUpdateSelected(); } void HistoryInner::dragActionFinish(const QPoint &screenPos, Qt::MouseButton button) { dragActionUpdate(screenPos); ClickHandlerPtr activated = ClickHandler::unpressed(); if (_dragAction == Dragging) { activated.clear(); } else if (HistoryItem *pressed = App::pressedLinkItem()) { // if we are in selecting items mode perhaps we want to // toggle selection instead of activating the pressed link if (_dragAction == PrepareDrag && !_dragWasInactive && !_selected.isEmpty() && _selected.cbegin().value() == FullSelection && button != Qt::RightButton) { if (HistoryMedia *media = pressed->getMedia()) { if (media->toggleSelectionByHandlerClick(activated)) { activated.clear(); } } } } if (App::pressedItem()) { repaintItem(App::pressedItem()); App::pressedItem(nullptr); } _wasSelectedText = false; if (activated) { dragActionCancel(); App::activateClickHandler(activated, button); return; } if (_dragAction == PrepareSelect && !_dragWasInactive && !_selected.isEmpty() && _selected.cbegin().value() == FullSelection) { SelectedItems::iterator i = _selected.find(_dragItem); if (i == _selected.cend() && !_dragItem->serviceMsg() && _dragItem->id > 0) { if (_selected.size() < MaxSelectedItems) { if (!_selected.isEmpty() && _selected.cbegin().value() != FullSelection) { _selected.clear(); } _selected.insert(_dragItem, FullSelection); } } else { _selected.erase(i); } repaintItem(_dragItem); } else if (_dragAction == PrepareDrag && !_dragWasInactive && button != Qt::RightButton) { SelectedItems::iterator i = _selected.find(_dragItem); if (i != _selected.cend() && i.value() == FullSelection) { _selected.erase(i); repaintItem(_dragItem); } else if (i == _selected.cend() && !_dragItem->serviceMsg() && _dragItem->id > 0 && !_selected.isEmpty() && _selected.cbegin().value() == FullSelection) { if (_selected.size() < MaxSelectedItems) { _selected.insert(_dragItem, FullSelection); repaintItem(_dragItem); } } else { _selected.clear(); update(); } } else if (_dragAction == Selecting) { if (_dragSelFrom && _dragSelTo) { applyDragSelection(); _dragSelFrom = _dragSelTo = 0; } else if (!_selected.isEmpty() && !_dragWasInactive) { auto sel = _selected.cbegin().value(); if (sel != FullSelection && sel.from == sel.to) { _selected.clear(); if (App::wnd()) App::wnd()->setInnerFocus(); } } } _dragAction = NoDrag; _dragItem = 0; _dragSelType = TextSelectLetters; _widget->noSelectingScroll(); _widget->updateTopBarSelection(); } void HistoryInner::mouseReleaseEvent(QMouseEvent *e) { dragActionFinish(e->globalPos(), e->button()); if (!rect().contains(e->pos())) { leaveEvent(e); } } void HistoryInner::mouseDoubleClickEvent(QMouseEvent *e) { if (!_history) return; dragActionStart(e->globalPos(), e->button()); if (((_dragAction == Selecting && !_selected.isEmpty() && _selected.cbegin().value() != FullSelection) || (_dragAction == NoDrag && (_selected.isEmpty() || _selected.cbegin().value() != FullSelection))) && _dragSelType == TextSelectLetters && _dragItem) { HistoryStateRequest request; request.flags |= Text::StateRequest::Flag::LookupSymbol; auto dragState = _dragItem->getState(_dragStartPos.x(), _dragStartPos.y(), request); if (dragState.cursor == HistoryInTextCursorState) { _dragSymbol = dragState.symbol; _dragSelType = TextSelectWords; if (_dragAction == NoDrag) { _dragAction = Selecting; TextSelection selStatus = { dragState.symbol, dragState.symbol }; if (!_selected.isEmpty()) { repaintItem(_selected.cbegin().key()); _selected.clear(); } _selected.insert(_dragItem, selStatus); } mouseMoveEvent(e); _trippleClickPoint = e->globalPos(); _trippleClickTimer.start(QApplication::doubleClickInterval()); } } } void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) { if (_menu) { _menu->deleteLater(); _menu = 0; } if (e->reason() == QContextMenuEvent::Mouse) { dragActionUpdate(e->globalPos()); } int32 selectedForForward, selectedForDelete; getSelectionState(selectedForForward, selectedForDelete); bool canSendMessages = _widget->canSendMessages(_peer); // -2 - has full selected items, but not over, -1 - has selection, but no over, 0 - no selection, 1 - over text, 2 - over full selected items int32 isUponSelected = 0, hasSelected = 0;; if (!_selected.isEmpty()) { isUponSelected = -1; if (_selected.cbegin().value() == FullSelection) { hasSelected = 2; if (App::hoveredItem() && _selected.constFind(App::hoveredItem()) != _selected.cend()) { isUponSelected = 2; } else { isUponSelected = -2; } } else { uint16 selFrom = _selected.cbegin().value().from, selTo = _selected.cbegin().value().to; hasSelected = (selTo > selFrom) ? 1 : 0; if (App::mousedItem() && App::mousedItem() == App::hoveredItem()) { QPoint mousePos(mapMouseToItem(mapFromGlobal(_dragPos), App::mousedItem())); HistoryStateRequest request; request.flags |= Text::StateRequest::Flag::LookupSymbol; auto dragState = App::mousedItem()->getState(mousePos.x(), mousePos.y(), request); if (dragState.cursor == HistoryInTextCursorState && dragState.symbol >= selFrom && dragState.symbol < selTo) { isUponSelected = 1; } } } } if (showFromTouch && hasSelected && isUponSelected < hasSelected) { isUponSelected = hasSelected; } _menu = new PopupMenu(); _contextMenuLnk = ClickHandler::getActive(); HistoryItem *item = App::hoveredItem() ? App::hoveredItem() : App::hoveredLinkItem(); PhotoClickHandler *lnkPhoto = dynamic_cast(_contextMenuLnk.data()); DocumentClickHandler *lnkDocument = dynamic_cast(_contextMenuLnk.data()); bool lnkIsVideo = lnkDocument ? lnkDocument->document()->isVideo() : false; bool lnkIsAudio = lnkDocument ? (lnkDocument->document()->voice() != nullptr) : false; bool lnkIsSong = lnkDocument ? (lnkDocument->document()->song() != nullptr) : false; if (lnkPhoto || lnkDocument) { if (isUponSelected > 0) { _menu->addAction(lang(lng_context_copy_selected), this, SLOT(copySelectedText()))->setEnabled(true); } if (item && item->id > 0 && isUponSelected != 2 && isUponSelected != -2) { if (canSendMessages) { _menu->addAction(lang(lng_context_reply_msg), _widget, SLOT(onReplyToMessage())); } if (item->canEdit(::date(unixtime()))) { _menu->addAction(lang(lng_context_edit_msg), _widget, SLOT(onEditMessage())); } if (item->canPin()) { bool ispinned = (item->history()->peer->asChannel()->mgInfo->pinnedMsgId == item->id); _menu->addAction(lang(ispinned ? lng_context_unpin_msg : lng_context_pin_msg), _widget, ispinned ? SLOT(onUnpinMessage()) : SLOT(onPinMessage())); } } if (lnkPhoto) { _menu->addAction(lang(lng_context_save_image), this, SLOT(saveContextImage()))->setEnabled(true); _menu->addAction(lang(lng_context_copy_image), this, SLOT(copyContextImage()))->setEnabled(true); } else { if (lnkDocument && lnkDocument->document()->loading()) { _menu->addAction(lang(lng_context_cancel_download), this, SLOT(cancelContextDownload()))->setEnabled(true); } else { if (lnkDocument && lnkDocument->document()->loaded() && lnkDocument->document()->isGifv()) { _menu->addAction(lang(lng_context_save_gif), this, SLOT(saveContextGif()))->setEnabled(true); } if (lnkDocument && !lnkDocument->document()->filepath(DocumentData::FilePathResolveChecked).isEmpty()) { _menu->addAction(lang((cPlatform() == dbipMac || cPlatform() == dbipMacOld) ? lng_context_show_in_finder : lng_context_show_in_folder), this, SLOT(showContextInFolder()))->setEnabled(true); } _menu->addAction(lang(lnkIsVideo ? lng_context_save_video : (lnkIsAudio ? lng_context_save_audio : (lnkIsSong ? lng_context_save_audio_file : lng_context_save_file))), this, SLOT(saveContextFile()))->setEnabled(true); } } if (item && item->hasDirectLink() && isUponSelected != 2 && isUponSelected != -2) { _menu->addAction(lang(lng_context_copy_post_link), _widget, SLOT(onCopyPostLink())); } if (isUponSelected > 1) { _menu->addAction(lang(lng_context_forward_selected), _widget, SLOT(onForwardSelected())); if (selectedForDelete == selectedForForward) { _menu->addAction(lang(lng_context_delete_selected), _widget, SLOT(onDeleteSelected())); } _menu->addAction(lang(lng_context_clear_selection), _widget, SLOT(onClearSelected())); } else if (App::hoveredLinkItem()) { if (isUponSelected != -2) { if (dynamic_cast(App::hoveredLinkItem()) && App::hoveredLinkItem()->id > 0) { _menu->addAction(lang(lng_context_forward_msg), _widget, SLOT(forwardMessage()))->setEnabled(true); } if (App::hoveredLinkItem()->canDelete()) { _menu->addAction(lang(lng_context_delete_msg), _widget, SLOT(deleteMessage()))->setEnabled(true); } } if (App::hoveredLinkItem()->id > 0 && !App::hoveredLinkItem()->serviceMsg()) { _menu->addAction(lang(lng_context_select_msg), _widget, SLOT(selectMessage()))->setEnabled(true); } App::contextItem(App::hoveredLinkItem()); } } else { // maybe cursor on some text history item? bool canDelete = (item && item->type() == HistoryItemMsg) && item->canDelete(); bool canForward = (item && item->type() == HistoryItemMsg) && (item->id > 0) && !item->serviceMsg(); HistoryMessage *msg = dynamic_cast(item); if (isUponSelected > 0) { _menu->addAction(lang(lng_context_copy_selected), this, SLOT(copySelectedText()))->setEnabled(true); if (item && item->id > 0 && isUponSelected != 2) { if (canSendMessages) { _menu->addAction(lang(lng_context_reply_msg), _widget, SLOT(onReplyToMessage())); } if (item->canEdit(::date(unixtime()))) { _menu->addAction(lang(lng_context_edit_msg), _widget, SLOT(onEditMessage())); } if (item->canPin()) { bool ispinned = (item->history()->peer->asChannel()->mgInfo->pinnedMsgId == item->id); _menu->addAction(lang(ispinned ? lng_context_unpin_msg : lng_context_pin_msg), _widget, ispinned ? SLOT(onUnpinMessage()) : SLOT(onPinMessage())); } } } else { if (item && item->id > 0 && isUponSelected != -2) { if (canSendMessages) { _menu->addAction(lang(lng_context_reply_msg), _widget, SLOT(onReplyToMessage())); } if (item->canEdit(::date(unixtime()))) { _menu->addAction(lang(lng_context_edit_msg), _widget, SLOT(onEditMessage())); } if (item->canPin()) { bool ispinned = (item->history()->peer->asChannel()->mgInfo->pinnedMsgId == item->id); _menu->addAction(lang(ispinned ? lng_context_unpin_msg : lng_context_pin_msg), _widget, ispinned ? SLOT(onUnpinMessage()) : SLOT(onPinMessage())); } } if (item && !isUponSelected) { bool mediaHasTextForCopy = false; if (HistoryMedia *media = (msg ? msg->getMedia() : nullptr)) { mediaHasTextForCopy = media->hasTextForCopy(); if (media->type() == MediaTypeWebPage && static_cast(media)->attach()) { media = static_cast(media)->attach(); } if (media->type() == MediaTypeSticker) { DocumentData *doc = media->getDocument(); if (doc && doc->sticker() && doc->sticker()->set.type() != mtpc_inputStickerSetEmpty) { _menu->addAction(lang(doc->sticker()->setInstalled() ? lng_context_pack_info : lng_context_pack_add), _widget, SLOT(onStickerPackInfo())); } _menu->addAction(lang(lng_context_save_image), this, SLOT(saveContextFile()))->setEnabled(true); } else if (media->type() == MediaTypeGif && !_contextMenuLnk) { DocumentData *doc = media->getDocument(); if (doc) { if (doc->loading()) { _menu->addAction(lang(lng_context_cancel_download), this, SLOT(cancelContextDownload()))->setEnabled(true); } else { if (doc->isGifv()) { _menu->addAction(lang(lng_context_save_gif), this, SLOT(saveContextGif()))->setEnabled(true); } if (!doc->filepath(DocumentData::FilePathResolveChecked).isEmpty()) { _menu->addAction(lang((cPlatform() == dbipMac || cPlatform() == dbipMacOld) ? lng_context_show_in_finder : lng_context_show_in_folder), this, SLOT(showContextInFolder()))->setEnabled(true); } _menu->addAction(lang(lng_context_save_file), this, SLOT(saveContextFile()))->setEnabled(true); } } } } if (msg && (!msg->emptyText() || mediaHasTextForCopy)) { _menu->addAction(lang(lng_context_copy_text), this, SLOT(copyContextText()))->setEnabled(true); } } } QString linkCopyToClipboardText = _contextMenuLnk ? _contextMenuLnk->copyToClipboardContextItemText() : QString(); if (!linkCopyToClipboardText.isEmpty()) { _menu->addAction(linkCopyToClipboardText, this, SLOT(copyContextUrl()))->setEnabled(true); } if (item && item->hasDirectLink() && isUponSelected != 2 && isUponSelected != -2) { _menu->addAction(lang(lng_context_copy_post_link), _widget, SLOT(onCopyPostLink())); } if (isUponSelected > 1) { _menu->addAction(lang(lng_context_forward_selected), _widget, SLOT(onForwardSelected())); if (selectedForDelete == selectedForForward) { _menu->addAction(lang(lng_context_delete_selected), _widget, SLOT(onDeleteSelected())); } _menu->addAction(lang(lng_context_clear_selection), _widget, SLOT(onClearSelected())); } else if (item && ((isUponSelected != -2 && (canForward || canDelete)) || item->id > 0)) { if (isUponSelected != -2) { if (canForward) { _menu->addAction(lang(lng_context_forward_msg), _widget, SLOT(forwardMessage()))->setEnabled(true); } if (canDelete) { _menu->addAction(lang((msg && msg->uploading()) ? lng_context_cancel_upload : lng_context_delete_msg), _widget, SLOT(deleteMessage()))->setEnabled(true); } } if (item->id > 0 && !item->serviceMsg()) { _menu->addAction(lang(lng_context_select_msg), _widget, SLOT(selectMessage()))->setEnabled(true); } } else { if (App::mousedItem() && !App::mousedItem()->serviceMsg() && App::mousedItem()->id > 0) { _menu->addAction(lang(lng_context_select_msg), _widget, SLOT(selectMessage()))->setEnabled(true); item = App::mousedItem(); } } App::contextItem(item); } if (_menu->actions().isEmpty()) { delete _menu; _menu = 0; } else { connect(_menu, SIGNAL(destroyed(QObject*)), this, SLOT(onMenuDestroy(QObject*))); _menu->popup(e->globalPos()); e->accept(); } } void HistoryInner::onMenuDestroy(QObject *obj) { if (_menu == obj) { _menu = 0; } } void HistoryInner::copySelectedText() { setToClipboard(getSelectedText()); } void HistoryInner::copyContextUrl() { if (_contextMenuLnk) { _contextMenuLnk->copyToClipboard(); } } void HistoryInner::saveContextImage() { PhotoClickHandler *lnk = dynamic_cast(_contextMenuLnk.data()); if (!lnk) return; PhotoData *photo = lnk->photo(); if (!photo || !photo->date || !photo->loaded()) return; QString file; if (filedialogGetSaveFile(file, lang(lng_save_photo), qsl("JPEG Image (*.jpg);;All files (*.*)"), filedialogDefaultName(qsl("photo"), qsl(".jpg")))) { if (!file.isEmpty()) { photo->full->pix().toImage().save(file, "JPG"); } } } void HistoryInner::copyContextImage() { PhotoClickHandler *lnk = dynamic_cast(_contextMenuLnk.data()); if (!lnk) return; PhotoData *photo = lnk->photo(); if (!photo || !photo->date || !photo->loaded()) return; QApplication::clipboard()->setPixmap(photo->full->pix()); } void HistoryInner::cancelContextDownload() { if (DocumentClickHandler *lnkDocument = dynamic_cast(_contextMenuLnk.data())) { lnkDocument->document()->cancel(); } else if (HistoryItem *item = App::contextItem()) { if (HistoryMedia *media = item->getMedia()) { if (DocumentData *doc = media->getDocument()) { doc->cancel(); } } } } void HistoryInner::showContextInFolder() { QString filepath; if (DocumentClickHandler *lnkDocument = dynamic_cast(_contextMenuLnk.data())) { filepath = lnkDocument->document()->filepath(DocumentData::FilePathResolveChecked); } else if (HistoryItem *item = App::contextItem()) { if (HistoryMedia *media = item->getMedia()) { if (DocumentData *doc = media->getDocument()) { filepath = doc->filepath(DocumentData::FilePathResolveChecked); } } } if (!filepath.isEmpty()) { psShowInFolder(filepath); } } void HistoryInner::saveContextFile() { if (DocumentClickHandler *lnkDocument = dynamic_cast(_contextMenuLnk.data())) { DocumentSaveClickHandler::doSave(lnkDocument->document(), true); } else if (HistoryItem *item = App::contextItem()) { if (HistoryMedia *media = item->getMedia()) { if (DocumentData *doc = media->getDocument()) { DocumentSaveClickHandler::doSave(doc, true); } } } } void HistoryInner::saveContextGif() { if (HistoryItem *item = App::contextItem()) { if (HistoryMedia *media = item->getMedia()) { if (DocumentData *doc = media->getDocument()) { _widget->saveGif(doc); } } } } void HistoryInner::copyContextText() { HistoryItem *item = App::contextItem(); if (!item || (item->getMedia() && item->getMedia()->type() == MediaTypeSticker)) { return; } setToClipboard(item->selectedText(FullSelection)); } void HistoryInner::setToClipboard(const TextWithEntities &forClipboard) { if (auto data = mimeDataFromTextWithEntities(forClipboard)) { QApplication::clipboard()->setMimeData(data); } } void HistoryInner::resizeEvent(QResizeEvent *e) { onUpdateSelected(); } TextWithEntities HistoryInner::getSelectedText() const { SelectedItems sel = _selected; if (_dragAction == Selecting && _dragSelFrom && _dragSelTo) { applyDragSelection(&sel); } if (sel.isEmpty()) { return TextWithEntities(); } if (sel.cbegin().value() != FullSelection) { return sel.cbegin().key()->selectedText(sel.cbegin().value()); } int fullSize = 0; QString timeFormat(qsl(", [dd.MM.yy hh:mm]\n")); QMap texts; for (auto i = sel.cbegin(), e = sel.cend(); i != e; ++i) { HistoryItem *item = i.key(); if (item->detached()) continue; QString time = item->date.toString(timeFormat); TextWithEntities part, unwrapped = item->selectedText(FullSelection); int size = item->author()->name.size() + time.size() + unwrapped.text.size(); part.text.reserve(size); int y = itemTop(item); if (y >= 0) { part.text.append(item->author()->name).append(time); appendTextWithEntities(part, std_::move(unwrapped)); texts.insert(y, part); fullSize += size; } } TextWithEntities result; auto sep = qsl("\n\n"); result.text.reserve(fullSize + (texts.size() - 1) * sep.size()); for (auto i = texts.begin(), e = texts.end(); i != e; ++i) { appendTextWithEntities(result, std_::move(i.value())); if (i + 1 != e) { result.text.append(sep); } } return result; } void HistoryInner::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) { _widget->onListEscapePressed(); } else if (e == QKeySequence::Copy && !_selected.isEmpty()) { copySelectedText(); } else if (e == QKeySequence::Delete) { int32 selectedForForward, selectedForDelete; getSelectionState(selectedForForward, selectedForDelete); if (!_selected.isEmpty() && selectedForDelete == selectedForForward) { _widget->onDeleteSelected(); } } else { e->ignore(); } } void HistoryInner::recountHeight() { int htop = historyTop(), mtop = migratedTop(); int ph = _scroll->height(), minadd = 0; int wasYSkip = ph - historyHeight() - st::historyPadding; if (_botAbout && !_botAbout->info->text.isEmpty()) { minadd = st::msgMargin.top() + st::msgMargin.bottom() + st::msgPadding.top() + st::msgPadding.bottom() + st::msgNameFont->height + st::botDescSkip + _botAbout->height; } if (wasYSkip < minadd) wasYSkip = minadd; _history->resizeGetHeight(_scroll->width()); if (_migrated) { _migrated->resizeGetHeight(_scroll->width()); } // with migrated history we perhaps do not need to display first _history message // (if last _migrated message and first _history message are both isGroupMigrate) // or at least we don't need to display first _history date (just skip it by height) _historySkipHeight = 0; if (_migrated) { if (!_migrated->isEmpty() && !_history->isEmpty() && _migrated->loadedAtBottom() && _history->loadedAtTop()) { if (_migrated->blocks.back()->items.back()->date.date() == _history->blocks.front()->items.front()->date.date()) { if (_migrated->blocks.back()->items.back()->isGroupMigrate() && _history->blocks.front()->items.front()->isGroupMigrate()) { _historySkipHeight += _history->blocks.front()->items.front()->height(); } else { _historySkipHeight += _history->blocks.front()->items.front()->displayedDateHeight(); } } } } updateBotInfo(false); if (_botAbout && !_botAbout->info->text.isEmpty()) { int32 tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); if (tw > st::msgMaxWidth) tw = st::msgMaxWidth; tw -= st::msgPadding.left() + st::msgPadding.right(); int32 mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); if (tw > mw) tw = mw; _botAbout->width = tw; _botAbout->height = _botAbout->info->text.countHeight(_botAbout->width); int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); int32 descMaxWidth = _scroll->width(); if (Adaptive::Wide()) { descMaxWidth = qMin(descMaxWidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } int32 descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); int32 descAtY = qMin(_historyOffset - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } else if (_botAbout) { _botAbout->width = _botAbout->height = 0; _botAbout->rect = QRect(); } int32 newYSkip = ph - historyHeight() - st::historyPadding; if (_botAbout && !_botAbout->info->text.isEmpty()) { minadd = st::msgMargin.top() + st::msgMargin.bottom() + st::msgPadding.top() + st::msgPadding.bottom() + st::msgNameFont->height + st::botDescSkip + _botAbout->height; } if (newYSkip < minadd) newYSkip = minadd; if (newYSkip != wasYSkip) { if (_history->scrollTopItem) { _history->scrollTopOffset += (newYSkip - wasYSkip); } else if (_migrated && _migrated->scrollTopItem) { _migrated->scrollTopOffset += (newYSkip - wasYSkip); } } } void HistoryInner::updateBotInfo(bool recount) { int newh = 0; if (_botAbout && !_botAbout->info->description.isEmpty()) { if (_botAbout->info->text.isEmpty()) { _botAbout->info->text.setText(st::msgFont, _botAbout->info->description, _historyBotNoMonoOptions); if (recount) { int32 tw = _scroll->width() - st::msgMargin.left() - st::msgMargin.right(); if (tw > st::msgMaxWidth) tw = st::msgMaxWidth; tw -= st::msgPadding.left() + st::msgPadding.right(); int32 mw = qMax(_botAbout->info->text.maxWidth(), st::msgNameFont->width(lang(lng_bot_description))); if (tw > mw) tw = mw; _botAbout->width = tw; newh = _botAbout->info->text.countHeight(_botAbout->width); } } else if (recount) { newh = _botAbout->height; } } if (recount && _botAbout) { if (_botAbout->height != newh) { _botAbout->height = newh; updateSize(); } if (_botAbout->height > 0) { int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); int32 descAtX = (_scroll->width() - _botAbout->width) / 2 - st::msgPadding.left(); int32 descAtY = qMin(_historyOffset - descH, (_scroll->height() - descH) / 2) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } else { _botAbout->width = 0; _botAbout->rect = QRect(); } } } bool HistoryInner::wasSelectedText() const { return _wasSelectedText; } void HistoryInner::setFirstLoading(bool loading) { _firstLoading = loading; update(); } HistoryItem *HistoryInner::atTopImportantMsg(int32 top, int32 height, int32 &bottomUnderScrollTop) const { adjustCurrent(top); if (!_curHistory || _curHistory->isEmpty() || _curHistory != _history) return 0; for (int32 blockIndex = _curBlock + 1, itemIndex = _curItem + 1; blockIndex > 0;) { --blockIndex; HistoryBlock *block = _history->blocks[blockIndex]; if (!itemIndex) itemIndex = block->items.size(); for (; itemIndex > 0;) { --itemIndex; HistoryItem *item = block->items[itemIndex]; if (item->isImportant()) { bottomUnderScrollTop = qMin(0, itemTop(item) + item->height() - top); return item; } } itemIndex = 0; } for (int32 blockIndex = _curBlock, itemIndex = _curItem + 1; blockIndex < _history->blocks.size(); ++blockIndex) { HistoryBlock *block = _history->blocks[blockIndex]; for (; itemIndex < block->items.size(); ++itemIndex) { HistoryItem *item = block->items[itemIndex]; if (item->isImportant()) { bottomUnderScrollTop = qMin(0, itemTop(item) + item->height() - top); return item; } } itemIndex = 0; } return 0; } void HistoryInner::visibleAreaUpdated(int top, int bottom) { _visibleAreaTop = top; _visibleAreaBottom = bottom; // if history has pending resize events we should not update scrollTopItem if (hasPendingResizedItems()) { return; } if (bottom >= historyHeight()) { _history->forgetScrollState(); if (_migrated) { _migrated->forgetScrollState(); } } else { int htop = historyTop(), mtop = migratedTop(); if ((htop >= 0 && top >= htop) || mtop < 0) { _history->countScrollState(top - htop); if (_migrated) { _migrated->forgetScrollState(); } } else if (mtop >= 0 && top >= mtop) { _history->forgetScrollState(); _migrated->countScrollState(top - mtop); } else { _history->countScrollState(top - htop); if (_migrated) { _migrated->forgetScrollState(); } } } } void HistoryInner::updateSize() { int32 ph = _scroll->height(), minadd = 0; int32 newYSkip = ph - historyHeight() - st::historyPadding; if (_botAbout && !_botAbout->info->text.isEmpty()) { minadd = st::msgMargin.top() + st::msgMargin.bottom() + st::msgPadding.top() + st::msgPadding.bottom() + st::msgNameFont->height + st::botDescSkip + _botAbout->height; } if (newYSkip < minadd) newYSkip = minadd; if (_botAbout && _botAbout->height > 0) { int32 descH = st::msgMargin.top() + st::msgPadding.top() + st::msgNameFont->height + st::botDescSkip + _botAbout->height + st::msgPadding.bottom() + st::msgMargin.bottom(); int32 descMaxWidth = _scroll->width(); if (Adaptive::Wide()) { descMaxWidth = qMin(descMaxWidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left())); } int32 descAtX = (descMaxWidth - _botAbout->width) / 2 - st::msgPadding.left(); int32 descAtY = qMin(newYSkip - descH, qMax(0, (_scroll->height() - descH) / 2)) + st::msgMargin.top(); _botAbout->rect = QRect(descAtX, descAtY, _botAbout->width + st::msgPadding.left() + st::msgPadding.right(), descH - st::msgMargin.top() - st::msgMargin.bottom()); } int32 yAdded = newYSkip - _historyOffset; _historyOffset = newYSkip; int32 nh = _historyOffset + historyHeight() + st::historyPadding; if (width() != _scroll->width() || height() != nh) { resize(_scroll->width(), nh); dragActionUpdate(QCursor::pos()); } else { update(); } } void HistoryInner::enterEvent(QEvent *e) { dragActionUpdate(QCursor::pos()); // return QWidget::enterEvent(e); } void HistoryInner::leaveEvent(QEvent *e) { if (HistoryItem *item = App::hoveredItem()) { repaintItem(item); App::hoveredItem(nullptr); } ClickHandler::clearActive(); if (!ClickHandler::getPressed() && _cursor != style::cur_default) { _cursor = style::cur_default; setCursor(_cursor); } return QWidget::leaveEvent(e); } HistoryInner::~HistoryInner() { delete _menu; _dragAction = NoDrag; } void HistoryInner::adjustCurrent(int32 y) const { int32 htop = historyTop(), hdrawtop = historyDrawTop(), mtop = migratedTop(); _curHistory = 0; if (mtop >= 0) { adjustCurrent(y - mtop, _migrated); } if (htop >= 0 && hdrawtop >= 0 && (mtop < 0 || y >= hdrawtop)) { adjustCurrent(y - htop, _history); } } void HistoryInner::adjustCurrent(int32 y, History *history) const { t_assert(!history->isEmpty()); _curHistory = history; if (_curBlock >= history->blocks.size()) { _curBlock = history->blocks.size() - 1; _curItem = 0; } while (history->blocks.at(_curBlock)->y > y && _curBlock > 0) { --_curBlock; _curItem = 0; } while (history->blocks.at(_curBlock)->y + history->blocks.at(_curBlock)->height <= y && _curBlock + 1 < history->blocks.size()) { ++_curBlock; _curItem = 0; } HistoryBlock *block = history->blocks.at(_curBlock); if (_curItem >= block->items.size()) { _curItem = block->items.size() - 1; } int by = block->y; while (block->items.at(_curItem)->y + by > y && _curItem > 0) { --_curItem; } while (block->items.at(_curItem)->y + block->items.at(_curItem)->height() + by <= y && _curItem + 1 < block->items.size()) { ++_curItem; } } HistoryItem *HistoryInner::prevItem(HistoryItem *item) { if (!item || item->detached()) return nullptr; HistoryBlock *block = item->block(); int blockIndex = block->indexInHistory(), itemIndex = item->indexInBlock(); if (itemIndex > 0) { return block->items.at(itemIndex - 1); } if (blockIndex > 0) { return item->history()->blocks.at(blockIndex - 1)->items.back(); } if (item->history() == _history && _migrated && _history->loadedAtTop() && !_migrated->isEmpty() && _migrated->loadedAtBottom()) { return _migrated->blocks.back()->items.back(); } return nullptr; } HistoryItem *HistoryInner::nextItem(HistoryItem *item) { if (!item || item->detached()) return nullptr; HistoryBlock *block = item->block(); int blockIndex = block->indexInHistory(), itemIndex = item->indexInBlock(); if (itemIndex + 1 < block->items.size()) { return block->items.at(itemIndex + 1); } if (blockIndex + 1 < item->history()->blocks.size()) { return item->history()->blocks.at(blockIndex + 1)->items.front(); } if (item->history() == _migrated && _history && _migrated->loadedAtBottom() && _history->loadedAtTop() && !_history->isEmpty()) { return _history->blocks.front()->items.front(); } return nullptr; } bool HistoryInner::canCopySelected() const { return !_selected.isEmpty(); } bool HistoryInner::canDeleteSelected() const { if (_selected.isEmpty() || _selected.cbegin().value() != FullSelection) return false; int32 selectedForForward, selectedForDelete; getSelectionState(selectedForForward, selectedForDelete); return (selectedForForward == selectedForDelete); } void HistoryInner::getSelectionState(int32 &selectedForForward, int32 &selectedForDelete) const { selectedForForward = selectedForDelete = 0; for (SelectedItems::const_iterator i = _selected.cbegin(), e = _selected.cend(); i != e; ++i) { if (i.key()->type() == HistoryItemMsg && i.value() == FullSelection) { if (i.key()->canDelete()) { ++selectedForDelete; } ++selectedForForward; } } if (!selectedForDelete && !selectedForForward && !_selected.isEmpty()) { // text selection selectedForForward = -1; } } void HistoryInner::clearSelectedItems(bool onlyTextSelection) { if (!_selected.isEmpty() && (!onlyTextSelection || _selected.cbegin().value() != FullSelection)) { _selected.clear(); _widget->updateTopBarSelection(); _widget->update(); } } void HistoryInner::fillSelectedItems(SelectedItemSet &sel, bool forDelete) { if (_selected.isEmpty() || _selected.cbegin().value() != FullSelection) return; for (SelectedItems::const_iterator i = _selected.cbegin(), e = _selected.cend(); i != e; ++i) { HistoryItem *item = i.key(); if (item && item->toHistoryMessage() && item->id > 0) { if (item->history() == _migrated) { sel.insert(item->id - ServerMaxMsgId, item); } else { sel.insert(item->id, item); } } } } void HistoryInner::selectItem(HistoryItem *item) { if (!_selected.isEmpty() && _selected.cbegin().value() != FullSelection) { _selected.clear(); } else if (_selected.size() == MaxSelectedItems && _selected.constFind(item) == _selected.cend()) { return; } _selected.insert(item, FullSelection); _widget->updateTopBarSelection(); _widget->update(); } void HistoryInner::onTouchSelect() { _touchSelect = true; dragActionStart(_touchPos); } void HistoryInner::onUpdateSelected() { if (!_history || hasPendingResizedItems()) { return; } QPoint mousePos(mapFromGlobal(_dragPos)); QPoint point(_widget->clampMousePosition(mousePos)); HistoryBlock *block = 0; HistoryItem *item = 0; QPoint m; adjustCurrent(point.y()); if (_curHistory && !_curHistory->isEmpty()) { block = _curHistory->blocks[_curBlock]; item = block->items[_curItem]; App::mousedItem(item); m = mapMouseToItem(point, item); if (item->hasPoint(m.x(), m.y())) { if (App::hoveredItem() != item) { repaintItem(App::hoveredItem()); App::hoveredItem(item); repaintItem(App::hoveredItem()); } } else if (App::hoveredItem()) { repaintItem(App::hoveredItem()); App::hoveredItem(0); } } if (_dragItem && _dragItem->detached()) { dragActionCancel(); } HistoryTextState dragState; ClickHandlerHost *lnkhost = nullptr; bool selectingText = (item == _dragItem && item == App::hoveredItem() && !_selected.isEmpty() && _selected.cbegin().value() != FullSelection); if (point.y() < _historyOffset) { if (_botAbout && !_botAbout->info->text.isEmpty() && _botAbout->height > 0) { dragState = _botAbout->info->text.getState(point.x() - _botAbout->rect.left() - st::msgPadding.left(), point.y() - _botAbout->rect.top() - st::msgPadding.top() - st::botDescSkip - st::msgNameFont->height, _botAbout->width); lnkhost = _botAbout.get(); } } else if (item) { if (item != _dragItem || (m - _dragStartPos).manhattanLength() >= QApplication::startDragDistance()) { if (_dragAction == PrepareDrag) { _dragAction = Dragging; QTimer::singleShot(1, this, SLOT(onDragExec())); } else if (_dragAction == PrepareSelect) { _dragAction = Selecting; } } HistoryStateRequest request; if (_dragAction == Selecting) { request.flags |= Text::StateRequest::Flag::LookupSymbol; } else { selectingText = false; } dragState = item->getState(m.x(), m.y(), request); lnkhost = item; if (!dragState.link && m.x() >= st::msgMargin.left() && m.x() < st::msgMargin.left() + st::msgPhotoSize) { if (HistoryMessage *msg = item->toHistoryMessage()) { if (msg->hasFromPhoto()) { enumerateUserpics([&dragState, &lnkhost, &point](HistoryMessage *message, int userpicTop) -> bool { // stop enumeration if the userpic is above our point if (userpicTop + st::msgPhotoSize <= point.y()) { return false; } // stop enumeration if we've found a userpic under the cursor if (point.y() >= userpicTop && point.y() < userpicTop + st::msgPhotoSize) { dragState.link = message->from()->openLink(); lnkhost = message; return false; } return true; }); } } } } bool lnkChanged = ClickHandler::setActive(dragState.link, lnkhost); if (lnkChanged || dragState.cursor != _dragCursorState) { PopupTooltip::Hide(); } if (dragState.link || dragState.cursor == HistoryInDateCursorState || dragState.cursor == HistoryInForwardedCursorState) { PopupTooltip::Show(1000, this); } Qt::CursorShape cur = style::cur_default; if (_dragAction == NoDrag) { _dragCursorState = dragState.cursor; if (dragState.link) { cur = style::cur_pointer; } else if (_dragCursorState == HistoryInTextCursorState && (_selected.isEmpty() || _selected.cbegin().value() != FullSelection)) { cur = style::cur_text; } else if (_dragCursorState == HistoryInDateCursorState) { // cur = style::cur_cross; } } else if (item) { if (_dragAction == Selecting) { bool canSelectMany = (_history != nullptr); if (selectingText) { uint16 second = dragState.symbol; if (dragState.afterSymbol && _dragSelType == TextSelectLetters) { ++second; } auto selState = _dragItem->adjustSelection({ qMin(second, _dragSymbol), qMax(second, _dragSymbol) }, _dragSelType); if (_selected[_dragItem] != selState) { _selected[_dragItem] = selState; repaintItem(_dragItem); } if (!_wasSelectedText && (selState == FullSelection || selState.from != selState.to)) { _wasSelectedText = true; setFocus(); } updateDragSelection(0, 0, false); } else if (canSelectMany) { bool selectingDown = (itemTop(_dragItem) < itemTop(item)) || (_dragItem == item && _dragStartPos.y() < m.y()); HistoryItem *dragSelFrom = _dragItem, *dragSelTo = item; if (!dragSelFrom->hasPoint(_dragStartPos.x(), _dragStartPos.y())) { // maybe exclude dragSelFrom if (selectingDown) { if (_dragStartPos.y() >= dragSelFrom->height() - dragSelFrom->marginBottom() || ((item == dragSelFrom) && (m.y() < _dragStartPos.y() + QApplication::startDragDistance() || m.y() < dragSelFrom->marginTop()))) { dragSelFrom = (dragSelFrom == dragSelTo) ? 0 : nextItem(dragSelFrom); } } else { if (_dragStartPos.y() < dragSelFrom->marginTop() || ((item == dragSelFrom) && (m.y() >= _dragStartPos.y() - QApplication::startDragDistance() || m.y() >= dragSelFrom->height() - dragSelFrom->marginBottom()))) { dragSelFrom = (dragSelFrom == dragSelTo) ? 0 : prevItem(dragSelFrom); } } } if (_dragItem != item) { // maybe exclude dragSelTo if (selectingDown) { if (m.y() < dragSelTo->marginTop()) { dragSelTo = (dragSelFrom == dragSelTo) ? 0 : prevItem(dragSelTo); } } else { if (m.y() >= dragSelTo->height() - dragSelTo->marginBottom()) { dragSelTo = (dragSelFrom == dragSelTo) ? 0 : nextItem(dragSelTo); } } } bool dragSelecting = false; HistoryItem *dragFirstAffected = dragSelFrom; while (dragFirstAffected && (dragFirstAffected->id < 0 || dragFirstAffected->serviceMsg())) { dragFirstAffected = (dragFirstAffected == dragSelTo) ? 0 : (selectingDown ? nextItem(dragFirstAffected) : prevItem(dragFirstAffected)); } if (dragFirstAffected) { SelectedItems::const_iterator i = _selected.constFind(dragFirstAffected); dragSelecting = (i == _selected.cend() || i.value() != FullSelection); } updateDragSelection(dragSelFrom, dragSelTo, dragSelecting); } } else if (_dragAction == Dragging) { } if (ClickHandler::getPressed()) { cur = style::cur_pointer; } else if (_dragAction == Selecting && !_selected.isEmpty() && _selected.cbegin().value() != FullSelection) { if (!_dragSelFrom || !_dragSelTo) { cur = style::cur_text; } } } if (_dragAction == Selecting) { _widget->checkSelectingScroll(mousePos); } else { updateDragSelection(0, 0, false); _widget->noSelectingScroll(); } if (_dragAction == NoDrag && (lnkChanged || cur != _cursor)) { setCursor(_cursor = cur); } } void HistoryInner::updateDragSelection(HistoryItem *dragSelFrom, HistoryItem *dragSelTo, bool dragSelecting, bool force) { if (_dragSelFrom != dragSelFrom || _dragSelTo != dragSelTo || _dragSelecting != dragSelecting) { _dragSelFrom = dragSelFrom; _dragSelTo = dragSelTo; int32 fromy = itemTop(_dragSelFrom), toy = itemTop(_dragSelTo); if (fromy >= 0 && toy >= 0 && fromy > toy) { qSwap(_dragSelFrom, _dragSelTo); } _dragSelecting = dragSelecting; if (!_wasSelectedText && _dragSelFrom && _dragSelTo && _dragSelecting) { _wasSelectedText = true; setFocus(); } force = true; } if (!force) return; update(); } void HistoryInner::BotAbout::clickHandlerActiveChanged(const ClickHandlerPtr &p, bool active) { _parent->update(rect); } void HistoryInner::BotAbout::clickHandlerPressedChanged(const ClickHandlerPtr &p, bool pressed) { _parent->update(rect); } int HistoryInner::historyHeight() const { int result = 0; if (!_history || _history->isEmpty()) { result += _migrated ? _migrated->height : 0; } else { result += _history->height - _historySkipHeight + (_migrated ? _migrated->height : 0); } return result; } int HistoryInner::historyScrollTop() const { int htop = historyTop(), mtop = migratedTop(); if (htop >= 0 && _history->scrollTopItem) { t_assert(!_history->scrollTopItem->detached()); return htop + _history->scrollTopItem->block()->y + _history->scrollTopItem->y + _history->scrollTopOffset; } if (mtop >= 0 && _migrated->scrollTopItem) { t_assert(!_migrated->scrollTopItem->detached()); return mtop + _migrated->scrollTopItem->block()->y + _migrated->scrollTopItem->y + _migrated->scrollTopOffset; } return ScrollMax; } int HistoryInner::migratedTop() const { return (_migrated && !_migrated->isEmpty()) ? _historyOffset : -1; } int HistoryInner::historyTop() const { int mig = migratedTop(); return (_history && !_history->isEmpty()) ? (mig >= 0 ? (mig + _migrated->height - _historySkipHeight) : _historyOffset) : -1; } int HistoryInner::historyDrawTop() const { int his = historyTop(); return (his >= 0) ? (his + _historySkipHeight) : -1; } int HistoryInner::itemTop(const HistoryItem *item) const { // -1 if should not be visible, -2 if bad history() if (!item) return -2; if (item->detached()) return -1; int top = (item->history() == _history) ? historyTop() : (item->history() == _migrated ? migratedTop() : -2); return (top < 0) ? top : (top + item->y + item->block()->y); } void HistoryInner::notifyIsBotChanged() { BotInfo *newinfo = (_history && _history->peer->isUser()) ? _history->peer->asUser()->botInfo : nullptr; if ((!newinfo && !_botAbout) || (newinfo && _botAbout && _botAbout->info == newinfo)) { return; } if (newinfo) { _botAbout.reset(new BotAbout(this, newinfo)); if (newinfo && !newinfo->inited && App::api()) { App::api()->requestFullPeer(_peer); } } else { _botAbout = nullptr; } } void HistoryInner::notifyMigrateUpdated() { _migrated = _peer->migrateFrom() ? App::history(_peer->migrateFrom()->id) : 0; } int HistoryInner::moveScrollFollowingInlineKeyboard(const HistoryItem *item, int oldKeyboardTop, int newKeyboardTop) { if (item == App::mousedItem()) { int top = itemTop(item); if (top >= oldKeyboardTop) { return newKeyboardTop - oldKeyboardTop; } } return 0; } void HistoryInner::applyDragSelection() { applyDragSelection(&_selected); } void HistoryInner::addSelectionRange(SelectedItems *toItems, int32 fromblock, int32 fromitem, int32 toblock, int32 toitem, History *h) const { if (fromblock >= 0 && fromitem >= 0 && toblock >= 0 && toitem >= 0) { for (; fromblock <= toblock; ++fromblock) { HistoryBlock *block = h->blocks[fromblock]; for (int32 cnt = (fromblock < toblock) ? block->items.size() : (toitem + 1); fromitem < cnt; ++fromitem) { HistoryItem *item = block->items[fromitem]; SelectedItems::iterator i = toItems->find(item); if (item->id > 0 && !item->serviceMsg()) { if (i == toItems->cend()) { if (toItems->size() >= MaxSelectedItems) break; toItems->insert(item, FullSelection); } else if (i.value() != FullSelection) { *i = FullSelection; } } else { if (i != toItems->cend()) { toItems->erase(i); } } } if (toItems->size() >= MaxSelectedItems) break; fromitem = 0; } } } void HistoryInner::applyDragSelection(SelectedItems *toItems) const { int32 selfromy = itemTop(_dragSelFrom), seltoy = itemTop(_dragSelTo); if (selfromy < 0 || seltoy < 0) { return; } seltoy += _dragSelTo->height(); if (!toItems->isEmpty() && toItems->cbegin().value() != FullSelection) { toItems->clear(); } if (_dragSelecting) { int32 fromblock = _dragSelFrom->block()->indexInHistory(), fromitem = _dragSelFrom->indexInBlock(); int32 toblock = _dragSelTo->block()->indexInHistory(), toitem = _dragSelTo->indexInBlock(); if (_migrated) { if (_dragSelFrom->history() == _migrated) { if (_dragSelTo->history() == _migrated) { addSelectionRange(toItems, fromblock, fromitem, toblock, toitem, _migrated); toblock = -1; toitem = -1; } else { addSelectionRange(toItems, fromblock, fromitem, _migrated->blocks.size() - 1, _migrated->blocks.back()->items.size() - 1, _migrated); } fromblock = 0; fromitem = 0; } else if (_dragSelTo->history() == _migrated) { // wtf toblock = -1; toitem = -1; } } addSelectionRange(toItems, fromblock, fromitem, toblock, toitem, _history); } else { for (SelectedItems::iterator i = toItems->begin(); i != toItems->cend();) { int32 iy = itemTop(i.key()); if (iy < 0) { if (iy < -1) i = toItems->erase(i); continue; } if (iy >= selfromy && iy < seltoy) { i = toItems->erase(i); } else { ++i; } } } } QString HistoryInner::tooltipText() const { if (_dragCursorState == HistoryInDateCursorState && _dragAction == NoDrag) { if (App::hoveredItem()) { QString dateText = App::hoveredItem()->date.toString(QLocale::system().dateTimeFormat(QLocale::LongFormat)); if (auto edited = App::hoveredItem()->Get()) { dateText += '\n' + lng_edited_date(lt_date, edited->_editDate.toString(QLocale::system().dateTimeFormat(QLocale::LongFormat))); } return dateText; } } else if (_dragCursorState == HistoryInForwardedCursorState && _dragAction == NoDrag) { if (App::hoveredItem()) { if (HistoryMessageForwarded *fwd = App::hoveredItem()->Get()) { return fwd->_text.originalText(AllTextSelection, ExpandLinksNone); } } } else if (ClickHandlerPtr lnk = ClickHandler::getActive()) { return lnk->tooltip(); } return QString(); } QPoint HistoryInner::tooltipPos() const { return _dragPos; } void HistoryInner::onParentGeometryChanged() { bool needToUpdate = (_dragAction != NoDrag || _touchScroll || rect().contains(mapFromGlobal(QCursor::pos()))); if (needToUpdate) { dragActionUpdate(QCursor::pos()); } } MessageField::MessageField(HistoryWidget *history, const style::flatTextarea &st, const QString &ph, const QString &val) : FlatTextarea(history, st, ph, val), history(history) { setMinHeight(st::btnSend.height - 2 * st::sendPadding); setMaxHeight(st::maxFieldHeight); } bool MessageField::hasSendText() const { auto &text(getTextWithTags().text); for (auto *ch = text.constData(), *e = ch + text.size(); ch != e; ++ch) { ushort code = ch->unicode(); if (code != ' ' && code != '\n' && code != '\r' && !chReplacedBySpace(code)) { return true; } } return false; } void MessageField::onEmojiInsert(EmojiPtr emoji) { if (isHidden()) return; insertEmoji(emoji, textCursor()); } void MessageField::dropEvent(QDropEvent *e) { FlatTextarea::dropEvent(e); if (e->isAccepted()) { App::wnd()->activateWindow(); } } bool MessageField::canInsertFromMimeData(const QMimeData *source) const { if (source->hasUrls()) { int32 files = 0; for (int32 i = 0; i < source->urls().size(); ++i) { if (source->urls().at(i).isLocalFile()) { ++files; } } if (files > 1) return false; // multiple confirm with "compressed" checkbox } if (source->hasImage()) return true; return FlatTextarea::canInsertFromMimeData(source); } void MessageField::insertFromMimeData(const QMimeData *source) { if (source->hasUrls()) { int32 files = 0; QUrl url; for (int32 i = 0; i < source->urls().size(); ++i) { if (source->urls().at(i).isLocalFile()) { url = source->urls().at(i); ++files; } } if (files == 1) { history->uploadFile(url.toLocalFile(), PrepareAuto, FileLoadAlwaysConfirm); return; } if (files > 1) return; //if (files > 1) return uploadFiles(files, PrepareAuto); // multiple confirm with "compressed" checkbox } if (source->hasImage()) { QImage img = qvariant_cast(source->imageData()); if (!img.isNull()) { history->uploadImage(img, PrepareAuto, FileLoadAlwaysConfirm, source->text()); return; } } FlatTextarea::insertFromMimeData(source); } void MessageField::focusInEvent(QFocusEvent *e) { FlatTextarea::focusInEvent(e); emit focused(); } ReportSpamPanel::ReportSpamPanel(HistoryWidget *parent) : TWidget(parent), _report(this, lang(lng_report_spam), st::reportSpamHide), _hide(this, lang(lng_report_spam_hide), st::reportSpamHide), _clear(this, lang(lng_profile_delete_conversation)) { resize(parent->width(), _hide.height() + st::lineWidth); connect(&_report, SIGNAL(clicked()), this, SIGNAL(reportClicked())); connect(&_hide, SIGNAL(clicked()), this, SIGNAL(hideClicked())); connect(&_clear, SIGNAL(clicked()), this, SIGNAL(clearClicked())); _clear.hide(); } void ReportSpamPanel::resizeEvent(QResizeEvent *e) { _report.resize(width() - (_hide.width() + st::reportSpamSeparator) * 2, _report.height()); _report.moveToLeft(_hide.width() + st::reportSpamSeparator, 0); _hide.moveToRight(0, 0); _clear.move((width() - _clear.width()) / 2, height() - _clear.height() - ((height() - st::msgFont->height - _clear.height()) / 2)); } void ReportSpamPanel::paintEvent(QPaintEvent *e) { Painter p(this); p.fillRect(QRect(0, 0, width(), height() - st::lineWidth), st::reportSpamBg->b); p.fillRect(Adaptive::OneColumn() ? 0 : st::lineWidth, height() - st::lineWidth, width() - (Adaptive::OneColumn() ? 0 : st::lineWidth), st::lineWidth, st::shadowColor->b); if (!_clear.isHidden()) { p.setPen(st::black->p); p.setFont(st::msgFont->f); p.drawText(QRect(_report.x(), (_clear.y() - st::msgFont->height) / 2, _report.width(), st::msgFont->height), lang(lng_report_spam_thanks), style::al_top); } } void ReportSpamPanel::setReported(bool reported, PeerData *onPeer) { if (reported) { _report.hide(); _clear.setText(lang(onPeer->isChannel() ? (onPeer->isMegagroup() ? lng_profile_leave_group : lng_profile_leave_channel) : lng_profile_delete_conversation)); _clear.show(); } else { _report.show(); _clear.hide(); } update(); } BotKeyboard::BotKeyboard() { setGeometry(0, 0, _st->margin, st::botKbScroll.deltat); _height = st::botKbScroll.deltat; setMouseTracking(true); } void BotKeyboard::paintEvent(QPaintEvent *e) { Painter p(this); QRect clip(e->rect()); p.fillRect(clip, st::white); if (_impl) { int x = rtl() ? st::botKbScroll.width : _st->margin; p.translate(x, st::botKbScroll.deltat); _impl->paint(p, clip.translated(-x, -st::botKbScroll.deltat)); } } void BotKeyboard::Style::startPaint(Painter &p) const { p.setPen(st::botKbColor); p.setFont(st::botKbFont); } style::font BotKeyboard::Style::textFont() const { return st::botKbFont; } void BotKeyboard::Style::repaint(const HistoryItem *item) const { _parent->update(); } void BotKeyboard::Style::paintButtonBg(Painter &p, const QRect &rect, bool down, float64 howMuchOver) const { if (down) { App::roundRect(p, rect, st::botKbDownBg, BotKeyboardDownCorners); } else { App::roundRect(p, rect, st::botKbBg, BotKeyboardCorners); if (howMuchOver > 0) { p.setOpacity(howMuchOver); App::roundRect(p, rect, st::botKbOverBg, BotKeyboardOverCorners); p.setOpacity(1); } } } void BotKeyboard::Style::paintButtonIcon(Painter &p, const QRect &rect, HistoryMessageReplyMarkup::Button::Type type) const { // Buttons with icons should not appear here. } void BotKeyboard::Style::paintButtonLoading(Painter &p, const QRect &rect) const { // Buttons with loading progress should not appear here. } int BotKeyboard::Style::minButtonWidth(HistoryMessageReplyMarkup::Button::Type type) const { int result = 2 * buttonPadding(); return result; } void BotKeyboard::resizeEvent(QResizeEvent *e) { if (!_impl) return; updateStyle(); _height = _impl->naturalHeight() + st::botKbScroll.deltat + st::botKbScroll.deltab; if (_maximizeSize) _height = qMax(_height, _maxOuterHeight); if (height() != _height) { resize(width(), _height); return; } _impl->resize(width() - _st->margin - st::botKbScroll.width, _height - (st::botKbScroll.deltat + st::botKbScroll.deltab)); } void BotKeyboard::mousePressEvent(QMouseEvent *e) { _lastMousePos = e->globalPos(); updateSelected(); ClickHandler::pressed(); } void BotKeyboard::mouseMoveEvent(QMouseEvent *e) { _lastMousePos = e->globalPos(); updateSelected(); } void BotKeyboard::mouseReleaseEvent(QMouseEvent *e) { _lastMousePos = e->globalPos(); updateSelected(); if (ClickHandlerPtr activated = ClickHandler::unpressed()) { App::activateClickHandler(activated, e->button()); } } void BotKeyboard::enterEvent(QEvent *e) { _lastMousePos = QCursor::pos(); updateSelected(); } void BotKeyboard::leaveEvent(QEvent *e) { clearSelection(); } void BotKeyboard::clickHandlerActiveChanged(const ClickHandlerPtr &p, bool active) { if (!_impl) return; _impl->clickHandlerActiveChanged(p, active); } void BotKeyboard::clickHandlerPressedChanged(const ClickHandlerPtr &p, bool pressed) { if (!_impl) return; _impl->clickHandlerPressedChanged(p, pressed); } bool BotKeyboard::updateMarkup(HistoryItem *to, bool force) { if (!to || !to->definesReplyKeyboard()) { if (_wasForMsgId.msg) { _maximizeSize = _singleUse = _forceReply = false; _wasForMsgId = FullMsgId(); _impl = nullptr; return true; } return false; } if (_wasForMsgId == FullMsgId(to->channelId(), to->id) && !force) { return false; } _wasForMsgId = FullMsgId(to->channelId(), to->id); auto markupFlags = to->replyKeyboardFlags(); _forceReply = markupFlags & MTPDreplyKeyboardMarkup_ClientFlag::f_force_reply; _maximizeSize = !(markupFlags & MTPDreplyKeyboardMarkup::Flag::f_resize); _singleUse = _forceReply || (markupFlags & MTPDreplyKeyboardMarkup::Flag::f_single_use); _impl = nullptr; if (auto markup = to->Get()) { if (!markup->rows.isEmpty()) { _impl.reset(new ReplyKeyboard(to, std_::make_unique