history_inner_widget.cpp 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "history/history_inner_widget.h"
  8. #include "chat_helpers/stickers_emoji_pack.h"
  9. #include "core/file_utilities.h"
  10. #include "core/click_handler_types.h"
  11. #include "core/phone_click_handler.h"
  12. #include "history/history_item_helpers.h"
  13. #include "history/view/controls/history_view_forward_panel.h"
  14. #include "history/view/controls/history_view_draft_options.h"
  15. #include "boxes/moderate_messages_box.h"
  16. #include "history/view/media/history_view_sticker.h"
  17. #include "history/view/media/history_view_web_page.h"
  18. #include "history/view/reactions/history_view_reactions.h"
  19. #include "history/view/reactions/history_view_reactions_button.h"
  20. #include "history/view/reactions/history_view_reactions_selector.h"
  21. #include "history/view/history_view_about_view.h"
  22. #include "history/view/history_view_message.h"
  23. #include "history/view/history_view_service_message.h"
  24. #include "history/view/history_view_cursor_state.h"
  25. #include "history/view/history_view_context_menu.h"
  26. #include "history/view/history_view_quick_action.h"
  27. #include "history/view/history_view_emoji_interactions.h"
  28. #include "history/history_item_components.h"
  29. #include "history/history_item_text.h"
  30. #include "payments/payments_reaction_process.h"
  31. #include "ui/widgets/menu/menu_add_action_callback_factory.h"
  32. #include "ui/widgets/menu/menu_multiline_action.h"
  33. #include "ui/widgets/popup_menu.h"
  34. #include "ui/effects/path_shift_gradient.h"
  35. #include "ui/effects/message_sending_animation_controller.h"
  36. #include "ui/effects/reaction_fly_animation.h"
  37. #include "ui/text/text_isolated_emoji.h"
  38. #include "ui/text/text_utilities.h"
  39. #include "ui/boxes/edit_factcheck_box.h"
  40. #include "ui/boxes/report_box_graphics.h"
  41. #include "ui/controls/delete_message_context_action.h"
  42. #include "ui/controls/swipe_handler.h"
  43. #include "ui/inactive_press.h"
  44. #include "ui/painter.h"
  45. #include "ui/rect.h"
  46. #include "ui/ui_utility.h"
  47. #include "window/window_session_controller.h"
  48. #include "window/window_controller.h"
  49. #include "window/window_peer_menu.h"
  50. #include "window/notifications_manager.h"
  51. #include "info/info_memento.h"
  52. #include "info/statistics/info_statistics_widget.h"
  53. #include "boxes/about_sponsored_box.h"
  54. #include "boxes/delete_messages_box.h"
  55. #include "boxes/report_messages_box.h"
  56. #include "boxes/star_gift_box.h" // ShowStarGiftBox
  57. #include "boxes/sticker_set_box.h"
  58. #include "boxes/translate_box.h"
  59. #include "chat_helpers/message_field.h"
  60. #include "chat_helpers/emoji_interactions.h"
  61. #include "history/history_widget.h"
  62. #include "history/view/history_view_translate_tracker.h"
  63. #include "base/platform/base_platform_info.h"
  64. #include "base/qt/qt_common_adapters.h"
  65. #include "base/qt/qt_key_modifiers.h"
  66. #include "base/unixtime.h"
  67. #include "base/call_delayed.h"
  68. #include "main/main_session.h"
  69. #include "main/main_session_settings.h"
  70. #include "mainwidget.h"
  71. #include "menu/menu_item_download_files.h"
  72. #include "menu/menu_sponsored.h"
  73. #include "core/application.h"
  74. #include "apiwrap.h"
  75. #include "api/api_attached_stickers.h"
  76. #include "api/api_toggling_media.h"
  77. #include "api/api_who_reacted.h"
  78. #include "api/api_views.h"
  79. #include "lang/lang_keys.h"
  80. #include "data/components/factchecks.h"
  81. #include "data/components/sponsored_messages.h"
  82. #include "data/data_session.h"
  83. #include "data/data_document.h"
  84. #include "data/data_channel.h"
  85. #include "data/data_forum_topic.h"
  86. #include "data/data_photo_media.h"
  87. #include "data/data_peer_values.h"
  88. #include "data/data_chat.h"
  89. #include "data/data_user.h"
  90. #include "data/data_file_click_handler.h"
  91. #include "data/data_histories.h"
  92. #include "data/data_changes.h"
  93. #include "dialogs/ui/dialogs_video_userpic.h"
  94. #include "styles/style_chat.h"
  95. #include "styles/style_menu_icons.h"
  96. #include <QtGui/QClipboard>
  97. #include <QtWidgets/QApplication>
  98. #include <QtCore/QMimeData>
  99. namespace {
  100. constexpr auto kScrollDateHideTimeout = 1000;
  101. constexpr auto kUnloadHeavyPartsPages = 2;
  102. constexpr auto kClearUserpicsAfter = 50;
  103. // Helper binary search for an item in a list that is not completely
  104. // above the given top of the visible area or below the given bottom of the visible area
  105. // is applied once for blocks list in a history and once for items list in the found block.
  106. template <bool TopToBottom, typename T>
  107. int BinarySearchBlocksOrItems(const T &list, int edge) {
  108. // static_cast to work around GCC bug #78693
  109. auto start = 0, end = static_cast<int>(list.size());
  110. while (end - start > 1) {
  111. auto middle = (start + end) / 2;
  112. auto top = list[middle]->y();
  113. auto chooseLeft = (TopToBottom ? (top <= edge) : (top < edge));
  114. if (chooseLeft) {
  115. start = middle;
  116. } else {
  117. end = middle;
  118. }
  119. }
  120. return start;
  121. }
  122. } // namespace
  123. // flick scroll taken from http://qt-project.org/doc/qt-4.8/demos-embedded-anomaly-src-flickcharm-cpp.html
  124. HistoryMainElementDelegateMixin::HistoryMainElementDelegateMixin() = default;
  125. HistoryMainElementDelegateMixin::~HistoryMainElementDelegateMixin()
  126. = default;
  127. class HistoryMainElementDelegate final
  128. : public HistoryView::ElementDelegate
  129. , public HistoryMainElementDelegateMixin {
  130. public:
  131. using Element = HistoryView::Element;
  132. HistoryView::Context elementContext() override {
  133. return HistoryView::Context::History;
  134. }
  135. bool elementUnderCursor(
  136. not_null<const Element*> view) override {
  137. return (Element::Moused() == view);
  138. }
  139. HistoryView::SelectionModeResult elementInSelectionMode(
  140. const Element *view) override {
  141. if (view && view->data()->isSponsored()) {
  142. return HistoryView::SelectionModeResult();
  143. }
  144. return _widget
  145. ? _widget->inSelectionMode()
  146. : HistoryView::SelectionModeResult();
  147. }
  148. bool elementIntersectsRange(
  149. not_null<const Element*> view,
  150. int from,
  151. int till) override {
  152. return _widget
  153. ? _widget->elementIntersectsRange(view, from, till)
  154. : false;
  155. }
  156. void elementStartStickerLoop(
  157. not_null<const Element*> view) override {
  158. if (_widget) {
  159. _widget->elementStartStickerLoop(view);
  160. }
  161. }
  162. void elementShowPollResults(
  163. not_null<PollData*> poll,
  164. FullMsgId context) override {
  165. if (_widget) {
  166. _widget->elementShowPollResults(poll, context);
  167. }
  168. }
  169. void elementOpenPhoto(
  170. not_null<PhotoData*> photo,
  171. FullMsgId context) override {
  172. if (_widget) {
  173. _widget->elementOpenPhoto(photo, context);
  174. }
  175. }
  176. void elementOpenDocument(
  177. not_null<DocumentData*> document,
  178. FullMsgId context,
  179. bool showInMediaView = false) override {
  180. if (_widget) {
  181. _widget->elementOpenDocument(
  182. document,
  183. context,
  184. showInMediaView);
  185. }
  186. }
  187. void elementCancelUpload(const FullMsgId &context) override {
  188. if (_widget) {
  189. _widget->elementCancelUpload(context);
  190. }
  191. }
  192. void elementShowTooltip(
  193. const TextWithEntities &text,
  194. Fn<void()> hiddenCallback) override {
  195. if (_widget) {
  196. _widget->elementShowTooltip(text, hiddenCallback);
  197. }
  198. }
  199. bool elementAnimationsPaused() override {
  200. return _widget ? _widget->elementAnimationsPaused() : false;
  201. }
  202. bool elementHideReply(not_null<const Element*> view) override {
  203. if (!view->isTopicRootReply()) {
  204. return false;
  205. }
  206. const auto reply = view->data()->Get<HistoryMessageReply>();
  207. return reply && !reply->fields().manualQuote;
  208. }
  209. bool elementShownUnread(not_null<const Element*> view) override {
  210. return view->data()->unread(view->data()->history());
  211. }
  212. void elementSendBotCommand(
  213. const QString &command,
  214. const FullMsgId &context) override {
  215. if (_widget) {
  216. _widget->elementSendBotCommand(command, context);
  217. }
  218. }
  219. void elementSearchInList(
  220. const QString &query,
  221. const FullMsgId &context) override {
  222. if (_widget) {
  223. _widget->elementSearchInList(query, context);
  224. }
  225. }
  226. void elementHandleViaClick(not_null<UserData*> bot) override {
  227. if (_widget) {
  228. _widget->elementHandleViaClick(bot);
  229. }
  230. }
  231. bool elementIsChatWide() override {
  232. return _widget ? _widget->elementIsChatWide() : false;
  233. }
  234. not_null<Ui::PathShiftGradient*> elementPathShiftGradient() override {
  235. Expects(_widget != nullptr);
  236. return _widget->elementPathShiftGradient();
  237. }
  238. void elementReplyTo(const FullReplyTo &to) override {
  239. if (_widget) {
  240. _widget->elementReplyTo(to);
  241. }
  242. }
  243. void elementStartInteraction(not_null<const Element*> view) override {
  244. if (_widget) {
  245. _widget->elementStartInteraction(view);
  246. }
  247. }
  248. void elementStartPremium(
  249. not_null<const Element*> view,
  250. Element *replacing) override {
  251. if (_widget) {
  252. _widget->elementStartPremium(view, replacing);
  253. }
  254. }
  255. void elementCancelPremium(not_null<const Element*> view) override {
  256. if (_widget) {
  257. _widget->elementCancelPremium(view);
  258. }
  259. }
  260. void elementStartEffect(
  261. not_null<const Element*> view,
  262. Element *replacing) override {
  263. if (_widget) {
  264. _widget->elementStartEffect(view, replacing);
  265. }
  266. }
  267. QString elementAuthorRank(not_null<const Element*> view) override {
  268. return {};
  269. }
  270. bool elementHideTopicButton(not_null<const Element*> view) override {
  271. return false;
  272. }
  273. not_null<HistoryView::ElementDelegate*> delegate() override {
  274. return this;
  275. }
  276. };
  277. HistoryInner::HistoryInner(
  278. not_null<HistoryWidget*> historyWidget,
  279. not_null<Ui::ScrollArea*> scroll,
  280. not_null<Window::SessionController*> controller,
  281. not_null<History*> history)
  282. : RpWidget(nullptr)
  283. , _widget(historyWidget)
  284. , _scroll(scroll)
  285. , _controller(controller)
  286. , _peer(history->peer)
  287. , _history(history)
  288. , _elementDelegate(_history->delegateMixin()->delegate())
  289. , _emojiInteractions(std::make_unique<HistoryView::EmojiInteractions>(
  290. this,
  291. controller->content(),
  292. &controller->session(),
  293. [=](not_null<const Element*> view) { return itemTop(view); }))
  294. , _migrated(history->migrateFrom())
  295. , _translateTracker(std::make_unique<HistoryView::TranslateTracker>(history))
  296. , _pathGradient(
  297. HistoryView::MakePathShiftGradient(
  298. controller->chatStyle(),
  299. [=] { update(); }))
  300. , _reactionsManager(
  301. std::make_unique<HistoryView::Reactions::Manager>(
  302. this,
  303. [=](QRect updated) { update(updated); }))
  304. , _touchSelectTimer([=] { onTouchSelect(); })
  305. , _touchScrollTimer([=] { onTouchScrollTimer(); })
  306. , _scrollDateCheck([this] { scrollDateCheck(); })
  307. , _scrollDateHideTimer([this] { scrollDateHideByTimer(); }) {
  308. _history->delegateMixin()->setCurrent(this);
  309. if (_migrated) {
  310. _migrated->delegateMixin()->setCurrent(this);
  311. _migrated->translateTo(_history->translatedTo());
  312. }
  313. Window::ChatThemeValueFromPeer(
  314. controller,
  315. _peer
  316. ) | rpl::start_with_next([=](std::shared_ptr<Ui::ChatTheme> &&theme) {
  317. _theme = std::move(theme);
  318. controller->setChatStyleTheme(_theme);
  319. }, lifetime());
  320. Assert(_theme != nullptr);
  321. setAttribute(Qt::WA_AcceptTouchEvents);
  322. refreshAboutView();
  323. setMouseTracking(true);
  324. _controller->gifPauseLevelChanged(
  325. ) | rpl::start_with_next([=] {
  326. if (!elementAnimationsPaused()) {
  327. update();
  328. }
  329. }, lifetime());
  330. using PlayRequest = ChatHelpers::EmojiInteractionPlayRequest;
  331. _controller->emojiInteractions().playRequests(
  332. ) | rpl::filter([=](const PlayRequest &request) {
  333. return (request.item->history() == _history)
  334. && _controller->widget()->isActive();
  335. }) | rpl::start_with_next([=](PlayRequest &&request) {
  336. if (const auto view = viewByItem(request.item)) {
  337. _emojiInteractions->play(std::move(request), view);
  338. }
  339. }, lifetime());
  340. _emojiInteractions->playStarted(
  341. ) | rpl::start_with_next([=](QString &&emoji) {
  342. _controller->emojiInteractions().playStarted(_peer, std::move(emoji));
  343. }, lifetime());
  344. _reactionsManager->chosen(
  345. ) | rpl::start_with_next([=](ChosenReaction reaction) {
  346. _reactionsManager->updateButton({});
  347. reactionChosen(reaction);
  348. }, lifetime());
  349. session().data().peerDecorationsUpdated(
  350. ) | rpl::start_with_next([=] {
  351. update();
  352. }, lifetime());
  353. session().data().itemRemoved(
  354. ) | rpl::start_with_next(
  355. [this](auto item) { itemRemoved(item); },
  356. lifetime());
  357. session().data().viewRemoved(
  358. ) | rpl::start_with_next(
  359. [this](auto view) { viewRemoved(view); },
  360. lifetime());
  361. rpl::merge(
  362. session().data().historyUnloaded(),
  363. session().data().historyCleared()
  364. ) | rpl::filter([this](not_null<const History*> history) {
  365. return (_history == history);
  366. }) | rpl::start_with_next([this] {
  367. mouseActionCancel();
  368. }, lifetime());
  369. session().data().viewRepaintRequest(
  370. ) | rpl::start_with_next([this](not_null<const Element*> view) {
  371. repaintItem(view);
  372. }, lifetime());
  373. session().data().viewLayoutChanged(
  374. ) | rpl::filter([=](not_null<const Element*> view) {
  375. return (view == viewByItem(view->data())) && view->isUnderCursor();
  376. }) | rpl::start_with_next([=](not_null<const Element*> view) {
  377. mouseActionUpdate();
  378. }, lifetime());
  379. session().data().itemDataChanges(
  380. ) | rpl::start_with_next([=](not_null<HistoryItem*> item) {
  381. if (const auto view = viewByItem(item)) {
  382. view->itemDataChanged();
  383. }
  384. }, lifetime());
  385. session().changes().historyUpdates(
  386. _history,
  387. (Data::HistoryUpdate::Flag::OutboxRead
  388. | Data::HistoryUpdate::Flag::TranslatedTo)
  389. ) | rpl::start_with_next([=] {
  390. update();
  391. }, lifetime());
  392. HistoryView::Reactions::SetupManagerList(
  393. _reactionsManager.get(),
  394. _reactionsItem.value());
  395. Core::App().settings().cornerReactionValue(
  396. ) | rpl::start_with_next([=](bool value) {
  397. _useCornerReaction = value;
  398. if (!value) {
  399. _reactionsManager->updateButton({});
  400. }
  401. }, lifetime());
  402. controller->adaptive().chatWideValue(
  403. ) | rpl::start_with_next([=](bool wide) {
  404. _isChatWide = wide;
  405. }, lifetime());
  406. _selectScroll.scrolls(
  407. ) | rpl::start_with_next([=](int d) {
  408. _scroll->scrollToY(_scroll->scrollTop() + d);
  409. }, _scroll->lifetime());
  410. setupSharingDisallowed();
  411. setupSwipeReplyAndBack();
  412. }
  413. void HistoryInner::reactionChosen(const ChosenReaction &reaction) {
  414. const auto item = session().data().message(reaction.context);
  415. if (!item) {
  416. return;
  417. } else if (reaction.id.paid()) {
  418. Payments::ShowPaidReactionDetails(
  419. _controller,
  420. item,
  421. viewByItem(item),
  422. HistoryReactionSource::Selector);
  423. return;
  424. } else if (Window::ShowReactPremiumError(
  425. _controller,
  426. item,
  427. reaction.id)) {
  428. if (_menu) {
  429. _menu->hideMenu();
  430. }
  431. return;
  432. }
  433. item->toggleReaction(reaction.id, HistoryReactionSource::Selector);
  434. if (!ranges::contains(item->chosenReactions(), reaction.id)) {
  435. return;
  436. } else if (const auto view = viewByItem(item)) {
  437. if (const auto top = itemTop(view); top >= 0) {
  438. const auto geometry = reaction.localGeometry.isEmpty()
  439. ? mapFromGlobal(reaction.globalGeometry)
  440. : reaction.localGeometry;
  441. view->animateReaction({
  442. .id = reaction.id,
  443. .flyIcon = reaction.icon,
  444. .flyFrom = geometry.translated(0, -top),
  445. });
  446. }
  447. }
  448. }
  449. Main::Session &HistoryInner::session() const {
  450. return _controller->session();
  451. }
  452. void HistoryInner::setupSharingDisallowed() {
  453. Expects(_peer != nullptr);
  454. if (_peer->isUser()) {
  455. _sharingDisallowed = false;
  456. return;
  457. }
  458. const auto chat = _peer->asChat();
  459. const auto channel = _peer->asChannel();
  460. _sharingDisallowed = chat
  461. ? Data::PeerFlagValue(chat, ChatDataFlag::NoForwards)
  462. : Data::PeerFlagValue(
  463. channel,
  464. ChannelDataFlag::NoForwards
  465. ) | rpl::type_erased();
  466. auto rights = chat
  467. ? chat->adminRightsValue()
  468. : channel->adminRightsValue();
  469. auto canDelete = std::move(
  470. rights
  471. ) | rpl::map([=] {
  472. return chat
  473. ? chat->canDeleteMessages()
  474. : channel->canDeleteMessages();
  475. });
  476. rpl::combine(
  477. _sharingDisallowed.value(),
  478. std::move(canDelete)
  479. ) | rpl::filter([=](bool disallowed, bool canDelete) {
  480. return hasSelectRestriction() && !getSelectedItems().empty();
  481. }) | rpl::start_with_next([=] {
  482. _widget->clearSelected();
  483. if (_mouseAction == MouseAction::PrepareSelect) {
  484. mouseActionCancel();
  485. }
  486. }, lifetime());
  487. }
  488. void HistoryInner::setupSwipeReplyAndBack() {
  489. if (!_peer) {
  490. return;
  491. }
  492. const auto peer = _peer;
  493. Ui::Controls::SetupSwipeHandler(this, _scroll, [=, history = _history](
  494. Ui::Controls::SwipeContextData data) {
  495. if (data.translation > 0) {
  496. if (!_swipeBackData.callback) {
  497. _swipeBackData = Ui::Controls::SetupSwipeBack(
  498. _widget,
  499. [=]() -> std::pair<QColor, QColor> {
  500. auto context = preparePaintContext({});
  501. return {
  502. context.st->msgServiceBg()->c,
  503. context.st->msgServiceFg()->c,
  504. };
  505. });
  506. }
  507. _swipeBackData.callback(data);
  508. return;
  509. } else if (_swipeBackData.lifetime) {
  510. _swipeBackData = {};
  511. }
  512. const auto changed = (_gestureHorizontal.msgBareId != data.msgBareId)
  513. || (_gestureHorizontal.translation != data.translation)
  514. || (_gestureHorizontal.reachRatio != data.reachRatio);
  515. if (changed) {
  516. _gestureHorizontal = data;
  517. const auto item = history->peer->owner().message(
  518. history->peer->id,
  519. MsgId{ data.msgBareId });
  520. if (item) {
  521. repaintItem(item);
  522. }
  523. }
  524. }, [=, show = _controller->uiShow()](
  525. int cursorTop,
  526. Qt::LayoutDirection direction) {
  527. if (direction == Qt::RightToLeft) {
  528. return Ui::Controls::DefaultSwipeBackHandlerFinishData([=] {
  529. _controller->showBackFromStack();
  530. });
  531. }
  532. auto result = Ui::Controls::SwipeHandlerFinishData();
  533. if (inSelectionMode().inSelectionMode
  534. || (peer->isChannel() && !peer->isMegagroup())) {
  535. return result;
  536. }
  537. enumerateItems<EnumItemsDirection::BottomToTop>([&](
  538. not_null<Element*> view,
  539. int itemtop,
  540. int itembottom) {
  541. if ((cursorTop < itemtop)
  542. || (cursorTop > itembottom)
  543. || !view->data()->isRegular()
  544. || view->data()->isService()) {
  545. return true;
  546. }
  547. const auto item = view->data();
  548. const auto canSendReply = CanSendReply(item);
  549. const auto canReply = (canSendReply || item->allowsForward());
  550. if (!canReply) {
  551. return true;
  552. }
  553. result.msgBareId = item->fullId().msg.bare;
  554. result.callback = [=, itemId = item->fullId()] {
  555. const auto still = show->session().data().message(itemId);
  556. const auto selected = selectedQuote(still);
  557. const auto replyToItemId = (selected.item
  558. ? selected.item
  559. : still)->fullId();
  560. _widget->replyToMessage({
  561. .messageId = replyToItemId,
  562. .quote = selected.text,
  563. .quoteOffset = selected.offset,
  564. });
  565. if (!selected.text.empty()) {
  566. _widget->clearSelected();
  567. }
  568. };
  569. return false;
  570. });
  571. return result;
  572. }, _touchMaybeSelecting.value());
  573. }
  574. bool HistoryInner::hasSelectRestriction() const {
  575. if (!_sharingDisallowed.current()) {
  576. return false;
  577. } else if (const auto chat = _peer->asChat()) {
  578. return !chat->canDeleteMessages();
  579. } else if (const auto channel = _peer->asChannel()) {
  580. return !channel->canDeleteMessages();
  581. }
  582. return true;
  583. }
  584. void HistoryInner::messagesReceived(
  585. not_null<PeerData*> peer,
  586. const QVector<MTPMessage> &messages) {
  587. if (_history->peer == peer) {
  588. _history->addOlderSlice(messages);
  589. if (!messages.isEmpty()) {
  590. _translateTracker->addBunchFromBlocks();
  591. }
  592. } else if (_migrated && _migrated->peer == peer) {
  593. const auto newLoaded = _migrated
  594. && _migrated->isEmpty()
  595. && !_history->isEmpty();
  596. _migrated->addOlderSlice(messages);
  597. if (newLoaded) {
  598. _migrated->addNewerSlice(QVector<MTPMessage>());
  599. }
  600. }
  601. }
  602. void HistoryInner::messagesReceivedDown(
  603. not_null<PeerData*> peer,
  604. const QVector<MTPMessage> &messages) {
  605. if (_history->peer == peer) {
  606. const auto oldLoaded = _migrated
  607. && _history->isEmpty()
  608. && !_migrated->isEmpty();
  609. _history->addNewerSlice(messages);
  610. if (oldLoaded) {
  611. _history->addOlderSlice(QVector<MTPMessage>());
  612. }
  613. } else if (_migrated && _migrated->peer == peer) {
  614. _migrated->addNewerSlice(messages);
  615. }
  616. }
  617. void HistoryInner::repaintItem(const HistoryItem *item) {
  618. if (const auto view = viewByItem(item)) {
  619. repaintItem(view);
  620. }
  621. }
  622. void HistoryInner::repaintItem(const Element *view) {
  623. if (_widget->skipItemRepaint()) {
  624. return;
  625. }
  626. const auto top = itemTop(view);
  627. if (top >= 0) {
  628. const auto range = view->verticalRepaintRange();
  629. update(0, top + range.top, width(), range.height);
  630. const auto id = view->data()->fullId();
  631. if (const auto area = _reactionsManager->lookupEffectArea(id)) {
  632. update(*area);
  633. }
  634. }
  635. }
  636. template <bool TopToBottom, typename Method>
  637. void HistoryInner::enumerateItemsInHistory(History *history, int historytop, Method method) {
  638. // No displayed messages in this history.
  639. if (historytop < 0 || history->isEmpty()) {
  640. return;
  641. }
  642. if (_visibleAreaBottom <= historytop || historytop + history->height() <= _visibleAreaTop) {
  643. return;
  644. }
  645. auto searchEdge = TopToBottom ? _visibleAreaTop : _visibleAreaBottom;
  646. // Binary search for blockIndex of the first block that is not completely below the visible area.
  647. auto blockIndex = BinarySearchBlocksOrItems<TopToBottom>(history->blocks, searchEdge - historytop);
  648. // Binary search for itemIndex of the first item that is not completely below the visible area.
  649. auto block = history->blocks[blockIndex].get();
  650. auto blocktop = historytop + block->y();
  651. auto blockbottom = blocktop + block->height();
  652. auto itemIndex = BinarySearchBlocksOrItems<TopToBottom>(block->messages, searchEdge - blocktop);
  653. while (true) {
  654. while (true) {
  655. auto view = block->messages[itemIndex].get();
  656. auto itemtop = blocktop + view->y();
  657. auto itembottom = itemtop + view->height();
  658. // Binary search should've skipped all the items that are above / below the visible area.
  659. if (TopToBottom) {
  660. Assert(itembottom > _visibleAreaTop);
  661. } else {
  662. Assert(itemtop < _visibleAreaBottom);
  663. }
  664. if (!method(view, itemtop, itembottom)) {
  665. return;
  666. }
  667. // Skip all the items that are below / above the visible area.
  668. if (TopToBottom) {
  669. if (itembottom >= _visibleAreaBottom) {
  670. return;
  671. }
  672. } else {
  673. if (itemtop <= _visibleAreaTop) {
  674. return;
  675. }
  676. }
  677. if (TopToBottom) {
  678. if (++itemIndex >= block->messages.size()) {
  679. break;
  680. }
  681. } else {
  682. if (--itemIndex < 0) {
  683. break;
  684. }
  685. }
  686. }
  687. // Skip all the rest blocks that are below / above the visible area.
  688. if (TopToBottom) {
  689. if (blockbottom >= _visibleAreaBottom) {
  690. return;
  691. }
  692. } else {
  693. if (blocktop <= _visibleAreaTop) {
  694. return;
  695. }
  696. }
  697. if (TopToBottom) {
  698. if (++blockIndex >= history->blocks.size()) {
  699. return;
  700. }
  701. } else {
  702. if (--blockIndex < 0) {
  703. return;
  704. }
  705. }
  706. block = history->blocks[blockIndex].get();
  707. blocktop = historytop + block->y();
  708. blockbottom = blocktop + block->height();
  709. if (TopToBottom) {
  710. itemIndex = 0;
  711. } else {
  712. itemIndex = block->messages.size() - 1;
  713. }
  714. }
  715. }
  716. bool HistoryInner::canHaveFromUserpics() const {
  717. if (_peer->isUser()
  718. && !_peer->isSelf()
  719. && !_peer->isRepliesChat()
  720. && !_peer->isVerifyCodes()
  721. && !_isChatWide) {
  722. return false;
  723. } else if (const auto channel = _peer->asBroadcast()) {
  724. return channel->signatureProfiles();
  725. }
  726. return true;
  727. }
  728. template <typename Method>
  729. void HistoryInner::enumerateUserpics(Method method) {
  730. if (!canHaveFromUserpics()) {
  731. return;
  732. }
  733. // Find and remember the top of an attached messages pack
  734. // -1 means we didn't find an attached to next message yet.
  735. int lowestAttachedItemTop = -1;
  736. auto userpicCallback = [&](not_null<Element*> view, int itemtop, int itembottom) {
  737. // Skip all service messages.
  738. const auto item = view->data();
  739. if (view->isHidden() || item->isService()) {
  740. return true;
  741. }
  742. if (lowestAttachedItemTop < 0 && view->isAttachedToNext()) {
  743. lowestAttachedItemTop = itemtop + view->marginTop();
  744. }
  745. // Call method on a userpic for all messages that have it and for those who are not showing it
  746. // because of their attachment to the next message if they are bottom-most visible.
  747. if (view->displayFromPhoto() || (view->hasFromPhoto() && itembottom >= _visibleAreaBottom)) {
  748. if (lowestAttachedItemTop < 0) {
  749. lowestAttachedItemTop = itemtop + view->marginTop();
  750. }
  751. // Attach userpic to the bottom of the visible area with the same margin as the last message.
  752. auto userpicMinBottomSkip = st::historyPaddingBottom + st::msgMargin.bottom();
  753. auto userpicBottom = qMin(itembottom - view->marginBottom(), _visibleAreaBottom - userpicMinBottomSkip);
  754. // Do not let the userpic go above the attached messages pack top line.
  755. userpicBottom = qMax(userpicBottom, lowestAttachedItemTop + st::msgPhotoSize);
  756. // Call the template callback function that was passed
  757. // and return if it finished everything it needed.
  758. if (!method(view, userpicBottom - st::msgPhotoSize)) {
  759. return false;
  760. }
  761. }
  762. // Forget the found top of the pack, search for the next one from scratch.
  763. if (!view->isAttachedToNext()) {
  764. lowestAttachedItemTop = -1;
  765. }
  766. return true;
  767. };
  768. enumerateItems<EnumItemsDirection::TopToBottom>(userpicCallback);
  769. }
  770. template <typename Method>
  771. void HistoryInner::enumerateDates(Method method) {
  772. auto drawtop = historyDrawTop();
  773. // Find and remember the bottom of an single-day messages pack
  774. // -1 means we didn't find a same-day with previous message yet.
  775. auto lowestInOneDayItemBottom = -1;
  776. auto dateCallback = [&](not_null<Element*> view, int itemtop, int itembottom) {
  777. const auto item = view->data();
  778. if (lowestInOneDayItemBottom < 0 && view->isInOneDayWithPrevious()) {
  779. lowestInOneDayItemBottom = itembottom - view->marginBottom();
  780. }
  781. // Call method on a date for all messages that have it and for those who are not showing it
  782. // because they are in a one day together with the previous message if they are top-most visible.
  783. if (view->displayDate() || (!item->isEmpty() && itemtop <= _visibleAreaTop)) {
  784. // skip the date of history migrate item if it will be in migrated
  785. if (itemtop < drawtop && item->history() == _history) {
  786. if (itemtop > _visibleAreaTop) {
  787. // Previous item (from the _migrated history) is drawing date now.
  788. return false;
  789. }
  790. }
  791. if (lowestInOneDayItemBottom < 0) {
  792. lowestInOneDayItemBottom = itembottom - view->marginBottom();
  793. }
  794. // Attach date to the top of the visible area with the same margin as it has in service message.
  795. int dateTop = qMax(itemtop, _visibleAreaTop) + st::msgServiceMargin.top();
  796. // Do not let the date go below the single-day messages pack bottom line.
  797. int dateHeight = st::msgServicePadding.bottom() + st::msgServiceFont->height + st::msgServicePadding.top();
  798. dateTop = qMin(dateTop, lowestInOneDayItemBottom - dateHeight);
  799. // Call the template callback function that was passed
  800. // and return if it finished everything it needed.
  801. if (!method(view, itemtop, dateTop)) {
  802. return false;
  803. }
  804. }
  805. // Forget the found bottom of the pack, search for the next one from scratch.
  806. if (!view->isInOneDayWithPrevious()) {
  807. lowestInOneDayItemBottom = -1;
  808. }
  809. return true;
  810. };
  811. enumerateItems<EnumItemsDirection::BottomToTop>(dateCallback);
  812. }
  813. TextSelection HistoryInner::computeRenderSelection(
  814. not_null<const SelectedItems*> selected,
  815. not_null<Element*> view) const {
  816. if (view->isHiddenByGroup()) {
  817. return TextSelection();
  818. }
  819. const auto item = view->data();
  820. const auto itemSelection = [&](not_null<HistoryItem*> item) {
  821. auto i = selected->find(item);
  822. if (i != selected->end()) {
  823. return i->second;
  824. }
  825. return TextSelection();
  826. };
  827. const auto result = itemSelection(item);
  828. if (result != TextSelection() && result != FullSelection) {
  829. return result;
  830. }
  831. if (const auto group = session().data().groups().find(item)) {
  832. auto parts = TextSelection();
  833. auto allFullSelected = true;
  834. const auto count = int(group->items.size());
  835. for (auto i = 0; i != count; ++i) {
  836. const auto part = group->items[i];
  837. const auto selection = itemSelection(part);
  838. if (part == item
  839. && selection != FullSelection
  840. && selection != TextSelection()) {
  841. return selection;
  842. } else if (selection == FullSelection) {
  843. parts = AddGroupItemSelection(parts, i);
  844. } else {
  845. allFullSelected = false;
  846. }
  847. }
  848. return allFullSelected ? FullSelection : parts;
  849. }
  850. return itemSelection(item);
  851. }
  852. TextSelection HistoryInner::itemRenderSelection(
  853. not_null<Element*> view,
  854. int selfromy,
  855. int seltoy) const {
  856. const auto item = view->data();
  857. const auto y = view->block()->y() + view->y();
  858. if (y >= selfromy && y < seltoy) {
  859. if (_dragSelecting && !item->isService() && item->isRegular()) {
  860. return FullSelection;
  861. }
  862. } else if (!_selected.empty()) {
  863. return computeRenderSelection(&_selected, view);
  864. }
  865. return TextSelection();
  866. }
  867. void HistoryInner::paintEmpty(
  868. Painter &p,
  869. not_null<const Ui::ChatStyle*> st,
  870. int width,
  871. int height) {
  872. if (!_emptyPainter) {
  873. _emptyPainter = std::make_unique<HistoryView::EmptyPainter>(
  874. _history);
  875. }
  876. _emptyPainter->paint(p, st, width, height);
  877. }
  878. Ui::ChatPaintContext HistoryInner::preparePaintContext(
  879. const QRect &clip) const {
  880. const auto visibleAreaPositionGlobal = mapToGlobal(
  881. QPoint(0, _visibleAreaTop));
  882. return _controller->preparePaintContext({
  883. .theme = _theme.get(),
  884. .clip = clip,
  885. .visibleAreaPositionGlobal = visibleAreaPositionGlobal,
  886. .visibleAreaTop = _visibleAreaTop,
  887. .visibleAreaWidth = width(),
  888. });
  889. }
  890. void HistoryInner::startEffectOnRead(not_null<HistoryItem*> item) {
  891. if (item->history() == _history) {
  892. if (const auto view = item->mainView()) {
  893. _emojiInteractions->playEffectOnRead(view);
  894. }
  895. }
  896. }
  897. void HistoryInner::paintEvent(QPaintEvent *e) {
  898. if (_controller->contentOverlapped(this, e)
  899. || hasPendingResizedItems()) {
  900. return;
  901. } else if (_recountedAfterPendingResizedItems) {
  902. _recountedAfterPendingResizedItems = false;
  903. mouseActionUpdate();
  904. }
  905. Painter p(this);
  906. auto clip = e->rect();
  907. auto context = preparePaintContext(clip);
  908. context.gestureHorizontal = _gestureHorizontal;
  909. context.highlightPathCache = &_highlightPathCache;
  910. _pathGradient->startFrame(
  911. 0,
  912. width(),
  913. std::min(st::msgMaxWidth / 2, width() / 2));
  914. const auto historyDisplayedEmpty = _history->isDisplayedEmpty()
  915. && (!_migrated || _migrated->isDisplayedEmpty());
  916. if (const auto view = _aboutView ? _aboutView->view() : nullptr) {
  917. if (clip.y() < _aboutView->top + _aboutView->height
  918. && clip.y() + clip.height() > _aboutView->top) {
  919. const auto top = _aboutView->top;
  920. context.translate(0, -top);
  921. context.selection = computeRenderSelection(&_selected, view);
  922. p.translate(0, top);
  923. view->draw(p, context);
  924. context.translate(0, top);
  925. p.translate(0, -top);
  926. }
  927. } else if (historyDisplayedEmpty) {
  928. paintEmpty(p, context.st, width(), height());
  929. } else {
  930. _emptyPainter = nullptr;
  931. }
  932. const auto mtop = migratedTop();
  933. const auto htop = historyTop();
  934. if (historyDisplayedEmpty || (mtop < 0 && htop < 0)) {
  935. return;
  936. }
  937. _translateTracker->startBunch();
  938. auto readTill = (HistoryItem*)nullptr;
  939. auto readContents = base::flat_set<not_null<HistoryItem*>>();
  940. auto startEffects = base::flat_set<not_null<const Element*>>();
  941. const auto markingAsViewed = _widget->markingContentsRead();
  942. const auto guard = gsl::finally([&] {
  943. if (_pinnedItem) {
  944. _translateTracker->add(_pinnedItem);
  945. }
  946. _translateTracker->finishBunch();
  947. if (!startEffects.empty()) {
  948. for (const auto &view : startEffects) {
  949. _emojiInteractions->playEffectOnRead(view);
  950. }
  951. }
  952. if (readTill && _widget->markingMessagesRead()) {
  953. session().data().histories().readInboxTill(readTill);
  954. }
  955. if (markingAsViewed && !readContents.empty()) {
  956. session().api().markContentsRead(readContents);
  957. }
  958. _userpicsCache.clear();
  959. });
  960. const auto processPainted = [&](
  961. not_null<Element*> view,
  962. int top,
  963. int height) {
  964. _translateTracker->add(view);
  965. const auto item = view->data();
  966. const auto isSponsored = item->isSponsored();
  967. const auto isUnread = !item->out()
  968. && item->unread(_history)
  969. && (item->history() == _history);
  970. const auto withReaction = item->hasUnreadReaction();
  971. const auto yShown = [&](int y) {
  972. return (_visibleAreaBottom >= y && _visibleAreaTop <= y);
  973. };
  974. const auto markShown = isSponsored
  975. ? view->markSponsoredViewed(_visibleAreaBottom - top)
  976. : withReaction
  977. ? yShown(top + context.reactionInfo->position.y())
  978. : isUnread
  979. ? yShown(top + height)
  980. : yShown(top + height / 2);
  981. if (markShown) {
  982. if (isSponsored) {
  983. session().sponsoredMessages().view(item->fullId());
  984. } else if (isUnread) {
  985. readTill = item;
  986. }
  987. if (markingAsViewed && item->hasUnwatchedEffect()) {
  988. startEffects.emplace(view);
  989. }
  990. if (markingAsViewed && item->hasViews()) {
  991. session().api().views().scheduleIncrement(item);
  992. }
  993. if (withReaction) {
  994. readContents.insert(item);
  995. } else if (item->isUnreadMention()
  996. && !item->isUnreadMedia()) {
  997. readContents.insert(item);
  998. _widget->enqueueMessageHighlight({ item });
  999. }
  1000. }
  1001. session().data().reactions().poll(item, context.now);
  1002. if (item->hasUnpaidContent()) {
  1003. session().api().views().pollExtendedMedia(item);
  1004. }
  1005. _reactionsManager->recordCurrentReactionEffect(
  1006. item->fullId(),
  1007. QPoint(0, top));
  1008. };
  1009. adjustCurrent(clip.top());
  1010. const auto drawToY = clip.y() + clip.height();
  1011. auto selfromy = itemTop(_dragSelFrom);
  1012. auto seltoy = itemTop(_dragSelTo);
  1013. if (selfromy < 0 || seltoy < 0) {
  1014. selfromy = seltoy = -1;
  1015. } else {
  1016. seltoy += _dragSelTo->height();
  1017. }
  1018. const auto hdrawtop = historyDrawTop();
  1019. if (mtop >= 0) {
  1020. auto iBlock = (_curHistory == _migrated ? _curBlock : (_migrated->blocks.size() - 1));
  1021. auto block = _migrated->blocks[iBlock].get();
  1022. auto iItem = (_curHistory == _migrated ? _curItem : (block->messages.size() - 1));
  1023. auto view = block->messages[iItem].get();
  1024. auto top = mtop + block->y() + view->y();
  1025. context.translate(0, -top);
  1026. p.translate(0, top);
  1027. if (context.clip.y() < view->height()) while (top < drawToY) {
  1028. const auto height = view->height();
  1029. context.reactionInfo
  1030. = _reactionsManager->currentReactionPaintInfo();
  1031. context.outbg = view->hasOutLayout();
  1032. context.selection = itemRenderSelection(
  1033. view,
  1034. selfromy - mtop,
  1035. seltoy - mtop);
  1036. context.highlight = _widget->itemHighlight(view->data());
  1037. view->draw(p, context);
  1038. processPainted(view, top, height);
  1039. top += height;
  1040. context.translate(0, -height);
  1041. p.translate(0, height);
  1042. ++iItem;
  1043. if (iItem == block->messages.size()) {
  1044. iItem = 0;
  1045. ++iBlock;
  1046. if (iBlock == _migrated->blocks.size()) {
  1047. break;
  1048. }
  1049. block = _migrated->blocks[iBlock].get();
  1050. }
  1051. view = block->messages[iItem].get();
  1052. }
  1053. context.translate(0, top);
  1054. p.translate(0, -top);
  1055. }
  1056. if (htop >= 0) {
  1057. auto iBlock = (_curHistory == _history ? _curBlock : 0);
  1058. auto block = _history->blocks[iBlock].get();
  1059. auto iItem = (_curHistory == _history ? _curItem : 0);
  1060. auto view = block->messages[iItem].get();
  1061. auto top = htop + block->y() + view->y();
  1062. context.clip = clip.intersected(
  1063. QRect(0, hdrawtop, width(), clip.top() + clip.height()));
  1064. context.translate(0, -top);
  1065. p.translate(0, top);
  1066. const auto &sendingAnimation = _controller->sendingAnimation();
  1067. while (top < drawToY) {
  1068. const auto height = view->height();
  1069. const auto item = view->data();
  1070. if ((context.clip.y() < height)
  1071. && (hdrawtop < top + height)
  1072. && !sendingAnimation.hasAnimatedMessage(item)) {
  1073. context.reactionInfo
  1074. = _reactionsManager->currentReactionPaintInfo();
  1075. context.outbg = view->hasOutLayout();
  1076. context.selection = itemRenderSelection(
  1077. view,
  1078. selfromy - htop,
  1079. seltoy - htop);
  1080. context.highlight = _widget->itemHighlight(item);
  1081. view->draw(p, context);
  1082. processPainted(view, top, height);
  1083. }
  1084. top += height;
  1085. context.translate(0, -height);
  1086. p.translate(0, height);
  1087. ++iItem;
  1088. if (iItem == block->messages.size()) {
  1089. iItem = 0;
  1090. ++iBlock;
  1091. if (iBlock == _history->blocks.size()) {
  1092. break;
  1093. }
  1094. block = _history->blocks[iBlock].get();
  1095. }
  1096. view = block->messages[iItem].get();
  1097. }
  1098. context.translate(0, top);
  1099. p.translate(0, -top);
  1100. }
  1101. enumerateUserpics([&](not_null<Element*> view, int userpicTop) {
  1102. // stop the enumeration if the userpic is below the painted rect
  1103. if (userpicTop >= clip.top() + clip.height()) {
  1104. return false;
  1105. }
  1106. // paint the userpic if it intersects the painted rect
  1107. if (userpicTop + st::msgPhotoSize > clip.top()) {
  1108. const auto item = view->data();
  1109. const auto hasTranslation = context.gestureHorizontal.translation
  1110. && (context.gestureHorizontal.msgBareId
  1111. == item->fullId().msg.bare);
  1112. if (hasTranslation) {
  1113. p.translate(context.gestureHorizontal.translation, 0);
  1114. update(
  1115. QRect(
  1116. st::historyPhotoLeft
  1117. + context.gestureHorizontal.translation,
  1118. userpicTop,
  1119. st::msgPhotoSize
  1120. - context.gestureHorizontal.translation,
  1121. st::msgPhotoSize));
  1122. }
  1123. if (const auto from = item->displayFrom()) {
  1124. Dialogs::Ui::PaintUserpic(
  1125. p,
  1126. from,
  1127. validateVideoUserpic(from),
  1128. _userpics[from],
  1129. st::historyPhotoLeft,
  1130. userpicTop,
  1131. width(),
  1132. st::msgPhotoSize,
  1133. context.paused);
  1134. } else if (const auto info = item->displayHiddenSenderInfo()) {
  1135. if (info->customUserpic.empty()) {
  1136. info->emptyUserpic.paintCircle(
  1137. p,
  1138. st::historyPhotoLeft,
  1139. userpicTop,
  1140. width(),
  1141. st::msgPhotoSize);
  1142. } else {
  1143. auto &userpic = _hiddenSenderUserpics[item->id];
  1144. const auto valid = info->paintCustomUserpic(
  1145. p,
  1146. userpic,
  1147. st::historyPhotoLeft,
  1148. userpicTop,
  1149. width(),
  1150. st::msgPhotoSize);
  1151. if (!valid) {
  1152. info->customUserpic.load(&session(), item->fullId());
  1153. }
  1154. }
  1155. } else {
  1156. Unexpected("Corrupt forwarded information in message.");
  1157. }
  1158. if (hasTranslation) {
  1159. p.translate(-_gestureHorizontal.translation, 0);
  1160. }
  1161. }
  1162. return true;
  1163. });
  1164. const auto dateHeight = st::msgServicePadding.bottom()
  1165. + st::msgServiceFont->height
  1166. + st::msgServicePadding.top();
  1167. //QDate lastDate;
  1168. //if (!_history->isEmpty()) {
  1169. // lastDate = _history->blocks.back()->messages.back()->data()->date.date();
  1170. //}
  1171. //// if item top is before this value always show date as a floating date
  1172. //int showFloatingBefore = height() - 2 * (_visibleAreaBottom - _visibleAreaTop) - dateHeight;
  1173. auto scrollDateOpacity = _scrollDateOpacity.value(_scrollDateShown ? 1. : 0.);
  1174. enumerateDates([&](not_null<Element*> view, int itemtop, int dateTop) {
  1175. // stop the enumeration if the date is above the painted rect
  1176. if (dateTop + dateHeight <= clip.top()) {
  1177. return false;
  1178. }
  1179. const auto displayDate = view->displayDate();
  1180. auto dateInPlace = displayDate;
  1181. if (dateInPlace) {
  1182. const auto correctDateTop = itemtop + st::msgServiceMargin.top();
  1183. dateInPlace = (dateTop < correctDateTop + dateHeight);
  1184. }
  1185. //bool noFloatingDate = (item->date.date() == lastDate && displayDate);
  1186. //if (noFloatingDate) {
  1187. // if (itemtop < showFloatingBefore) {
  1188. // noFloatingDate = false;
  1189. // }
  1190. //}
  1191. // paint the date if it intersects the painted rect
  1192. if (dateTop < clip.top() + clip.height()) {
  1193. auto opacity = (dateInPlace/* || noFloatingDate*/) ? 1. : scrollDateOpacity;
  1194. if (opacity > 0.) {
  1195. p.setOpacity(opacity);
  1196. const auto dateY = false // noFloatingDate
  1197. ? itemtop
  1198. : (dateTop - st::msgServiceMargin.top());
  1199. if (const auto date = view->Get<HistoryView::DateBadge>()) {
  1200. date->paint(p, context.st, dateY, _contentWidth, _isChatWide);
  1201. } else {
  1202. HistoryView::ServiceMessagePainter::PaintDate(
  1203. p,
  1204. context.st,
  1205. view->dateTime(),
  1206. dateY,
  1207. _contentWidth,
  1208. _isChatWide);
  1209. }
  1210. }
  1211. }
  1212. return true;
  1213. });
  1214. p.setOpacity(1.);
  1215. _reactionsManager->paint(p, context);
  1216. }
  1217. bool HistoryInner::eventHook(QEvent *e) {
  1218. if (e->type() == QEvent::TouchBegin
  1219. || e->type() == QEvent::TouchUpdate
  1220. || e->type() == QEvent::TouchEnd
  1221. || e->type() == QEvent::TouchCancel) {
  1222. QTouchEvent *ev = static_cast<QTouchEvent*>(e);
  1223. if (ev->device()->type() == base::TouchDevice::TouchScreen) {
  1224. touchEvent(ev);
  1225. return true;
  1226. }
  1227. }
  1228. return RpWidget::eventHook(e);
  1229. }
  1230. int HistoryInner::SelectionViewOffset(
  1231. not_null<const HistoryInner*> inner,
  1232. not_null<const Element*> view) {
  1233. if (inner->_lastInSelectionMode) {
  1234. const auto translation
  1235. = Element::AdditionalSpaceForSelectionCheckbox(view);
  1236. const auto progress = inner->_inSelectionModeAnimation.value(1.);
  1237. return translation * progress;
  1238. }
  1239. return 0;
  1240. }
  1241. HistoryInner::VideoUserpic *HistoryInner::validateVideoUserpic(
  1242. not_null<PeerData*> peer) {
  1243. if (!peer->isPremium()
  1244. || peer->userpicPhotoUnknown()
  1245. || !peer->userpicHasVideo()) {
  1246. _videoUserpics.remove(peer);
  1247. return nullptr;
  1248. }
  1249. const auto i = _videoUserpics.find(peer);
  1250. if (i != end(_videoUserpics)) {
  1251. return i->second.get();
  1252. }
  1253. const auto repaint = [=] {
  1254. if (hasPendingResizedItems()) {
  1255. return;
  1256. }
  1257. enumerateUserpics([&](not_null<Element*> view, int userpicTop) {
  1258. // stop the enumeration if the userpic is below the painted rect
  1259. if (userpicTop >= _visibleAreaBottom) {
  1260. return false;
  1261. }
  1262. // repaint the userpic if it intersects the painted rect
  1263. if (userpicTop + st::msgPhotoSize > _visibleAreaTop) {
  1264. if (const auto from = view->data()->displayFrom()) {
  1265. if (from == peer) {
  1266. rtlupdate(
  1267. st::historyPhotoLeft,
  1268. userpicTop,
  1269. st::msgPhotoSize,
  1270. st::msgPhotoSize);
  1271. }
  1272. }
  1273. }
  1274. return true;
  1275. });
  1276. };
  1277. return _videoUserpics.emplace(peer, std::make_unique<VideoUserpic>(
  1278. peer,
  1279. repaint
  1280. )).first->second.get();
  1281. }
  1282. void HistoryInner::onTouchScrollTimer() {
  1283. auto nowTime = crl::now();
  1284. if (_touchScrollState == Ui::TouchScrollState::Acceleration && _touchWaitingAcceleration && (nowTime - _touchAccelerationTime) > 40) {
  1285. _touchScrollState = Ui::TouchScrollState::Manual;
  1286. touchResetSpeed();
  1287. } else if (_touchScrollState == Ui::TouchScrollState::Auto || _touchScrollState == Ui::TouchScrollState::Acceleration) {
  1288. int32 elapsed = int32(nowTime - _touchTime);
  1289. QPoint delta = _touchSpeed * elapsed / 1000;
  1290. const auto consumedHorizontal = consumeScrollAction(delta);
  1291. if (consumedHorizontal) {
  1292. _horizontalScrollLocked = true;
  1293. }
  1294. const auto hasScrolled = consumedHorizontal
  1295. || (!_horizontalScrollLocked && _widget->touchScroll(delta));
  1296. if (_touchSpeed.isNull() || !hasScrolled) {
  1297. _touchScrollState = Ui::TouchScrollState::Manual;
  1298. _touchScroll = false;
  1299. _horizontalScrollLocked = false;
  1300. _touchScrollTimer.cancel();
  1301. } else {
  1302. _touchTime = nowTime;
  1303. }
  1304. touchDeaccelerate(elapsed);
  1305. }
  1306. }
  1307. void HistoryInner::touchUpdateSpeed() {
  1308. const auto nowTime = crl::now();
  1309. if (_touchPrevPosValid) {
  1310. const int elapsed = nowTime - _touchSpeedTime;
  1311. if (elapsed) {
  1312. const QPoint newPixelDiff = (_touchPos - _touchPrevPos);
  1313. const QPoint pixelsPerSecond = newPixelDiff * (1000 / elapsed);
  1314. // fingers are inacurates, we ignore small changes to avoid stopping the autoscroll because
  1315. // of a small horizontal offset when scrolling vertically
  1316. const int newSpeedY = (qAbs(pixelsPerSecond.y()) > Ui::kFingerAccuracyThreshold) ? pixelsPerSecond.y() : 0;
  1317. const int newSpeedX = (qAbs(pixelsPerSecond.x()) > Ui::kFingerAccuracyThreshold) ? pixelsPerSecond.x() : 0;
  1318. if (_touchScrollState == Ui::TouchScrollState::Auto) {
  1319. const int oldSpeedY = _touchSpeed.y();
  1320. const int oldSpeedX = _touchSpeed.x();
  1321. if ((oldSpeedY <= 0 && newSpeedY <= 0) || ((oldSpeedY >= 0 && newSpeedY >= 0)
  1322. && (oldSpeedX <= 0 && newSpeedX <= 0)) || (oldSpeedX >= 0 && newSpeedX >= 0)) {
  1323. _touchSpeed.setY(std::clamp(
  1324. (oldSpeedY + (newSpeedY / 4)),
  1325. -Ui::kMaxScrollAccelerated,
  1326. +Ui::kMaxScrollAccelerated));
  1327. _touchSpeed.setX(std::clamp(
  1328. (oldSpeedX + (newSpeedX / 4)),
  1329. -Ui::kMaxScrollAccelerated,
  1330. +Ui::kMaxScrollAccelerated));
  1331. } else {
  1332. _touchSpeed = QPoint();
  1333. }
  1334. } else {
  1335. // we average the speed to avoid strange effects with the last delta
  1336. if (!_touchSpeed.isNull()) {
  1337. _touchSpeed.setX(std::clamp(
  1338. (_touchSpeed.x() / 4) + (newSpeedX * 3 / 4),
  1339. -Ui::kMaxScrollFlick,
  1340. +Ui::kMaxScrollFlick));
  1341. _touchSpeed.setY(std::clamp(
  1342. (_touchSpeed.y() / 4) + (newSpeedY * 3 / 4),
  1343. -Ui::kMaxScrollFlick,
  1344. +Ui::kMaxScrollFlick));
  1345. } else {
  1346. _touchSpeed = QPoint(newSpeedX, newSpeedY);
  1347. }
  1348. }
  1349. }
  1350. } else {
  1351. _touchPrevPosValid = true;
  1352. }
  1353. _touchSpeedTime = nowTime;
  1354. _touchPrevPos = _touchPos;
  1355. }
  1356. void HistoryInner::touchResetSpeed() {
  1357. _touchSpeed = QPoint();
  1358. _touchPrevPosValid = false;
  1359. }
  1360. void HistoryInner::touchDeaccelerate(int32 elapsed) {
  1361. int32 x = _touchSpeed.x();
  1362. int32 y = _touchSpeed.y();
  1363. _touchSpeed.setX((x == 0) ? x : (x > 0) ? qMax(0, x - elapsed) : qMin(0, x + elapsed));
  1364. _touchSpeed.setY((y == 0) ? y : (y > 0) ? qMax(0, y - elapsed) : qMin(0, y + elapsed));
  1365. }
  1366. void HistoryInner::touchEvent(QTouchEvent *e) {
  1367. if (e->type() == QEvent::TouchCancel) { // cancel
  1368. if (!_touchInProgress) {
  1369. return;
  1370. }
  1371. _touchInProgress = false;
  1372. _touchSelectTimer.cancel();
  1373. _touchScroll = _touchSelect = false;
  1374. _horizontalScrollLocked = false;
  1375. _touchScrollState = Ui::TouchScrollState::Manual;
  1376. _touchMaybeSelecting = false;
  1377. mouseActionCancel();
  1378. return;
  1379. }
  1380. if (!e->touchPoints().isEmpty()) {
  1381. _touchPrevPos = _touchPos;
  1382. _touchPos = e->touchPoints().cbegin()->screenPos().toPoint();
  1383. }
  1384. switch (e->type()) {
  1385. case QEvent::TouchBegin: {
  1386. if (_menu) {
  1387. e->accept();
  1388. return; // ignore mouse press, that was hiding context menu
  1389. }
  1390. if (_touchInProgress || e->touchPoints().isEmpty()) {
  1391. return;
  1392. }
  1393. _touchInProgress = true;
  1394. _horizontalScrollLocked = false;
  1395. if (_touchScrollState == Ui::TouchScrollState::Auto) {
  1396. _touchMaybeSelecting = false;
  1397. _touchScrollState = Ui::TouchScrollState::Acceleration;
  1398. _touchWaitingAcceleration = true;
  1399. _touchAccelerationTime = crl::now();
  1400. touchUpdateSpeed();
  1401. _touchStart = _touchPos;
  1402. } else {
  1403. _touchScroll = false;
  1404. _touchMaybeSelecting = true;
  1405. _touchSelectTimer.callOnce(QApplication::startDragTime());
  1406. }
  1407. _touchSelect = false;
  1408. _touchStart = _touchPrevPos = _touchPos;
  1409. } break;
  1410. case QEvent::TouchUpdate: {
  1411. LOG(("UPDATE: %1,%2 -> %3,%4"
  1412. ).arg(_touchStart.x()
  1413. ).arg(_touchStart.y()
  1414. ).arg(_touchPos.x()
  1415. ).arg(_touchPos.y()));
  1416. if (!_touchInProgress) {
  1417. return;
  1418. } else if (_touchSelect) {
  1419. mouseActionUpdate(_touchPos);
  1420. } else if (!_touchScroll && (_touchPos - _touchStart).manhattanLength() >= QApplication::startDragDistance()) {
  1421. _touchSelectTimer.cancel();
  1422. _touchMaybeSelecting = false;
  1423. _touchScroll = true;
  1424. touchUpdateSpeed();
  1425. }
  1426. if (_touchScroll) {
  1427. if (_touchScrollState == Ui::TouchScrollState::Manual) {
  1428. touchScrollUpdated(_touchPos);
  1429. } else if (_touchScrollState == Ui::TouchScrollState::Acceleration) {
  1430. touchUpdateSpeed();
  1431. _touchAccelerationTime = crl::now();
  1432. if (_touchSpeed.isNull()) {
  1433. _touchScrollState = Ui::TouchScrollState::Manual;
  1434. }
  1435. }
  1436. }
  1437. } break;
  1438. case QEvent::TouchEnd: {
  1439. if (!_touchInProgress) {
  1440. return;
  1441. }
  1442. _touchInProgress = false;
  1443. const auto notMoved = (_touchPos - _touchStart).manhattanLength()
  1444. < QApplication::startDragDistance();
  1445. auto weak = Ui::MakeWeak(this);
  1446. if (_touchSelect) {
  1447. if (notMoved || _touchMaybeSelecting.current()) {
  1448. mouseActionFinish(_touchPos, Qt::RightButton);
  1449. auto contextMenu = QContextMenuEvent(
  1450. QContextMenuEvent::Mouse,
  1451. mapFromGlobal(_touchPos),
  1452. _touchPos);
  1453. showContextMenu(&contextMenu, true);
  1454. }
  1455. _touchScroll = false;
  1456. } else if (_touchScroll) {
  1457. if (_touchScrollState == Ui::TouchScrollState::Manual) {
  1458. _touchScrollState = Ui::TouchScrollState::Auto;
  1459. _touchPrevPosValid = false;
  1460. _touchScrollTimer.callEach(15);
  1461. _touchTime = crl::now();
  1462. } else if (_touchScrollState == Ui::TouchScrollState::Auto) {
  1463. _touchScrollState = Ui::TouchScrollState::Manual;
  1464. _horizontalScrollLocked = false;
  1465. _touchScroll = false;
  1466. touchResetSpeed();
  1467. } else if (_touchScrollState == Ui::TouchScrollState::Acceleration) {
  1468. _touchScrollState = Ui::TouchScrollState::Auto;
  1469. _touchWaitingAcceleration = false;
  1470. _touchPrevPosValid = false;
  1471. }
  1472. } else if (notMoved) { // One short tap is like left mouse click.
  1473. mouseActionStart(_touchPos, Qt::LeftButton);
  1474. mouseActionFinish(_touchPos, Qt::LeftButton);
  1475. }
  1476. if (weak) {
  1477. _touchSelectTimer.cancel();
  1478. _touchMaybeSelecting = false;
  1479. _touchSelect = false;
  1480. }
  1481. } break;
  1482. }
  1483. }
  1484. void HistoryInner::mouseMoveEvent(QMouseEvent *e) {
  1485. static auto lastGlobalPosition = e->globalPos();
  1486. auto reallyMoved = (lastGlobalPosition != e->globalPos());
  1487. auto buttonsPressed = (e->buttons() & (Qt::LeftButton | Qt::MiddleButton));
  1488. if (!buttonsPressed && _mouseAction != MouseAction::None) {
  1489. mouseReleaseEvent(e);
  1490. }
  1491. if (reallyMoved) {
  1492. _mouseActive = true;
  1493. lastGlobalPosition = e->globalPos();
  1494. if (!buttonsPressed || (_scrollDateLink && ClickHandler::getPressed() == _scrollDateLink)) {
  1495. keepScrollDateForNow();
  1496. }
  1497. }
  1498. mouseActionUpdate(e->globalPos());
  1499. }
  1500. void HistoryInner::mouseActionUpdate(const QPoint &screenPos) {
  1501. _mousePosition = screenPos;
  1502. mouseActionUpdate();
  1503. }
  1504. void HistoryInner::touchScrollUpdated(const QPoint &screenPos) {
  1505. _touchPos = screenPos;
  1506. if (consumeScrollAction(_touchPos - _touchPrevPos)) {
  1507. _horizontalScrollLocked = true;
  1508. } else if (!_horizontalScrollLocked) {
  1509. _widget->touchScroll(_touchPos - _touchPrevPos);
  1510. }
  1511. touchUpdateSpeed();
  1512. }
  1513. QPoint HistoryInner::mapPointToItem(QPoint p, const Element *view) const {
  1514. if (view) {
  1515. const auto top = itemTop(view);
  1516. p.setY(p.y() - top);
  1517. return p;
  1518. }
  1519. return QPoint();
  1520. }
  1521. QPoint HistoryInner::mapPointToItem(
  1522. QPoint p,
  1523. const HistoryItem *item) const {
  1524. if (const auto view = viewByItem(item)) {
  1525. return mapPointToItem(p, view);
  1526. }
  1527. return QPoint();
  1528. }
  1529. void HistoryInner::mousePressEvent(QMouseEvent *e) {
  1530. if (_menu) {
  1531. e->accept();
  1532. return; // ignore mouse press, that was hiding context menu
  1533. }
  1534. _mouseActive = true;
  1535. mouseActionStart(e->globalPos(), e->button());
  1536. }
  1537. void HistoryInner::mouseActionStart(const QPoint &screenPos, Qt::MouseButton button) {
  1538. mouseActionUpdate(screenPos);
  1539. if (button != Qt::LeftButton) return;
  1540. ClickHandler::pressed();
  1541. if (Element::Pressed() != Element::Hovered()) {
  1542. repaintItem(Element::Pressed());
  1543. Element::Pressed(Element::Hovered());
  1544. repaintItem(Element::Pressed());
  1545. }
  1546. const auto mouseActionView = Element::Moused();
  1547. _mouseAction = MouseAction::None;
  1548. _mouseActionItem = mouseActionView
  1549. ? mouseActionView->data().get()
  1550. : nullptr;
  1551. _dragStartPosition = mapPointToItem(mapFromGlobal(screenPos), mouseActionView);
  1552. _pressWasInactive = Ui::WasInactivePress(_controller->widget());
  1553. if (_pressWasInactive) {
  1554. Ui::MarkInactivePress(_controller->widget(), false);
  1555. }
  1556. const auto pressed = ClickHandler::getPressed();
  1557. if (pressed
  1558. && (!Element::Hovered()
  1559. || !Element::Hovered()->allowTextSelectionByHandler(pressed))) {
  1560. _mouseAction = MouseAction::PrepareDrag;
  1561. } else if (inSelectionMode().inSelectionMode) {
  1562. if (_dragStateItem
  1563. && _selected.find(_dragStateItem) != _selected.cend()
  1564. && Element::Hovered()) {
  1565. _mouseAction = MouseAction::PrepareDrag; // start items drag
  1566. } else if (!_pressWasInactive) {
  1567. _mouseAction = MouseAction::PrepareSelect; // start items select
  1568. }
  1569. }
  1570. if (_mouseAction == MouseAction::None && mouseActionView) {
  1571. TextState dragState;
  1572. if (_trippleClickTimer.isActive() && (screenPos - _trippleClickPoint).manhattanLength() < QApplication::startDragDistance()) {
  1573. StateRequest request;
  1574. request.flags = Ui::Text::StateRequest::Flag::LookupSymbol;
  1575. dragState = mouseActionView->textState(_dragStartPosition, request);
  1576. if (dragState.cursor == CursorState::Text) {
  1577. TextSelection selStatus = { dragState.symbol, dragState.symbol };
  1578. if (selStatus != FullSelection && (_selected.empty() || _selected.cbegin()->second != FullSelection)) {
  1579. if (!_selected.empty()) {
  1580. repaintItem(_selected.cbegin()->first);
  1581. _selected.clear();
  1582. }
  1583. _selected.emplace(_mouseActionItem, selStatus);
  1584. _mouseTextSymbol = dragState.symbol;
  1585. _mouseAction = MouseAction::Selecting;
  1586. _mouseSelectType = TextSelectType::Paragraphs;
  1587. mouseActionUpdate(_mousePosition);
  1588. _trippleClickTimer.callOnce(
  1589. QApplication::doubleClickInterval());
  1590. }
  1591. }
  1592. } else if (Element::Pressed()) {
  1593. StateRequest request;
  1594. request.flags = Ui::Text::StateRequest::Flag::LookupSymbol;
  1595. dragState = mouseActionView->textState(_dragStartPosition, request);
  1596. }
  1597. if (_mouseSelectType != TextSelectType::Paragraphs) {
  1598. if (Element::Pressed()) {
  1599. _mouseTextSymbol = dragState.symbol;
  1600. bool uponSelected = (dragState.cursor == CursorState::Text);
  1601. if (uponSelected) {
  1602. if (_selected.empty()
  1603. || _selected.cbegin()->second == FullSelection
  1604. || _selected.cbegin()->first != _mouseActionItem) {
  1605. uponSelected = false;
  1606. } else {
  1607. uint16 selFrom = _selected.cbegin()->second.from, selTo = _selected.cbegin()->second.to;
  1608. if (_mouseTextSymbol < selFrom || _mouseTextSymbol >= selTo) {
  1609. uponSelected = false;
  1610. }
  1611. }
  1612. }
  1613. if (uponSelected) {
  1614. _mouseAction = MouseAction::PrepareDrag; // start text drag
  1615. } else if (!_pressWasInactive) {
  1616. if (_mouseCursorState == CursorState::Date) {
  1617. _mouseAction = MouseAction::PrepareDrag; // start sticker drag or by-date drag
  1618. } else {
  1619. if (dragState.afterSymbol) ++_mouseTextSymbol;
  1620. TextSelection selStatus = { _mouseTextSymbol, _mouseTextSymbol };
  1621. if (selStatus != FullSelection && (_selected.empty() || _selected.cbegin()->second != FullSelection)) {
  1622. if (!_selected.empty()) {
  1623. repaintItem(_selected.cbegin()->first);
  1624. _selected.clear();
  1625. }
  1626. _selected.emplace(_mouseActionItem, selStatus);
  1627. _mouseAction = MouseAction::Selecting;
  1628. repaintItem(_mouseActionItem);
  1629. } else if (!hasSelectRestriction()) {
  1630. _mouseAction = MouseAction::PrepareSelect;
  1631. }
  1632. }
  1633. }
  1634. } else if (!_pressWasInactive && !hasSelectRestriction()) {
  1635. _mouseAction = MouseAction::PrepareSelect; // start items select
  1636. }
  1637. }
  1638. }
  1639. if (!_mouseActionItem) {
  1640. _mouseAction = MouseAction::None;
  1641. } else if (_mouseAction == MouseAction::None) {
  1642. _mouseActionItem = nullptr;
  1643. }
  1644. }
  1645. void HistoryInner::mouseActionCancel() {
  1646. _mouseActionItem = nullptr;
  1647. _dragStateItem = nullptr;
  1648. _mouseAction = MouseAction::None;
  1649. _dragStartPosition = QPoint(0, 0);
  1650. _dragSelFrom = _dragSelTo = nullptr;
  1651. _wasSelectedText = false;
  1652. _selectScroll.cancel();
  1653. }
  1654. std::unique_ptr<QMimeData> HistoryInner::prepareDrag() {
  1655. if (_mouseAction != MouseAction::Dragging) {
  1656. return nullptr;
  1657. }
  1658. const auto pressedHandler = ClickHandler::getPressed();
  1659. if (dynamic_cast<VoiceSeekClickHandler*>(pressedHandler.get())
  1660. || hasCopyRestriction()) {
  1661. return nullptr;
  1662. }
  1663. const auto pressedView = viewByItem(_mouseActionItem);
  1664. bool uponSelected = false;
  1665. if (pressedView) {
  1666. if (!_selected.empty() && _selected.cbegin()->second == FullSelection) {
  1667. uponSelected = _mouseActionItem
  1668. && (_selected.find(_mouseActionItem) != _selected.cend());
  1669. } else {
  1670. StateRequest request;
  1671. request.flags |= Ui::Text::StateRequest::Flag::LookupSymbol;
  1672. auto dragState = pressedView->textState(_dragStartPosition, request);
  1673. uponSelected = (dragState.cursor == CursorState::Text);
  1674. if (uponSelected) {
  1675. if (_selected.empty()
  1676. || _selected.cbegin()->second == FullSelection
  1677. || _selected.cbegin()->first != _mouseActionItem) {
  1678. uponSelected = false;
  1679. } else {
  1680. uint16 selFrom = _selected.cbegin()->second.from, selTo = _selected.cbegin()->second.to;
  1681. if (dragState.symbol < selFrom || dragState.symbol >= selTo) {
  1682. uponSelected = false;
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. auto urls = QList<QUrl>();
  1689. const auto selectedText = [&] {
  1690. if (uponSelected) {
  1691. return getSelectedText();
  1692. } else if (pressedHandler) {
  1693. //if (!sel.isEmpty() && sel.at(0) != '/' && sel.at(0) != '@' && sel.at(0) != '#') {
  1694. // urls.push_back(QUrl::fromEncoded(sel.toUtf8())); // Google Chrome crashes in Mac OS X O_o
  1695. //}
  1696. return TextForMimeData::Simple(pressedHandler->dragText());
  1697. }
  1698. return TextForMimeData();
  1699. }();
  1700. if (auto mimeData = TextUtilities::MimeDataFromText(selectedText)) {
  1701. updateDragSelection(nullptr, nullptr, false);
  1702. _selectScroll.cancel();
  1703. if (!urls.isEmpty()) {
  1704. mimeData->setUrls(urls);
  1705. }
  1706. if (uponSelected && !_controller->adaptive().isOneColumn()) {
  1707. auto selectedState = getSelectionState();
  1708. if (selectedState.count > 0 && selectedState.count == selectedState.canForwardCount) {
  1709. session().data().setMimeForwardIds(getSelectedItems());
  1710. mimeData->setData(u"application/x-td-forward"_q, "1");
  1711. }
  1712. }
  1713. return mimeData;
  1714. } else if (pressedView) {
  1715. auto forwardIds = MessageIdsList();
  1716. const auto tryForwardSelection = uponSelected
  1717. && !_controller->adaptive().isOneColumn();
  1718. const auto forwardSelectionState = tryForwardSelection
  1719. ? getSelectionState()
  1720. : HistoryView::TopBarWidget::SelectedState();
  1721. if (forwardSelectionState.count > 0
  1722. && (forwardSelectionState.count
  1723. == forwardSelectionState.canForwardCount)) {
  1724. forwardIds = getSelectedItems();
  1725. } else if (_mouseCursorState == CursorState::Date) {
  1726. const auto item = _mouseActionItem;
  1727. if (item && item->allowsForward()) {
  1728. forwardIds = session().data().itemOrItsGroup(item);
  1729. }
  1730. } else if ((pressedView->isHiddenByGroup() && pressedHandler)
  1731. || (pressedView->media()
  1732. && pressedView->media()->dragItemByHandler(pressedHandler))) {
  1733. const auto item = _dragStateItem
  1734. ? _dragStateItem
  1735. : _mouseActionItem;
  1736. if (item && item->allowsForward()) {
  1737. forwardIds = MessageIdsList(1, item->fullId());
  1738. }
  1739. }
  1740. if (pressedHandler) {
  1741. const auto lnkDocument = reinterpret_cast<DocumentData*>(
  1742. pressedHandler->property(
  1743. kDocumentLinkMediaProperty).toULongLong());
  1744. if (lnkDocument) {
  1745. const auto filepath = lnkDocument->filepath(true);
  1746. if (!filepath.isEmpty()) {
  1747. urls.push_back(QUrl::fromLocalFile(filepath));
  1748. }
  1749. }
  1750. }
  1751. if (forwardIds.empty() && urls.isEmpty()) {
  1752. return nullptr;
  1753. }
  1754. auto result = std::make_unique<QMimeData>();
  1755. if (!forwardIds.empty()) {
  1756. session().data().setMimeForwardIds(std::move(forwardIds));
  1757. result->setData(u"application/x-td-forward"_q, "1");
  1758. }
  1759. if (!urls.isEmpty()) {
  1760. result->setUrls(urls);
  1761. }
  1762. return result;
  1763. }
  1764. return nullptr;
  1765. }
  1766. void HistoryInner::performDrag() {
  1767. if (auto mimeData = prepareDrag()) {
  1768. // This call enters event loop and can destroy any QObject.
  1769. _reactionsManager->updateButton({});
  1770. _controller->widget()->launchDrag(
  1771. std::move(mimeData),
  1772. crl::guard(this, [=] { mouseActionUpdate(QCursor::pos()); }));
  1773. }
  1774. }
  1775. void HistoryInner::itemRemoved(not_null<const HistoryItem*> item) {
  1776. if (_pinnedItem == item) {
  1777. _pinnedItem = nullptr;
  1778. }
  1779. if (_history != item->history() && _migrated != item->history()) {
  1780. return;
  1781. }
  1782. if (_reactionsItem.current() == item) {
  1783. _reactionsItem = nullptr;
  1784. }
  1785. _animatedStickersPlayed.remove(item);
  1786. _reactionsManager->remove(item->fullId());
  1787. auto i = _selected.find(item);
  1788. if (i != _selected.cend()) {
  1789. _selected.erase(i);
  1790. _widget->updateTopBarSelection();
  1791. }
  1792. if (_mouseActionItem == item) {
  1793. mouseActionCancel();
  1794. }
  1795. if (_dragStateItem == item) {
  1796. _dragStateItem = nullptr;
  1797. }
  1798. if ((_dragSelFrom && _dragSelFrom->data() == item)
  1799. || (_dragSelTo && _dragSelTo->data() == item)) {
  1800. _dragSelFrom = nullptr;
  1801. _dragSelTo = nullptr;
  1802. update();
  1803. }
  1804. if (_scrollDateLastItem && _scrollDateLastItem->data() == item) {
  1805. _scrollDateLastItem = nullptr;
  1806. }
  1807. mouseActionUpdate();
  1808. }
  1809. void HistoryInner::viewRemoved(not_null<const Element*> view) {
  1810. const auto refresh = [&](auto &saved) {
  1811. if (saved == view) {
  1812. const auto now = viewByItem(view->data());
  1813. saved = (now && now != view) ? now : nullptr;
  1814. }
  1815. };
  1816. refresh(_dragSelFrom);
  1817. refresh(_dragSelTo);
  1818. refresh(_scrollDateLastItem);
  1819. }
  1820. void HistoryInner::mouseActionFinish(
  1821. const QPoint &screenPos,
  1822. Qt::MouseButton button) {
  1823. mouseActionUpdate(screenPos);
  1824. auto activated = ClickHandler::unpressed();
  1825. if (_mouseAction == MouseAction::Dragging) {
  1826. activated = nullptr;
  1827. } else if (_mouseActionItem) {
  1828. // if we are in selecting items mode perhaps we want to
  1829. // toggle selection instead of activating the pressed link
  1830. if (_mouseAction == MouseAction::PrepareDrag
  1831. && !_pressWasInactive
  1832. && inSelectionMode().inSelectionMode
  1833. && button != Qt::RightButton) {
  1834. if (const auto view = viewByItem(_mouseActionItem)) {
  1835. if (view->toggleSelectionByHandlerClick(activated)) {
  1836. activated = nullptr;
  1837. }
  1838. }
  1839. }
  1840. }
  1841. const auto pressedItemView = Element::Pressed();
  1842. if (pressedItemView) {
  1843. repaintItem(pressedItemView);
  1844. Element::Pressed(nullptr);
  1845. }
  1846. _wasSelectedText = false;
  1847. if (activated) {
  1848. const auto pressedItemId = pressedItemView
  1849. ? pressedItemView->data()->fullId()
  1850. : _mouseActionItem
  1851. ? _mouseActionItem->fullId()
  1852. : FullMsgId();
  1853. const auto weak = base::make_weak(_controller);
  1854. mouseActionCancel();
  1855. ActivateClickHandler(
  1856. window(),
  1857. activated,
  1858. prepareClickContext(button, pressedItemId));
  1859. return;
  1860. }
  1861. if ((_mouseAction == MouseAction::PrepareSelect)
  1862. && !_pressWasInactive
  1863. && inSelectionMode().inSelectionMode) {
  1864. changeSelectionAsGroup(
  1865. &_selected,
  1866. _mouseActionItem,
  1867. SelectAction::Invert);
  1868. repaintItem(_mouseActionItem);
  1869. } else if ((_mouseAction == MouseAction::PrepareDrag)
  1870. && !_pressWasInactive
  1871. && _dragStateItem
  1872. && (button != Qt::RightButton)) {
  1873. auto i = _selected.find(_dragStateItem);
  1874. if (i != _selected.cend() && i->second == FullSelection) {
  1875. _selected.erase(i);
  1876. repaintItem(_mouseActionItem);
  1877. } else if ((i == _selected.cend())
  1878. && !_dragStateItem->isService()
  1879. && _dragStateItem->isRegular()
  1880. && inSelectionMode().inSelectionMode) {
  1881. if (_selected.size() < MaxSelectedItems) {
  1882. _selected.emplace(_dragStateItem, FullSelection);
  1883. repaintItem(_mouseActionItem);
  1884. }
  1885. } else {
  1886. _selected.clear();
  1887. update();
  1888. }
  1889. } else if (_mouseAction == MouseAction::Selecting) {
  1890. if (_dragSelFrom && _dragSelTo) {
  1891. applyDragSelection();
  1892. _dragSelFrom = _dragSelTo = nullptr;
  1893. } else if (!_selected.empty() && !_pressWasInactive) {
  1894. auto sel = _selected.cbegin()->second;
  1895. if (sel != FullSelection && sel.from == sel.to) {
  1896. _selected.clear();
  1897. _controller->widget()->setInnerFocus();
  1898. }
  1899. }
  1900. }
  1901. _mouseAction = MouseAction::None;
  1902. _mouseActionItem = nullptr;
  1903. _mouseSelectType = TextSelectType::Letters;
  1904. _selectScroll.cancel();
  1905. _widget->updateTopBarSelection();
  1906. if (QGuiApplication::clipboard()->supportsSelection()
  1907. && !_selected.empty()
  1908. && _selected.cbegin()->second != FullSelection
  1909. && !hasCopyRestriction(_selected.cbegin()->first)) {
  1910. const auto &[item, selection] = *_selected.cbegin();
  1911. if (const auto view = viewByItem(item)) {
  1912. TextUtilities::SetClipboardText(
  1913. view->selectedText(selection),
  1914. QClipboard::Selection);
  1915. }
  1916. }
  1917. }
  1918. void HistoryInner::mouseReleaseEvent(QMouseEvent *e) {
  1919. mouseActionFinish(e->globalPos(), e->button());
  1920. if (!rect().contains(e->pos())) {
  1921. leaveEvent(e);
  1922. }
  1923. }
  1924. void HistoryInner::mouseDoubleClickEvent(QMouseEvent *e) {
  1925. mouseActionStart(e->globalPos(), e->button());
  1926. const auto mouseActionView = viewByItem(_mouseActionItem);
  1927. if (_mouseSelectType == TextSelectType::Letters
  1928. && mouseActionView
  1929. && ((_mouseAction == MouseAction::Selecting
  1930. && !_selected.empty()
  1931. && _selected.cbegin()->second != FullSelection)
  1932. || (_mouseAction == MouseAction::None
  1933. && (_selected.empty()
  1934. || _selected.cbegin()->second != FullSelection)))) {
  1935. StateRequest request;
  1936. request.flags |= Ui::Text::StateRequest::Flag::LookupSymbol;
  1937. auto dragState = mouseActionView->textState(_dragStartPosition, request);
  1938. if (dragState.cursor == CursorState::Text) {
  1939. _mouseTextSymbol = dragState.symbol;
  1940. _mouseSelectType = TextSelectType::Words;
  1941. if (_mouseAction == MouseAction::None) {
  1942. _mouseAction = MouseAction::Selecting;
  1943. TextSelection selStatus = { dragState.symbol, dragState.symbol };
  1944. if (!_selected.empty()) {
  1945. repaintItem(_selected.cbegin()->first);
  1946. _selected.clear();
  1947. }
  1948. _selected.emplace(_mouseActionItem, selStatus);
  1949. }
  1950. mouseMoveEvent(e);
  1951. _trippleClickPoint = e->globalPos();
  1952. _trippleClickTimer.callOnce(QApplication::doubleClickInterval());
  1953. }
  1954. }
  1955. if (!ClickHandler::getActive()
  1956. && !ClickHandler::getPressed()
  1957. && (_mouseCursorState == CursorState::None
  1958. || _mouseCursorState == CursorState::Date)
  1959. && !inSelectionMode().inSelectionMode
  1960. && !_emptyPainter
  1961. && e->button() == Qt::LeftButton) {
  1962. if (const auto view = Element::Moused()) {
  1963. mouseActionCancel();
  1964. switch (HistoryView::CurrentQuickAction()) {
  1965. case HistoryView::DoubleClickQuickAction::Reply: {
  1966. _widget->replyToMessage(view->data());
  1967. } break;
  1968. case HistoryView::DoubleClickQuickAction::React: {
  1969. toggleFavoriteReaction(view);
  1970. } break;
  1971. default: break;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. void HistoryInner::toggleFavoriteReaction(not_null<Element*> view) const {
  1977. const auto item = view->data();
  1978. const auto favorite = session().data().reactions().favoriteId();
  1979. if (!ranges::contains(
  1980. Data::LookupPossibleReactions(item).recent,
  1981. favorite,
  1982. &Data::Reaction::id)
  1983. || Window::ShowReactPremiumError(_controller, item, favorite)) {
  1984. return;
  1985. } else if (!ranges::contains(item->chosenReactions(), favorite)) {
  1986. if (const auto top = itemTop(view); top >= 0) {
  1987. view->animateReaction({ .id = favorite });
  1988. }
  1989. }
  1990. item->toggleReaction(favorite, HistoryReactionSource::Quick);
  1991. }
  1992. HistoryView::SelectedQuote HistoryInner::selectedQuote(
  1993. not_null<HistoryItem*> item) const {
  1994. if (_selected.size() != 1
  1995. || _selected.begin()->first != item
  1996. || _selected.begin()->second == FullSelection) {
  1997. return {};
  1998. }
  1999. const auto view = item->mainView();
  2000. if (!view) {
  2001. return {};
  2002. }
  2003. return view->selectedQuote(_selected.begin()->second);
  2004. }
  2005. void HistoryInner::contextMenuEvent(QContextMenuEvent *e) {
  2006. showContextMenu(e);
  2007. }
  2008. void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
  2009. if (e->reason() == QContextMenuEvent::Mouse) {
  2010. mouseActionUpdate(e->globalPos());
  2011. }
  2012. const auto link = ClickHandler::getActive();
  2013. if (link
  2014. && !link->property(
  2015. kSendReactionEmojiProperty).value<Data::ReactionId>().empty()
  2016. && _reactionsManager->showContextMenu(
  2017. this,
  2018. e,
  2019. session().data().reactions().favoriteId())) {
  2020. return;
  2021. }
  2022. auto selectedState = getSelectionState();
  2023. // -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
  2024. auto isUponSelected = 0;
  2025. auto hasSelected = 0;
  2026. if (!_selected.empty()) {
  2027. isUponSelected = -1;
  2028. if (_selected.cbegin()->second == FullSelection) {
  2029. hasSelected = 2;
  2030. if (_dragStateItem && _selected.find(_dragStateItem) != _selected.cend()) {
  2031. isUponSelected = 2;
  2032. } else {
  2033. isUponSelected = -2;
  2034. }
  2035. } else if (Element::Moused()
  2036. && Element::Moused() == Element::Hovered()
  2037. && _selected.cbegin()->first == Element::Moused()->data()) {
  2038. uint16 selFrom = _selected.cbegin()->second.from, selTo = _selected.cbegin()->second.to;
  2039. hasSelected = (selTo > selFrom) ? 1 : 0;
  2040. auto mousePos = mapPointToItem(mapFromGlobal(_mousePosition), Element::Moused());
  2041. StateRequest request;
  2042. request.flags |= Ui::Text::StateRequest::Flag::LookupSymbol;
  2043. auto dragState = Element::Moused()->textState(mousePos, request);
  2044. if (dragState.cursor == CursorState::Text
  2045. && dragState.symbol >= selFrom
  2046. && dragState.symbol < selTo) {
  2047. isUponSelected = 1;
  2048. }
  2049. }
  2050. }
  2051. if (showFromTouch && hasSelected && isUponSelected < hasSelected) {
  2052. isUponSelected = hasSelected;
  2053. }
  2054. const auto groupLeaderOrSelf = [](HistoryItem *item) -> HistoryItem* {
  2055. if (!item) {
  2056. return nullptr;
  2057. } else if (const auto group = item->history()->owner().groups().find(item)) {
  2058. return group->items.front();
  2059. }
  2060. return item;
  2061. };
  2062. const auto leaderOrSelf = groupLeaderOrSelf(_dragStateItem);
  2063. const auto hasWhoReactedItem = leaderOrSelf
  2064. && Api::WhoReactedExists(leaderOrSelf, Api::WhoReactedList::All);
  2065. using namespace HistoryView::Reactions;
  2066. const auto clickedReaction = ReactionIdOfLink(link);
  2067. const auto linkPhoneNumber = link
  2068. ? link->property(kPhoneNumberLinkProperty).toString()
  2069. : QString();
  2070. const auto linkUserpicPeerId = (link && _dragStateUserpic)
  2071. ? link->property(kPeerLinkPeerIdProperty).toULongLong()
  2072. : 0;
  2073. const auto session = &this->session();
  2074. _whoReactedMenuLifetime.destroy();
  2075. if (!clickedReaction.empty()
  2076. && leaderOrSelf
  2077. && Api::WhoReactedExists(leaderOrSelf, Api::WhoReactedList::One)) {
  2078. HistoryView::ShowWhoReactedMenu(
  2079. &_menu,
  2080. e->globalPos(),
  2081. this,
  2082. leaderOrSelf,
  2083. clickedReaction,
  2084. _controller,
  2085. _whoReactedMenuLifetime);
  2086. e->accept();
  2087. return;
  2088. } else if (!linkPhoneNumber.isEmpty()) {
  2089. PhoneClickHandler(session, linkPhoneNumber).onClick(
  2090. prepareClickContext(
  2091. Qt::LeftButton,
  2092. _dragStateItem ? _dragStateItem->fullId() : FullMsgId()));
  2093. return;
  2094. }
  2095. _menu = base::make_unique_q<Ui::PopupMenu>(this, st::popupMenuWithIcons);
  2096. if (linkUserpicPeerId) {
  2097. _widget->fillSenderUserpicMenu(
  2098. _menu.get(),
  2099. session->data().peer(PeerId(linkUserpicPeerId)));
  2100. _menu->popup(e->globalPos());
  2101. e->accept();
  2102. return;
  2103. }
  2104. const auto controller = _controller;
  2105. const auto addItemActions = [&](
  2106. HistoryItem *item,
  2107. HistoryItem *albumPartItem) {
  2108. if (!item
  2109. || !item->isRegular()
  2110. || isUponSelected == 2
  2111. || isUponSelected == -2) {
  2112. return;
  2113. }
  2114. const auto itemId = item->fullId();
  2115. const auto repliesCount = item->repliesCount();
  2116. const auto withReplies = (repliesCount > 0);
  2117. const auto topicRootId = item->history()->isForum()
  2118. ? item->topicRootId()
  2119. : 0;
  2120. if (topicRootId
  2121. || (withReplies && item->history()->peer->isMegagroup())) {
  2122. const auto highlightId = topicRootId ? item->id : 0;
  2123. const auto rootId = topicRootId
  2124. ? topicRootId
  2125. : repliesCount
  2126. ? item->id
  2127. : item->replyToTop();
  2128. const auto phrase = topicRootId
  2129. ? tr::lng_replies_view_topic(tr::now)
  2130. : (repliesCount > 0)
  2131. ? tr::lng_replies_view(
  2132. tr::now,
  2133. lt_count,
  2134. repliesCount)
  2135. : tr::lng_replies_view_thread(tr::now);
  2136. _menu->addAction(phrase, [=] {
  2137. controller->showRepliesForMessage(
  2138. _history,
  2139. rootId,
  2140. highlightId);
  2141. }, &st::menuIconViewReplies);
  2142. }
  2143. const auto t = base::unixtime::now();
  2144. const auto editItem = (albumPartItem && albumPartItem->allowsEdit(t))
  2145. ? albumPartItem
  2146. : item->allowsEdit(t)
  2147. ? item
  2148. : nullptr;
  2149. if (editItem) {
  2150. const auto editItemId = editItem->fullId();
  2151. _menu->addAction(tr::lng_context_edit_msg(tr::now), [=] {
  2152. if (const auto item = session->data().message(editItemId)) {
  2153. auto it = _selected.find(item);
  2154. const auto selection = ((it != _selected.end())
  2155. && (it->second != FullSelection))
  2156. ? it->second
  2157. : TextSelection();
  2158. if (!selection.empty()) {
  2159. clearSelected(true);
  2160. }
  2161. _widget->editMessage(item, selection);
  2162. }
  2163. }, &st::menuIconEdit);
  2164. }
  2165. if (session->factchecks().canEdit(item)) {
  2166. const auto text = item->factcheckText();
  2167. const auto phrase = text.empty()
  2168. ? tr::lng_context_add_factcheck(tr::now)
  2169. : tr::lng_context_edit_factcheck(tr::now);
  2170. _menu->addAction(phrase, [=] {
  2171. const auto limit = session->factchecks().lengthLimit();
  2172. controller->show(Box(EditFactcheckBox, text, limit, [=](
  2173. TextWithEntities result) {
  2174. const auto show = controller->uiShow();
  2175. session->factchecks().save(itemId, text, result, show);
  2176. }, FactcheckFieldIniter(controller->uiShow())));
  2177. }, &st::menuIconFactcheck);
  2178. }
  2179. const auto pinItem = (item->canPin() && item->isPinned())
  2180. ? item
  2181. : groupLeaderOrSelf(item);
  2182. if (pinItem->canPin()) {
  2183. const auto isPinned = pinItem->isPinned();
  2184. const auto pinItemId = pinItem->fullId();
  2185. _menu->addAction(isPinned ? tr::lng_context_unpin_msg(tr::now) : tr::lng_context_pin_msg(tr::now), crl::guard(controller, [=] {
  2186. Window::ToggleMessagePinned(controller, pinItemId, !isPinned);
  2187. }), isPinned ? &st::menuIconUnpin : &st::menuIconPin);
  2188. }
  2189. if (!item->isService()
  2190. && peerIsChannel(itemId.peer)
  2191. && !_peer->isMegagroup()) {
  2192. constexpr auto kMinViewsCount = 10;
  2193. if (const auto channel = _peer->asChannel()) {
  2194. if ((channel->flags() & ChannelDataFlag::CanGetStatistics)
  2195. || (channel->canPostMessages()
  2196. && item->viewsCount() >= kMinViewsCount)) {
  2197. auto callback = crl::guard(controller, [=] {
  2198. controller->showSection(
  2199. Info::Statistics::Make(channel, itemId, {}));
  2200. });
  2201. _menu->addAction(
  2202. tr::lng_stats_title(tr::now),
  2203. std::move(callback),
  2204. &st::menuIconStats);
  2205. }
  2206. }
  2207. }
  2208. };
  2209. const auto addPhotoActions = [&](not_null<PhotoData*> photo, HistoryItem *item) {
  2210. const auto media = photo->activeMediaView();
  2211. const auto itemId = item ? item->fullId() : FullMsgId();
  2212. if (!photo->isNull() && media && media->loaded() && !hasCopyMediaRestriction(item)) {
  2213. _menu->addAction(tr::lng_context_save_image(tr::now), base::fn_delayed(st::defaultDropdownMenu.menu.ripple.hideDuration, this, [=] {
  2214. savePhotoToFile(photo);
  2215. }), &st::menuIconSaveImage);
  2216. _menu->addAction(tr::lng_context_copy_image(tr::now), [=] {
  2217. copyContextImage(photo, itemId);
  2218. }, &st::menuIconCopy);
  2219. }
  2220. if (photo->hasAttachedStickers()) {
  2221. _menu->addAction(tr::lng_context_attached_stickers(tr::now), [=] {
  2222. session->api().attachedStickers().requestAttachedStickerSets(
  2223. controller,
  2224. photo);
  2225. }, &st::menuIconStickers);
  2226. }
  2227. };
  2228. const auto addDocumentActions = [&](not_null<DocumentData*> document, HistoryItem *item) {
  2229. if (document->loading()) {
  2230. _menu->addAction(tr::lng_context_cancel_download(tr::now), [=] {
  2231. cancelContextDownload(document);
  2232. }, &st::menuIconCancel);
  2233. return;
  2234. }
  2235. const auto itemId = item ? item->fullId() : FullMsgId();
  2236. const auto lnkIsVideo = document->isVideoFile();
  2237. const auto lnkIsVoice = document->isVoiceMessage();
  2238. const auto lnkIsAudio = document->isAudioFile();
  2239. if (document->isGifv()) {
  2240. const auto notAutoplayedGif = [&] {
  2241. return item
  2242. && !Data::AutoDownload::ShouldAutoPlay(
  2243. session->settings().autoDownload(),
  2244. item->history()->peer,
  2245. document);
  2246. }();
  2247. if (notAutoplayedGif) {
  2248. _menu->addAction(tr::lng_context_open_gif(tr::now), [=] {
  2249. openContextGif(itemId);
  2250. }, &st::menuIconShowInChat);
  2251. }
  2252. if (!hasCopyMediaRestriction(item)) {
  2253. _menu->addAction(tr::lng_context_save_gif(tr::now), [=] {
  2254. saveContextGif(itemId);
  2255. }, &st::menuIconGif);
  2256. }
  2257. }
  2258. if (!document->filepath(true).isEmpty()) {
  2259. _menu->addAction(Platform::IsMac() ? tr::lng_context_show_in_finder(tr::now) : tr::lng_context_show_in_folder(tr::now), [=] {
  2260. showContextInFolder(document);
  2261. }, &st::menuIconShowInFolder);
  2262. }
  2263. if (item
  2264. && !hasCopyMediaRestriction(item)
  2265. && !HistoryView::ItemHasTtl(item)) {
  2266. HistoryView::AddSaveSoundForNotifications(
  2267. _menu,
  2268. item,
  2269. document,
  2270. controller);
  2271. _menu->addAction(lnkIsVideo ? tr::lng_context_save_video(tr::now) : (lnkIsVoice ? tr::lng_context_save_audio(tr::now) : (lnkIsAudio ? tr::lng_context_save_audio_file(tr::now) : tr::lng_context_save_file(tr::now))), base::fn_delayed(st::defaultDropdownMenu.menu.ripple.hideDuration, this, [=] {
  2272. saveDocumentToFile(itemId, document);
  2273. }), &st::menuIconDownload);
  2274. HistoryView::AddCopyFilename(
  2275. _menu,
  2276. document,
  2277. [=] { return showCopyRestrictionForSelected(); });
  2278. }
  2279. if (document->hasAttachedStickers()) {
  2280. _menu->addAction(tr::lng_context_attached_stickers(tr::now), [=] {
  2281. session->api().attachedStickers().requestAttachedStickerSets(
  2282. controller,
  2283. document);
  2284. }, &st::menuIconStickers);
  2285. }
  2286. };
  2287. #ifdef _DEBUG // Sometimes we need to save emoji to files.
  2288. if (const auto item = _dragStateItem) {
  2289. const auto emojiStickers = &session->emojiStickersPack();
  2290. if (const auto view = item->media() ? nullptr : item->mainView()) {
  2291. if (const auto isolated = view->isolatedEmoji()) {
  2292. if (const auto sticker = emojiStickers->stickerForEmoji(
  2293. isolated)) {
  2294. addDocumentActions(sticker.document, item);
  2295. } else if (v::is<QString>(isolated.items.front())
  2296. && v::is_null(isolated.items[1])) {
  2297. const auto id = v::get<QString>(isolated.items.front());
  2298. const auto docId = id.toULongLong();
  2299. const auto document = session->data().document(docId);
  2300. if (document->sticker()) {
  2301. addDocumentActions(document, item);
  2302. }
  2303. }
  2304. }
  2305. }
  2306. }
  2307. #endif
  2308. const auto asGroup = !Element::Moused()
  2309. || (Element::Moused() != Element::Hovered())
  2310. || (Element::Moused()->pointState(
  2311. mapPointToItem(
  2312. mapFromGlobal(_mousePosition),
  2313. Element::Moused())
  2314. ) != HistoryView::PointState::GroupPart);
  2315. const auto addSelectMessageAction = [&](not_null<HistoryItem*> item) {
  2316. if (item->isRegular()
  2317. && !item->isService()
  2318. && !hasSelectRestriction()) {
  2319. const auto itemId = item->fullId();
  2320. _menu->addAction(tr::lng_context_select_msg(tr::now), [=] {
  2321. if (const auto item = session->data().message(itemId)) {
  2322. if (const auto view = viewByItem(item)) {
  2323. if (asGroup) {
  2324. changeSelectionAsGroup(&_selected, item, SelectAction::Select);
  2325. } else {
  2326. changeSelection(&_selected, item, SelectAction::Select);
  2327. }
  2328. repaintItem(item);
  2329. _widget->updateTopBarSelection();
  2330. }
  2331. }
  2332. }, &st::menuIconSelect);
  2333. const auto collectBetween = [=](
  2334. not_null<HistoryItem*> from,
  2335. not_null<HistoryItem*> to,
  2336. int max) -> HistoryItemsList {
  2337. auto current = from;
  2338. auto collected = HistoryItemsList();
  2339. collected.reserve(max);
  2340. collected.push_back(from);
  2341. collected.push_back(to);
  2342. const auto toId = to->fullId();
  2343. while (true) {
  2344. if (collected.size() > max) {
  2345. return {};
  2346. }
  2347. const auto view = viewByItem(current);
  2348. const auto nextView = nextItem(view);
  2349. if (!nextView) {
  2350. return {};
  2351. }
  2352. const auto nextItem = nextView->data();
  2353. if (nextItem->fullId() == toId) {
  2354. return collected;
  2355. }
  2356. if (nextItem->isRegular() && !nextItem->isService()) {
  2357. collected.push_back(nextItem);
  2358. }
  2359. current = nextItem;
  2360. }
  2361. };
  2362. [&] { // Select up to this message.
  2363. if (selectedState.count <= 0) {
  2364. return;
  2365. }
  2366. const auto toItem = groupLeaderOrSelf(item);
  2367. auto topToBottom = false;
  2368. auto nearestItem = (HistoryItem*)(nullptr);
  2369. {
  2370. auto minDiff = std::numeric_limits<int>::max();
  2371. for (const auto &[item, _] : _selected) {
  2372. const auto diff = item->fullId().msg.bare
  2373. - toItem->fullId().msg.bare;
  2374. if (std::abs(diff) < minDiff) {
  2375. nearestItem = item;
  2376. minDiff = std::abs(diff);
  2377. topToBottom = (diff < 0);
  2378. }
  2379. }
  2380. }
  2381. if (!nearestItem) {
  2382. return;
  2383. }
  2384. const auto start = (topToBottom ? nearestItem : toItem);
  2385. const auto end = (topToBottom ? toItem : nearestItem);
  2386. const auto left = MaxSelectedItems
  2387. - selectedState.count
  2388. + (topToBottom ? 0 : 1);
  2389. if (collectBetween(start, end, left).empty()) {
  2390. return;
  2391. }
  2392. const auto startId = start->fullId();
  2393. const auto endId = end->fullId();
  2394. const auto callback = [=] {
  2395. const auto from = session->data().message(startId);
  2396. const auto to = session->data().message(endId);
  2397. if (from && to) {
  2398. for (const auto &i : collectBetween(from, to, left)) {
  2399. changeSelectionAsGroup(
  2400. &_selected,
  2401. i,
  2402. SelectAction::Select);
  2403. }
  2404. update();
  2405. _widget->updateTopBarSelection();
  2406. }
  2407. };
  2408. _menu->addAction(
  2409. tr::lng_context_select_msg_bulk(tr::now),
  2410. callback,
  2411. &st::menuIconSelect);
  2412. }();
  2413. }
  2414. };
  2415. const auto addReplyAction = [&](HistoryItem *item) {
  2416. if (!item || !item->isRegular()) {
  2417. return;
  2418. }
  2419. const auto canSendReply = CanSendReply(item);
  2420. const auto canReply = canSendReply || item->allowsForward();
  2421. if (canReply) {
  2422. const auto selected = selectedQuote(item);
  2423. auto text = (selected
  2424. ? tr::lng_context_quote_and_reply
  2425. : tr::lng_context_reply_msg)(
  2426. tr::now,
  2427. Ui::Text::FixAmpersandInAction);
  2428. const auto replyToItem = selected.item ? selected.item : item;
  2429. const auto itemId = replyToItem->fullId();
  2430. const auto quote = selected.text;
  2431. const auto quoteOffset = selected.offset;
  2432. _menu->addAction(std::move(text), [=] {
  2433. _widget->replyToMessage({
  2434. .messageId = itemId,
  2435. .quote = quote,
  2436. .quoteOffset = quoteOffset,
  2437. });
  2438. if (!quote.empty()) {
  2439. _widget->clearSelected();
  2440. }
  2441. }, &st::menuIconReply);
  2442. }
  2443. };
  2444. const auto lnkPhoto = link
  2445. ? reinterpret_cast<PhotoData*>(
  2446. link->property(kPhotoLinkMediaProperty).toULongLong())
  2447. : nullptr;
  2448. const auto lnkDocument = link
  2449. ? reinterpret_cast<DocumentData*>(
  2450. link->property(kDocumentLinkMediaProperty).toULongLong())
  2451. : nullptr;
  2452. if (lnkPhoto || lnkDocument) {
  2453. const auto item = _dragStateItem;
  2454. const auto itemId = item ? item->fullId() : FullMsgId();
  2455. addReplyAction(item);
  2456. if (isUponSelected > 0) {
  2457. const auto selectedText = getSelectedText();
  2458. if (!hasCopyRestrictionForSelected()
  2459. && !selectedText.empty()) {
  2460. _menu->addAction(
  2461. (isUponSelected > 1
  2462. ? tr::lng_context_copy_selected_items(tr::now)
  2463. : tr::lng_context_copy_selected(tr::now)),
  2464. [=] { copySelectedText(); },
  2465. &st::menuIconCopy);
  2466. }
  2467. if (item && !Ui::SkipTranslate(selectedText.rich)) {
  2468. const auto peer = item->history()->peer;
  2469. _menu->addAction(tr::lng_context_translate_selected({}), [=] {
  2470. _controller->show(Box(
  2471. Ui::TranslateBox,
  2472. peer,
  2473. MsgId(),
  2474. getSelectedText().rich,
  2475. hasCopyRestrictionForSelected()));
  2476. }, &st::menuIconTranslate);
  2477. }
  2478. }
  2479. addItemActions(item, item);
  2480. if (!selectedState.count) {
  2481. if (lnkPhoto) {
  2482. addPhotoActions(lnkPhoto, item);
  2483. } else {
  2484. addDocumentActions(lnkDocument, item);
  2485. }
  2486. }
  2487. if (item && item->hasDirectLink() && isUponSelected != 2 && isUponSelected != -2) {
  2488. _menu->addAction(item->history()->peer->isMegagroup() ? tr::lng_context_copy_message_link(tr::now) : tr::lng_context_copy_post_link(tr::now), [=] {
  2489. HistoryView::CopyPostLink(controller, itemId, HistoryView::Context::History);
  2490. }, &st::menuIconLink);
  2491. }
  2492. if (isUponSelected > 1) {
  2493. if (selectedState.count > 0 && selectedState.canForwardCount == selectedState.count) {
  2494. _menu->addAction(tr::lng_context_forward_selected(tr::now), [=] {
  2495. _widget->forwardSelected();
  2496. }, &st::menuIconForward);
  2497. }
  2498. if (selectedState.count > 0 && selectedState.canDeleteCount == selectedState.count) {
  2499. _menu->addAction(tr::lng_context_delete_selected(tr::now), [=] {
  2500. _widget->confirmDeleteSelected();
  2501. }, &st::menuIconDelete);
  2502. }
  2503. if (selectedState.count > 0 && !hasCopyRestrictionForSelected()) {
  2504. Menu::AddDownloadFilesAction(_menu, controller, _selected, this);
  2505. }
  2506. _menu->addAction(tr::lng_context_clear_selection(tr::now), [=] {
  2507. _widget->clearSelected();
  2508. }, &st::menuIconSelect);
  2509. } else if (item) {
  2510. const auto itemId = item->fullId();
  2511. const auto blockSender = item->history()->peer->isRepliesChat();
  2512. if (isUponSelected != -2) {
  2513. if (item->allowsForward()) {
  2514. _menu->addAction(tr::lng_context_forward_msg(tr::now), [=] {
  2515. forwardItem(itemId);
  2516. }, &st::menuIconForward);
  2517. }
  2518. if (item->canDelete()) {
  2519. const auto callback = [=] { deleteItem(itemId); };
  2520. if (item->isUploading()) {
  2521. _menu->addAction(tr::lng_context_cancel_upload(tr::now), callback, &st::menuIconCancel);
  2522. } else {
  2523. _menu->addAction(Ui::DeleteMessageContextAction(
  2524. _menu->menu(),
  2525. callback,
  2526. item->ttlDestroyAt(),
  2527. [=] { _menu = nullptr; }));
  2528. }
  2529. }
  2530. if (!blockSender && item->suggestReport()) {
  2531. _menu->addAction(tr::lng_context_report_msg(tr::now), [=] {
  2532. reportItem(itemId);
  2533. }, &st::menuIconReport);
  2534. }
  2535. }
  2536. addSelectMessageAction(item);
  2537. if (isUponSelected != -2 && blockSender) {
  2538. _menu->addAction(tr::lng_profile_block_user(tr::now), [=] {
  2539. blockSenderItem(itemId);
  2540. }, &st::menuIconBlock);
  2541. }
  2542. }
  2543. } else { // maybe cursor on some text history item?
  2544. const auto albumPartItem = _dragStateItem;
  2545. const auto item = [&] {
  2546. const auto result = Element::Hovered()
  2547. ? Element::Hovered()->data().get()
  2548. : Element::HoveredLink()
  2549. ? Element::HoveredLink()->data().get()
  2550. : nullptr;
  2551. return result ? groupLeaderOrSelf(result) : nullptr;
  2552. }();
  2553. const auto partItemOrLeader = (asGroup || !albumPartItem)
  2554. ? item
  2555. : albumPartItem;
  2556. const auto itemId = item ? item->fullId() : FullMsgId();
  2557. const auto canDelete = item
  2558. && item->canDelete()
  2559. && (item->isRegular() || !item->isService());
  2560. const auto canForward = item && item->allowsForward();
  2561. const auto canReport = item && item->suggestReport();
  2562. const auto canBlockSender = item && item->history()->peer->isRepliesChat();
  2563. const auto view = viewByItem(item);
  2564. const auto actionText = link
  2565. ? link->copyToClipboardContextItemText()
  2566. : QString();
  2567. const auto sponsored = (item && item->isSponsored())
  2568. ? item
  2569. : (Element::Moused() && Element::Moused()->data()->isSponsored())
  2570. ? Element::Moused()->data().get()
  2571. : nullptr;
  2572. if (sponsored) {
  2573. Menu::FillSponsored(
  2574. this,
  2575. Ui::Menu::CreateAddActionCallback(_menu),
  2576. controller->uiShow(),
  2577. sponsored->fullId(),
  2578. false);
  2579. }
  2580. if (isUponSelected > 0) {
  2581. addReplyAction(item);
  2582. const auto selectedText = getSelectedText();
  2583. if (!hasCopyRestrictionForSelected() && !selectedText.empty()) {
  2584. _menu->addAction(
  2585. ((isUponSelected > 1)
  2586. ? tr::lng_context_copy_selected_items(tr::now)
  2587. : tr::lng_context_copy_selected(tr::now)),
  2588. [=] { copySelectedText(); },
  2589. &st::menuIconCopy);
  2590. }
  2591. if (item && !Ui::SkipTranslate(selectedText.rich)) {
  2592. const auto peer = item->history()->peer;
  2593. _menu->addAction(tr::lng_context_translate_selected({}), [=] {
  2594. _controller->show(Box(
  2595. Ui::TranslateBox,
  2596. peer,
  2597. MsgId(),
  2598. selectedText.rich,
  2599. hasCopyRestrictionForSelected()));
  2600. }, &st::menuIconTranslate);
  2601. }
  2602. addItemActions(item, item);
  2603. } else {
  2604. addReplyAction(partItemOrLeader);
  2605. addItemActions(item, albumPartItem);
  2606. if (item && !isUponSelected) {
  2607. const auto media = (view ? view->media() : nullptr);
  2608. const auto mediaHasTextForCopy = media && media->hasTextForCopy();
  2609. if (const auto document = media ? media->getDocument() : nullptr) {
  2610. if (!view->isIsolatedEmoji() && document->sticker()) {
  2611. if (document->sticker()->set) {
  2612. _menu->addAction(document->isStickerSetInstalled() ? tr::lng_context_pack_info(tr::now) : tr::lng_context_pack_add(tr::now), [=] {
  2613. showStickerPackInfo(document);
  2614. }, &st::menuIconStickers);
  2615. const auto isFaved = session->data().stickers().isFaved(document);
  2616. _menu->addAction(isFaved ? tr::lng_faved_stickers_remove(tr::now) : tr::lng_faved_stickers_add(tr::now), [=] {
  2617. Api::ToggleFavedSticker(controller->uiShow(), document, itemId);
  2618. }, isFaved ? &st::menuIconUnfave : &st::menuIconFave);
  2619. }
  2620. if (!hasCopyMediaRestriction(item)) {
  2621. _menu->addAction(tr::lng_context_save_image(tr::now), base::fn_delayed(st::defaultDropdownMenu.menu.ripple.hideDuration, this, [=] {
  2622. saveDocumentToFile(itemId, document);
  2623. }), &st::menuIconDownload);
  2624. }
  2625. }
  2626. }
  2627. if (const auto media = item->media()) {
  2628. if (const auto poll = media->poll()) {
  2629. HistoryView::AddPollActions(
  2630. _menu,
  2631. poll,
  2632. item,
  2633. HistoryView::Context::History,
  2634. _controller);
  2635. } else if (const auto contact = media->sharedContact()) {
  2636. const auto phone = contact->phoneNumber;
  2637. _menu->addAction(tr::lng_profile_copy_phone(tr::now), [=] {
  2638. QGuiApplication::clipboard()->setText(phone);
  2639. }, &st::menuIconCopy);
  2640. } else if (const auto gift = media->gift()) {
  2641. const auto peer = item->history()->peer;
  2642. const auto user = peer->asUser();
  2643. if (!user
  2644. || (!user->isInaccessible()
  2645. && !user->isNotificationsUser())) {
  2646. const auto controller = _controller;
  2647. const auto starGiftUpgrade = gift->upgrade
  2648. && (gift->type == Data::GiftType::StarGift);
  2649. const auto isGift = gift->slug.isEmpty()
  2650. || !gift->channel;
  2651. const auto out = item->out();
  2652. const auto outgoingGift = isGift
  2653. && (starGiftUpgrade ? !out : out);
  2654. if (outgoingGift) {
  2655. _menu->addAction(
  2656. tr::lng_context_gift_send(tr::now),
  2657. [=] {
  2658. Ui::ShowStarGiftBox(controller, peer);
  2659. },
  2660. &st::menuIconGiftPremium);
  2661. }
  2662. }
  2663. }
  2664. }
  2665. if (!item->isService() && view && actionText.isEmpty()) {
  2666. const auto hasRestriction = hasCopyRestriction(item);
  2667. if (!hasRestriction
  2668. && (view->hasVisibleText() || mediaHasTextForCopy)) {
  2669. _menu->addAction(
  2670. tr::lng_context_copy_text(tr::now),
  2671. [=] { copyContextText(itemId); },
  2672. &st::menuIconCopy);
  2673. }
  2674. if ((!item->translation() || !_history->translatedTo())
  2675. && (view->hasVisibleText() || mediaHasTextForCopy)) {
  2676. const auto peer = item->history()->peer;
  2677. const auto itemId = item->id;
  2678. const auto translate = mediaHasTextForCopy
  2679. ? (HistoryView::TransribedText(item)
  2680. .append('\n')
  2681. .append(item->originalText()))
  2682. : item->originalText();
  2683. if (!translate.text.isEmpty()
  2684. && !Ui::SkipTranslate(translate)) {
  2685. _menu->addAction(tr::lng_context_translate(tr::now), [=] {
  2686. _controller->show(Box(
  2687. Ui::TranslateBox,
  2688. peer,
  2689. mediaHasTextForCopy ? MsgId() : itemId,
  2690. translate,
  2691. hasRestriction));
  2692. }, &st::menuIconTranslate);
  2693. }
  2694. }
  2695. }
  2696. }
  2697. }
  2698. if (!actionText.isEmpty()) {
  2699. _menu->addAction(
  2700. actionText,
  2701. [text = link->copyToClipboardText()] {
  2702. QGuiApplication::clipboard()->setText(text);
  2703. },
  2704. &st::menuIconCopy);
  2705. } else if (item && item->hasDirectLink() && isUponSelected != 2 && isUponSelected != -2) {
  2706. _menu->addAction(item->history()->peer->isMegagroup() ? tr::lng_context_copy_message_link(tr::now) : tr::lng_context_copy_post_link(tr::now), [=] {
  2707. HistoryView::CopyPostLink(controller, itemId, HistoryView::Context::History);
  2708. }, &st::menuIconLink);
  2709. }
  2710. if (sponsored) {
  2711. const auto hasAbout = ranges::any_of(
  2712. _menu->actions(),
  2713. [about = tr::lng_sponsored_menu_revenued_about(tr::now)](
  2714. const QAction *action) {
  2715. return action->text() == about;
  2716. });
  2717. if (!hasAbout) {
  2718. if (!_menu->empty()) {
  2719. _menu->addSeparator(&st::expandedMenuSeparator);
  2720. }
  2721. auto item = base::make_unique_q<Ui::Menu::MultilineAction>(
  2722. _menu,
  2723. st::menuWithIcons,
  2724. st::historyHasCustomEmoji,
  2725. st::historySponsoredAboutMenuLabelPosition,
  2726. TextWithEntities{ tr::lng_sponsored_title(tr::now) },
  2727. &st::menuIconInfo);
  2728. item->clicks(
  2729. ) | rpl::start_with_next([=] {
  2730. controller->show(Box(Ui::AboutSponsoredBox));
  2731. }, item->lifetime());
  2732. _menu->addAction(std::move(item));
  2733. }
  2734. }
  2735. if (isUponSelected > 1) {
  2736. if (selectedState.count > 0 && selectedState.count == selectedState.canForwardCount) {
  2737. _menu->addAction(tr::lng_context_forward_selected(tr::now), [=] {
  2738. _widget->forwardSelected();
  2739. }, &st::menuIconForward);
  2740. }
  2741. if (selectedState.count > 0 && selectedState.count == selectedState.canDeleteCount) {
  2742. _menu->addAction(tr::lng_context_delete_selected(tr::now), [=] {
  2743. _widget->confirmDeleteSelected();
  2744. }, &st::menuIconDelete);
  2745. }
  2746. if (selectedState.count > 0 && !hasCopyRestrictionForSelected()) {
  2747. Menu::AddDownloadFilesAction(_menu, controller, _selected, this);
  2748. }
  2749. _menu->addAction(tr::lng_context_clear_selection(tr::now), [=] {
  2750. _widget->clearSelected();
  2751. }, &st::menuIconSelect);
  2752. } else if (item && ((isUponSelected != -2 && (canForward || canDelete)) || item->isRegular())) {
  2753. if (isUponSelected != -2) {
  2754. if (canForward) {
  2755. _menu->addAction(tr::lng_context_forward_msg(tr::now), [=] {
  2756. forwardAsGroup(itemId);
  2757. }, &st::menuIconForward);
  2758. }
  2759. if (canDelete) {
  2760. const auto callback = [=] {
  2761. deleteAsGroup(itemId);
  2762. };
  2763. if (item->isUploading()) {
  2764. _menu->addAction(tr::lng_context_cancel_upload(tr::now), callback, &st::menuIconCancel);
  2765. } else {
  2766. _menu->addAction(Ui::DeleteMessageContextAction(
  2767. _menu->menu(),
  2768. callback,
  2769. item->ttlDestroyAt(),
  2770. [=] { _menu = nullptr; }));
  2771. }
  2772. }
  2773. if (!canBlockSender && canReport) {
  2774. _menu->addAction(tr::lng_context_report_msg(tr::now), [=] {
  2775. reportAsGroup(itemId);
  2776. }, &st::menuIconReport);
  2777. }
  2778. }
  2779. addSelectMessageAction(partItemOrLeader);
  2780. if (isUponSelected != -2 && canBlockSender) {
  2781. _menu->addAction(tr::lng_profile_block_user(tr::now), [=] {
  2782. blockSenderAsGroup(itemId);
  2783. }, &st::menuIconBlock);
  2784. }
  2785. } else if (Element::Moused()) {
  2786. addSelectMessageAction(Element::Moused()->data());
  2787. }
  2788. }
  2789. if (_dragStateItem) {
  2790. const auto view = viewByItem(_dragStateItem);
  2791. const auto textItem = view ? view->textItem() : _dragStateItem;
  2792. const auto wasAmount = _menu->actions().size();
  2793. HistoryView::AddEmojiPacksAction(
  2794. _menu,
  2795. textItem ? textItem : _dragStateItem,
  2796. HistoryView::EmojiPacksSource::Message,
  2797. _controller);
  2798. const auto added = (_menu->actions().size() > wasAmount);
  2799. HistoryView::AddSelectRestrictionAction(
  2800. _menu,
  2801. textItem ? textItem : _dragStateItem,
  2802. !added);
  2803. }
  2804. if (hasWhoReactedItem) {
  2805. HistoryView::AddWhoReactedAction(
  2806. _menu,
  2807. this,
  2808. leaderOrSelf,
  2809. _controller);
  2810. } else if (leaderOrSelf) {
  2811. HistoryView::MaybeAddWhenEditedForwardedAction(_menu, leaderOrSelf);
  2812. }
  2813. if (_menu->empty()) {
  2814. _menu = nullptr;
  2815. return;
  2816. }
  2817. using namespace HistoryView::Reactions;
  2818. const auto desiredPosition = e->globalPos();
  2819. const auto reactItem = Element::Hovered()
  2820. ? Element::Hovered()->data().get()
  2821. : nullptr;
  2822. const auto attached = reactItem
  2823. ? AttachSelectorToMenu(
  2824. _menu.get(),
  2825. controller,
  2826. desiredPosition,
  2827. reactItem,
  2828. [=](ChosenReaction reaction) { reactionChosen(reaction); },
  2829. ItemReactionsAbout(reactItem))
  2830. : AttachSelectorResult::Skipped;
  2831. if (attached == AttachSelectorResult::Failed) {
  2832. _menu = nullptr;
  2833. return;
  2834. } else if (attached == AttachSelectorResult::Attached) {
  2835. _menu->popupPrepared();
  2836. } else {
  2837. _menu->popup(desiredPosition);
  2838. }
  2839. e->accept();
  2840. }
  2841. bool HistoryInner::hasCopyRestriction(HistoryItem *item) const {
  2842. return !_peer->allowsForwarding() || (item && item->forbidsForward());
  2843. }
  2844. bool HistoryInner::hasCopyMediaRestriction(
  2845. not_null<HistoryItem*> item) const {
  2846. return hasCopyRestriction(item) || item->forbidsSaving();
  2847. }
  2848. bool HistoryInner::showCopyRestriction(HistoryItem *item) {
  2849. if (!hasCopyRestriction(item)) {
  2850. return false;
  2851. }
  2852. _controller->showToast(_peer->isBroadcast()
  2853. ? tr::lng_error_nocopy_channel(tr::now)
  2854. : tr::lng_error_nocopy_group(tr::now));
  2855. return true;
  2856. }
  2857. bool HistoryInner::showCopyMediaRestriction(not_null<HistoryItem*> item) {
  2858. if (!hasCopyMediaRestriction(item)) {
  2859. return false;
  2860. }
  2861. _controller->showToast(_peer->isBroadcast()
  2862. ? tr::lng_error_nocopy_channel(tr::now)
  2863. : tr::lng_error_nocopy_group(tr::now));
  2864. return true;
  2865. }
  2866. bool HistoryInner::hasCopyRestrictionForSelected() const {
  2867. if (hasCopyRestriction()) {
  2868. return true;
  2869. }
  2870. for (const auto &[item, selection] : _selected) {
  2871. if (item && item->forbidsForward()) {
  2872. return true;
  2873. }
  2874. }
  2875. return false;
  2876. }
  2877. bool HistoryInner::showCopyRestrictionForSelected() {
  2878. for (const auto &[item, selection] : _selected) {
  2879. if (showCopyRestriction(item)) {
  2880. return true;
  2881. }
  2882. }
  2883. return false;
  2884. }
  2885. void HistoryInner::copySelectedText() {
  2886. if (!showCopyRestrictionForSelected()) {
  2887. TextUtilities::SetClipboardText(getSelectedText());
  2888. }
  2889. }
  2890. void HistoryInner::savePhotoToFile(not_null<PhotoData*> photo) {
  2891. const auto media = photo->activeMediaView();
  2892. if (photo->isNull() || !media || !media->loaded()) {
  2893. return;
  2894. }
  2895. auto filter = u"JPEG Image (*.jpg);;"_q + FileDialog::AllFilesFilter();
  2896. FileDialog::GetWritePath(
  2897. this,
  2898. tr::lng_save_photo(tr::now),
  2899. filter,
  2900. filedialogDefaultName(u"photo"_q, u".jpg"_q),
  2901. crl::guard(this, [=](const QString &result) {
  2902. if (!result.isEmpty()) {
  2903. media->saveToFile(result);
  2904. }
  2905. }));
  2906. }
  2907. void HistoryInner::copyContextImage(
  2908. not_null<PhotoData*> photo,
  2909. FullMsgId itemId) {
  2910. const auto item = session().data().message(itemId);
  2911. const auto media = photo->activeMediaView();
  2912. const auto restricted = item
  2913. ? showCopyMediaRestriction(item)
  2914. : IsServerMsgId(itemId.msg);
  2915. if (photo->isNull() || !media || !media->loaded()) {
  2916. return;
  2917. } else if (!restricted) {
  2918. media->setToClipboard();
  2919. }
  2920. }
  2921. void HistoryInner::showStickerPackInfo(not_null<DocumentData*> document) {
  2922. StickerSetBox::Show(_controller->uiShow(), document);
  2923. }
  2924. void HistoryInner::cancelContextDownload(not_null<DocumentData*> document) {
  2925. document->cancel();
  2926. }
  2927. void HistoryInner::showContextInFolder(not_null<DocumentData*> document) {
  2928. const auto filepath = document->filepath(true);
  2929. if (!filepath.isEmpty()) {
  2930. File::ShowInFolder(filepath);
  2931. }
  2932. }
  2933. void HistoryInner::saveDocumentToFile(
  2934. FullMsgId contextId,
  2935. not_null<DocumentData*> document) {
  2936. DocumentSaveClickHandler::SaveAndTrack(
  2937. contextId,
  2938. document,
  2939. DocumentSaveClickHandler::Mode::ToNewFile);
  2940. }
  2941. void HistoryInner::openContextGif(FullMsgId itemId) {
  2942. if (const auto item = session().data().message(itemId)) {
  2943. if (const auto media = item->media()) {
  2944. if (const auto document = media->document()) {
  2945. _controller->openDocument(document, true, { itemId });
  2946. }
  2947. }
  2948. }
  2949. }
  2950. void HistoryInner::saveContextGif(FullMsgId itemId) {
  2951. if (const auto item = session().data().message(itemId)) {
  2952. if (!hasCopyMediaRestriction(item)) {
  2953. if (const auto media = item->media()) {
  2954. if (const auto document = media->document()) {
  2955. Api::ToggleSavedGif(
  2956. _controller->uiShow(),
  2957. document,
  2958. item->fullId(),
  2959. true);
  2960. }
  2961. }
  2962. }
  2963. }
  2964. }
  2965. void HistoryInner::copyContextText(FullMsgId itemId) {
  2966. if (const auto item = session().data().message(itemId)) {
  2967. if (!showCopyRestriction(item)) {
  2968. if (const auto group = session().data().groups().find(item)) {
  2969. TextUtilities::SetClipboardText(HistoryGroupText(group));
  2970. } else {
  2971. TextUtilities::SetClipboardText(HistoryItemText(item));
  2972. }
  2973. }
  2974. }
  2975. }
  2976. void HistoryInner::resizeEvent(QResizeEvent *e) {
  2977. mouseActionUpdate();
  2978. }
  2979. TextForMimeData HistoryInner::getSelectedText() const {
  2980. auto selected = _selected;
  2981. if (_mouseAction == MouseAction::Selecting && _dragSelFrom && _dragSelTo) {
  2982. applyDragSelection(&selected);
  2983. }
  2984. if (selected.empty()) {
  2985. return TextForMimeData();
  2986. }
  2987. if (selected.cbegin()->second != FullSelection) {
  2988. const auto &[item, selection] = *selected.cbegin();
  2989. if (const auto view = viewByItem(item)) {
  2990. return view->selectedText(selection);
  2991. }
  2992. return TextForMimeData();
  2993. }
  2994. struct Part {
  2995. QString name;
  2996. QString time;
  2997. TextForMimeData unwrapped;
  2998. };
  2999. auto groups = base::flat_set<not_null<const Data::Group*>>();
  3000. auto fullSize = 0;
  3001. auto texts = base::flat_map<Data::MessagePosition, Part>();
  3002. const auto wrapItem = [&](
  3003. not_null<HistoryItem*> item,
  3004. TextForMimeData &&unwrapped) {
  3005. const auto i = texts.emplace(item->position(), Part{
  3006. .name = item->author()->name(),
  3007. .time = QString(", [%1]\n").arg(
  3008. QLocale().toString(ItemDateTime(item), QLocale::ShortFormat)),
  3009. .unwrapped = std::move(unwrapped),
  3010. }).first;
  3011. fullSize += i->second.name.size()
  3012. + i->second.time.size()
  3013. + i->second.unwrapped.expanded.size();
  3014. };
  3015. const auto addItem = [&](not_null<HistoryItem*> item) {
  3016. wrapItem(item, HistoryItemText(item));
  3017. };
  3018. const auto addGroup = [&](not_null<const Data::Group*> group) {
  3019. Expects(!group->items.empty());
  3020. wrapItem(group->items.back(), HistoryGroupText(group));
  3021. };
  3022. for (const auto &[item, selection] : selected) {
  3023. if (const auto group = session().data().groups().find(item)) {
  3024. if (groups.contains(group)) {
  3025. continue;
  3026. }
  3027. if (isSelectedGroup(&selected, group)) {
  3028. groups.emplace(group);
  3029. addGroup(group);
  3030. } else {
  3031. addItem(item);
  3032. }
  3033. } else {
  3034. addItem(item);
  3035. }
  3036. }
  3037. if (texts.size() == 1) {
  3038. return texts.front().second.unwrapped;
  3039. }
  3040. auto result = TextForMimeData();
  3041. const auto sep = u"\n\n"_q;
  3042. result.reserve(fullSize + (texts.size() - 1) * sep.size());
  3043. for (auto i = texts.begin(), e = texts.end(); i != e;) {
  3044. result.append(i->second.name).append(i->second.time);
  3045. result.append(std::move(i->second.unwrapped));
  3046. if (++i != e) {
  3047. result.append(sep);
  3048. }
  3049. }
  3050. return result;
  3051. }
  3052. void HistoryInner::keyPressEvent(QKeyEvent *e) {
  3053. if (e->key() == Qt::Key_Escape) {
  3054. _widget->escape();
  3055. } else if (e == QKeySequence::Copy && !_selected.empty()) {
  3056. copySelectedText();
  3057. #ifdef Q_OS_MAC
  3058. } else if (e->key() == Qt::Key_E
  3059. && e->modifiers().testFlag(Qt::ControlModifier)
  3060. && !showCopyRestrictionForSelected()) {
  3061. TextUtilities::SetClipboardText(getSelectedText(), QClipboard::FindBuffer);
  3062. #endif // Q_OS_MAC
  3063. } else if (e == QKeySequence::Delete || e->key() == Qt::Key_Backspace) {
  3064. auto selectedState = getSelectionState();
  3065. if (selectedState.count > 0
  3066. && selectedState.canDeleteCount == selectedState.count) {
  3067. _widget->confirmDeleteSelected();
  3068. }
  3069. } else if (!(e->modifiers() & ~Qt::ShiftModifier)
  3070. && e->key() != Qt::Key_Shift) {
  3071. _widget->tryProcessKeyInput(e);
  3072. } else {
  3073. e->ignore();
  3074. }
  3075. }
  3076. void HistoryInner::checkActivation() {
  3077. if (!_widget->markingMessagesRead()) {
  3078. return;
  3079. }
  3080. adjustCurrent(_visibleAreaBottom);
  3081. if (_history->loadedAtBottom() && _visibleAreaBottom >= height()) {
  3082. // Clear possible message notifications.
  3083. // Side-effect: Also clears all notifications from forum topics.
  3084. Core::App().notifications().clearFromHistory(_history);
  3085. }
  3086. if (_curHistory != _history || _history->isEmpty()) {
  3087. return;
  3088. }
  3089. auto block = _history->blocks[_curBlock].get();
  3090. auto view = block->messages[_curItem].get();
  3091. while (_curBlock > 0 || _curItem > 0) {
  3092. const auto bottom = itemTop(view) + view->height();
  3093. if (_visibleAreaBottom >= bottom) {
  3094. break;
  3095. }
  3096. if (_curItem > 0) {
  3097. view = block->messages[--_curItem].get();
  3098. } else {
  3099. while (_curBlock > 0) {
  3100. block = _history->blocks[--_curBlock].get();
  3101. _curItem = block->messages.size();
  3102. if (_curItem > 0) {
  3103. view = block->messages[--_curItem].get();
  3104. break;
  3105. }
  3106. }
  3107. }
  3108. }
  3109. session().data().histories().readInboxTill(view->data());
  3110. }
  3111. void HistoryInner::recountHistoryGeometry(bool initial) {
  3112. _contentWidth = _scroll->width();
  3113. if (_history->hasPendingResizedItems()
  3114. || (_migrated && _migrated->hasPendingResizedItems())) {
  3115. _recountedAfterPendingResizedItems = true;
  3116. }
  3117. const auto visibleHeight = _scroll->height();
  3118. auto oldHistoryPaddingTop = qMax(
  3119. visibleHeight - historyHeight() - st::historyPaddingBottom,
  3120. 0);
  3121. if (_aboutView) {
  3122. accumulate_max(oldHistoryPaddingTop, _aboutView->height);
  3123. }
  3124. updateBotInfo(false);
  3125. _history->resizeToWidth(_contentWidth);
  3126. if (_migrated) {
  3127. _migrated->resizeToWidth(_contentWidth);
  3128. }
  3129. // With migrated history we perhaps do not need to display
  3130. // the first _history message date (just skip it by height).
  3131. _historySkipHeight = 0;
  3132. if (_migrated
  3133. && _migrated->loadedAtBottom()
  3134. && _history->loadedAtTop()) {
  3135. if (const auto first = _history->findFirstNonEmpty()) {
  3136. if (const auto last = _migrated->findLastNonEmpty()) {
  3137. if (first->dateTime().date() == last->dateTime().date()) {
  3138. const auto dateHeight = first->displayedDateHeight();
  3139. if (_migrated->height() > dateHeight) {
  3140. _historySkipHeight += dateHeight;
  3141. }
  3142. }
  3143. }
  3144. }
  3145. }
  3146. if (const auto view = _aboutView ? _aboutView->view() : nullptr) {
  3147. _aboutView->height = view->resizeGetHeight(_contentWidth);
  3148. _aboutView->top = qMin(
  3149. _historyPaddingTop - _aboutView->height,
  3150. qMax(0, (_scroll->height() - _aboutView->height) / 2));
  3151. } else if (_aboutView) {
  3152. _aboutView->top = _aboutView->height = 0;
  3153. }
  3154. auto newHistoryPaddingTop = qMax(
  3155. visibleHeight - historyHeight() - st::historyPaddingBottom,
  3156. 0);
  3157. if (_aboutView) {
  3158. accumulate_max(newHistoryPaddingTop, _aboutView->height);
  3159. }
  3160. auto historyPaddingTopDelta = (newHistoryPaddingTop - oldHistoryPaddingTop);
  3161. if (!initial && historyPaddingTopDelta != 0) {
  3162. if (_history->scrollTopItem) {
  3163. _history->scrollTopOffset += historyPaddingTopDelta;
  3164. } else if (_migrated && _migrated->scrollTopItem) {
  3165. _migrated->scrollTopOffset += historyPaddingTopDelta;
  3166. }
  3167. }
  3168. }
  3169. void HistoryInner::updateBotInfo(bool recount) {
  3170. if (!_aboutView) {
  3171. return;
  3172. } else if (_aboutView->refresh() && recount && _contentWidth > 0) {
  3173. const auto view = _aboutView->view();
  3174. const auto now = view ? view->resizeGetHeight(_contentWidth) : 0;
  3175. if (_aboutView->height != now) {
  3176. _aboutView->height = now;
  3177. updateSize();
  3178. }
  3179. }
  3180. }
  3181. bool HistoryInner::wasSelectedText() const {
  3182. return _wasSelectedText;
  3183. }
  3184. void HistoryInner::visibleAreaUpdated(int top, int bottom) {
  3185. auto scrolledUp = (top < _visibleAreaTop);
  3186. _visibleAreaTop = top;
  3187. _visibleAreaBottom = bottom;
  3188. const auto visibleAreaHeight = bottom - top;
  3189. // if history has pending resize events we should not update scrollTopItem
  3190. if (hasPendingResizedItems()) {
  3191. return;
  3192. }
  3193. if (bottom >= _historyPaddingTop + historyHeight() + st::historyPaddingBottom) {
  3194. _history->forgetScrollState();
  3195. if (_migrated) {
  3196. _migrated->forgetScrollState();
  3197. }
  3198. } else {
  3199. int htop = historyTop(), mtop = migratedTop();
  3200. if ((htop >= 0 && top >= htop) || mtop < 0) {
  3201. _history->countScrollState(top - htop);
  3202. if (_migrated) {
  3203. _migrated->forgetScrollState();
  3204. }
  3205. } else if (mtop >= 0 && top >= mtop) {
  3206. _history->forgetScrollState();
  3207. _migrated->countScrollState(top - mtop);
  3208. } else {
  3209. _history->countScrollState(top - htop);
  3210. if (_migrated) {
  3211. _migrated->forgetScrollState();
  3212. }
  3213. }
  3214. }
  3215. if (scrolledUp) {
  3216. _scrollDateCheck.call();
  3217. } else {
  3218. scrollDateHideByTimer();
  3219. }
  3220. // Unload userpics.
  3221. if (_userpics.size() > kClearUserpicsAfter) {
  3222. _userpicsCache = std::move(_userpics);
  3223. }
  3224. // Unload lottie animations.
  3225. const auto pages = kUnloadHeavyPartsPages;
  3226. const auto from = _visibleAreaTop - pages * visibleAreaHeight;
  3227. const auto till = _visibleAreaBottom + pages * visibleAreaHeight;
  3228. session().data().unloadHeavyViewParts(_elementDelegate, from, till);
  3229. if (_migratedElementDelegate) {
  3230. session().data().unloadHeavyViewParts(
  3231. _migratedElementDelegate,
  3232. from,
  3233. till);
  3234. }
  3235. checkActivation();
  3236. _emojiInteractions->visibleAreaUpdated(
  3237. _visibleAreaTop,
  3238. _visibleAreaBottom);
  3239. }
  3240. bool HistoryInner::displayScrollDate() const {
  3241. return (_visibleAreaTop <= height() - 2 * (_visibleAreaBottom - _visibleAreaTop));
  3242. }
  3243. void HistoryInner::scrollDateCheck() {
  3244. auto newScrollDateItem = _history->scrollTopItem ? _history->scrollTopItem : (_migrated ? _migrated->scrollTopItem : nullptr);
  3245. auto newScrollDateItemTop = _history->scrollTopItem ? _history->scrollTopOffset : (_migrated ? _migrated->scrollTopOffset : 0);
  3246. //if (newScrollDateItem && !displayScrollDate()) {
  3247. // if (!_history->isEmpty() && newScrollDateItem->date.date() == _history->blocks.back()->messages.back()->data()->date.date()) {
  3248. // newScrollDateItem = nullptr;
  3249. // }
  3250. //}
  3251. if (!newScrollDateItem) {
  3252. _scrollDateLastItem = nullptr;
  3253. _scrollDateLastItemTop = 0;
  3254. scrollDateHide();
  3255. } else if (newScrollDateItem != _scrollDateLastItem || newScrollDateItemTop != _scrollDateLastItemTop) {
  3256. // Show scroll date only if it is not the initial onScroll() event (with empty _scrollDateLastItem).
  3257. if (_scrollDateLastItem && !_scrollDateShown) {
  3258. toggleScrollDateShown();
  3259. }
  3260. _scrollDateLastItem = newScrollDateItem;
  3261. _scrollDateLastItemTop = newScrollDateItemTop;
  3262. _scrollDateHideTimer.callOnce(kScrollDateHideTimeout);
  3263. }
  3264. }
  3265. void HistoryInner::scrollDateHideByTimer() {
  3266. _scrollDateHideTimer.cancel();
  3267. if (!_scrollDateLink || ClickHandler::getPressed() != _scrollDateLink) {
  3268. scrollDateHide();
  3269. }
  3270. }
  3271. void HistoryInner::scrollDateHide() {
  3272. if (_scrollDateShown) {
  3273. toggleScrollDateShown();
  3274. }
  3275. }
  3276. void HistoryInner::keepScrollDateForNow() {
  3277. if (!_scrollDateShown && _scrollDateLastItem && _scrollDateOpacity.animating()) {
  3278. toggleScrollDateShown();
  3279. }
  3280. _scrollDateHideTimer.callOnce(kScrollDateHideTimeout);
  3281. }
  3282. void HistoryInner::toggleScrollDateShown() {
  3283. _scrollDateShown = !_scrollDateShown;
  3284. auto from = _scrollDateShown ? 0. : 1.;
  3285. auto to = _scrollDateShown ? 1. : 0.;
  3286. _scrollDateOpacity.start([this] { repaintScrollDateCallback(); }, from, to, st::historyDateFadeDuration);
  3287. }
  3288. void HistoryInner::repaintScrollDateCallback() {
  3289. int updateTop = _visibleAreaTop;
  3290. int updateHeight = st::msgServiceMargin.top() + st::msgServicePadding.top() + st::msgServiceFont->height + st::msgServicePadding.bottom();
  3291. update(0, updateTop, width(), updateHeight);
  3292. }
  3293. void HistoryInner::setItemsRevealHeight(int revealHeight) {
  3294. _revealHeight = revealHeight;
  3295. }
  3296. void HistoryInner::changeItemsRevealHeight(int revealHeight) {
  3297. if (_revealHeight == revealHeight) {
  3298. return;
  3299. }
  3300. _revealHeight = revealHeight;
  3301. updateSize();
  3302. }
  3303. void HistoryInner::updateSize() {
  3304. const auto visibleHeight = _scroll->height();
  3305. const auto itemsHeight = historyHeight() - _revealHeight;
  3306. auto newHistoryPaddingTop = qMax(visibleHeight - itemsHeight - st::historyPaddingBottom, 0);
  3307. if (_aboutView) {
  3308. accumulate_max(newHistoryPaddingTop, _aboutView->height);
  3309. }
  3310. if (_aboutView && _aboutView->height > 0) {
  3311. _aboutView->top = qMin(
  3312. newHistoryPaddingTop - _aboutView->height,
  3313. qMax(0, (_scroll->height() - _aboutView->height) / 2));
  3314. }
  3315. if (_historyPaddingTop != newHistoryPaddingTop) {
  3316. _historyPaddingTop = newHistoryPaddingTop;
  3317. }
  3318. int newHeight = _historyPaddingTop + itemsHeight + st::historyPaddingBottom;
  3319. if (width() != _scroll->width() || height() != newHeight) {
  3320. resize(_scroll->width(), newHeight);
  3321. if (!_revealHeight) {
  3322. mouseActionUpdate(QCursor::pos());
  3323. }
  3324. } else {
  3325. update();
  3326. }
  3327. }
  3328. void HistoryInner::setShownPinned(HistoryItem *item) {
  3329. _pinnedItem = item;
  3330. }
  3331. void HistoryInner::enterEventHook(QEnterEvent *e) {
  3332. _mouseActive = true;
  3333. mouseActionUpdate(QCursor::pos());
  3334. return TWidget::enterEventHook(e);
  3335. }
  3336. void HistoryInner::leaveEventHook(QEvent *e) {
  3337. _reactionsManager->updateButton({ .cursorLeft = true });
  3338. if (auto item = Element::Hovered()) {
  3339. repaintItem(item);
  3340. Element::Hovered(nullptr);
  3341. }
  3342. ClickHandler::clearActive();
  3343. Ui::Tooltip::Hide();
  3344. if (!ClickHandler::getPressed() && _cursor != style::cur_default) {
  3345. _cursor = style::cur_default;
  3346. setCursor(_cursor);
  3347. }
  3348. _mouseActive = false;
  3349. return TWidget::leaveEventHook(e);
  3350. }
  3351. HistoryInner::~HistoryInner() {
  3352. _aboutView = nullptr;
  3353. for (const auto &item : _animatedStickersPlayed) {
  3354. if (const auto view = item->mainView()) {
  3355. if (const auto media = view->media()) {
  3356. media->stickerClearLoopPlayed();
  3357. }
  3358. }
  3359. }
  3360. _history->delegateMixin()->setCurrent(nullptr);
  3361. if (_migrated) {
  3362. _migrated->delegateMixin()->setCurrent(nullptr);
  3363. }
  3364. delete _menu;
  3365. _mouseAction = MouseAction::None;
  3366. }
  3367. bool HistoryInner::focusNextPrevChild(bool next) {
  3368. if (_selected.empty()) {
  3369. return TWidget::focusNextPrevChild(next);
  3370. } else {
  3371. clearSelected();
  3372. return true;
  3373. }
  3374. }
  3375. void HistoryInner::adjustCurrent(int32 y) const {
  3376. int32 htop = historyTop(), hdrawtop = historyDrawTop(), mtop = migratedTop();
  3377. _curHistory = nullptr;
  3378. if (mtop >= 0) {
  3379. adjustCurrent(y - mtop, _migrated);
  3380. }
  3381. if (htop >= 0 && hdrawtop >= 0 && (mtop < 0 || y >= hdrawtop)) {
  3382. adjustCurrent(y - htop, _history);
  3383. }
  3384. }
  3385. void HistoryInner::adjustCurrent(int32 y, History *history) const {
  3386. Expects(!history->isEmpty());
  3387. _curHistory = history;
  3388. if (_curBlock >= history->blocks.size()) {
  3389. _curBlock = history->blocks.size() - 1;
  3390. _curItem = 0;
  3391. }
  3392. while (history->blocks[_curBlock]->y() > y && _curBlock > 0) {
  3393. --_curBlock;
  3394. _curItem = 0;
  3395. }
  3396. while (history->blocks[_curBlock]->y() + history->blocks[_curBlock]->height() <= y && _curBlock + 1 < history->blocks.size()) {
  3397. ++_curBlock;
  3398. _curItem = 0;
  3399. }
  3400. auto block = history->blocks[_curBlock].get();
  3401. if (_curItem >= block->messages.size()) {
  3402. _curItem = block->messages.size() - 1;
  3403. }
  3404. auto by = block->y();
  3405. while (block->messages[_curItem]->y() + by > y && _curItem > 0) {
  3406. --_curItem;
  3407. }
  3408. while (block->messages[_curItem]->y() + block->messages[_curItem]->height() + by <= y && _curItem + 1 < block->messages.size()) {
  3409. ++_curItem;
  3410. }
  3411. }
  3412. auto HistoryInner::prevItem(Element *view) -> Element* {
  3413. if (!view) {
  3414. return nullptr;
  3415. } else if (const auto result = view->previousDisplayedInBlocks()) {
  3416. return result;
  3417. } else if (view->history() == _history
  3418. && _migrated
  3419. && _history->loadedAtTop()
  3420. && !_migrated->isEmpty()
  3421. && _migrated->loadedAtBottom()) {
  3422. return _migrated->findLastDisplayed();
  3423. }
  3424. return nullptr;
  3425. }
  3426. auto HistoryInner::nextItem(Element *view) -> Element* {
  3427. if (!view) {
  3428. return nullptr;
  3429. } else if (const auto result = view->nextDisplayedInBlocks()) {
  3430. return result;
  3431. } else if (view->history() == _migrated
  3432. && _migrated->loadedAtBottom()
  3433. && _history->loadedAtTop()
  3434. && !_history->isEmpty()) {
  3435. return _history->findFirstDisplayed();
  3436. }
  3437. return nullptr;
  3438. }
  3439. bool HistoryInner::canCopySelected() const {
  3440. return !_selected.empty();
  3441. }
  3442. bool HistoryInner::canDeleteSelected() const {
  3443. const auto selectedState = getSelectionState();
  3444. return (selectedState.count > 0)
  3445. && (selectedState.count == selectedState.canDeleteCount);
  3446. }
  3447. HistoryView::SelectionModeResult HistoryInner::inSelectionMode() const {
  3448. const auto inSelectionMode = [&] {
  3449. if (hasSelectedItems()) {
  3450. return true;
  3451. }
  3452. const auto isSelecting = _mouseAction == MouseAction::Selecting;
  3453. if (isSelecting && _dragSelFrom && _dragSelTo) {
  3454. return true;
  3455. } else if (_chooseForReportReason.has_value()) {
  3456. return true;
  3457. } else if (_lastInSelectionMode && isSelecting) {
  3458. return true;
  3459. }
  3460. return false;
  3461. }();
  3462. const auto now = inSelectionMode;
  3463. if (_lastInSelectionMode != now) {
  3464. _lastInSelectionMode = now;
  3465. if (_inSelectionModeAnimation.animating()) {
  3466. const auto progress = !now
  3467. ? _inSelectionModeAnimation.value(0.)
  3468. : 1. - _inSelectionModeAnimation.value(0.);
  3469. _inSelectionModeAnimation.change(
  3470. now ? 1. : 0.,
  3471. st::universalDuration * (1. - progress));
  3472. } else {
  3473. _inSelectionModeAnimation.stop();
  3474. _inSelectionModeAnimation.start(
  3475. [this] {
  3476. const_cast<HistoryInner*>(this)->update(
  3477. QRect(
  3478. 0,
  3479. _visibleAreaTop,
  3480. width(),
  3481. _visibleAreaBottom - _visibleAreaTop));
  3482. },
  3483. now ? 0. : 1.,
  3484. now ? 1. : 0.,
  3485. st::universalDuration);
  3486. }
  3487. }
  3488. return { now, _inSelectionModeAnimation.value(now ? 1. : 0.) };
  3489. }
  3490. bool HistoryInner::elementIntersectsRange(
  3491. not_null<const Element*> view,
  3492. int from,
  3493. int till) const {
  3494. const auto top = itemTop(view);
  3495. if (top < 0) {
  3496. return false;
  3497. }
  3498. const auto bottom = top + view->height();
  3499. return (top < till && bottom > from);
  3500. }
  3501. void HistoryInner::elementStartStickerLoop(
  3502. not_null<const Element*> view) {
  3503. _animatedStickersPlayed.emplace(view->data());
  3504. }
  3505. void HistoryInner::elementShowPollResults(
  3506. not_null<PollData*> poll,
  3507. FullMsgId context) {
  3508. _controller->showPollResults(poll, context);
  3509. }
  3510. void HistoryInner::elementOpenPhoto(
  3511. not_null<PhotoData*> photo,
  3512. FullMsgId context) {
  3513. _controller->openPhoto(photo, { context });
  3514. }
  3515. void HistoryInner::elementOpenDocument(
  3516. not_null<DocumentData*> document,
  3517. FullMsgId context,
  3518. bool showInMediaView) {
  3519. _controller->openDocument(document, showInMediaView, { context });
  3520. }
  3521. void HistoryInner::elementCancelUpload(const FullMsgId &context) {
  3522. if (const auto item = session().data().message(context)) {
  3523. _controller->cancelUploadLayer(item);
  3524. }
  3525. }
  3526. void HistoryInner::elementShowTooltip(
  3527. const TextWithEntities &text,
  3528. Fn<void()> hiddenCallback) {
  3529. _widget->showInfoTooltip(text, std::move(hiddenCallback));
  3530. }
  3531. bool HistoryInner::elementAnimationsPaused() {
  3532. return _controller->isGifPausedAtLeastFor(Window::GifPauseReason::Any);
  3533. }
  3534. void HistoryInner::elementSendBotCommand(
  3535. const QString &command,
  3536. const FullMsgId &context) {
  3537. _widget->sendBotCommand({ _history->peer, command, context });
  3538. }
  3539. void HistoryInner::elementSearchInList(
  3540. const QString &query,
  3541. const FullMsgId &context) {
  3542. const auto inChat = _history->peer->isUser()
  3543. ? Dialogs::Key()
  3544. : Dialogs::Key(_history);
  3545. _controller->searchMessages(query, inChat);
  3546. }
  3547. void HistoryInner::elementHandleViaClick(not_null<UserData*> bot) {
  3548. _widget->insertBotCommand('@' + bot->username());
  3549. }
  3550. bool HistoryInner::elementIsChatWide() {
  3551. return _isChatWide;
  3552. }
  3553. not_null<Ui::PathShiftGradient*> HistoryInner::elementPathShiftGradient() {
  3554. return _pathGradient.get();
  3555. }
  3556. void HistoryInner::elementReplyTo(const FullReplyTo &to) {
  3557. return _widget->replyToMessage(to);
  3558. }
  3559. void HistoryInner::elementStartInteraction(not_null<const Element*> view) {
  3560. _controller->emojiInteractions().startOutgoing(view);
  3561. }
  3562. void HistoryInner::elementStartPremium(
  3563. not_null<const Element*> view,
  3564. Element *replacing) {
  3565. const auto already = !_emojiInteractions->playPremiumEffect(
  3566. view,
  3567. replacing);
  3568. _animatedStickersPlayed.emplace(view->data());
  3569. if (already) {
  3570. _widget->showPremiumStickerTooltip(view);
  3571. }
  3572. }
  3573. void HistoryInner::elementCancelPremium(not_null<const Element*> view) {
  3574. _emojiInteractions->cancelPremiumEffect(view);
  3575. }
  3576. void HistoryInner::elementStartEffect(
  3577. not_null<const Element*> view,
  3578. Element *replacing) {
  3579. _emojiInteractions->playEffect(view);
  3580. }
  3581. auto HistoryInner::getSelectionState() const
  3582. -> HistoryView::TopBarWidget::SelectedState {
  3583. auto result = HistoryView::TopBarWidget::SelectedState {};
  3584. for (auto &selected : _selected) {
  3585. if (selected.second == FullSelection) {
  3586. ++result.count;
  3587. if (selected.first->canDelete()) {
  3588. ++result.canDeleteCount;
  3589. }
  3590. if (selected.first->allowsForward()) {
  3591. ++result.canForwardCount;
  3592. }
  3593. } else if (selected.second.from != selected.second.to) {
  3594. result.textSelected = true;
  3595. }
  3596. }
  3597. return result;
  3598. }
  3599. void HistoryInner::clearSelected(bool onlyTextSelection) {
  3600. if (!_selected.empty() && (!onlyTextSelection || _selected.cbegin()->second != FullSelection)) {
  3601. _selected.clear();
  3602. _widget->updateTopBarSelection();
  3603. _widget->update();
  3604. }
  3605. }
  3606. bool HistoryInner::hasSelectedItems() const {
  3607. return !_selected.empty() && _selected.cbegin()->second == FullSelection;
  3608. }
  3609. MessageIdsList HistoryInner::getSelectedItems() const {
  3610. using namespace ranges;
  3611. if (!hasSelectedItems()) {
  3612. return {};
  3613. }
  3614. auto result = ranges::make_subrange(
  3615. _selected.begin(),
  3616. _selected.end()
  3617. ) | views::filter([](const auto &selected) {
  3618. const auto item = selected.first;
  3619. return item && !item->isService() && item->isRegular();
  3620. }) | views::transform([](const auto &selected) {
  3621. return selected.first->fullId();
  3622. }) | to_vector;
  3623. result |= actions::sort(less{}, [](const FullMsgId &msgId) {
  3624. return peerIsChannel(msgId.peer)
  3625. ? msgId.msg
  3626. : (msgId.msg - ServerMaxMsgId);
  3627. });
  3628. return result;
  3629. }
  3630. void HistoryInner::onTouchSelect() {
  3631. _touchSelect = true;
  3632. _touchMaybeSelecting = true;
  3633. mouseActionStart(_touchPos, Qt::LeftButton);
  3634. }
  3635. auto HistoryInner::reactionButtonParameters(
  3636. not_null<const Element*> view,
  3637. QPoint position,
  3638. const HistoryView::TextState &reactionState) const
  3639. -> HistoryView::Reactions::ButtonParameters {
  3640. if (!_useCornerReaction) {
  3641. return {};
  3642. }
  3643. const auto top = itemTop(view);
  3644. if (top < 0
  3645. || !view->data()->canReact()
  3646. || _mouseAction == MouseAction::Dragging
  3647. || _mouseAction == MouseAction::Selecting
  3648. || inSelectionMode().inSelectionMode) {
  3649. return {};
  3650. }
  3651. auto result = view->reactionButtonParameters(
  3652. position,
  3653. reactionState
  3654. ).translated({ 0, itemTop(view) });
  3655. result.visibleTop = _visibleAreaTop;
  3656. result.visibleBottom = _visibleAreaBottom;
  3657. result.globalPointer = _mousePosition;
  3658. return result;
  3659. }
  3660. void HistoryInner::mouseActionUpdate() {
  3661. if (hasPendingResizedItems()
  3662. || (!_mouseActive && !window()->isActiveWindow())) {
  3663. return;
  3664. }
  3665. auto mousePos = mapFromGlobal(_mousePosition);
  3666. auto point = _widget->clampMousePosition(mousePos);
  3667. auto m = QPoint();
  3668. adjustCurrent(point.y());
  3669. const auto reactionState = _reactionsManager->buttonTextState(point);
  3670. const auto reactionItem = session().data().message(reactionState.itemId);
  3671. const auto reactionView = viewByItem(reactionItem);
  3672. const auto view = reactionView
  3673. ? reactionView
  3674. : (_aboutView
  3675. && _aboutView->view()
  3676. && point.y() >= _aboutView->top
  3677. && point.y() < _aboutView->top + _aboutView->view()->height())
  3678. ? _aboutView->view()
  3679. : (_curHistory && !_curHistory->isEmpty())
  3680. ? _curHistory->blocks[_curBlock]->messages[_curItem].get()
  3681. : nullptr;
  3682. const auto item = view ? view->data().get() : nullptr;
  3683. const auto selectionViewOffset = view
  3684. ? QPoint(SelectionViewOffset(this, view), 0)
  3685. : QPoint(0, 0);
  3686. point -= selectionViewOffset;
  3687. if (view) {
  3688. const auto changed = (Element::Moused() != view);
  3689. if (changed) {
  3690. repaintItem(Element::Moused());
  3691. Element::Moused(view);
  3692. repaintItem(Element::Moused());
  3693. }
  3694. m = mapPointToItem(point, view);
  3695. _reactionsManager->updateButton(reactionButtonParameters(
  3696. view,
  3697. m,
  3698. reactionState));
  3699. if (changed) {
  3700. _reactionsItem = item;
  3701. }
  3702. if (view->pointState(m) != PointState::Outside) {
  3703. if (Element::Hovered() != view) {
  3704. repaintItem(Element::Hovered());
  3705. Element::Hovered(view);
  3706. repaintItem(Element::Hovered());
  3707. }
  3708. } else if (Element::Hovered()) {
  3709. repaintItem(Element::Hovered());
  3710. Element::Hovered(nullptr);
  3711. }
  3712. } else {
  3713. if (Element::Moused()) {
  3714. repaintItem(Element::Moused());
  3715. Element::Moused(nullptr);
  3716. }
  3717. _reactionsManager->updateButton({});
  3718. }
  3719. if (_mouseActionItem && !viewByItem(_mouseActionItem)) {
  3720. mouseActionCancel();
  3721. }
  3722. TextState dragState;
  3723. ClickHandlerHost *lnkhost = nullptr;
  3724. auto dragStateUserpic = false;
  3725. auto selectingText = (item == _mouseActionItem)
  3726. && (view == Element::Hovered())
  3727. && !_selected.empty()
  3728. && (_selected.cbegin()->second != FullSelection);
  3729. const auto overReaction = reactionView && reactionState.link;
  3730. if (overReaction) {
  3731. dragState = reactionState;
  3732. lnkhost = reactionView;
  3733. } else if (item) {
  3734. if (item != _mouseActionItem || ((m + selectionViewOffset) - _dragStartPosition).manhattanLength() >= QApplication::startDragDistance()) {
  3735. if (_mouseAction == MouseAction::PrepareDrag) {
  3736. _mouseAction = MouseAction::Dragging;
  3737. InvokeQueued(this, [=] { performDrag(); });
  3738. } else if (_mouseAction == MouseAction::PrepareSelect) {
  3739. _mouseAction = MouseAction::Selecting;
  3740. }
  3741. }
  3742. auto dateHeight = st::msgServicePadding.bottom() + st::msgServiceFont->height + st::msgServicePadding.top();
  3743. auto scrollDateOpacity = _scrollDateOpacity.value(_scrollDateShown ? 1. : 0.);
  3744. enumerateDates([&](not_null<Element*> view, int itemtop, int dateTop) {
  3745. // stop enumeration if the date is above our point
  3746. if (dateTop + dateHeight <= point.y()) {
  3747. return false;
  3748. }
  3749. const auto displayDate = view->displayDate();
  3750. auto dateInPlace = displayDate;
  3751. if (dateInPlace) {
  3752. const auto correctDateTop = itemtop + st::msgServiceMargin.top();
  3753. dateInPlace = (dateTop < correctDateTop + dateHeight);
  3754. }
  3755. // stop enumeration if we've found a date under the cursor
  3756. if (dateTop <= point.y()) {
  3757. auto opacity = (dateInPlace/* || noFloatingDate*/) ? 1. : scrollDateOpacity;
  3758. if (opacity > 0.) {
  3759. const auto item = view->data();
  3760. auto dateWidth = 0;
  3761. if (const auto date = view->Get<HistoryView::DateBadge>()) {
  3762. dateWidth = date->width;
  3763. } else {
  3764. dateWidth = st::msgServiceFont->width(langDayOfMonthFull(view->dateTime().date()));
  3765. }
  3766. dateWidth += st::msgServicePadding.left() + st::msgServicePadding.right();
  3767. auto dateLeft = st::msgServiceMargin.left();
  3768. auto maxwidth = _contentWidth;
  3769. if (_isChatWide) {
  3770. maxwidth = qMin(maxwidth, int32(st::msgMaxWidth + 2 * st::msgPhotoSkip + 2 * st::msgMargin.left()));
  3771. }
  3772. auto widthForDate = maxwidth - st::msgServiceMargin.left() - st::msgServiceMargin.left();
  3773. dateLeft += (widthForDate - dateWidth) / 2;
  3774. if (point.x() >= dateLeft && point.x() < dateLeft + dateWidth) {
  3775. if (!_scrollDateLink) {
  3776. _scrollDateLink = std::make_shared<Window::DateClickHandler>(item->history(), view->dateTime().date());
  3777. } else {
  3778. static_cast<Window::DateClickHandler*>(_scrollDateLink.get())->setDate(view->dateTime().date());
  3779. }
  3780. dragState = TextState(
  3781. nullptr,
  3782. _scrollDateLink);
  3783. _dragStateItem = session().data().message(dragState.itemId);
  3784. lnkhost = view;
  3785. }
  3786. }
  3787. return false;
  3788. }
  3789. return true;
  3790. });
  3791. if (!dragState.link) {
  3792. StateRequest request;
  3793. if (_mouseAction == MouseAction::Selecting) {
  3794. request.flags |= Ui::Text::StateRequest::Flag::LookupSymbol;
  3795. } else {
  3796. selectingText = false;
  3797. }
  3798. if (base::IsAltPressed()) {
  3799. request.flags &= ~Ui::Text::StateRequest::Flag::LookupLink;
  3800. }
  3801. dragState = view->textState(m, request);
  3802. _dragStateItem = session().data().message(dragState.itemId);
  3803. lnkhost = view;
  3804. if (!dragState.link && m.x() >= st::historyPhotoLeft && m.x() < st::historyPhotoLeft + st::msgPhotoSize) {
  3805. if (!item->isService() && view->hasFromPhoto()) {
  3806. enumerateUserpics([&](not_null<Element*> view, int userpicTop) -> bool {
  3807. // stop enumeration if the userpic is below our point
  3808. if (userpicTop > point.y()) {
  3809. return false;
  3810. }
  3811. // stop enumeration if we've found a userpic under the cursor
  3812. if (point.y() >= userpicTop && point.y() < userpicTop + st::msgPhotoSize) {
  3813. dragState = TextState(nullptr, view->fromPhotoLink());
  3814. dragStateUserpic = true;
  3815. _dragStateItem = nullptr;
  3816. lnkhost = view;
  3817. return false;
  3818. }
  3819. return true;
  3820. });
  3821. }
  3822. }
  3823. }
  3824. }
  3825. auto lnkChanged = ClickHandler::setActive(dragState.link, lnkhost);
  3826. _dragStateUserpic = dragStateUserpic;
  3827. if (lnkChanged || dragState.cursor != _mouseCursorState) {
  3828. Ui::Tooltip::Hide();
  3829. }
  3830. if (dragState.link
  3831. || dragState.cursor == CursorState::Date
  3832. || dragState.cursor == CursorState::Forwarded
  3833. || dragState.customTooltip) {
  3834. Ui::Tooltip::Show(1000, this);
  3835. }
  3836. Qt::CursorShape cur = style::cur_default;
  3837. _acceptsHorizontalScroll = dragState.horizontalScroll;
  3838. if (_mouseAction == MouseAction::None) {
  3839. _mouseCursorState = dragState.cursor;
  3840. if (dragState.link) {
  3841. cur = style::cur_pointer;
  3842. } else if (_mouseCursorState == CursorState::Text && (_selected.empty() || _selected.cbegin()->second != FullSelection)) {
  3843. cur = style::cur_text;
  3844. } else if (_mouseCursorState == CursorState::Date) {
  3845. //cur = style::cur_cross;
  3846. }
  3847. } else if (item) {
  3848. if (_mouseAction == MouseAction::Selecting) {
  3849. if (selectingText) {
  3850. uint16 second = dragState.symbol;
  3851. if (dragState.afterSymbol && _mouseSelectType == TextSelectType::Letters) {
  3852. ++second;
  3853. }
  3854. auto selState = TextSelection { qMin(second, _mouseTextSymbol), qMax(second, _mouseTextSymbol) };
  3855. if (_mouseSelectType != TextSelectType::Letters) {
  3856. if (const auto view = viewByItem(_mouseActionItem)) {
  3857. selState = view->adjustSelection(selState, _mouseSelectType);
  3858. }
  3859. }
  3860. if (!selState.empty()) {
  3861. // We started selecting text in web page preview.
  3862. ClickHandler::unpressed();
  3863. }
  3864. if (_selected[_mouseActionItem] != selState) {
  3865. _selected[_mouseActionItem] = selState;
  3866. repaintItem(_mouseActionItem);
  3867. }
  3868. if (!_wasSelectedText && (selState == FullSelection || selState.from != selState.to)) {
  3869. _wasSelectedText = true;
  3870. setFocus();
  3871. }
  3872. updateDragSelection(nullptr, nullptr, false);
  3873. } else {
  3874. auto selectingDown = (itemTop(_mouseActionItem) < itemTop(item)) || (_mouseActionItem == item && _dragStartPosition.y() < m.y());
  3875. auto dragSelFrom = viewByItem(_mouseActionItem);
  3876. auto dragSelTo = view;
  3877. // Maybe exclude dragSelFrom.
  3878. if (dragSelFrom->pointState(_dragStartPosition) == PointState::Outside) {
  3879. if (selectingDown) {
  3880. if (_dragStartPosition.y() >= dragSelFrom->height() - dragSelFrom->marginBottom() || ((view == dragSelFrom) && (m.y() < _dragStartPosition.y() + QApplication::startDragDistance() || m.y() < dragSelFrom->marginTop()))) {
  3881. dragSelFrom = (dragSelFrom != dragSelTo)
  3882. ? nextItem(dragSelFrom)
  3883. : nullptr;
  3884. }
  3885. } else {
  3886. if (_dragStartPosition.y() < dragSelFrom->marginTop() || ((view == dragSelFrom) && (m.y() >= _dragStartPosition.y() - QApplication::startDragDistance() || m.y() >= dragSelFrom->height() - dragSelFrom->marginBottom()))) {
  3887. dragSelFrom = (dragSelFrom != dragSelTo)
  3888. ? prevItem(dragSelFrom)
  3889. : nullptr;
  3890. }
  3891. }
  3892. }
  3893. if (_mouseActionItem != item) { // maybe exclude dragSelTo
  3894. if (selectingDown) {
  3895. if (m.y() < dragSelTo->marginTop()) {
  3896. dragSelTo = (dragSelFrom != dragSelTo)
  3897. ? prevItem(dragSelTo)
  3898. : nullptr;
  3899. }
  3900. } else {
  3901. if (m.y() >= dragSelTo->height() - dragSelTo->marginBottom()) {
  3902. dragSelTo = (dragSelFrom != dragSelTo)
  3903. ? nextItem(dragSelTo)
  3904. : nullptr;
  3905. }
  3906. }
  3907. }
  3908. auto dragSelecting = false;
  3909. auto dragFirstAffected = dragSelFrom;
  3910. while (dragFirstAffected
  3911. && (!dragFirstAffected->data()->isRegular()
  3912. || dragFirstAffected->data()->isService())) {
  3913. dragFirstAffected = (dragFirstAffected != dragSelTo)
  3914. ? (selectingDown
  3915. ? nextItem(dragFirstAffected)
  3916. : prevItem(dragFirstAffected))
  3917. : nullptr;
  3918. }
  3919. if (dragFirstAffected) {
  3920. auto i = _selected.find(dragFirstAffected->data());
  3921. dragSelecting = (i == _selected.cend() || i->second != FullSelection);
  3922. }
  3923. updateDragSelection(dragSelFrom, dragSelTo, dragSelecting);
  3924. }
  3925. } else if (_mouseAction == MouseAction::Dragging) {
  3926. }
  3927. if (ClickHandler::getPressed()) {
  3928. cur = style::cur_pointer;
  3929. } else if ((_mouseAction == MouseAction::Selecting)
  3930. && !_selected.empty()
  3931. && (_selected.cbegin()->second != FullSelection)) {
  3932. if (!_dragSelFrom || !_dragSelTo) {
  3933. cur = style::cur_text;
  3934. }
  3935. }
  3936. }
  3937. // Voice message seek support.
  3938. if (const auto pressedItem = _dragStateItem) {
  3939. if (const auto pressedView = viewByItem(pressedItem)) {
  3940. if (pressedItem->history() == _history || pressedItem->history() == _migrated) {
  3941. auto adjustedPoint = mapPointToItem(point, pressedView);
  3942. pressedView->updatePressed(adjustedPoint);
  3943. }
  3944. }
  3945. }
  3946. if (_mouseAction == MouseAction::Selecting) {
  3947. _selectScroll.checkDeltaScroll(
  3948. mousePos,
  3949. _scroll->scrollTop(),
  3950. _scroll->scrollTop() + _scroll->height());
  3951. } else {
  3952. updateDragSelection(nullptr, nullptr, false);
  3953. _selectScroll.cancel();
  3954. }
  3955. if (_mouseAction == MouseAction::None && (lnkChanged || cur != _cursor)) {
  3956. setCursor(_cursor = cur);
  3957. }
  3958. }
  3959. void HistoryInner::updateDragSelection(Element *dragSelFrom, Element *dragSelTo, bool dragSelecting) {
  3960. if (_dragSelFrom == dragSelFrom && _dragSelTo == dragSelTo && _dragSelecting == dragSelecting) {
  3961. return;
  3962. } else if (dragSelFrom && hasSelectRestriction()) {
  3963. updateDragSelection(nullptr, nullptr, false);
  3964. return;
  3965. }
  3966. _dragSelFrom = dragSelFrom;
  3967. _dragSelTo = dragSelTo;
  3968. int32 fromy = itemTop(_dragSelFrom), toy = itemTop(_dragSelTo);
  3969. if (fromy >= 0 && toy >= 0 && fromy > toy) {
  3970. std::swap(_dragSelFrom, _dragSelTo);
  3971. }
  3972. _dragSelecting = dragSelecting;
  3973. if (!_wasSelectedText && _dragSelFrom && _dragSelTo && _dragSelecting) {
  3974. _wasSelectedText = true;
  3975. setFocus();
  3976. }
  3977. update();
  3978. }
  3979. int HistoryInner::historyHeight() const {
  3980. int result = 0;
  3981. if (_history->isEmpty()) {
  3982. result += _migrated ? _migrated->height() : 0;
  3983. } else {
  3984. result += _history->height() - _historySkipHeight + (_migrated ? _migrated->height() : 0);
  3985. }
  3986. return result;
  3987. }
  3988. int HistoryInner::historyScrollTop() const {
  3989. auto htop = historyTop();
  3990. auto mtop = migratedTop();
  3991. if (htop >= 0 && _history->scrollTopItem) {
  3992. return htop + _history->scrollTopItem->block()->y() + _history->scrollTopItem->y() + _history->scrollTopOffset;
  3993. }
  3994. if (mtop >= 0 && _migrated->scrollTopItem) {
  3995. return mtop + _migrated->scrollTopItem->block()->y() + _migrated->scrollTopItem->y() + _migrated->scrollTopOffset;
  3996. }
  3997. return ScrollMax;
  3998. }
  3999. int HistoryInner::migratedTop() const {
  4000. return (_migrated && !_migrated->isEmpty()) ? _historyPaddingTop : -1;
  4001. }
  4002. int HistoryInner::historyTop() const {
  4003. int mig = migratedTop();
  4004. return !_history->isEmpty()
  4005. ? (mig >= 0
  4006. ? (mig + _migrated->height() - _historySkipHeight)
  4007. : _historyPaddingTop)
  4008. : -1;
  4009. }
  4010. int HistoryInner::historyDrawTop() const {
  4011. auto top = historyTop();
  4012. return (top >= 0) ? (top + _historySkipHeight) : -1;
  4013. }
  4014. void HistoryInner::setChooseReportReason(Data::ReportInput reportInput) {
  4015. _chooseForReportReason = reportInput;
  4016. }
  4017. void HistoryInner::clearChooseReportReason() {
  4018. _chooseForReportReason = std::nullopt;
  4019. }
  4020. auto HistoryInner::viewByItem(const HistoryItem *item) const -> Element* {
  4021. return !item
  4022. ? nullptr
  4023. : (_aboutView && _aboutView->item() == item)
  4024. ? _aboutView->view()
  4025. : item->mainView();
  4026. }
  4027. // -1 if should not be visible, -2 if bad history()
  4028. int HistoryInner::itemTop(const HistoryItem *item) const {
  4029. return item ? itemTop(viewByItem(item)) : -2;
  4030. }
  4031. int HistoryInner::itemTop(const Element *view) const {
  4032. if (!view) {
  4033. return -1;
  4034. } else if (_aboutView && view == _aboutView->view()) {
  4035. return _aboutView->top;
  4036. } else if (view->data()->mainView() != view) {
  4037. return -1;
  4038. }
  4039. const auto top = (view->history() == _history)
  4040. ? historyTop()
  4041. : (view->history() == _migrated
  4042. ? migratedTop()
  4043. : -2);
  4044. return (top < 0) ? top : (top + view->y() + view->block()->y());
  4045. }
  4046. auto HistoryInner::findViewForPinnedTracking(int top) const
  4047. -> std::pair<Element*, int> {
  4048. const auto normalTop = historyTop();
  4049. const auto oldTop = migratedTop();
  4050. const auto fromHistory = [&](not_null<History*> history, int historyTop)
  4051. -> std::pair<Element*, int> {
  4052. auto [view, offset] = history->findItemAndOffset(top - historyTop);
  4053. while (view && !view->data()->isRegular()) {
  4054. offset -= view->height();
  4055. view = view->nextInBlocks();
  4056. }
  4057. return { view, offset };
  4058. };
  4059. if (normalTop >= 0 && (oldTop < 0 || top >= normalTop)) {
  4060. return fromHistory(_history, normalTop);
  4061. } else if (oldTop >= 0) {
  4062. auto [view, offset] = fromHistory(_migrated, oldTop);
  4063. if (!view && normalTop >= 0) {
  4064. return fromHistory(_history, normalTop);
  4065. }
  4066. return { view, offset };
  4067. }
  4068. return { nullptr, 0 };
  4069. }
  4070. void HistoryInner::refreshAboutView(bool force) {
  4071. const auto refresh = [&] {
  4072. if (force) {
  4073. _aboutView = nullptr;
  4074. }
  4075. if (!_aboutView) {
  4076. _aboutView = std::make_unique<HistoryView::AboutView>(
  4077. _history,
  4078. _history->delegateMixin()->delegate());
  4079. _aboutView->refreshRequests() | rpl::start_with_next([=] {
  4080. updateBotInfo();
  4081. }, _aboutView->lifetime());
  4082. _aboutView->sendIntroSticker() | rpl::start_to_stream(
  4083. _sendIntroSticker,
  4084. _aboutView->lifetime());
  4085. }
  4086. };
  4087. if (const auto user = _peer->asUser()) {
  4088. if (const auto info = user->botInfo.get()) {
  4089. refresh();
  4090. if (!info->inited) {
  4091. session().api().requestFullPeer(user);
  4092. }
  4093. } else if (!user->isContact()
  4094. && !user->phoneCountryCode().isEmpty()) {
  4095. refresh();
  4096. } else if (!historyHeight()) {
  4097. if (user->starsPerMessage() > 0
  4098. || (user->requiresPremiumToWrite()
  4099. && !user->session().premium())
  4100. || user->isFullLoaded()) {
  4101. refresh();
  4102. } else {
  4103. session().api().requestFullPeer(user);
  4104. }
  4105. }
  4106. }
  4107. }
  4108. void HistoryInner::notifyMigrateUpdated() {
  4109. const auto migrated = _history->migrateFrom();
  4110. if (_migrated != migrated) {
  4111. if (_migrated) {
  4112. _migrated->delegateMixin()->setCurrent(nullptr);
  4113. }
  4114. _migrated = migrated;
  4115. if (_migrated) {
  4116. _migrated->delegateMixin()->setCurrent(this);
  4117. _migrated->translateTo(_history->translatedTo());
  4118. }
  4119. }
  4120. }
  4121. void HistoryInner::applyDragSelection() {
  4122. if (!hasSelectRestriction()) {
  4123. applyDragSelection(&_selected);
  4124. }
  4125. }
  4126. bool HistoryInner::isSelected(
  4127. not_null<SelectedItems*> toItems,
  4128. not_null<HistoryItem*> item) const {
  4129. const auto i = toItems->find(item);
  4130. return (i != toItems->cend()) && (i->second == FullSelection);
  4131. }
  4132. bool HistoryInner::isSelectedGroup(
  4133. not_null<SelectedItems*> toItems,
  4134. not_null<const Data::Group*> group) const {
  4135. for (const auto &other : group->items) {
  4136. if (!isSelected(toItems, other)) {
  4137. return false;
  4138. }
  4139. }
  4140. return true;
  4141. }
  4142. bool HistoryInner::isSelectedAsGroup(
  4143. not_null<SelectedItems*> toItems,
  4144. not_null<HistoryItem*> item) const {
  4145. if (const auto group = session().data().groups().find(item)) {
  4146. return isSelectedGroup(toItems, group);
  4147. }
  4148. return isSelected(toItems, item);
  4149. }
  4150. bool HistoryInner::goodForSelection(
  4151. not_null<SelectedItems*> toItems,
  4152. not_null<HistoryItem*> item,
  4153. int &totalCount) const {
  4154. if (!item->isRegular() || item->isService()) {
  4155. return false;
  4156. } else if (toItems->find(item) == toItems->end()) {
  4157. ++totalCount;
  4158. }
  4159. return true;
  4160. }
  4161. void HistoryInner::addToSelection(
  4162. not_null<SelectedItems*> toItems,
  4163. not_null<HistoryItem*> item) const {
  4164. const auto i = toItems->find(item);
  4165. if (i == toItems->cend()) {
  4166. if (toItems->size() == 1
  4167. && toItems->begin()->second != FullSelection) {
  4168. toItems->clear();
  4169. }
  4170. toItems->emplace(item, FullSelection);
  4171. } else if (i->second != FullSelection) {
  4172. i->second = FullSelection;
  4173. }
  4174. }
  4175. void HistoryInner::removeFromSelection(
  4176. not_null<SelectedItems*> toItems,
  4177. not_null<HistoryItem*> item) const {
  4178. const auto i = toItems->find(item);
  4179. if (i != toItems->cend()) {
  4180. toItems->erase(i);
  4181. }
  4182. }
  4183. void HistoryInner::changeSelection(
  4184. not_null<SelectedItems*> toItems,
  4185. not_null<HistoryItem*> item,
  4186. SelectAction action) const {
  4187. if (action == SelectAction::Invert) {
  4188. action = isSelected(toItems, item)
  4189. ? SelectAction::Deselect
  4190. : SelectAction::Select;
  4191. }
  4192. auto total = int(toItems->size());
  4193. const auto add = (action == SelectAction::Select);
  4194. if (add
  4195. && goodForSelection(toItems, item, total)
  4196. && total <= MaxSelectedItems) {
  4197. addToSelection(toItems, item);
  4198. } else {
  4199. removeFromSelection(toItems, item);
  4200. }
  4201. }
  4202. void HistoryInner::changeSelectionAsGroup(
  4203. not_null<SelectedItems*> toItems,
  4204. not_null<HistoryItem*> item,
  4205. SelectAction action) const {
  4206. const auto group = session().data().groups().find(item);
  4207. if (!group) {
  4208. return changeSelection(toItems, item, action);
  4209. }
  4210. if (action == SelectAction::Invert) {
  4211. action = isSelectedAsGroup(toItems, item)
  4212. ? SelectAction::Deselect
  4213. : SelectAction::Select;
  4214. }
  4215. auto total = int(toItems->size());
  4216. const auto canSelect = [&] {
  4217. for (const auto &other : group->items) {
  4218. if (!goodForSelection(toItems, other, total)) {
  4219. return false;
  4220. }
  4221. }
  4222. return (total <= MaxSelectedItems);
  4223. }();
  4224. if (action == SelectAction::Select && canSelect) {
  4225. for (const auto &other : group->items) {
  4226. addToSelection(toItems, other);
  4227. }
  4228. } else {
  4229. for (const auto &other : group->items) {
  4230. removeFromSelection(toItems, other);
  4231. }
  4232. }
  4233. }
  4234. void HistoryInner::forwardItem(FullMsgId itemId) {
  4235. Window::ShowForwardMessagesBox(_controller, { 1, itemId });
  4236. }
  4237. void HistoryInner::forwardAsGroup(FullMsgId itemId) {
  4238. if (const auto item = session().data().message(itemId)) {
  4239. Window::ShowForwardMessagesBox(
  4240. _controller,
  4241. session().data().itemOrItsGroup(item));
  4242. }
  4243. }
  4244. void HistoryInner::deleteItem(FullMsgId itemId) {
  4245. if (const auto item = session().data().message(itemId)) {
  4246. deleteItem(item);
  4247. }
  4248. }
  4249. void HistoryInner::deleteItem(not_null<HistoryItem*> item) {
  4250. if (item->isUploading()) {
  4251. _controller->cancelUploadLayer(item);
  4252. return;
  4253. }
  4254. const auto list = HistoryItemsList{ item };
  4255. if (CanCreateModerateMessagesBox(list)) {
  4256. _controller->show(Box(CreateModerateMessagesBox, list, nullptr));
  4257. } else {
  4258. const auto suggestModerate = false;
  4259. _controller->show(Box<DeleteMessagesBox>(item, suggestModerate));
  4260. }
  4261. }
  4262. bool HistoryInner::hasPendingResizedItems() const {
  4263. return _history->hasPendingResizedItems()
  4264. || (_migrated && _migrated->hasPendingResizedItems());
  4265. }
  4266. void HistoryInner::deleteAsGroup(FullMsgId itemId) {
  4267. if (const auto item = session().data().message(itemId)) {
  4268. const auto group = session().data().groups().find(item);
  4269. if (!group) {
  4270. return deleteItem(item);
  4271. } else if (CanCreateModerateMessagesBox(group->items)) {
  4272. _controller->show(Box(
  4273. CreateModerateMessagesBox,
  4274. group->items,
  4275. nullptr));
  4276. } else {
  4277. _controller->show(Box<DeleteMessagesBox>(
  4278. &session(),
  4279. session().data().itemsToIds(group->items)));
  4280. }
  4281. }
  4282. }
  4283. void HistoryInner::reportItem(FullMsgId itemId) {
  4284. ShowReportMessageBox(_controller->uiShow(), _peer, { itemId.msg }, {});
  4285. }
  4286. void HistoryInner::reportAsGroup(FullMsgId itemId) {
  4287. if (const auto item = session().data().message(itemId)) {
  4288. const auto group = session().data().groups().find(item);
  4289. const auto ids = group
  4290. ? (ranges::views::all(
  4291. group->items
  4292. ) | ranges::views::transform([](const auto &i) {
  4293. return i->fullId().msg;
  4294. }) | ranges::to_vector)
  4295. : std::vector<MsgId>{ 1, itemId.msg };
  4296. ShowReportMessageBox(_controller->uiShow(), _peer, ids, {});
  4297. }
  4298. }
  4299. void HistoryInner::blockSenderItem(FullMsgId itemId) {
  4300. if (const auto item = session().data().message(itemId)) {
  4301. _controller->show(Box(
  4302. Window::BlockSenderFromRepliesBox,
  4303. _controller,
  4304. itemId));
  4305. }
  4306. }
  4307. void HistoryInner::blockSenderAsGroup(FullMsgId itemId) {
  4308. blockSenderItem(itemId);
  4309. }
  4310. void HistoryInner::addSelectionRange(
  4311. not_null<SelectedItems*> toItems,
  4312. not_null<History*> history,
  4313. int fromblock,
  4314. int fromitem,
  4315. int toblock,
  4316. int toitem) const {
  4317. if (fromblock >= 0 && fromitem >= 0 && toblock >= 0 && toitem >= 0) {
  4318. for (; fromblock <= toblock; ++fromblock) {
  4319. auto block = history->blocks[fromblock].get();
  4320. for (int cnt = (fromblock < toblock) ? block->messages.size() : (toitem + 1); fromitem < cnt; ++fromitem) {
  4321. auto item = block->messages[fromitem]->data();
  4322. changeSelectionAsGroup(toItems, item, SelectAction::Select);
  4323. }
  4324. if (toItems->size() >= MaxSelectedItems) break;
  4325. fromitem = 0;
  4326. }
  4327. }
  4328. }
  4329. void HistoryInner::applyDragSelection(
  4330. not_null<SelectedItems*> toItems) const {
  4331. const auto selfromy = itemTop(_dragSelFrom);
  4332. const auto seltoy = [&] {
  4333. auto result = itemTop(_dragSelTo);
  4334. return (result < 0) ? result : (result + _dragSelTo->height());
  4335. }();
  4336. if (selfromy < 0 || seltoy < 0) {
  4337. return;
  4338. }
  4339. if (!toItems->empty() && toItems->cbegin()->second != FullSelection) {
  4340. toItems->clear();
  4341. }
  4342. const auto botAboutView = _aboutView ? _aboutView->view() : nullptr;
  4343. if (_dragSelecting) {
  4344. auto fromblock = (_dragSelFrom != botAboutView)
  4345. ? _dragSelFrom->block()->indexInHistory()
  4346. : _history->blocks.empty()
  4347. ? -1
  4348. : 0;
  4349. auto fromitem = (_dragSelFrom != botAboutView)
  4350. ? _dragSelFrom->indexInBlock()
  4351. : (_history->blocks.empty()
  4352. || _history->blocks[0]->messages.empty())
  4353. ? -1
  4354. : 0;
  4355. auto toblock = (_dragSelTo != botAboutView)
  4356. ? _dragSelTo->block()->indexInHistory()
  4357. : _history->blocks.empty()
  4358. ? -1
  4359. : 0;
  4360. auto toitem = (_dragSelTo != botAboutView)
  4361. ? _dragSelTo->indexInBlock()
  4362. : (_history->blocks.empty()
  4363. || _history->blocks[0]->messages.empty())
  4364. ? -1
  4365. : 0;
  4366. if (_migrated) {
  4367. if (_dragSelFrom->history() == _migrated) {
  4368. if (_dragSelTo->history() == _migrated) {
  4369. addSelectionRange(toItems, _migrated, fromblock, fromitem, toblock, toitem);
  4370. toblock = -1;
  4371. toitem = -1;
  4372. } else {
  4373. addSelectionRange(toItems, _migrated, fromblock, fromitem, _migrated->blocks.size() - 1, _migrated->blocks.back()->messages.size() - 1);
  4374. }
  4375. fromblock = 0;
  4376. fromitem = 0;
  4377. } else if (_dragSelTo->history() == _migrated) { // wtf
  4378. toblock = -1;
  4379. toitem = -1;
  4380. }
  4381. }
  4382. addSelectionRange(toItems, _history, fromblock, fromitem, toblock, toitem);
  4383. } else {
  4384. auto toRemove = std::vector<not_null<HistoryItem*>>();
  4385. for (const auto &item : *toItems) {
  4386. auto iy = itemTop(item.first);
  4387. if (iy < -1) {
  4388. toRemove.emplace_back(item.first);
  4389. } else if (iy >= 0 && iy >= selfromy && iy < seltoy) {
  4390. toRemove.emplace_back(item.first);
  4391. }
  4392. }
  4393. for (const auto item : toRemove) {
  4394. changeSelectionAsGroup(toItems, item, SelectAction::Deselect);
  4395. }
  4396. }
  4397. }
  4398. QString HistoryInner::tooltipText() const {
  4399. if (_mouseCursorState == CursorState::Date
  4400. && _mouseAction == MouseAction::None) {
  4401. if (const auto view = Element::Hovered()) {
  4402. return HistoryView::DateTooltipText(view);
  4403. }
  4404. } else if (_mouseCursorState == CursorState::Forwarded
  4405. && _mouseAction == MouseAction::None) {
  4406. if (const auto view = Element::Moused()) {
  4407. if (const auto forwarded = view->data()->Get<HistoryMessageForwarded>()) {
  4408. return forwarded->text.toString();
  4409. }
  4410. }
  4411. } else if (const auto lnk = ClickHandler::getActive()) {
  4412. using namespace HistoryView::Reactions;
  4413. const auto count = ReactionCountOfLink(_dragStateItem, lnk);
  4414. if (count.count && count.shortened) {
  4415. return Lang::FormatCountDecimal(count.count);
  4416. }
  4417. return lnk->tooltip();
  4418. } else if (const auto view = Element::Moused()) {
  4419. StateRequest request;
  4420. const auto local = mapFromGlobal(_mousePosition);
  4421. const auto point = _widget->clampMousePosition(local);
  4422. request.flags |= Ui::Text::StateRequest::Flag::LookupCustomTooltip;
  4423. const auto state = view->textState(
  4424. mapPointToItem(point, view),
  4425. request);
  4426. return state.customTooltipText;
  4427. }
  4428. return QString();
  4429. }
  4430. QPoint HistoryInner::tooltipPos() const {
  4431. return _mousePosition;
  4432. }
  4433. bool HistoryInner::tooltipWindowActive() const {
  4434. return Ui::AppInFocus() && Ui::InFocusChain(window());
  4435. }
  4436. void HistoryInner::onParentGeometryChanged() {
  4437. auto mousePos = QCursor::pos();
  4438. auto mouseOver = _widget->rect().contains(_widget->mapFromGlobal(mousePos));
  4439. auto needToUpdate = (_mouseAction != MouseAction::None || _touchScroll || mouseOver);
  4440. if (needToUpdate) {
  4441. mouseActionUpdate(mousePos);
  4442. }
  4443. }
  4444. bool HistoryInner::consumeScrollAction(QPoint delta) {
  4445. const auto horizontal = (std::abs(delta.x()) > std::abs(delta.y()));
  4446. if (!horizontal || !_acceptsHorizontalScroll || !Element::Moused()) {
  4447. return false;
  4448. }
  4449. const auto position = mapPointToItem(
  4450. mapFromGlobal(_mousePosition),
  4451. Element::Moused());
  4452. return Element::Moused()->consumeHorizontalScroll(position, delta.x());
  4453. }
  4454. Fn<HistoryView::ElementDelegate*()> HistoryInner::elementDelegateFactory(
  4455. FullMsgId itemId) const {
  4456. const auto weak = base::make_weak(_controller);
  4457. return [=]() -> HistoryView::ElementDelegate* {
  4458. if (const auto strong = weak.get()) {
  4459. auto &data = strong->session().data();
  4460. if (const auto item = data.message(itemId)) {
  4461. const auto history = item->history();
  4462. return history->delegateMixin()->delegate();
  4463. }
  4464. }
  4465. return nullptr;
  4466. };
  4467. }
  4468. ClickHandlerContext HistoryInner::prepareClickHandlerContext(
  4469. FullMsgId itemId) const {
  4470. return ClickHandlerContext{
  4471. .itemId = itemId,
  4472. .elementDelegate = elementDelegateFactory(itemId),
  4473. .sessionWindow = base::make_weak(_controller),
  4474. };
  4475. }
  4476. ClickContext HistoryInner::prepareClickContext(
  4477. Qt::MouseButton button,
  4478. FullMsgId itemId) const {
  4479. return {
  4480. button,
  4481. QVariant::fromValue(prepareClickHandlerContext(itemId)),
  4482. };
  4483. }
  4484. auto HistoryInner::sendIntroSticker() const
  4485. -> rpl::producer<not_null<DocumentData*>> {
  4486. return _sendIntroSticker.events();
  4487. }
  4488. auto HistoryInner::DelegateMixin()
  4489. -> std::unique_ptr<HistoryMainElementDelegateMixin> {
  4490. return std::make_unique<HistoryMainElementDelegate>();
  4491. }
  4492. bool CanSendReply(not_null<const HistoryItem*> item) {
  4493. const auto peer = item->history()->peer;
  4494. const auto topic = item->topic();
  4495. return topic
  4496. ? Data::CanSendAnything(topic)
  4497. : (Data::CanSendAnything(peer)
  4498. && (!peer->isChannel() || peer->asChannel()->amIn()));
  4499. }