dialogs_inner_widget.cpp 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168
  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 "dialogs/dialogs_inner_widget.h"
  8. #include "dialogs/dialogs_three_state_icon.h"
  9. #include "dialogs/ui/chat_search_empty.h"
  10. #include "dialogs/ui/chat_search_in.h"
  11. #include "dialogs/ui/dialogs_layout.h"
  12. #include "dialogs/ui/dialogs_video_userpic.h"
  13. #include "dialogs/dialogs_indexed_list.h"
  14. #include "dialogs/dialogs_widget.h"
  15. #include "dialogs/dialogs_search_from_controllers.h"
  16. #include "dialogs/dialogs_search_tags.h"
  17. #include "dialogs/dialogs_quick_action.h"
  18. #include "history/view/history_view_context_menu.h"
  19. #include "history/history.h"
  20. #include "history/history_item.h"
  21. #include "core/application.h"
  22. #include "core/click_handler_types.h"
  23. #include "core/shortcuts.h"
  24. #include "core/ui_integration.h"
  25. #include "ui/widgets/buttons.h"
  26. #include "ui/widgets/popup_menu.h"
  27. #include "ui/widgets/scroll_area.h"
  28. #include "ui/text/text_utilities.h"
  29. #include "ui/text/text_options.h"
  30. #include "ui/dynamic_thumbnails.h"
  31. #include "ui/painter.h"
  32. #include "ui/rect.h"
  33. #include "ui/ui_utility.h"
  34. #include "data/data_drafts.h"
  35. #include "data/data_folder.h"
  36. #include "data/data_forum.h"
  37. #include "data/data_forum_icons.h"
  38. #include "data/data_session.h"
  39. #include "data/data_channel.h"
  40. #include "data/data_forum_topic.h"
  41. #include "data/data_chat.h"
  42. #include "data/data_user.h"
  43. #include "data/data_peer_values.h"
  44. #include "data/data_histories.h"
  45. #include "data/data_chat_filters.h"
  46. #include "data/data_changes.h"
  47. #include "data/data_message_reactions.h"
  48. #include "data/data_saved_messages.h"
  49. #include "data/data_saved_sublist.h"
  50. #include "data/data_stories.h"
  51. #include "data/stickers/data_stickers.h"
  52. #include "data/data_send_action.h"
  53. #include "base/unixtime.h"
  54. #include "base/options.h"
  55. #include "lang/lang_keys.h"
  56. #include "lottie/lottie_icon.h"
  57. #include "mainwindow.h"
  58. #include "mainwidget.h"
  59. #include "storage/storage_account.h"
  60. #include "apiwrap.h"
  61. #include "main/main_session.h"
  62. #include "main/main_session_settings.h"
  63. #include "window/notifications_manager.h"
  64. #include "window/window_controller.h"
  65. #include "window/window_session_controller.h"
  66. #include "window/window_peer_menu.h"
  67. #include "ui/chat/chats_filter_tag.h"
  68. #include "ui/effects/ripple_animation.h"
  69. #include "ui/effects/loading_element.h"
  70. #include "ui/widgets/multi_select.h"
  71. #include "ui/widgets/menu/menu_add_action_callback_factory.h"
  72. #include "ui/unread_badge.h"
  73. #include "boxes/filters/edit_filter_box.h"
  74. #include "boxes/peers/edit_forum_topic_box.h"
  75. #include "api/api_chat_filters.h"
  76. #include "base/qt/qt_common_adapters.h"
  77. #include "styles/style_dialogs.h"
  78. #include "styles/style_chat.h" // popupMenuExpandedSeparator
  79. #include "styles/style_chat_helpers.h"
  80. #include "styles/style_color_indices.h"
  81. #include "styles/style_window.h"
  82. #include "styles/style_media_player.h"
  83. #include "styles/style_menu_icons.h"
  84. #include <QtWidgets/QApplication>
  85. namespace Dialogs {
  86. namespace {
  87. constexpr auto kHashtagResultsLimit = 5;
  88. constexpr auto kStartReorderThreshold = 30;
  89. constexpr auto kQueryPreviewLimit = 32;
  90. constexpr auto kPreviewPostsLimit = 3;
  91. [[nodiscard]] InnerWidget::ChatsFilterTagsKey SerializeFilterTagsKey(
  92. FilterId filterId,
  93. uint8 more,
  94. bool active) {
  95. return (filterId & 0xFFFFFFFF)
  96. | (static_cast<int64_t>(more) << 32)
  97. | (static_cast<int64_t>(active) << 40);
  98. }
  99. [[nodiscard]] int FixedOnTopDialogsCount(not_null<Dialogs::IndexedList*> list) {
  100. auto result = 0;
  101. for (const auto &row : *list) {
  102. if (!row->entry()->fixedOnTopIndex()) {
  103. break;
  104. }
  105. ++result;
  106. }
  107. return result;
  108. }
  109. [[nodiscard]] int PinnedDialogsCount(
  110. FilterId filterId,
  111. not_null<Dialogs::IndexedList*> list) {
  112. auto result = 0;
  113. for (const auto &row : *list) {
  114. if (row->entry()->fixedOnTopIndex()) {
  115. continue;
  116. } else if (!row->entry()->isPinnedDialog(filterId)) {
  117. break;
  118. }
  119. ++result;
  120. }
  121. return result;
  122. }
  123. [[nodiscard]] UserData *MaybeBotWithApp(Row *row) {
  124. if (row) {
  125. if (const auto history = row->key().history()) {
  126. if (const auto user = history->peer->asUser()) {
  127. if (user->botInfo && user->botInfo->hasMainApp) {
  128. if (!history->unreadCount() && !history->unreadMark()) {
  129. return user;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. return nullptr;
  136. }
  137. [[nodiscard]] object_ptr<SearchEmpty> MakeSearchEmpty(
  138. QWidget *parent,
  139. SearchState state,
  140. Fn<void()> resetChatTypeFilter) {
  141. const auto query = state.query.trimmed();
  142. const auto hashtag = !query.isEmpty() && (query[0] == '#');
  143. const auto trimmed = hashtag ? query.mid(1).trimmed() : query;
  144. const auto fromPeer = (state.tab == ChatSearchTab::MyMessages
  145. || state.tab == ChatSearchTab::PublicPosts
  146. || !state.inChat.peer()
  147. || !(state.inChat.peer()->isChat()
  148. || state.inChat.peer()->isMegagroup()))
  149. ? nullptr
  150. : state.fromPeer;
  151. const auto waiting = trimmed.isEmpty()
  152. && state.tags.empty()
  153. && !fromPeer;
  154. const auto suggestAllChats = !waiting
  155. && state.tab == ChatSearchTab::MyMessages
  156. && state.filter != ChatTypeFilter::All;
  157. const auto icon = waiting
  158. ? SearchEmptyIcon::Search
  159. : SearchEmptyIcon::NoResults;
  160. auto text = TextWithEntities();
  161. if (waiting) {
  162. if (hashtag) {
  163. text.append(tr::lng_search_tab_by_hashtag(tr::now));
  164. } else {
  165. text.append(tr::lng_dlg_search_for_messages(tr::now));
  166. }
  167. } else {
  168. text.append(tr::lng_search_tab_no_results(
  169. tr::now,
  170. Ui::Text::Bold));
  171. if (!trimmed.isEmpty()) {
  172. const auto preview = (trimmed.size() > kQueryPreviewLimit + 3)
  173. ? (trimmed.mid(0, kQueryPreviewLimit) + Ui::kQEllipsis)
  174. : trimmed;
  175. text.append("\n").append(
  176. tr::lng_search_tab_no_results_text(
  177. tr::now,
  178. lt_query,
  179. trimmed.mid(0, kQueryPreviewLimit)));
  180. if (suggestAllChats) {
  181. text.append("\n\n").append(
  182. Ui::Text::Link(tr::lng_search_tab_try_in_all(tr::now)));
  183. } else if (hashtag) {
  184. text.append("\n").append(
  185. tr::lng_search_tab_no_results_retry(tr::now));
  186. }
  187. }
  188. }
  189. auto result = object_ptr<SearchEmpty>(
  190. parent,
  191. icon,
  192. rpl::single(std::move(text)));
  193. if (suggestAllChats) {
  194. result->handlerActivated(
  195. ) | rpl::start_with_next(resetChatTypeFilter, result->lifetime());
  196. }
  197. result->show();
  198. result->resizeToWidth(parent->width());
  199. return result;
  200. }
  201. [[nodiscard]] QString ChatTypeFilterLabel(ChatTypeFilter filter) {
  202. switch (filter) {
  203. case ChatTypeFilter::All:
  204. return tr::lng_search_filter_all(tr::now);
  205. case ChatTypeFilter::Private:
  206. return tr::lng_search_filter_private(tr::now);
  207. case ChatTypeFilter::Groups:
  208. return tr::lng_search_filter_group(tr::now);
  209. case ChatTypeFilter::Channels:
  210. return tr::lng_search_filter_channel(tr::now);
  211. }
  212. Unexpected("Chat type filter in search results.");
  213. }
  214. } // namespace
  215. struct InnerWidget::CollapsedRow {
  216. CollapsedRow(Data::Folder *folder) : folder(folder) {
  217. }
  218. Data::Folder *folder = nullptr;
  219. BasicRow row;
  220. };
  221. struct InnerWidget::HashtagResult {
  222. HashtagResult(const QString &tag) : tag(tag) {
  223. }
  224. QString tag;
  225. BasicRow row;
  226. };
  227. struct InnerWidget::PeerSearchResult {
  228. explicit PeerSearchResult(not_null<PeerData*> peer) : peer(peer) {
  229. }
  230. not_null<PeerData*> peer;
  231. mutable Ui::Text::String name;
  232. mutable Ui::PeerBadge badge;
  233. BasicRow row;
  234. };
  235. struct InnerWidget::TagCache {
  236. Ui::ChatsFilterTagContext context;
  237. QImage frame;
  238. };
  239. Key InnerWidget::FilterResult::key() const {
  240. return row->key();
  241. }
  242. int InnerWidget::FilterResult::bottom() const {
  243. return top + row->height();
  244. }
  245. InnerWidget::InnerWidget(
  246. QWidget *parent,
  247. not_null<Window::SessionController*> controller,
  248. rpl::producer<ChildListShown> childListShown)
  249. : RpWidget(parent)
  250. , _controller(controller)
  251. , _shownList(controller->session().data().chatsList()->indexed())
  252. , _st(&st::defaultDialogRow)
  253. , _pinnedShiftAnimation([=](crl::time now) {
  254. return pinnedShiftAnimationCallback(now);
  255. })
  256. , _narrowWidth(st::defaultDialogRow.padding.left()
  257. + st::defaultDialogRow.photoSize
  258. + st::defaultDialogRow.padding.left())
  259. , _childListShown(std::move(childListShown)) {
  260. setAttribute(Qt::WA_OpaquePaintEvent, true);
  261. style::PaletteChanged(
  262. ) | rpl::start_with_next([=] {
  263. _topicJumpCache = nullptr;
  264. _chatsFilterTags.clear();
  265. _rightButtons.clear();
  266. }, lifetime());
  267. session().downloaderTaskFinished(
  268. ) | rpl::start_with_next([=] {
  269. update();
  270. }, lifetime());
  271. Core::App().notifications().settingsChanged(
  272. ) | rpl::start_with_next([=](Window::Notifications::ChangeType change) {
  273. if (change == Window::Notifications::ChangeType::CountMessages) {
  274. // Folder rows change their unread badge with this setting.
  275. update();
  276. }
  277. }, lifetime());
  278. session().data().contactsLoaded().changes(
  279. ) | rpl::start_with_next([=] {
  280. refresh();
  281. refreshEmpty();
  282. }, lifetime());
  283. session().data().itemRemoved(
  284. ) | rpl::start_with_next([=](not_null<const HistoryItem*> item) {
  285. itemRemoved(item);
  286. }, lifetime());
  287. session().data().dialogsRowReplacements(
  288. ) | rpl::start_with_next([=](Data::Session::DialogsRowReplacement r) {
  289. dialogRowReplaced(r.old, r.now);
  290. }, lifetime());
  291. session().data().sendActionManager().animationUpdated(
  292. ) | rpl::start_with_next([=](
  293. const Data::SendActionManager::AnimationUpdate &update) {
  294. const auto updateRect = Ui::RowPainter::SendActionAnimationRect(
  295. _st,
  296. update.left,
  297. update.width,
  298. update.height,
  299. width(),
  300. update.textUpdated);
  301. updateDialogRow(
  302. RowDescriptor(update.thread, FullMsgId()),
  303. updateRect,
  304. UpdateRowSection::Default | UpdateRowSection::Filtered);
  305. }, lifetime());
  306. session().data().sendActionManager().speakingAnimationUpdated(
  307. ) | rpl::start_with_next([=](not_null<History*> history) {
  308. repaintDialogRowCornerStatus(history);
  309. }, lifetime());
  310. setupOnlineStatusCheck();
  311. rpl::merge(
  312. session().data().chatsListChanges(),
  313. session().data().chatsListLoadedEvents()
  314. ) | rpl::filter([=](Data::Folder *folder) {
  315. return !_savedSublists
  316. && !_openedForum
  317. && (folder == _openedFolder);
  318. }) | rpl::start_with_next([=] {
  319. refresh();
  320. }, lifetime());
  321. rpl::merge(
  322. session().settings().archiveCollapsedChanges() | rpl::map_to(false),
  323. session().data().chatsFilters().changed() | rpl::map_to(true)
  324. ) | rpl::start_with_next([=](bool refreshHeight) {
  325. if (refreshHeight) {
  326. _chatsFilterTags.clear();
  327. }
  328. if (refreshHeight && _filterId) {
  329. // Height of the main list will be refreshed in other way.
  330. _shownList->updateHeights(_narrowRatio);
  331. }
  332. refreshWithCollapsedRows();
  333. }, lifetime());
  334. session().data().chatsFilters().tagsEnabledValue(
  335. ) | rpl::distinct_until_changed() | rpl::start_with_next([=](bool tags) {
  336. _handleChatListEntryTagRefreshesLifetime.destroy();
  337. if (_shownList->updateHeights(_narrowRatio)) {
  338. refresh();
  339. }
  340. if (!tags) {
  341. return;
  342. }
  343. using Event = Data::Session::ChatListEntryRefresh;
  344. session().data().chatListEntryRefreshes(
  345. ) | rpl::filter([=](const Event &event) {
  346. if (_waitingAllChatListEntryRefreshesForTags) {
  347. return false;
  348. }
  349. if (event.existenceChanged) {
  350. if (event.key.entry()->inChatList(_filterId)) {
  351. _waitingAllChatListEntryRefreshesForTags = true;
  352. return true;
  353. }
  354. }
  355. return false;
  356. }) | rpl::start_with_next([=](const Event &event) {
  357. Ui::PostponeCall(crl::guard(this, [=] {
  358. _waitingAllChatListEntryRefreshesForTags = false;
  359. if (_shownList->updateHeights(_narrowRatio)) {
  360. refresh();
  361. }
  362. }));
  363. }, _handleChatListEntryTagRefreshesLifetime);
  364. session().data().chatsFilters().tagColorChanged(
  365. ) | rpl::start_with_next([=](Data::TagColorChanged data) {
  366. const auto filterId = data.filterId;
  367. const auto key = SerializeFilterTagsKey(filterId, 0, false);
  368. const auto activeKey = SerializeFilterTagsKey(filterId, 0, true);
  369. {
  370. auto &tags = _chatsFilterTags;
  371. if (const auto it = tags.find(key); it != tags.end()) {
  372. tags.erase(it);
  373. }
  374. if (const auto it = tags.find(activeKey); it != tags.end()) {
  375. tags.erase(it);
  376. }
  377. }
  378. if (data.colorExistenceChanged) {
  379. auto &filters = session().data().chatsFilters();
  380. for (const auto &filter : filters.list()) {
  381. if (filter.id() != filterId) {
  382. continue;
  383. }
  384. const auto c = filter.colorIndex();
  385. const auto list = filters.chatsList(filterId);
  386. for (const auto &row : list->indexed()->all()) {
  387. row->entry()->setColorIndexForFilterId(filterId, c);
  388. }
  389. }
  390. if (_shownList->updateHeights(_narrowRatio)) {
  391. refresh();
  392. }
  393. } else {
  394. update();
  395. }
  396. }, _handleChatListEntryTagRefreshesLifetime);
  397. }, lifetime());
  398. session().settings().archiveInMainMenuChanges(
  399. ) | rpl::start_with_next([=] {
  400. refresh();
  401. }, lifetime());
  402. session().changes().historyUpdates(
  403. Data::HistoryUpdate::Flag::IsPinned
  404. | Data::HistoryUpdate::Flag::ChatOccupied
  405. ) | rpl::start_with_next([=](const Data::HistoryUpdate &update) {
  406. if (update.flags & Data::HistoryUpdate::Flag::IsPinned) {
  407. stopReorderPinned();
  408. }
  409. if (update.flags & Data::HistoryUpdate::Flag::ChatOccupied) {
  410. this->update();
  411. _updated.fire({});
  412. }
  413. }, lifetime());
  414. using UpdateFlag = Data::PeerUpdate::Flag;
  415. session().changes().peerUpdates(
  416. UpdateFlag::Name
  417. | UpdateFlag::Photo
  418. | UpdateFlag::IsContact
  419. | UpdateFlag::FullInfo
  420. | UpdateFlag::EmojiStatus
  421. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  422. if (update.flags
  423. & (UpdateFlag::Name
  424. | UpdateFlag::Photo
  425. | UpdateFlag::FullInfo
  426. | UpdateFlag::EmojiStatus)) {
  427. const auto peer = update.peer;
  428. const auto history = peer->owner().historyLoaded(peer);
  429. if (_state == WidgetState::Default) {
  430. if (history) {
  431. updateDialogRow({ history, FullMsgId() });
  432. }
  433. } else {
  434. this->update();
  435. }
  436. _updated.fire({});
  437. }
  438. if (update.flags & UpdateFlag::IsContact) {
  439. // contactsNoChatsList could've changed.
  440. Ui::PostponeCall(this, [=] { refresh(); });
  441. }
  442. }, lifetime());
  443. session().changes().messageUpdates(
  444. Data::MessageUpdate::Flag::DialogRowRefresh
  445. ) | rpl::start_with_next([=](const Data::MessageUpdate &update) {
  446. refreshDialogRow({ update.item->history(), update.item->fullId() });
  447. }, lifetime());
  448. session().changes().entryUpdates(
  449. Data::EntryUpdate::Flag::Repaint
  450. | Data::EntryUpdate::Flag::Height
  451. ) | rpl::start_with_next([=](const Data::EntryUpdate &update) {
  452. const auto entry = update.entry;
  453. if (update.flags & Data::EntryUpdate::Flag::Height) {
  454. if (updateEntryHeight(entry)) {
  455. refresh();
  456. }
  457. return;
  458. }
  459. const auto repaintId = (_state == WidgetState::Default)
  460. ? _filterId
  461. : 0;
  462. if (const auto links = entry->chatListLinks(repaintId)) {
  463. repaintDialogRow(repaintId, links->main);
  464. }
  465. if (session().supportMode()
  466. && !session().settings().supportAllSearchResults()) {
  467. repaintDialogRow({ entry, FullMsgId() });
  468. }
  469. }, lifetime());
  470. _controller->activeChatEntryValue(
  471. ) | rpl::combine_previous(
  472. ) | rpl::start_with_next([=](
  473. RowDescriptor previous,
  474. RowDescriptor next) {
  475. updateDialogRow(previous);
  476. updateDialogRow(next);
  477. }, lifetime());
  478. _controller->activeChatsFilter(
  479. ) | rpl::start_with_next([=](FilterId filterId) {
  480. switchToFilter(filterId);
  481. }, lifetime());
  482. _controller->window().widget()->globalForceClicks(
  483. ) | rpl::start_with_next([=](QPoint globalPosition) {
  484. processGlobalForceClick(globalPosition);
  485. }, lifetime());
  486. session().data().stories().incrementPreloadingMainSources();
  487. handleChatListEntryRefreshes();
  488. refreshWithCollapsedRows(true);
  489. setupShortcuts();
  490. }
  491. bool InnerWidget::updateEntryHeight(not_null<Entry*> entry) {
  492. if (!_geometryInited) {
  493. return false;
  494. }
  495. auto changing = false;
  496. auto top = 0;
  497. for (auto &result : _filterResults) {
  498. if (changing) {
  499. result.top = top;
  500. }
  501. if (result.row->key().entry() == entry) {
  502. result.row->recountHeight(_narrowRatio, _filterId);
  503. changing = true;
  504. top = result.top;
  505. }
  506. if (changing) {
  507. top += result.row->height();
  508. }
  509. }
  510. return _shownList->updateHeight(entry, _narrowRatio) || changing;
  511. }
  512. void InnerWidget::setNarrowRatio(float64 narrowRatio) {
  513. if (_geometryInited && _narrowRatio == narrowRatio) {
  514. return;
  515. }
  516. _geometryInited = true;
  517. _narrowRatio = narrowRatio;
  518. if (_shownList->updateHeights(_narrowRatio) || !height()) {
  519. refresh();
  520. }
  521. }
  522. Main::Session &InnerWidget::session() const {
  523. return _controller->session();
  524. }
  525. void InnerWidget::refreshWithCollapsedRows(bool toTop) {
  526. const auto pressed = _collapsedPressed;
  527. const auto selected = _collapsedSelected;
  528. setCollapsedPressed(-1);
  529. _collapsedSelected = -1;
  530. _collapsedRows.clear();
  531. const auto archive = !_shownList->empty()
  532. ? _shownList->begin()->get()->folder()
  533. : nullptr;
  534. const auto inMainMenu = session().settings().archiveInMainMenu();
  535. if (archive && (session().settings().archiveCollapsed() || inMainMenu)) {
  536. if (_selected && _selected->folder() == archive) {
  537. _selected = nullptr;
  538. }
  539. if (_pressed && _pressed->folder() == archive) {
  540. clearPressed();
  541. }
  542. _skipTopDialog = true;
  543. if (!inMainMenu && !_filterId) {
  544. _collapsedRows.push_back(
  545. std::make_unique<CollapsedRow>(archive));
  546. }
  547. } else {
  548. _skipTopDialog = false;
  549. }
  550. Assert(!needCollapsedRowsRefresh());
  551. refresh(toTop);
  552. if (selected >= 0 && selected < _collapsedRows.size()) {
  553. _collapsedSelected = selected;
  554. }
  555. if (pressed >= 0 && pressed < _collapsedRows.size()) {
  556. setCollapsedPressed(pressed);
  557. }
  558. }
  559. int InnerWidget::skipTopHeight() const {
  560. return (_skipTopDialog && !_shownList->empty())
  561. ? _shownList->begin()->get()->height()
  562. : 0;
  563. }
  564. int InnerWidget::collapsedRowsOffset() const {
  565. return 0;
  566. }
  567. int InnerWidget::dialogsOffset() const {
  568. return collapsedRowsOffset()
  569. + (_collapsedRows.size() * st::dialogsImportantBarHeight)
  570. - skipTopHeight();
  571. }
  572. int InnerWidget::fixedOnTopCount() const {
  573. auto result = 0;
  574. for (const auto &row : *_shownList) {
  575. if (row->entry()->fixedOnTopIndex()) {
  576. ++result;
  577. } else {
  578. break;
  579. }
  580. }
  581. return result;
  582. }
  583. int InnerWidget::shownHeight(int till) const {
  584. return !till
  585. ? 0
  586. : (till > 0 && till < _shownList->size())
  587. ? (_shownList->begin() + till)->get()->top()
  588. : _shownList->height();
  589. }
  590. int InnerWidget::pinnedOffset() const {
  591. return dialogsOffset() + shownHeight(fixedOnTopCount());
  592. }
  593. int InnerWidget::hashtagsOffset() const {
  594. return searchInChatOffset() + searchInChatSkip();
  595. }
  596. int InnerWidget::filteredOffset() const {
  597. return hashtagsOffset() + (_hashtagResults.size() * st::mentionHeight);
  598. }
  599. int InnerWidget::filteredIndex(int y) const {
  600. return ranges::lower_bound(
  601. _filterResults,
  602. y,
  603. ranges::less(),
  604. &FilterResult::bottom
  605. ) - begin(_filterResults);
  606. }
  607. int InnerWidget::filteredHeight(int till) const {
  608. return (!till || _filterResults.empty())
  609. ? 0
  610. : (till > 0 && till < _filterResults.size())
  611. ? _filterResults[till].top
  612. : (_filterResults.back().top + _filterResults.back().row->height());
  613. }
  614. int InnerWidget::peerSearchOffset() const {
  615. return filteredOffset()
  616. + filteredHeight()
  617. + st::searchedBarHeight;
  618. }
  619. int InnerWidget::searchInChatOffset() const {
  620. return (_searchTags ? _searchTags->height() : 0);
  621. }
  622. int InnerWidget::searchInChatSkip() const {
  623. return _searchIn ? _searchIn->height() : 0;
  624. }
  625. int InnerWidget::previewOffset() const {
  626. auto result = peerSearchOffset();
  627. if (!_peerSearchResults.empty()) {
  628. result += (_peerSearchResults.size() * st::dialogsRowHeight)
  629. + st::searchedBarHeight;
  630. }
  631. return result;
  632. }
  633. int InnerWidget::searchedOffset() const {
  634. auto result = previewOffset();
  635. if (!_previewResults.empty()) {
  636. result += (_previewResults.size() * st::dialogsRowHeight)
  637. + st::searchedBarHeight;
  638. }
  639. return result;
  640. }
  641. void InnerWidget::changeOpenedFolder(Data::Folder *folder) {
  642. Expects(!folder || !_savedSublists);
  643. if (_openedFolder == folder) {
  644. return;
  645. }
  646. stopReorderPinned();
  647. clearSelection();
  648. _openedFolder = folder;
  649. refreshShownList();
  650. refreshWithCollapsedRows(true);
  651. if (_loadMoreCallback) {
  652. _loadMoreCallback();
  653. }
  654. }
  655. void InnerWidget::changeOpenedForum(Data::Forum *forum) {
  656. Expects(!forum || !_savedSublists);
  657. if (_openedForum == forum) {
  658. return;
  659. }
  660. stopReorderPinned();
  661. clearSelection();
  662. if (forum) {
  663. saveChatsFilterScrollState(_filterId);
  664. }
  665. _filterId = forum
  666. ? 0
  667. : _controller->activeChatsFilterCurrent();
  668. if (_openedForum) {
  669. // If we close it inside forum destruction we should not schedule.
  670. session().data().forumIcons().scheduleUserpicsReset(_openedForum);
  671. }
  672. _openedForum = forum;
  673. _st = forum ? &st::forumTopicRow : &st::defaultDialogRow;
  674. refreshShownList();
  675. _openedForumLifetime.destroy();
  676. if (forum) {
  677. rpl::merge(
  678. forum->chatsListChanges(),
  679. forum->chatsListLoadedEvents()
  680. ) | rpl::start_with_next([=] {
  681. refresh();
  682. }, _openedForumLifetime);
  683. }
  684. refreshWithCollapsedRows(true);
  685. if (_loadMoreCallback) {
  686. _loadMoreCallback();
  687. }
  688. if (!forum) {
  689. restoreChatsFilterScrollState(_filterId);
  690. }
  691. }
  692. void InnerWidget::showSavedSublists() {
  693. Expects(!_geometryInited);
  694. Expects(!_savedSublists);
  695. _savedSublists = true;
  696. stopReorderPinned();
  697. clearSelection();
  698. _filterId = 0;
  699. _openedForum = nullptr;
  700. _st = &st::defaultDialogRow;
  701. refreshShownList();
  702. _openedForumLifetime.destroy();
  703. //session().data().savedMessages().chatsListChanges(
  704. //) | rpl::start_with_next([=] {
  705. // refresh();
  706. //}, lifetime());
  707. refreshWithCollapsedRows(true);
  708. if (_loadMoreCallback) {
  709. _loadMoreCallback();
  710. }
  711. }
  712. void InnerWidget::paintEvent(QPaintEvent *e) {
  713. Painter p(this);
  714. p.setInactive(
  715. _controller->isGifPausedAtLeastFor(Window::GifPauseReason::Any));
  716. if (!_savedSublists && _controller->contentOverlapped(this, e)) {
  717. return;
  718. }
  719. const auto activeEntry = _controller->activeChatEntryCurrent();
  720. const auto videoPaused = _controller->isGifPausedAtLeastFor(
  721. Window::GifPauseReason::Any);
  722. auto fullWidth = width();
  723. const auto r = e->rect();
  724. auto dialogsClip = r;
  725. const auto ms = crl::now();
  726. const auto childListShown = _childListShown.current();
  727. auto context = Ui::PaintContext{
  728. .st = _st,
  729. .topicJumpCache = _topicJumpCache.get(),
  730. .folder = _openedFolder,
  731. .forum = _openedForum,
  732. .currentBg = currentBg(),
  733. .filter = _filterId,
  734. .now = ms,
  735. .width = fullWidth,
  736. .paused = videoPaused,
  737. .narrow = (fullWidth < st::columnMinimalWidthLeft / 2),
  738. };
  739. const auto fillGuard = gsl::finally([&] {
  740. // We translate painter down, but it'll be cropped below rect.
  741. p.fillRect(rect(), context.currentBg);
  742. });
  743. const auto paintRow = [&](
  744. not_null<Row*> row,
  745. bool selected,
  746. bool mayBeActive) {
  747. const auto &key = row->key();
  748. const auto active = mayBeActive && isRowActive(row, activeEntry);
  749. const auto forum = key.history() && key.history()->isForum();
  750. if (forum && !_topicJumpCache) {
  751. _topicJumpCache = std::make_unique<Ui::TopicJumpCache>();
  752. }
  753. const auto expanding = forum
  754. && (key.history()->peer->id == childListShown.peerId);
  755. context.rightButton = maybeCacheRightButton(row);
  756. if (key.history()) {
  757. const auto it = _quickActions.find(key.history()->peer->id.value);
  758. context.quickActionContext = (it != _quickActions.end())
  759. ? it->second.get()
  760. : nullptr;
  761. }
  762. context.st = (forum ? &st::forumDialogRow : _st.get());
  763. auto chatsFilterTags = std::vector<QImage*>();
  764. if (context.narrow) {
  765. context.chatsFilterTags = nullptr;
  766. } else if (row->entry()->hasChatsFilterTags(context.filter)) {
  767. const auto a = active;
  768. context.st = forum
  769. ? &st::taggedForumDialogRow
  770. : &st::taggedDialogRow;
  771. auto availableWidth = context.width
  772. - context.st->padding.right()
  773. - st::dialogsUnreadPadding
  774. - context.st->nameLeft;
  775. auto more = uint8(0);
  776. const auto &list = session().data().chatsFilters().list();
  777. for (const auto &filter : list) {
  778. if (!row->entry()->inChatList(filter.id())
  779. || (filter.id() == context.filter)) {
  780. continue;
  781. }
  782. if (active
  783. && (filter.flags() & Data::ChatFilter::Flag::NoRead)
  784. && !filter.contains(key.history(), true)) {
  785. // Hack for History::fakeUnreadWhileOpened().
  786. continue;
  787. }
  788. if (const auto tag = cacheChatsFilterTag(filter, 0, a)) {
  789. if (more) {
  790. more++;
  791. continue;
  792. }
  793. const auto tagWidth = tag->width()
  794. / style::DevicePixelRatio();
  795. if (availableWidth < tagWidth) {
  796. more++;
  797. } else {
  798. chatsFilterTags.push_back(tag);
  799. availableWidth -= tagWidth
  800. + st::dialogRowFilterTagSkip;
  801. }
  802. }
  803. }
  804. if (more) {
  805. if (const auto tag = cacheChatsFilterTag({}, more, a)) {
  806. const auto tagWidth = tag->width()
  807. / style::DevicePixelRatio();
  808. if (availableWidth < tagWidth) {
  809. more++;
  810. if (!chatsFilterTags.empty()) {
  811. const auto tag = cacheChatsFilterTag({}, more, a);
  812. if (tag) {
  813. chatsFilterTags.back() = tag;
  814. }
  815. }
  816. } else {
  817. chatsFilterTags.push_back(tag);
  818. }
  819. }
  820. }
  821. context.chatsFilterTags = &chatsFilterTags;
  822. } else {
  823. context.chatsFilterTags = nullptr;
  824. }
  825. context.topicsExpanded = (expanding && !active)
  826. ? childListShown.shown
  827. : 0.;
  828. context.active = active;
  829. context.selected = _menuRow.key
  830. ? (row->key() == _menuRow.key)
  831. : _chatPreviewRow.key
  832. ? (row->key() == _chatPreviewRow.key)
  833. : selected;
  834. context.topicJumpSelected = selected
  835. && _selectedTopicJump
  836. && (!_pressed || _pressedTopicJump);
  837. Ui::RowPainter::Paint(p, row, validateVideoUserpic(row), context);
  838. };
  839. if (_state == WidgetState::Default) {
  840. const auto collapsedSkip = collapsedRowsOffset();
  841. p.translate(0, collapsedSkip);
  842. paintCollapsedRows(p, r.translated(0, -collapsedSkip));
  843. const auto &list = _shownList->all();
  844. const auto shownBottom = _shownList->height() - skipTopHeight();
  845. const auto selected = isPressed()
  846. ? (_pressed ? _pressed->key() : Key())
  847. : (_selected ? _selected->key() : Key());
  848. if (shownBottom) {
  849. const auto skip = dialogsOffset();
  850. const auto promoted = fixedOnTopCount();
  851. const auto reorderingPinned = (_aboveIndex >= 0)
  852. && !_pinnedRows.empty();
  853. const auto reorderingIndex = reorderingPinned
  854. ? (promoted + _aboveIndex)
  855. : -1;
  856. const auto reorderingRow = (reorderingIndex >= 0
  857. && reorderingIndex < list.size())
  858. ? (list.cbegin() + reorderingIndex)->get()
  859. : nullptr;
  860. if (reorderingRow) {
  861. dialogsClip = dialogsClip.marginsAdded({
  862. 0,
  863. reorderingRow->height(),
  864. 0,
  865. reorderingRow->height(),
  866. });
  867. }
  868. const auto skippedTop = skipTopHeight();
  869. const auto paintDialog = [&](not_null<Row*> row) {
  870. const auto pinned = row->index() - promoted;
  871. const auto count = _pinnedRows.size();
  872. const auto xadd = 0;
  873. const auto yadd = base::in_range(pinned, 0, count)
  874. ? qRound(_pinnedRows[pinned].yadd.current())
  875. : 0;
  876. if (xadd || yadd) {
  877. p.translate(xadd, yadd);
  878. }
  879. paintRow(row, (row->key() == selected), true);
  880. if (xadd || yadd) {
  881. p.translate(-xadd, -yadd);
  882. }
  883. };
  884. auto i = list.findByY(dialogsClip.top() - skip);
  885. if (_skipTopDialog && i != list.cend() && !(*i)->index()) {
  886. ++i;
  887. }
  888. if (i != list.cend()) {
  889. auto top = (*i)->top();
  890. // If we're reordering pinned chats we need to fill this area background first.
  891. if (reorderingPinned) {
  892. const auto pinnedBottom = shownHeight(promoted + _pinnedRows.size());
  893. const auto pinnedTop = shownHeight(promoted);
  894. p.fillRect(0, pinnedTop - skippedTop, fullWidth, pinnedBottom - pinnedTop, currentBg());
  895. }
  896. p.translate(0, top - skippedTop);
  897. for (auto e = list.cend(); i != e; ++i) {
  898. auto row = (*i);
  899. if (top >= dialogsClip.top() - skip + dialogsClip.height()) {
  900. break;
  901. }
  902. // Skip currently dragged chat to paint it above others after.
  903. if (row->index() != promoted + _aboveIndex || _aboveIndex < 0) {
  904. paintDialog(row);
  905. }
  906. p.translate(0, row->height());
  907. top += row->height();
  908. }
  909. // Paint the dragged chat above all others.
  910. if (reorderingRow) {
  911. p.translate(0, reorderingRow->top() - top);
  912. paintDialog(reorderingRow);
  913. p.translate(0, top - reorderingRow->top());
  914. }
  915. }
  916. } else {
  917. p.fillRect(dialogsClip, currentBg());
  918. }
  919. } else if (_state == WidgetState::Filtered) {
  920. if (_searchTags) {
  921. paintSearchTags(p, {
  922. .st = &st::forumTopicRow,
  923. .currentBg = currentBg(),
  924. .now = ms,
  925. .width = fullWidth,
  926. .paused = videoPaused,
  927. });
  928. p.translate(0, _searchTags->height());
  929. }
  930. if (_searchIn) {
  931. p.translate(0, searchInChatSkip());
  932. if (_previewResults.empty() && _searchResults.empty()) {
  933. p.fillRect(0, 0, fullWidth, st::lineWidth, st::shadowFg);
  934. }
  935. }
  936. if (!_hashtagResults.empty()) {
  937. const auto skip = hashtagsOffset();
  938. auto from = floorclamp(r.y() - skip, st::mentionHeight, 0, _hashtagResults.size());
  939. auto to = ceilclamp(r.y() + r.height() - skip, st::mentionHeight, 0, _hashtagResults.size());
  940. p.translate(0, from * st::mentionHeight);
  941. if (from < _hashtagResults.size()) {
  942. const auto htagleft = st::defaultDialogRow.padding.left();
  943. auto htagwidth = fullWidth
  944. - htagleft
  945. - st::defaultDialogRow.padding.right();
  946. p.setFont(st::mentionFont);
  947. for (; from < to; ++from) {
  948. auto &result = _hashtagResults[from];
  949. bool selected = (from == (isPressed() ? _hashtagPressed : _hashtagSelected));
  950. p.fillRect(0, 0, fullWidth, st::mentionHeight, selected ? st::mentionBgOver : currentBg());
  951. result->row.paintRipple(p, 0, 0, fullWidth);
  952. auto &tag = result->tag;
  953. if (selected) {
  954. int skip = (st::mentionHeight - st::smallCloseIconOver.height()) / 2;
  955. st::smallCloseIconOver.paint(p, QPoint(fullWidth - st::smallCloseIconOver.width() - skip, skip), width());
  956. }
  957. auto first = (_hashtagFilter.size() < 2) ? QString() : ('#' + tag.mid(0, _hashtagFilter.size() - 1));
  958. auto second = (_hashtagFilter.size() < 2) ? ('#' + tag) : tag.mid(_hashtagFilter.size() - 1);
  959. auto firstwidth = st::mentionFont->width(first);
  960. auto secondwidth = st::mentionFont->width(second);
  961. if (htagwidth < firstwidth + secondwidth) {
  962. if (htagwidth < firstwidth + st::mentionFont->elidew) {
  963. first = st::mentionFont->elided(first + second, htagwidth);
  964. second = QString();
  965. } else {
  966. second = st::mentionFont->elided(second, htagwidth - firstwidth);
  967. }
  968. }
  969. p.setFont(st::mentionFont);
  970. if (!first.isEmpty()) {
  971. p.setPen(selected ? st::mentionFgOverActive : st::mentionFgActive);
  972. p.drawText(htagleft, st::mentionTop + st::mentionFont->ascent, first);
  973. }
  974. if (!second.isEmpty()) {
  975. p.setPen(selected ? st::mentionFgOver : st::mentionFg);
  976. p.drawText(htagleft + firstwidth, st::mentionTop + st::mentionFont->ascent, second);
  977. }
  978. p.translate(0, st::mentionHeight);
  979. }
  980. if (to < _hashtagResults.size()) {
  981. p.translate(0, (_hashtagResults.size() - to) * st::mentionHeight);
  982. }
  983. }
  984. }
  985. if (!_filterResults.empty()) {
  986. auto skip = filteredOffset();
  987. auto from = filteredIndex(r.y() - skip);
  988. auto to = std::min(
  989. filteredIndex(r.y() + r.height() - skip) + 1,
  990. int(_filterResults.size()));
  991. const auto height = filteredHeight(from);
  992. p.translate(0, height);
  993. for (; from < to; ++from) {
  994. const auto selected = isPressed()
  995. ? (from == _filteredPressed)
  996. : (from == _filteredSelected);
  997. const auto row = _filterResults[from].row;
  998. paintRow(row, selected, !activeEntry.fullId);
  999. p.translate(0, row->height());
  1000. }
  1001. }
  1002. if (!_peerSearchResults.empty()) {
  1003. p.fillRect(0, 0, fullWidth, st::searchedBarHeight, st::searchedBarBg);
  1004. p.setFont(st::searchedBarFont);
  1005. p.setPen(st::searchedBarFg);
  1006. p.drawTextLeft(st::searchedBarPosition.x(), st::searchedBarPosition.y(), width(), tr::lng_search_global_results(tr::now));
  1007. p.translate(0, st::searchedBarHeight);
  1008. auto skip = peerSearchOffset();
  1009. auto from = floorclamp(r.y() - skip, st::dialogsRowHeight, 0, _peerSearchResults.size());
  1010. auto to = ceilclamp(r.y() + r.height() - skip, st::dialogsRowHeight, 0, _peerSearchResults.size());
  1011. p.translate(0, from * st::dialogsRowHeight);
  1012. if (from < _peerSearchResults.size()) {
  1013. const auto activePeer = activeEntry.key.peer();
  1014. for (; from < to; ++from) {
  1015. const auto &result = _peerSearchResults[from];
  1016. const auto peer = result->peer;
  1017. const auto active = !activeEntry.fullId
  1018. && activePeer
  1019. && ((peer == activePeer)
  1020. || (peer->migrateTo() == activePeer));
  1021. const auto selected = (from == (isPressed()
  1022. ? _peerSearchPressed
  1023. : _peerSearchSelected));
  1024. paintPeerSearchResult(p, result.get(), {
  1025. .st = &st::defaultDialogRow,
  1026. .currentBg = currentBg(),
  1027. .now = ms,
  1028. .width = fullWidth,
  1029. .active = active,
  1030. .selected = selected,
  1031. .paused = videoPaused,
  1032. });
  1033. p.translate(0, st::dialogsRowHeight);
  1034. }
  1035. if (to < _peerSearchResults.size()) {
  1036. p.translate(0, (_peerSearchResults.size() - to) * st::dialogsRowHeight);
  1037. }
  1038. }
  1039. }
  1040. const auto showUnreadInSearchResults = uniqueSearchResults();
  1041. if (_previewResults.empty() && _searchResults.empty()) {
  1042. if (_loadingAnimation) {
  1043. const auto text = tr::lng_contacts_loading(tr::now);
  1044. p.fillRect(0, 0, fullWidth, st::searchedBarHeight, st::searchedBarBg);
  1045. p.setFont(st::searchedBarFont);
  1046. p.setPen(st::searchedBarFg);
  1047. p.drawTextLeft(st::searchedBarPosition.x(), st::searchedBarPosition.y(), width(), text);
  1048. p.translate(0, st::searchedBarHeight);
  1049. }
  1050. return;
  1051. }
  1052. if (!_previewResults.empty()) {
  1053. const auto text = tr::lng_search_tab_public_posts(tr::now);
  1054. p.fillRect(0, 0, fullWidth, st::searchedBarHeight, st::searchedBarBg);
  1055. p.setFont(st::searchedBarFont);
  1056. p.setPen(st::searchedBarFg);
  1057. p.drawTextLeft(st::searchedBarPosition.x(), st::searchedBarPosition.y(), width(), text);
  1058. const auto moreFont = (_selectedMorePosts || _pressedMorePosts)
  1059. ? st::searchedBarFont->underline()
  1060. : st::searchedBarFont;
  1061. {
  1062. const auto text = tr::lng_channels_your_more(tr::now);
  1063. if (!_morePostsWidth) {
  1064. _morePostsWidth = moreFont->width(text);
  1065. }
  1066. p.setFont(moreFont);
  1067. p.drawTextLeft(
  1068. width() - st::searchedBarPosition.x() - _morePostsWidth,
  1069. st::searchedBarPosition.y(),
  1070. width(),
  1071. text);
  1072. p.translate(0, st::searchedBarHeight);
  1073. }
  1074. auto skip = previewOffset();
  1075. auto from = floorclamp(r.y() - skip, _st->height, 0, _previewResults.size());
  1076. auto to = ceilclamp(r.y() + r.height() - skip, _st->height, 0, _previewResults.size());
  1077. p.translate(0, from * _st->height);
  1078. if (from < _previewResults.size()) {
  1079. for (; from < to; ++from) {
  1080. const auto &result = _previewResults[from];
  1081. const auto active = isSearchResultActive(result.get(), activeEntry);
  1082. const auto selected = _menuRow.key
  1083. ? isSearchResultActive(result.get(), _menuRow)
  1084. : _chatPreviewRow.key
  1085. ? isSearchResultActive(result.get(), _chatPreviewRow)
  1086. : (from == (isPressed()
  1087. ? _previewPressed
  1088. : _previewSelected));
  1089. Ui::RowPainter::Paint(p, result.get(), {
  1090. .st = _st,
  1091. .folder = _openedFolder,
  1092. .forum = _openedForum,
  1093. .currentBg = currentBg(),
  1094. .filter = _filterId,
  1095. .now = ms,
  1096. .width = fullWidth,
  1097. .active = active,
  1098. .selected = selected,
  1099. .paused = videoPaused,
  1100. .search = true,
  1101. .narrow = (fullWidth < st::columnMinimalWidthLeft / 2),
  1102. .displayUnreadInfo = showUnreadInSearchResults,
  1103. });
  1104. p.translate(0, _st->height);
  1105. }
  1106. }
  1107. if (to < _previewResults.size()) {
  1108. p.translate(0, (_previewResults.size() - to) * _st->height);
  1109. }
  1110. }
  1111. if (!_searchResults.empty()) {
  1112. const auto text = showUnreadInSearchResults
  1113. ? u"Search results"_q
  1114. : tr::lng_search_found_results(
  1115. tr::now,
  1116. lt_count,
  1117. _searchedMigratedCount + _searchedCount);
  1118. p.fillRect(0, 0, fullWidth, st::searchedBarHeight, st::searchedBarBg);
  1119. p.setFont(st::searchedBarFont);
  1120. p.setPen(st::searchedBarFg);
  1121. p.drawTextLeft(st::searchedBarPosition.x(), st::searchedBarPosition.y(), width(), text);
  1122. const auto filterOver = _selectedChatTypeFilter
  1123. || _pressedChatTypeFilter;
  1124. const auto filterFont = filterOver
  1125. ? st::searchedBarFont->underline()
  1126. : st::searchedBarFont;
  1127. if (hasChatTypeFilter()) {
  1128. const auto text = ChatTypeFilterLabel(_searchState.filter);
  1129. if (!_chatTypeFilterWidth) {
  1130. _chatTypeFilterWidth = filterFont->width(text);
  1131. }
  1132. p.setFont(filterFont);
  1133. p.drawTextLeft(
  1134. (width()
  1135. - st::searchedBarPosition.x()
  1136. - _chatTypeFilterWidth),
  1137. st::searchedBarPosition.y(),
  1138. width(),
  1139. text);
  1140. }
  1141. p.translate(0, st::searchedBarHeight);
  1142. auto skip = searchedOffset();
  1143. auto from = floorclamp(r.y() - skip, _st->height, 0, _searchResults.size());
  1144. auto to = ceilclamp(r.y() + r.height() - skip, _st->height, 0, _searchResults.size());
  1145. p.translate(0, from * _st->height);
  1146. if (from < _searchResults.size()) {
  1147. for (; from < to; ++from) {
  1148. const auto &result = _searchResults[from];
  1149. const auto active = isSearchResultActive(result.get(), activeEntry);
  1150. const auto selected = _menuRow.key
  1151. ? isSearchResultActive(result.get(), _menuRow)
  1152. : _chatPreviewRow.key
  1153. ? isSearchResultActive(result.get(), _chatPreviewRow)
  1154. : (from == (isPressed()
  1155. ? _searchedPressed
  1156. : _searchedSelected));
  1157. Ui::RowPainter::Paint(p, result.get(), {
  1158. .st = _st,
  1159. .folder = _openedFolder,
  1160. .forum = _openedForum,
  1161. .currentBg = currentBg(),
  1162. .filter = _filterId,
  1163. .now = ms,
  1164. .width = fullWidth,
  1165. .active = active,
  1166. .selected = selected,
  1167. .paused = videoPaused,
  1168. .search = true,
  1169. .narrow = (fullWidth < st::columnMinimalWidthLeft / 2),
  1170. .displayUnreadInfo = showUnreadInSearchResults,
  1171. });
  1172. p.translate(0, _st->height);
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. [[nodiscard]] RightButton *InnerWidget::maybeCacheRightButton(Row *row) {
  1179. if (const auto user = MaybeBotWithApp(row)) {
  1180. const auto it = _rightButtons.find(user->id);
  1181. if (it == _rightButtons.end()) {
  1182. auto rightButton = RightButton();
  1183. const auto text = tr::lng_profile_open_app_short(tr::now);
  1184. rightButton.text.setText(st::dialogRowOpenBotTextStyle, text);
  1185. const auto size = QSize(
  1186. rightButton.text.maxWidth()
  1187. + rightButton.text.minHeight(),
  1188. st::dialogRowOpenBotHeight);
  1189. const auto generateBg = [&](const style::color &c) {
  1190. auto bg = QImage(
  1191. style::DevicePixelRatio() * size,
  1192. QImage::Format_ARGB32_Premultiplied);
  1193. bg.setDevicePixelRatio(style::DevicePixelRatio());
  1194. bg.fill(Qt::transparent);
  1195. {
  1196. auto p = QPainter(&bg);
  1197. auto hq = PainterHighQualityEnabler(p);
  1198. p.setPen(Qt::NoPen);
  1199. p.setBrush(c);
  1200. const auto r = size.height() / 2;
  1201. p.drawRoundedRect(Rect(size), r, r);
  1202. }
  1203. return bg;
  1204. };
  1205. rightButton.bg = generateBg(st::activeButtonBg);
  1206. rightButton.selectedBg = generateBg(st::activeButtonBgOver);
  1207. rightButton.activeBg = generateBg(st::activeButtonFg);
  1208. return &(_rightButtons.emplace(
  1209. user->id,
  1210. std::move(rightButton)).first->second);
  1211. } else {
  1212. return &(it->second);
  1213. }
  1214. }
  1215. return nullptr;
  1216. }
  1217. Ui::VideoUserpic *InnerWidget::validateVideoUserpic(not_null<Row*> row) {
  1218. const auto history = row->history();
  1219. return history ? validateVideoUserpic(history) : nullptr;
  1220. }
  1221. Ui::VideoUserpic *InnerWidget::validateVideoUserpic(
  1222. not_null<History*> history) {
  1223. const auto peer = history->peer;
  1224. if (!peer->isPremium()
  1225. || peer->userpicPhotoUnknown()
  1226. || !peer->userpicHasVideo()) {
  1227. _videoUserpics.remove(peer);
  1228. return nullptr;
  1229. }
  1230. const auto i = _videoUserpics.find(peer);
  1231. if (i != end(_videoUserpics)) {
  1232. return i->second.get();
  1233. }
  1234. const auto repaint = [=] {
  1235. updateDialogRow({ history, FullMsgId() });
  1236. updateSearchResult(history->peer);
  1237. };
  1238. return _videoUserpics.emplace(peer, std::make_unique<Ui::VideoUserpic>(
  1239. peer,
  1240. repaint
  1241. )).first->second.get();
  1242. }
  1243. void InnerWidget::paintCollapsedRows(Painter &p, QRect clip) const {
  1244. auto index = 0;
  1245. const auto rowHeight = st::dialogsImportantBarHeight;
  1246. for (const auto &row : _collapsedRows) {
  1247. const auto increment = gsl::finally([&] {
  1248. p.translate(0, rowHeight);
  1249. ++index;
  1250. });
  1251. const auto y = index * rowHeight;
  1252. if (!clip.intersects(QRect(0, y, width(), rowHeight))) {
  1253. continue;
  1254. }
  1255. const auto selected = (index == _collapsedSelected)
  1256. || (index == _collapsedPressed);
  1257. paintCollapsedRow(p, row.get(), selected);
  1258. }
  1259. }
  1260. void InnerWidget::paintCollapsedRow(
  1261. Painter &p,
  1262. not_null<const CollapsedRow*> row,
  1263. bool selected) const {
  1264. Expects(row->folder != nullptr);
  1265. const auto text = row->folder->chatListName();
  1266. const auto unread = row->folder->chatListBadgesState().unreadCounter;
  1267. const auto fullWidth = width();
  1268. Ui::PaintCollapsedRow(p, row->row, row->folder, text, unread, {
  1269. .st = _st,
  1270. .currentBg = currentBg(),
  1271. .width = fullWidth,
  1272. .selected = selected,
  1273. .narrow = (fullWidth < st::columnMinimalWidthLeft / 2),
  1274. });
  1275. }
  1276. bool InnerWidget::isRowActive(
  1277. not_null<Row*> row,
  1278. const RowDescriptor &entry) const {
  1279. const auto key = row->key();
  1280. return (entry.key == key)
  1281. || (entry.key.sublist() && key.peer() && key.peer()->isSelf());
  1282. }
  1283. bool InnerWidget::isSearchResultActive(
  1284. not_null<FakeRow*> result,
  1285. const RowDescriptor &entry) const {
  1286. const auto item = result->item();
  1287. const auto peer = item->history()->peer;
  1288. return (item->fullId() == entry.fullId)
  1289. || (peer->migrateTo()
  1290. && (peer->migrateTo()->id == entry.fullId.peer)
  1291. && (item->id == -entry.fullId.msg))
  1292. || (uniqueSearchResults() && peer == entry.key.peer());
  1293. }
  1294. void InnerWidget::paintPeerSearchResult(
  1295. Painter &p,
  1296. not_null<const PeerSearchResult*> result,
  1297. const Ui::PaintContext &context) {
  1298. QRect fullRect(0, 0, context.width, st::dialogsRowHeight);
  1299. p.fillRect(
  1300. fullRect,
  1301. (context.active
  1302. ? st::dialogsBgActive
  1303. : context.selected
  1304. ? st::dialogsBgOver
  1305. : currentBg()));
  1306. if (!context.active) {
  1307. result->row.paintRipple(p, 0, 0, context.width);
  1308. }
  1309. auto peer = result->peer;
  1310. auto userpicPeer = (peer->migrateTo() ? peer->migrateTo() : peer);
  1311. userpicPeer->paintUserpicLeft(
  1312. p,
  1313. result->row.userpicView(),
  1314. context.st->padding.left(),
  1315. context.st->padding.top(),
  1316. width(),
  1317. context.st->photoSize);
  1318. auto nameleft = context.st->nameLeft;
  1319. auto namewidth = context.width - nameleft - context.st->padding.right();
  1320. QRect rectForName(nameleft, context.st->nameTop, namewidth, st::semiboldFont->height);
  1321. if (result->name.isEmpty()) {
  1322. result->name.setText(
  1323. st::semiboldTextStyle,
  1324. peer->name(),
  1325. Ui::NameTextOptions());
  1326. }
  1327. if (const auto info = peer->botVerifyDetails()) {
  1328. if (!result->badge.ready(info)) {
  1329. result->badge.set(
  1330. info,
  1331. peer->owner().customEmojiManager().factory(),
  1332. [=] { updateSearchResult(peer); });
  1333. }
  1334. const auto &st = Ui::VerifiedStyle(context);
  1335. const auto position = rectForName.topLeft();
  1336. const auto skip = result->badge.drawVerified(p, position, st);
  1337. rectForName.setLeft(position.x() + skip + st::dialogsChatTypeSkip);
  1338. } else if (const auto chatTypeIcon = Ui::ChatTypeIcon(peer, context)) {
  1339. chatTypeIcon->paint(p, rectForName.topLeft(), context.width);
  1340. rectForName.setLeft(rectForName.left()
  1341. + chatTypeIcon->width()
  1342. + st::dialogsChatTypeSkip);
  1343. }
  1344. const auto badgeWidth = result->badge.drawGetWidth(p, {
  1345. .peer = peer,
  1346. .rectForName = rectForName,
  1347. .nameWidth = result->name.maxWidth(),
  1348. .outerWidth = context.width,
  1349. .verified = (context.active
  1350. ? &st::dialogsVerifiedIconActive
  1351. : context.selected
  1352. ? &st::dialogsVerifiedIconOver
  1353. : &st::dialogsVerifiedIcon),
  1354. .premium = &ThreeStateIcon(
  1355. st::dialogsPremiumIcon,
  1356. context.active,
  1357. context.selected),
  1358. .scam = (context.active
  1359. ? &st::dialogsScamFgActive
  1360. : context.selected
  1361. ? &st::dialogsScamFgOver
  1362. : &st::dialogsScamFg),
  1363. .premiumFg = (context.active
  1364. ? &st::dialogsVerifiedIconBgActive
  1365. : context.selected
  1366. ? &st::dialogsVerifiedIconBgOver
  1367. : &st::dialogsVerifiedIconBg),
  1368. .customEmojiRepaint = [=] { updateSearchResult(peer); },
  1369. .now = context.now,
  1370. .prioritizeVerification = true,
  1371. .paused = context.paused,
  1372. });
  1373. rectForName.setWidth(rectForName.width() - badgeWidth);
  1374. QRect tr(context.st->textLeft, context.st->textTop, namewidth, st::dialogsTextFont->height);
  1375. p.setFont(st::dialogsTextFont);
  1376. QString username = peer->username();
  1377. if (!context.active && username.startsWith(_peerSearchQuery, Qt::CaseInsensitive)) {
  1378. auto first = '@' + username.mid(0, _peerSearchQuery.size());
  1379. auto second = username.mid(_peerSearchQuery.size());
  1380. auto w = st::dialogsTextFont->width(first);
  1381. if (w >= tr.width()) {
  1382. p.setPen(st::dialogsTextFgService);
  1383. p.drawText(tr.left(), tr.top() + st::dialogsTextFont->ascent, st::dialogsTextFont->elided(first, tr.width()));
  1384. } else {
  1385. p.setPen(st::dialogsTextFgService);
  1386. p.drawText(tr.left(), tr.top() + st::dialogsTextFont->ascent, first);
  1387. p.setPen(st::dialogsTextFg);
  1388. p.drawText(tr.left() + w, tr.top() + st::dialogsTextFont->ascent, st::dialogsTextFont->elided(second, tr.width() - w));
  1389. }
  1390. } else {
  1391. p.setPen(context.active ? st::dialogsTextFgActive : st::dialogsTextFgService);
  1392. p.drawText(tr.left(), tr.top() + st::dialogsTextFont->ascent, st::dialogsTextFont->elided('@' + username, tr.width()));
  1393. }
  1394. p.setPen(context.active ? st::dialogsTextFgActive : st::dialogsNameFg);
  1395. result->name.drawElided(p, rectForName.left(), rectForName.top(), rectForName.width());
  1396. }
  1397. QBrush InnerWidget::currentBg() const {
  1398. return anim::brush(
  1399. st::dialogsBg,
  1400. st::dialogsBgOver,
  1401. _childListShown.current().shown);
  1402. }
  1403. void InnerWidget::paintSearchTags(
  1404. Painter &p,
  1405. const Ui::PaintContext &context) const {
  1406. Expects(_searchTags != nullptr);
  1407. const auto height = _searchTags->height();
  1408. p.fillRect(0, 0, width(), height, currentBg());
  1409. const auto top = st::dialogsSearchTagBottom / 2;
  1410. const auto position = QPoint(_searchTagsLeft, top);
  1411. _searchTags->paint(p, position, context.now, context.paused);
  1412. }
  1413. void InnerWidget::showPeerMenu() {
  1414. if (!_selected) {
  1415. return;
  1416. }
  1417. const auto &padding = st::defaultDialogRow.padding;
  1418. const auto pos = QPoint(
  1419. width() - padding.right(),
  1420. _selected->top() + _selected->height() + padding.bottom());
  1421. auto event = QContextMenuEvent(
  1422. QContextMenuEvent::Keyboard,
  1423. pos,
  1424. mapToGlobal(pos));
  1425. InnerWidget::contextMenuEvent(&event);
  1426. }
  1427. void InnerWidget::mouseMoveEvent(QMouseEvent *e) {
  1428. if (_chatPreviewTouchGlobal || _touchDragStartGlobal) {
  1429. return;
  1430. }
  1431. const auto globalPosition = e->globalPos();
  1432. if (!_lastMousePosition) {
  1433. _lastMousePosition = globalPosition;
  1434. return;
  1435. } else if (!_mouseSelection
  1436. && *_lastMousePosition == globalPosition) {
  1437. return;
  1438. }
  1439. selectByMouse(globalPosition);
  1440. if (_chatPreviewScheduled && !isUserpicPress()) {
  1441. cancelChatPreview();
  1442. }
  1443. }
  1444. void InnerWidget::cancelChatPreview() {
  1445. _chatPreviewTouchGlobal = {};
  1446. _chatPreviewScheduled = false;
  1447. if (_chatPreviewRow.key) {
  1448. updateDialogRow(base::take(_chatPreviewRow));
  1449. }
  1450. _controller->cancelScheduledPreview();
  1451. }
  1452. void InnerWidget::clearIrrelevantState() {
  1453. if (_state == WidgetState::Default) {
  1454. _hashtagSelected = -1;
  1455. setHashtagPressed(-1);
  1456. _hashtagDeleteSelected = _hashtagDeletePressed = false;
  1457. _filteredSelected = -1;
  1458. setFilteredPressed(-1, false, false);
  1459. _peerSearchSelected = -1;
  1460. setPeerSearchPressed(-1);
  1461. _previewSelected = -1;
  1462. setPreviewPressed(-1);
  1463. _searchedSelected = -1;
  1464. setSearchedPressed(-1);
  1465. } else if (_state == WidgetState::Filtered) {
  1466. _collapsedSelected = -1;
  1467. setCollapsedPressed(-1);
  1468. _selected = nullptr;
  1469. clearPressed();
  1470. }
  1471. }
  1472. bool InnerWidget::lookupIsInBotAppButton(
  1473. Row *row,
  1474. QPoint localPosition) {
  1475. if (const auto user = MaybeBotWithApp(row)) {
  1476. const auto it = _rightButtons.find(user->id);
  1477. if (it != _rightButtons.end()) {
  1478. const auto s = it->second.bg.size() / style::DevicePixelRatio();
  1479. const auto r = QRect(
  1480. width() - s.width() - st::dialogRowOpenBotRight,
  1481. st::dialogRowOpenBotTop,
  1482. s.width(),
  1483. s.height());
  1484. if (r.contains(localPosition)) {
  1485. return true;
  1486. }
  1487. }
  1488. }
  1489. return false;
  1490. }
  1491. void InnerWidget::selectByMouse(QPoint globalPosition) {
  1492. const auto local = mapFromGlobal(globalPosition);
  1493. if (updateReorderPinned(local)) {
  1494. return;
  1495. }
  1496. _mouseSelection = true;
  1497. _lastMousePosition = globalPosition;
  1498. _lastRowLocalMouseX = local.x();
  1499. const auto tagBase = QPoint(
  1500. _searchTagsLeft,
  1501. st::dialogsSearchTagBottom / 2);
  1502. const auto tagPoint = local - tagBase;
  1503. const auto inTags = _searchTags
  1504. && QRect(
  1505. tagBase,
  1506. QSize(width() - 2 * _searchTagsLeft, _searchTags->height())
  1507. ).contains(local);
  1508. const auto tagLink = inTags
  1509. ? _searchTags->lookupHandler(tagPoint)
  1510. : nullptr;
  1511. ClickHandler::setActive(tagLink);
  1512. if (inTags) {
  1513. setCursor(tagLink ? style::cur_pointer : style::cur_default);
  1514. }
  1515. const auto w = width();
  1516. const auto mouseY = local.y();
  1517. clearIrrelevantState();
  1518. if (_state == WidgetState::Default) {
  1519. const auto offset = dialogsOffset();
  1520. const auto collapsedSelected = (mouseY >= 0
  1521. && mouseY < _collapsedRows.size() * st::dialogsImportantBarHeight)
  1522. ? (mouseY / st::dialogsImportantBarHeight)
  1523. : -1;
  1524. const auto selected = (collapsedSelected >= 0)
  1525. ? nullptr
  1526. : (mouseY >= offset)
  1527. ? _shownList->rowAtY(mouseY - offset)
  1528. : nullptr;
  1529. const auto mappedY = selected ? mouseY - offset - selected->top() : 0;
  1530. const auto selectedTopicJump = selected
  1531. && selected->lookupIsInTopicJump(local.x(), mappedY);
  1532. const auto selectedBotApp = selected
  1533. && lookupIsInBotAppButton(selected, QPoint(local.x(), mappedY));
  1534. if (_collapsedSelected != collapsedSelected
  1535. || _selected != selected
  1536. || _selectedTopicJump != selectedTopicJump
  1537. || _selectedBotApp != selectedBotApp) {
  1538. updateSelectedRow();
  1539. _selected = selected;
  1540. _selectedTopicJump = selectedTopicJump;
  1541. _selectedBotApp = selectedBotApp;
  1542. _collapsedSelected = collapsedSelected;
  1543. updateSelectedRow();
  1544. setCursor((_selected || _collapsedSelected >= 0)
  1545. ? style::cur_pointer
  1546. : style::cur_default);
  1547. }
  1548. } else if (_state == WidgetState::Filtered) {
  1549. auto wasSelected = isSelected();
  1550. if (_hashtagResults.empty()) {
  1551. _hashtagSelected = -1;
  1552. _hashtagDeleteSelected = false;
  1553. } else {
  1554. auto skip = hashtagsOffset();
  1555. auto hashtagSelected = (mouseY >= skip) ? ((mouseY - skip) / st::mentionHeight) : -1;
  1556. if (hashtagSelected < 0 || hashtagSelected >= _hashtagResults.size()) {
  1557. hashtagSelected = -1;
  1558. }
  1559. if (_hashtagSelected != hashtagSelected) {
  1560. updateSelectedRow();
  1561. _hashtagSelected = hashtagSelected;
  1562. updateSelectedRow();
  1563. }
  1564. _hashtagDeleteSelected = (_hashtagSelected >= 0) && (local.x() >= w - st::mentionHeight);
  1565. }
  1566. if (!_filterResults.empty()) {
  1567. auto skip = filteredOffset();
  1568. auto filteredSelected = (mouseY >= skip)
  1569. ? filteredIndex(mouseY - skip)
  1570. : -1;
  1571. if (filteredSelected < 0 || filteredSelected >= _filterResults.size()) {
  1572. filteredSelected = -1;
  1573. }
  1574. const auto mappedY = (filteredSelected >= 0)
  1575. ? mouseY - skip - _filterResults[filteredSelected].top
  1576. : 0;
  1577. const auto selectedTopicJump = (filteredSelected >= 0)
  1578. && _filterResults[filteredSelected].row->lookupIsInTopicJump(
  1579. local.x(),
  1580. mappedY);
  1581. const auto selectedBotApp = (filteredSelected >= 0)
  1582. && lookupIsInBotAppButton(
  1583. _filterResults[filteredSelected].row,
  1584. QPoint(local.x(), mappedY));
  1585. if (_filteredSelected != filteredSelected
  1586. || _selectedTopicJump != selectedTopicJump
  1587. || _selectedBotApp != selectedBotApp) {
  1588. updateSelectedRow();
  1589. _filteredSelected = filteredSelected;
  1590. _selectedTopicJump = selectedTopicJump;
  1591. _selectedBotApp = selectedBotApp;
  1592. updateSelectedRow();
  1593. }
  1594. }
  1595. if (!_peerSearchResults.empty()) {
  1596. auto skip = peerSearchOffset();
  1597. auto peerSearchSelected = (mouseY >= skip) ? ((mouseY - skip) / st::dialogsRowHeight) : -1;
  1598. if (peerSearchSelected < 0 || peerSearchSelected >= _peerSearchResults.size()) {
  1599. peerSearchSelected = -1;
  1600. }
  1601. if (_peerSearchSelected != peerSearchSelected) {
  1602. updateSelectedRow();
  1603. _peerSearchSelected = peerSearchSelected;
  1604. updateSelectedRow();
  1605. }
  1606. }
  1607. if (!_previewResults.empty()) {
  1608. auto skip = previewOffset();
  1609. auto previewSelected = (mouseY >= skip) ? ((mouseY - skip) / _st->height) : -1;
  1610. if (previewSelected < 0 || previewSelected >= _previewResults.size()) {
  1611. previewSelected = -1;
  1612. }
  1613. if (_previewSelected != previewSelected) {
  1614. updateSelectedRow();
  1615. _previewSelected = previewSelected;
  1616. updateSelectedRow();
  1617. }
  1618. auto selectedMorePosts = false;
  1619. const auto from = skip - st::searchedBarHeight;
  1620. if (mouseY <= skip && mouseY >= from) {
  1621. const auto left = width()
  1622. - _morePostsWidth
  1623. - 2 * st::searchedBarPosition.x();
  1624. if (_morePostsWidth > 0 && local.x() >= left) {
  1625. selectedMorePosts = true;
  1626. }
  1627. }
  1628. if (_selectedMorePosts != selectedMorePosts) {
  1629. update(0, from, width(), st::searchedBarHeight);
  1630. _selectedMorePosts = selectedMorePosts;
  1631. }
  1632. }
  1633. if (!_searchResults.empty()) {
  1634. auto skip = searchedOffset();
  1635. auto searchedSelected = (mouseY >= skip) ? ((mouseY - skip) / _st->height) : -1;
  1636. if (searchedSelected < 0 || searchedSelected >= _searchResults.size()) {
  1637. searchedSelected = -1;
  1638. }
  1639. if (_searchedSelected != searchedSelected) {
  1640. updateSelectedRow();
  1641. _searchedSelected = searchedSelected;
  1642. updateSelectedRow();
  1643. }
  1644. auto selectedChatTypeFilter = false;
  1645. const auto from = skip - st::searchedBarHeight;
  1646. if (hasChatTypeFilter() && mouseY <= skip && mouseY >= from) {
  1647. const auto left = width()
  1648. - _chatTypeFilterWidth
  1649. - 2 * st::searchedBarPosition.x();
  1650. if (_chatTypeFilterWidth > 0 && local.x() >= left) {
  1651. selectedChatTypeFilter = true;
  1652. }
  1653. }
  1654. if (_selectedChatTypeFilter != selectedChatTypeFilter) {
  1655. update(0, from, width(), st::searchedBarHeight);
  1656. _selectedChatTypeFilter = selectedChatTypeFilter;
  1657. }
  1658. }
  1659. if (!inTags && wasSelected != isSelected()) {
  1660. setCursor(wasSelected ? style::cur_default : style::cur_pointer);
  1661. }
  1662. }
  1663. }
  1664. RowDescriptor InnerWidget::computeChatPreviewRow() const {
  1665. auto result = computeChosenRow();
  1666. if (const auto peer = result.key.peer()) {
  1667. const auto topicId = _pressedTopicJump
  1668. ? _pressedTopicJumpRootId
  1669. : 0;
  1670. if (const auto topic = peer->forumTopicFor(topicId)) {
  1671. return { topic, FullMsgId() };
  1672. }
  1673. }
  1674. return { result.key, result.message.fullId };
  1675. }
  1676. void InnerWidget::processGlobalForceClick(QPoint globalPosition) {
  1677. const auto parent = parentWidget();
  1678. if (_pressButton == Qt::LeftButton
  1679. && parent->rect().contains(parent->mapFromGlobal(globalPosition))) {
  1680. showChatPreview();
  1681. }
  1682. }
  1683. void InnerWidget::mousePressEvent(QMouseEvent *e) {
  1684. selectByMouse(e->globalPos());
  1685. _pressButton = e->button();
  1686. setPressed(_selected, _selectedTopicJump, _selectedBotApp);
  1687. setCollapsedPressed(_collapsedSelected);
  1688. setHashtagPressed(_hashtagSelected);
  1689. _hashtagDeletePressed = _hashtagDeleteSelected;
  1690. setFilteredPressed(_filteredSelected, _selectedTopicJump, _selectedBotApp);
  1691. setPeerSearchPressed(_peerSearchSelected);
  1692. setPreviewPressed(_previewSelected);
  1693. setSearchedPressed(_searchedSelected);
  1694. _pressedMorePosts = _selectedMorePosts;
  1695. _pressedChatTypeFilter = _selectedChatTypeFilter;
  1696. const auto alt = (e->modifiers() & Qt::AltModifier);
  1697. if (alt && showChatPreview()) {
  1698. return;
  1699. } else if (!alt && isUserpicPress()) {
  1700. scheduleChatPreview(e->globalPos());
  1701. }
  1702. if (base::in_range(_collapsedSelected, 0, _collapsedRows.size())) {
  1703. auto row = &_collapsedRows[_collapsedSelected]->row;
  1704. row->addRipple(e->pos(), QSize(width(), st::dialogsImportantBarHeight), [this, index = _collapsedSelected] {
  1705. update(0, (index * st::dialogsImportantBarHeight), width(), st::dialogsImportantBarHeight);
  1706. });
  1707. } else if (_pressed) {
  1708. auto row = _pressed;
  1709. const auto weak = Ui::MakeWeak(this);
  1710. const auto updateCallback = [weak, row] {
  1711. const auto strong = weak.data();
  1712. if (!strong || !strong->_pinnedShiftAnimation.animating()) {
  1713. row->entry()->updateChatListEntry();
  1714. }
  1715. };
  1716. const auto origin = e->pos()
  1717. - QPoint(0, dialogsOffset() + _pressed->top());
  1718. if ((_pressButton == Qt::MiddleButton)
  1719. && addQuickActionRipple(row, updateCallback)) {
  1720. } else if (addBotAppRipple(origin, updateCallback)) {
  1721. } else if (_pressedTopicJump) {
  1722. row->addTopicJumpRipple(
  1723. origin,
  1724. _topicJumpCache.get(),
  1725. updateCallback);
  1726. } else {
  1727. row->clearTopicJumpRipple();
  1728. row->addRipple(
  1729. origin,
  1730. QSize(width(), _pressed->height()),
  1731. updateCallback);
  1732. }
  1733. _dragStart = e->pos();
  1734. } else if (base::in_range(_hashtagPressed, 0, _hashtagResults.size()) && !_hashtagDeletePressed) {
  1735. auto row = &_hashtagResults[_hashtagPressed]->row;
  1736. const auto origin = e->pos() - QPoint(0, hashtagsOffset() + _hashtagPressed * st::mentionHeight);
  1737. row->addRipple(origin, QSize(width(), st::mentionHeight), [this, index = _hashtagPressed] {
  1738. update(0, hashtagsOffset() + index * st::mentionHeight, width(), st::mentionHeight);
  1739. });
  1740. } else if (base::in_range(_filteredPressed, 0, _filterResults.size())) {
  1741. const auto &result = _filterResults[_filteredPressed];
  1742. const auto row = result.row;
  1743. const auto filterId = _filterId;
  1744. const auto origin = e->pos()
  1745. - QPoint(0, filteredOffset() + result.top);
  1746. const auto updateCallback = [=] { repaintDialogRow(filterId, row); };
  1747. if (addBotAppRipple(origin, updateCallback)) {
  1748. } else if (_pressedTopicJump) {
  1749. row->addTopicJumpRipple(
  1750. origin,
  1751. _topicJumpCache.get(),
  1752. updateCallback);
  1753. } else {
  1754. row->clearTopicJumpRipple();
  1755. row->addRipple(
  1756. origin,
  1757. QSize(width(), row->height()),
  1758. updateCallback);
  1759. }
  1760. } else if (base::in_range(_peerSearchPressed, 0, _peerSearchResults.size())) {
  1761. auto &result = _peerSearchResults[_peerSearchPressed];
  1762. auto row = &result->row;
  1763. row->addRipple(
  1764. e->pos() - QPoint(0, peerSearchOffset() + _peerSearchPressed * st::dialogsRowHeight),
  1765. QSize(width(), st::dialogsRowHeight),
  1766. [this, peer = result->peer] { updateSearchResult(peer); });
  1767. } else if (base::in_range(_searchedPressed, 0, _searchResults.size())) {
  1768. auto &row = _searchResults[_searchedPressed];
  1769. row->addRipple(
  1770. e->pos() - QPoint(0, searchedOffset() + _searchedPressed * _st->height),
  1771. QSize(width(), _st->height),
  1772. row->repaint());
  1773. }
  1774. ClickHandler::pressed();
  1775. if (anim::Disabled()
  1776. && !_chatPreviewScheduled
  1777. && (!_pressed || !_pressed->entry()->isPinnedDialog(_filterId))) {
  1778. mousePressReleased(e->globalPos(), e->button(), e->modifiers());
  1779. }
  1780. }
  1781. bool InnerWidget::addBotAppRipple(QPoint origin, Fn<void()> updateCallback) {
  1782. if (!(_pressedBotApp && _pressedBotAppData)) {
  1783. return false;
  1784. }
  1785. const auto size = _pressedBotAppData->bg.size()
  1786. / style::DevicePixelRatio();
  1787. if (!_pressedBotAppData->ripple) {
  1788. _pressedBotAppData->ripple = std::make_unique<Ui::RippleAnimation>(
  1789. st::defaultRippleAnimation,
  1790. Ui::RippleAnimation::RoundRectMask(size, size.height() / 2),
  1791. std::move(updateCallback));
  1792. }
  1793. const auto shift = QPoint(
  1794. width() - size.width() - st::dialogRowOpenBotRight,
  1795. st::dialogRowOpenBotTop);
  1796. _pressedBotAppData->ripple->add(origin - shift);
  1797. return true;
  1798. }
  1799. bool InnerWidget::addQuickActionRipple(
  1800. not_null<Row*> row,
  1801. Fn<void()> updateCallback) {
  1802. const auto action = Core::App().settings().quickDialogAction();
  1803. if (action == Dialogs::Ui::QuickDialogAction::Disabled) {
  1804. return false;
  1805. }
  1806. const auto history = row->history();
  1807. if (!history) {
  1808. return false;
  1809. }
  1810. const auto key = history->peer->id.value;
  1811. const auto context = ensureQuickAction(key);
  1812. auto name = ResolveQuickDialogLottieIconName(
  1813. history->peer,
  1814. action,
  1815. _filterId);
  1816. context->icon = Lottie::MakeIcon({
  1817. .name = std::move(name),
  1818. .sizeOverride = Size(st::dialogsQuickActionSize),
  1819. });
  1820. context->action = action;
  1821. context->icon->jumpTo(context->icon->framesCount() - 1, [=] {
  1822. const auto size = QSize(
  1823. st::dialogsQuickActionRippleSize,
  1824. row->height());
  1825. if (!context->ripple) {
  1826. context->ripple = std::make_unique<Ui::RippleAnimation>(
  1827. st::defaultRippleAnimation,
  1828. Ui::RippleAnimation::RectMask(size),
  1829. updateCallback);
  1830. }
  1831. if (!context->rippleFg) {
  1832. context->rippleFg = std::make_unique<Ui::RippleAnimation>(
  1833. st::defaultRippleAnimation,
  1834. Ui::RippleAnimation::MaskByDrawer(
  1835. size,
  1836. true,
  1837. [&](QPainter &p) {
  1838. p.setCompositionMode(
  1839. QPainter::CompositionMode_Source);
  1840. p.fillRect(Rect(size), Qt::transparent);
  1841. DrawQuickAction(
  1842. p,
  1843. Rect(size),
  1844. context->icon.get(),
  1845. ResolveQuickDialogLabel(
  1846. row->history(),
  1847. action,
  1848. _filterId));
  1849. }),
  1850. std::move(updateCallback));
  1851. }
  1852. context->ripple->add(QPoint(size.width() / 2, size.height() / 2));
  1853. context->rippleFg->add(QPoint(size.width() / 2, size.height() / 2));
  1854. });
  1855. return true;
  1856. }
  1857. const std::vector<Key> &InnerWidget::pinnedChatsOrder() const {
  1858. const auto owner = &session().data();
  1859. return _savedSublists
  1860. ? owner->pinnedChatsOrder(&owner->savedMessages())
  1861. : _openedForum
  1862. ? owner->pinnedChatsOrder(_openedForum)
  1863. : _filterId
  1864. ? owner->pinnedChatsOrder(_filterId)
  1865. : owner->pinnedChatsOrder(_openedFolder);
  1866. }
  1867. void InnerWidget::checkReorderPinnedStart(QPoint localPosition) {
  1868. if (!_pressed
  1869. || _dragging
  1870. || (_state != WidgetState::Default)
  1871. || _pressedBotApp) {
  1872. return;
  1873. } else if (qAbs(localPosition.y() - _dragStart.y())
  1874. < style::ConvertScale(kStartReorderThreshold)) {
  1875. return;
  1876. }
  1877. if ((_pressButton == Qt::MiddleButton)
  1878. && (Core::App().settings().quickDialogAction()
  1879. != Dialogs::Ui::QuickDialogAction::Disabled)) {
  1880. return;
  1881. }
  1882. _dragging = _pressed;
  1883. startReorderPinned(localPosition);
  1884. }
  1885. void InnerWidget::startReorderPinned(QPoint localPosition) {
  1886. Expects(_dragging != nullptr);
  1887. cancelChatPreview();
  1888. if (updateReorderIndexGetCount() < 2) {
  1889. _dragging = nullptr;
  1890. } else {
  1891. const auto &order = pinnedChatsOrder();
  1892. _pinnedOnDragStart = base::flat_set<Key>{
  1893. order.begin(),
  1894. order.end()
  1895. };
  1896. _pinnedRows[_draggingIndex].yadd = anim::value(0, localPosition.y() - _dragStart.y());
  1897. _pinnedRows[_draggingIndex].animStartTime = crl::now();
  1898. _pinnedShiftAnimation.start();
  1899. }
  1900. }
  1901. int InnerWidget::countPinnedIndex(Row *ofRow) {
  1902. if (!ofRow || !ofRow->entry()->isPinnedDialog(_filterId)) {
  1903. return -1;
  1904. }
  1905. auto result = 0;
  1906. for (const auto &row : *_shownList) {
  1907. if (row->entry()->fixedOnTopIndex()) {
  1908. continue;
  1909. } else if (!row->entry()->isPinnedDialog(_filterId)) {
  1910. break;
  1911. } else if (row == ofRow) {
  1912. return result;
  1913. }
  1914. ++result;
  1915. }
  1916. return -1;
  1917. }
  1918. void InnerWidget::savePinnedOrder() {
  1919. const auto &newOrder = pinnedChatsOrder();
  1920. if (newOrder.size() != _pinnedOnDragStart.size()) {
  1921. return; // Something has changed in the set of pinned chats.
  1922. }
  1923. for (const auto &key : newOrder) {
  1924. if (!_pinnedOnDragStart.contains(key)) {
  1925. return; // Something has changed in the set of pinned chats.
  1926. }
  1927. }
  1928. if (_savedSublists) {
  1929. session().api().savePinnedOrder(&session().data().savedMessages());
  1930. } else if (_openedForum) {
  1931. session().api().savePinnedOrder(_openedForum);
  1932. } else if (_filterId) {
  1933. Api::SaveNewFilterPinned(&session(), _filterId);
  1934. } else {
  1935. session().api().savePinnedOrder(_openedFolder);
  1936. }
  1937. }
  1938. void InnerWidget::finishReorderPinned() {
  1939. auto wasDragging = (_dragging != nullptr);
  1940. if (wasDragging) {
  1941. savePinnedOrder();
  1942. _dragging = nullptr;
  1943. _touchDragStartGlobal = {};
  1944. }
  1945. _draggingIndex = -1;
  1946. if (!_pinnedShiftAnimation.animating()) {
  1947. _pinnedRows.clear();
  1948. _aboveIndex = -1;
  1949. }
  1950. if (wasDragging) {
  1951. _draggingScroll.cancel();
  1952. }
  1953. }
  1954. bool InnerWidget::finishReorderOnRelease() {
  1955. if (!_dragging) {
  1956. return false;
  1957. }
  1958. updateReorderIndexGetCount();
  1959. if (_draggingIndex >= 0) {
  1960. _pinnedRows[_draggingIndex].yadd.start(0.);
  1961. _pinnedRows[_draggingIndex].animStartTime = crl::now();
  1962. if (!_pinnedShiftAnimation.animating()) {
  1963. _pinnedShiftAnimation.start();
  1964. }
  1965. }
  1966. finishReorderPinned();
  1967. return true;
  1968. }
  1969. void InnerWidget::stopReorderPinned() {
  1970. _pinnedShiftAnimation.stop();
  1971. finishReorderPinned();
  1972. }
  1973. int InnerWidget::updateReorderIndexGetCount() {
  1974. auto index = countPinnedIndex(_dragging);
  1975. if (index < 0) {
  1976. finishReorderPinned();
  1977. return 0;
  1978. }
  1979. const auto count = Dialogs::PinnedDialogsCount(_filterId, _shownList);
  1980. Assert(index < count);
  1981. if (count < 2) {
  1982. stopReorderPinned();
  1983. return 0;
  1984. }
  1985. _draggingIndex = index;
  1986. _aboveIndex = _draggingIndex;
  1987. while (count > _pinnedRows.size()) {
  1988. _pinnedRows.emplace_back();
  1989. }
  1990. while (count < _pinnedRows.size()) {
  1991. _pinnedRows.pop_back();
  1992. }
  1993. return count;
  1994. }
  1995. bool InnerWidget::updateReorderPinned(QPoint localPosition) {
  1996. checkReorderPinnedStart(localPosition);
  1997. auto pinnedCount = updateReorderIndexGetCount();
  1998. if (pinnedCount < 2) {
  1999. return false;
  2000. }
  2001. const auto draggingHeight = _dragging->height();
  2002. auto yaddWas = _pinnedRows[_draggingIndex].yadd.current();
  2003. auto shift = 0;
  2004. auto shiftHeight = 0;
  2005. auto now = crl::now();
  2006. if (_dragStart.y() > localPosition.y() && _draggingIndex > 0) {
  2007. shift = -floorclamp(_dragStart.y() - localPosition.y() + (draggingHeight / 2), draggingHeight, 0, _draggingIndex);
  2008. for (auto from = _draggingIndex, to = _draggingIndex + shift; from > to; --from) {
  2009. _shownList->movePinned(_dragging, -1);
  2010. std::swap(_pinnedRows[from], _pinnedRows[from - 1]);
  2011. _pinnedRows[from].yadd = anim::value(_pinnedRows[from].yadd.current() - draggingHeight, 0);
  2012. _pinnedRows[from].animStartTime = now;
  2013. shiftHeight -= (*(_shownList->cbegin() + from))->height();
  2014. }
  2015. } else if (_dragStart.y() < localPosition.y() && _draggingIndex + 1 < pinnedCount) {
  2016. shift = floorclamp(localPosition.y() - _dragStart.y() + (draggingHeight / 2), draggingHeight, 0, pinnedCount - _draggingIndex - 1);
  2017. for (auto from = _draggingIndex, to = _draggingIndex + shift; from < to; ++from) {
  2018. _shownList->movePinned(_dragging, 1);
  2019. std::swap(_pinnedRows[from], _pinnedRows[from + 1]);
  2020. _pinnedRows[from].yadd = anim::value(_pinnedRows[from].yadd.current() + draggingHeight, 0);
  2021. _pinnedRows[from].animStartTime = now;
  2022. shiftHeight += (*(_shownList->cbegin() + from))->height();
  2023. }
  2024. }
  2025. if (shift) {
  2026. _draggingIndex += shift;
  2027. _aboveIndex = _draggingIndex;
  2028. _dragStart.setY(_dragStart.y() + shiftHeight);
  2029. if (!_pinnedShiftAnimation.animating()) {
  2030. _pinnedShiftAnimation.start();
  2031. }
  2032. }
  2033. _aboveTopShift = qCeil(_pinnedRows[_aboveIndex].yadd.current());
  2034. _pinnedRows[_draggingIndex].yadd = anim::value(
  2035. yaddWas - shiftHeight,
  2036. localPosition.y() - _dragStart.y());
  2037. if (!_pinnedRows[_draggingIndex].animStartTime) {
  2038. _pinnedRows[_draggingIndex].yadd.finish();
  2039. }
  2040. pinnedShiftAnimationCallback(now);
  2041. const auto delta = [&] {
  2042. if (localPosition.y() < _visibleTop) {
  2043. return localPosition.y() - _visibleTop;
  2044. } else if ((_savedSublists || _openedFolder || _openedForum || _filterId)
  2045. && localPosition.y() > _visibleBottom) {
  2046. return localPosition.y() - _visibleBottom;
  2047. }
  2048. return 0;
  2049. }();
  2050. _draggingScroll.checkDeltaScroll(delta);
  2051. return true;
  2052. }
  2053. bool InnerWidget::pinnedShiftAnimationCallback(crl::time now) {
  2054. if (anim::Disabled()) {
  2055. now += st::stickersRowDuration;
  2056. }
  2057. auto animating = false;
  2058. auto updateMin = -1;
  2059. auto updateMax = 0;
  2060. for (auto i = 0, l = static_cast<int>(_pinnedRows.size()); i != l; ++i) {
  2061. auto start = _pinnedRows[i].animStartTime;
  2062. if (start) {
  2063. if (updateMin < 0) updateMin = i;
  2064. updateMax = i;
  2065. if (start + st::stickersRowDuration > now && now >= start) {
  2066. _pinnedRows[i].yadd.update(float64(now - start) / st::stickersRowDuration, anim::sineInOut);
  2067. animating = true;
  2068. } else {
  2069. _pinnedRows[i].yadd.finish();
  2070. _pinnedRows[i].animStartTime = 0;
  2071. }
  2072. }
  2073. }
  2074. updateReorderIndexGetCount();
  2075. if (_draggingIndex >= 0) {
  2076. if (updateMin < 0 || updateMin > _draggingIndex) {
  2077. updateMin = _draggingIndex;
  2078. }
  2079. if (updateMax < _draggingIndex) updateMax = _draggingIndex;
  2080. }
  2081. if (updateMin >= 0) {
  2082. const auto minHeight = _st->height;
  2083. const auto maxHeight = st::taggedForumDialogRow.height;
  2084. auto top = pinnedOffset();
  2085. auto updateFrom = top + minHeight * (updateMin - 1);
  2086. auto updateHeight = maxHeight * (updateMax - updateMin + 3);
  2087. if (base::in_range(_aboveIndex, 0, _pinnedRows.size())) {
  2088. // Always include currently dragged chat in its current and old positions.
  2089. auto aboveRowBottom = top + (_aboveIndex + 1) * maxHeight;
  2090. auto aboveTopShift = qCeil(_pinnedRows[_aboveIndex].yadd.current());
  2091. accumulate_max(updateHeight, (aboveRowBottom - updateFrom) + _aboveTopShift);
  2092. accumulate_max(updateHeight, (aboveRowBottom - updateFrom) + aboveTopShift);
  2093. _aboveTopShift = aboveTopShift;
  2094. }
  2095. update(0, updateFrom, width(), updateHeight);
  2096. }
  2097. if (!animating) {
  2098. _aboveIndex = _draggingIndex;
  2099. }
  2100. return animating;
  2101. }
  2102. void InnerWidget::mouseReleaseEvent(QMouseEvent *e) {
  2103. mousePressReleased(e->globalPos(), e->button(), e->modifiers());
  2104. }
  2105. void InnerWidget::mousePressReleased(
  2106. QPoint globalPosition,
  2107. Qt::MouseButton button,
  2108. Qt::KeyboardModifiers modifiers) {
  2109. if (_chatPreviewScheduled) {
  2110. _controller->cancelScheduledPreview();
  2111. }
  2112. _pressButton = Qt::NoButton;
  2113. const auto wasDragging = finishReorderOnRelease();
  2114. auto collapsedPressed = _collapsedPressed;
  2115. setCollapsedPressed(-1);
  2116. const auto pressedTopicRootId = _pressedTopicJumpRootId;
  2117. const auto pressedTopicJump = _pressedTopicJump;
  2118. const auto pressedBotApp = _pressedBotApp;
  2119. auto pressed = _pressed;
  2120. clearPressed();
  2121. auto hashtagPressed = _hashtagPressed;
  2122. setHashtagPressed(-1);
  2123. auto hashtagDeletePressed = _hashtagDeletePressed;
  2124. _hashtagDeletePressed = false;
  2125. auto filteredPressed = _filteredPressed;
  2126. setFilteredPressed(-1, false, false);
  2127. auto peerSearchPressed = _peerSearchPressed;
  2128. setPeerSearchPressed(-1);
  2129. auto previewPressed = _previewPressed;
  2130. setPreviewPressed(-1);
  2131. auto searchedPressed = _searchedPressed;
  2132. setSearchedPressed(-1);
  2133. const auto pressedMorePosts = _pressedMorePosts;
  2134. _pressedMorePosts = false;
  2135. const auto pressedChatTypeFilter = _pressedChatTypeFilter;
  2136. _pressedChatTypeFilter = false;
  2137. if (wasDragging) {
  2138. selectByMouse(globalPosition);
  2139. }
  2140. if (_pressedBotAppData && _pressedBotAppData->ripple) {
  2141. _pressedBotAppData->ripple->lastStop();
  2142. }
  2143. if (!_quickActions.empty() && pressed) {
  2144. if (const auto history = pressed->history()) {
  2145. const auto it = _quickActions.find(history->peer->id.value);
  2146. if (it != _quickActions.end()) {
  2147. if (it->second->ripple) {
  2148. it->second->ripple->lastStop();
  2149. it->second->rippleFg->lastStop();
  2150. }
  2151. if (pressed == _selected) {
  2152. PerformQuickDialogAction(
  2153. _controller,
  2154. history->peer,
  2155. it->second->action,
  2156. _filterId);
  2157. }
  2158. }
  2159. }
  2160. }
  2161. updateSelectedRow();
  2162. if (!wasDragging && button == Qt::LeftButton) {
  2163. if ((collapsedPressed >= 0 && collapsedPressed == _collapsedSelected)
  2164. || (pressed
  2165. && pressed == _selected
  2166. && pressedTopicJump == _selectedTopicJump
  2167. && pressedBotApp == _selectedBotApp)
  2168. || (hashtagPressed >= 0
  2169. && hashtagPressed == _hashtagSelected
  2170. && hashtagDeletePressed == _hashtagDeleteSelected)
  2171. || (filteredPressed >= 0 && filteredPressed == _filteredSelected)
  2172. || (peerSearchPressed >= 0
  2173. && peerSearchPressed == _peerSearchSelected)
  2174. || (previewPressed >= 0
  2175. && previewPressed == _previewSelected)
  2176. || (searchedPressed >= 0
  2177. && searchedPressed == _searchedSelected)
  2178. || (pressedMorePosts
  2179. && pressedMorePosts == _selectedMorePosts)
  2180. || (pressedChatTypeFilter
  2181. && pressedChatTypeFilter == _selectedChatTypeFilter)) {
  2182. if (pressedBotApp && (pressed || filteredPressed >= 0)) {
  2183. const auto &row = pressed
  2184. ? pressed
  2185. : _filterResults[filteredPressed].row.get();
  2186. if (const auto user = MaybeBotWithApp(row)) {
  2187. _openBotMainAppRequests.fire(peerToUser(user->id));
  2188. }
  2189. } else {
  2190. chooseRow(modifiers, pressedTopicRootId);
  2191. }
  2192. }
  2193. }
  2194. if (auto activated = ClickHandler::unpressed()) {
  2195. ActivateClickHandler(window(), activated, ClickContext{
  2196. button,
  2197. QVariant::fromValue(ClickHandlerContext{
  2198. .sessionWindow = _controller,
  2199. }) });
  2200. }
  2201. }
  2202. void InnerWidget::setCollapsedPressed(int pressed) {
  2203. if (_collapsedPressed != pressed) {
  2204. if (_collapsedPressed >= 0) {
  2205. _collapsedRows[_collapsedPressed]->row.stopLastRipple();
  2206. }
  2207. _collapsedPressed = pressed;
  2208. }
  2209. }
  2210. void InnerWidget::setPressed(
  2211. Row *pressed,
  2212. bool pressedTopicJump,
  2213. bool pressedBotApp) {
  2214. if ((_pressed != pressed)
  2215. || (pressed && _pressedTopicJump != pressedTopicJump)
  2216. || (pressed && _pressedBotApp != pressedBotApp)) {
  2217. if (_pressed) {
  2218. _pressed->stopLastRipple();
  2219. }
  2220. if (_pressedBotAppData && _pressedBotAppData->ripple) {
  2221. _pressedBotAppData->ripple->lastStop();
  2222. }
  2223. _pressed = pressed;
  2224. if (pressed || !pressedTopicJump || !pressedBotApp) {
  2225. _pressedTopicJump = pressedTopicJump;
  2226. _pressedBotApp = pressedBotApp;
  2227. if (pressedBotApp) {
  2228. if (const auto user = MaybeBotWithApp(pressed)) {
  2229. const auto it = _rightButtons.find(user->id);
  2230. if (it != _rightButtons.end()) {
  2231. _pressedBotAppData = &(it->second);
  2232. }
  2233. }
  2234. }
  2235. const auto history = pressedTopicJump
  2236. ? pressed->history()
  2237. : nullptr;
  2238. const auto item = history ? history->chatListMessage() : nullptr;
  2239. _pressedTopicJumpRootId = item ? item->topicRootId() : MsgId();
  2240. }
  2241. }
  2242. }
  2243. void InnerWidget::clearPressed() {
  2244. setPressed(nullptr, false, false);
  2245. }
  2246. void InnerWidget::setHashtagPressed(int pressed) {
  2247. if (base::in_range(_hashtagPressed, 0, _hashtagResults.size())) {
  2248. _hashtagResults[_hashtagPressed]->row.stopLastRipple();
  2249. }
  2250. _hashtagPressed = pressed;
  2251. }
  2252. void InnerWidget::setFilteredPressed(
  2253. int pressed,
  2254. bool pressedTopicJump,
  2255. bool pressedBotApp) {
  2256. if (_filteredPressed != pressed
  2257. || (pressed >= 0 && _pressedTopicJump != pressedTopicJump)
  2258. || (pressed >= 0 && _pressedBotApp != pressedBotApp)) {
  2259. if (base::in_range(_filteredPressed, 0, _filterResults.size())) {
  2260. _filterResults[_filteredPressed].row->stopLastRipple();
  2261. }
  2262. if (_pressedBotAppData && _pressedBotAppData->ripple) {
  2263. _pressedBotAppData->ripple->lastStop();
  2264. }
  2265. _filteredPressed = pressed;
  2266. if (pressed >= 0 || !pressedTopicJump || !pressedBotApp) {
  2267. _pressedTopicJump = pressedTopicJump;
  2268. _pressedBotApp = pressedBotApp;
  2269. if (pressed >= 0 && pressedBotApp) {
  2270. const auto &row = _filterResults[pressed].row;
  2271. if (const auto history = row->history()) {
  2272. const auto it = _rightButtons.find(history->peer->id);
  2273. if (it != _rightButtons.end()) {
  2274. _pressedBotAppData = &(it->second);
  2275. }
  2276. }
  2277. }
  2278. const auto history = pressedTopicJump
  2279. ? _filterResults[pressed].row->history()
  2280. : nullptr;
  2281. const auto item = history ? history->chatListMessage() : nullptr;
  2282. _pressedTopicJumpRootId = item ? item->topicRootId() : MsgId();
  2283. }
  2284. }
  2285. }
  2286. void InnerWidget::setPeerSearchPressed(int pressed) {
  2287. if (base::in_range(_peerSearchPressed, 0, _peerSearchResults.size())) {
  2288. _peerSearchResults[_peerSearchPressed]->row.stopLastRipple();
  2289. }
  2290. _peerSearchPressed = pressed;
  2291. }
  2292. void InnerWidget::setPreviewPressed(int pressed) {
  2293. if (base::in_range(_previewPressed, 0, _previewResults.size())) {
  2294. _previewResults[_previewPressed]->stopLastRipple();
  2295. }
  2296. _previewPressed = pressed;
  2297. }
  2298. void InnerWidget::setSearchedPressed(int pressed) {
  2299. if (base::in_range(_searchedPressed, 0, _searchResults.size())) {
  2300. _searchResults[_searchedPressed]->stopLastRipple();
  2301. }
  2302. _searchedPressed = pressed;
  2303. }
  2304. void InnerWidget::resizeEvent(QResizeEvent *e) {
  2305. if (_searchTags) {
  2306. _searchTags->resizeToWidth(width() - 2 * _searchTagsLeft);
  2307. }
  2308. resizeEmpty();
  2309. moveSearchIn();
  2310. }
  2311. void InnerWidget::moveSearchIn() {
  2312. if (!_searchIn) {
  2313. return;
  2314. }
  2315. const auto searchInWidth = std::max(
  2316. width(),
  2317. st::columnMinimalWidthLeft - _narrowWidth);
  2318. _searchIn->resizeToWidth(searchInWidth);
  2319. _searchIn->moveToLeft(0, searchInChatOffset());
  2320. }
  2321. void InnerWidget::dialogRowReplaced(
  2322. Row *oldRow,
  2323. Row *newRow) {
  2324. auto found = false;
  2325. if (_state == WidgetState::Filtered) {
  2326. auto top = 0;
  2327. for (auto i = _filterResults.begin(); i != _filterResults.end();) {
  2328. if (i->row == oldRow) { // this row is shown in filtered and maybe is in contacts!
  2329. found = true;
  2330. top = i->top;
  2331. if (!newRow) {
  2332. i = _filterResults.erase(i);
  2333. continue;
  2334. }
  2335. i->row = newRow;
  2336. }
  2337. if (found) {
  2338. i->top = top;
  2339. top += i->row->height();
  2340. }
  2341. ++i;
  2342. }
  2343. }
  2344. if (_selected == oldRow) {
  2345. _selected = newRow;
  2346. }
  2347. if (_pressed == oldRow) {
  2348. setPressed(newRow, _pressedTopicJump, _pressedBotApp);
  2349. }
  2350. if (_dragging == oldRow) {
  2351. if (newRow) {
  2352. _dragging = newRow;
  2353. } else {
  2354. stopReorderPinned();
  2355. }
  2356. }
  2357. if (found) {
  2358. refresh();
  2359. }
  2360. }
  2361. void InnerWidget::handleChatListEntryRefreshes() {
  2362. using Event = Data::Session::ChatListEntryRefresh;
  2363. session().data().chatListEntryRefreshes(
  2364. ) | rpl::filter([=](const Event &event) {
  2365. if (event.filterId != _filterId) {
  2366. return false;
  2367. } else if (const auto topic = event.key.topic()) {
  2368. return (topic->forum() == _openedForum);
  2369. } else if (event.key.sublist()) {
  2370. return _savedSublists;
  2371. } else {
  2372. return !_openedForum;
  2373. }
  2374. }) | rpl::start_with_next([=](const Event &event) {
  2375. const auto offset = dialogsOffset();
  2376. const auto from = offset + event.moved.from;
  2377. const auto to = offset + event.moved.to;
  2378. const auto &key = event.key;
  2379. const auto entry = key.entry();
  2380. // Don't jump in chats list scroll position while dragging.
  2381. if (!_dragging
  2382. && (from != to)
  2383. && (_state == WidgetState::Default)
  2384. && (key.topic()
  2385. ? (key.topic()->forum() == _openedForum)
  2386. : key.sublist()
  2387. ? _savedSublists
  2388. : (entry->folder() == _openedFolder))) {
  2389. _dialogMoved.fire({ from, to });
  2390. }
  2391. if (event.existenceChanged) {
  2392. if (!entry->inChatList()) {
  2393. if (key == _menuRow.key && _menu) {
  2394. InvokeQueued(this, [=] { _menu = nullptr; });
  2395. }
  2396. if (_selected && _selected->key() == key) {
  2397. _selected = nullptr;
  2398. }
  2399. if (_pressed && _pressed->key() == key) {
  2400. clearPressed();
  2401. }
  2402. const auto i = ranges::find(
  2403. _filterResults,
  2404. key,
  2405. &FilterResult::key);
  2406. if (i != _filterResults.end()) {
  2407. if (_filteredSelected == (i - _filterResults.begin())
  2408. && (i + 1) == _filterResults.end()) {
  2409. _filteredSelected = -1;
  2410. }
  2411. _filterResults.erase(i);
  2412. }
  2413. _updated.fire({});
  2414. }
  2415. refresh();
  2416. } else if (_state == WidgetState::Default && from != to) {
  2417. update(
  2418. 0,
  2419. std::min(from, to),
  2420. width(),
  2421. std::abs(from - to) + event.moved.height);
  2422. }
  2423. }, lifetime());
  2424. }
  2425. void InnerWidget::repaintCollapsedFolderRow(not_null<Data::Folder*> folder) {
  2426. for (auto i = 0, l = int(_collapsedRows.size()); i != l; ++i) {
  2427. if (_collapsedRows[i]->folder == folder) {
  2428. update(0, i * st::dialogsImportantBarHeight, width(), st::dialogsImportantBarHeight);
  2429. return;
  2430. }
  2431. }
  2432. }
  2433. int InnerWidget::defaultRowTop(not_null<Row*> row) const {
  2434. const auto index = row->index();
  2435. auto top = dialogsOffset();
  2436. if (base::in_range(index, 0, _pinnedRows.size())) {
  2437. top += qRound(_pinnedRows[index].yadd.current());
  2438. }
  2439. return top + row->top();
  2440. }
  2441. void InnerWidget::repaintDialogRow(
  2442. FilterId filterId,
  2443. not_null<Row*> row) {
  2444. if (_state == WidgetState::Default) {
  2445. if (_filterId == filterId) {
  2446. if (const auto folder = row->folder()) {
  2447. repaintCollapsedFolderRow(folder);
  2448. }
  2449. update(0, defaultRowTop(row), width(), row->height());
  2450. }
  2451. } else if (_state == WidgetState::Filtered) {
  2452. if (!filterId) {
  2453. for (auto i = 0, l = int(_filterResults.size()); i != l; ++i) {
  2454. const auto &result = _filterResults[i];
  2455. if (result.key() == row->key()) {
  2456. update(
  2457. 0,
  2458. filteredOffset() + result.top,
  2459. width(),
  2460. result.row->height());
  2461. break;
  2462. }
  2463. }
  2464. }
  2465. }
  2466. }
  2467. void InnerWidget::repaintDialogRow(RowDescriptor row) {
  2468. updateDialogRow(row);
  2469. }
  2470. void InnerWidget::refreshDialogRow(RowDescriptor row) {
  2471. if (row.fullId) {
  2472. for (const auto &result : _searchResults) {
  2473. if (result->item()->fullId() == row.fullId) {
  2474. result->itemView().itemInvalidated(result->item());
  2475. }
  2476. }
  2477. }
  2478. repaintDialogRow(row);
  2479. }
  2480. void InnerWidget::updateSearchResult(not_null<PeerData*> peer) {
  2481. if (_state == WidgetState::Filtered) {
  2482. const auto i = ranges::find(
  2483. _peerSearchResults,
  2484. peer,
  2485. &PeerSearchResult::peer);
  2486. if (i != end(_peerSearchResults)) {
  2487. const auto top = peerSearchOffset();
  2488. const auto index = (i - begin(_peerSearchResults));
  2489. rtlupdate(
  2490. 0,
  2491. top + index * st::dialogsRowHeight,
  2492. width(),
  2493. st::dialogsRowHeight);
  2494. }
  2495. }
  2496. }
  2497. void InnerWidget::updateDialogRow(
  2498. RowDescriptor row,
  2499. QRect updateRect,
  2500. UpdateRowSections sections) {
  2501. if (IsServerMsgId(-row.fullId.msg)) {
  2502. if (const auto peer = row.key.peer()) {
  2503. if (const auto from = peer->migrateFrom()) {
  2504. if (const auto migrated = from->owner().historyLoaded(from)) {
  2505. row = RowDescriptor(
  2506. migrated,
  2507. FullMsgId(from->id, -row.fullId.msg));
  2508. }
  2509. }
  2510. }
  2511. }
  2512. const auto updateRow = [&](int rowTop, int rowHeight) {
  2513. if (!updateRect.isEmpty()) {
  2514. rtlupdate(updateRect.translated(0, rowTop));
  2515. } else {
  2516. rtlupdate(0, rowTop, width(), rowHeight);
  2517. }
  2518. };
  2519. if (_state == WidgetState::Default) {
  2520. if (sections & UpdateRowSection::Default) {
  2521. if (const auto folder = row.key.folder()) {
  2522. repaintCollapsedFolderRow(folder);
  2523. }
  2524. if (const auto dialog = _shownList->getRow(row.key)) {
  2525. const auto position = dialog->index();
  2526. auto top = dialogsOffset();
  2527. if (base::in_range(position, 0, _pinnedRows.size())) {
  2528. top += qRound(_pinnedRows[position].yadd.current());
  2529. }
  2530. updateRow(top + dialog->top(), dialog->height());
  2531. }
  2532. }
  2533. } else if (_state == WidgetState::Filtered) {
  2534. if ((sections & UpdateRowSection::Filtered)
  2535. && !_filterResults.empty()) {
  2536. for (const auto &result : _filterResults) {
  2537. if (result.key() == row.key) {
  2538. updateRow(
  2539. filteredOffset() + result.top,
  2540. result.row->height());
  2541. break;
  2542. }
  2543. }
  2544. }
  2545. if ((sections & UpdateRowSection::PeerSearch)
  2546. && !_peerSearchResults.empty()) {
  2547. if (const auto peer = row.key.peer()) {
  2548. const auto rowHeight = st::dialogsRowHeight;
  2549. auto index = 0;
  2550. for (const auto &result : _peerSearchResults) {
  2551. if (result->peer == peer) {
  2552. updateRow(
  2553. peerSearchOffset() + index * rowHeight,
  2554. rowHeight);
  2555. break;
  2556. }
  2557. ++index;
  2558. }
  2559. }
  2560. }
  2561. if ((sections & UpdateRowSection::MessageSearch)
  2562. && !_searchResults.empty()) {
  2563. const auto add = searchedOffset();
  2564. auto index = 0;
  2565. for (const auto &result : _searchResults) {
  2566. if (isSearchResultActive(result.get(), row)) {
  2567. updateRow(add + index * _st->height, _st->height);
  2568. break;
  2569. }
  2570. ++index;
  2571. }
  2572. }
  2573. }
  2574. }
  2575. void InnerWidget::enterEventHook(QEnterEvent *e) {
  2576. setMouseTracking(true);
  2577. }
  2578. Row *InnerWidget::shownRowByKey(Key key) {
  2579. const auto entry = key.entry();
  2580. if (_savedSublists) {
  2581. if (!entry->asSublist()) {
  2582. return nullptr;
  2583. }
  2584. } else if (_openedForum) {
  2585. const auto topic = entry->asTopic();
  2586. if (!topic || topic->forum() != _openedForum) {
  2587. return nullptr;
  2588. }
  2589. } else if (_openedFolder) {
  2590. const auto history = entry->asHistory();
  2591. if (!history || history->folder() != _openedFolder) {
  2592. return nullptr;
  2593. }
  2594. } else {
  2595. const auto history = entry->asHistory();
  2596. if (!entry->asFolder() && (!history || history->folder())) {
  2597. return nullptr;
  2598. }
  2599. }
  2600. const auto links = entry->chatListLinks(FilterId());
  2601. return links ? links->main.get() : nullptr;
  2602. }
  2603. void InnerWidget::updateSelectedRow(Key key) {
  2604. if (_state == WidgetState::Default) {
  2605. if (key) {
  2606. const auto row = shownRowByKey(key);
  2607. if (!row) {
  2608. return;
  2609. }
  2610. auto position = row->index();
  2611. auto top = dialogsOffset();
  2612. if (base::in_range(position, 0, _pinnedRows.size())) {
  2613. top += qRound(_pinnedRows[position].yadd.current());
  2614. }
  2615. update(0, top + row->top(), width(), row->height());
  2616. } else if (_selected) {
  2617. update(0, dialogsOffset() + _selected->top(), width(), _selected->height());
  2618. } else if (_collapsedSelected >= 0) {
  2619. update(0, _collapsedSelected * st::dialogsImportantBarHeight, width(), st::dialogsImportantBarHeight);
  2620. }
  2621. } else if (_state == WidgetState::Filtered) {
  2622. if (key) {
  2623. for (auto i = 0, l = int(_filterResults.size()); i != l; ++i) {
  2624. const auto &result = _filterResults[i];
  2625. if (result.key() == key) {
  2626. update(0, filteredOffset() + result.top, width(), result.row->height());
  2627. break;
  2628. }
  2629. }
  2630. } else if (_hashtagSelected >= 0) {
  2631. update(0, hashtagsOffset() + _hashtagSelected * st::mentionHeight, width(), st::mentionHeight);
  2632. } else if (_filteredSelected >= 0) {
  2633. if (_filteredSelected < _filterResults.size()) {
  2634. const auto &result = _filterResults[_filteredSelected];
  2635. update(0, filteredOffset() + result.top, width(), result.row->height());
  2636. }
  2637. } else if (_peerSearchSelected >= 0) {
  2638. update(0, peerSearchOffset() + _peerSearchSelected * st::dialogsRowHeight, width(), st::dialogsRowHeight);
  2639. } else if (_previewSelected >= 0) {
  2640. update(0, previewOffset() + _previewSelected * _st->height, width(), _st->height);
  2641. } else if (_searchedSelected >= 0) {
  2642. update(0, searchedOffset() + _searchedSelected * _st->height, width(), _st->height);
  2643. }
  2644. }
  2645. }
  2646. void InnerWidget::refreshShownList() {
  2647. const auto list = _savedSublists
  2648. ? session().data().savedMessages().chatsList()->indexed()
  2649. : _openedForum
  2650. ? _openedForum->topicsList()->indexed()
  2651. : _filterId
  2652. ? session().data().chatsFilters().chatsList(_filterId)->indexed()
  2653. : session().data().chatsList(_openedFolder)->indexed();
  2654. if (_shownList != list) {
  2655. _shownList = list;
  2656. _shownList->updateHeights(_narrowRatio);
  2657. }
  2658. }
  2659. void InnerWidget::leaveEventHook(QEvent *e) {
  2660. setMouseTracking(false);
  2661. clearSelection();
  2662. }
  2663. void InnerWidget::dragLeft() {
  2664. setMouseTracking(false);
  2665. clearSelection();
  2666. }
  2667. FilterId InnerWidget::filterId() const {
  2668. return _filterId;
  2669. }
  2670. void InnerWidget::clearSelection() {
  2671. _mouseSelection = false;
  2672. _lastMousePosition = std::nullopt;
  2673. _lastRowLocalMouseX = -1;
  2674. if (isSelected()) {
  2675. updateSelectedRow();
  2676. _collapsedSelected = -1;
  2677. _selectedMorePosts = false;
  2678. _selectedChatTypeFilter = false;
  2679. _selected = nullptr;
  2680. _filteredSelected
  2681. = _searchedSelected
  2682. = _previewSelected
  2683. = _peerSearchSelected
  2684. = _hashtagSelected
  2685. = -1;
  2686. setCursor(style::cur_default);
  2687. }
  2688. }
  2689. void InnerWidget::fillSupportSearchMenu(not_null<Ui::PopupMenu*> menu) {
  2690. const auto all = session().settings().supportAllSearchResults();
  2691. const auto text = all ? "Only one from chat" : "Show all messages";
  2692. menu->addAction(text, [=] {
  2693. session().settings().setSupportAllSearchResults(!all);
  2694. session().saveSettingsDelayed();
  2695. });
  2696. }
  2697. void InnerWidget::fillArchiveSearchMenu(not_null<Ui::PopupMenu*> menu) {
  2698. const auto folder = session().data().folderLoaded(Data::Folder::kId);
  2699. if (!folder
  2700. || !folder->chatsList()->fullSize().current()
  2701. || _searchState.inChat) {
  2702. return;
  2703. }
  2704. const auto skip = session().settings().skipArchiveInSearch();
  2705. const auto text = skip
  2706. ? tr::lng_dialogs_show_archive_in_search(tr::now)
  2707. : tr::lng_dialogs_skip_archive_in_search(tr::now);
  2708. menu->addAction(text, [=] {
  2709. session().settings().setSkipArchiveInSearch(!skip);
  2710. session().saveSettingsDelayed();
  2711. });
  2712. }
  2713. bool InnerWidget::showChatPreview() {
  2714. const auto row = computeChatPreviewRow();
  2715. const auto callback = crl::guard(this, [=](bool shown) {
  2716. chatPreviewShown(shown, row);
  2717. });
  2718. return _controller->showChatPreview(row, callback);
  2719. }
  2720. void InnerWidget::chatPreviewShown(bool shown, RowDescriptor row) {
  2721. _chatPreviewScheduled = false;
  2722. if (shown) {
  2723. _chatPreviewRow = row;
  2724. if (base::take(_chatPreviewTouchGlobal)) {
  2725. _touchCancelRequests.fire({});
  2726. }
  2727. ClickHandler::unpressed();
  2728. mousePressReleased(QCursor::pos(), Qt::NoButton, Qt::NoModifier);
  2729. } else {
  2730. cancelChatPreview();
  2731. const auto globalPosition = QCursor::pos();
  2732. if (rect().contains(mapFromGlobal(globalPosition))) {
  2733. setMouseTracking(true);
  2734. selectByMouse(globalPosition);
  2735. }
  2736. }
  2737. }
  2738. bool InnerWidget::scheduleChatPreview(QPoint positionOverride) {
  2739. const auto row = computeChatPreviewRow();
  2740. const auto callback = crl::guard(this, [=](bool shown) {
  2741. chatPreviewShown(shown, row);
  2742. });
  2743. _chatPreviewScheduled = _controller->scheduleChatPreview(
  2744. row,
  2745. callback,
  2746. nullptr,
  2747. positionOverride);
  2748. return _chatPreviewScheduled;
  2749. }
  2750. void InnerWidget::contextMenuEvent(QContextMenuEvent *e) {
  2751. _menu = nullptr;
  2752. const auto fromMouse = e->reason() == QContextMenuEvent::Mouse;
  2753. if (fromMouse) {
  2754. selectByMouse(e->globalPos());
  2755. }
  2756. const auto row = [&]() -> RowDescriptor {
  2757. if (_state == WidgetState::Default) {
  2758. if (_selected) {
  2759. return { _selected->key(), FullMsgId() };
  2760. } else if (base::in_range(_collapsedSelected, 0, _collapsedRows.size())) {
  2761. if (const auto folder = _collapsedRows[_collapsedSelected]->folder) {
  2762. return { folder, FullMsgId() };
  2763. }
  2764. }
  2765. } else if (_state == WidgetState::Filtered) {
  2766. if (base::in_range(_filteredSelected, 0, _filterResults.size())) {
  2767. return { _filterResults[_filteredSelected].key(), FullMsgId() };
  2768. } else if (base::in_range(_previewSelected, 0, _previewResults.size())) {
  2769. return {
  2770. _previewResults[_previewSelected]->item()->history(),
  2771. _previewResults[_previewSelected]->item()->fullId()
  2772. };
  2773. } else if (base::in_range(_searchedSelected, 0, _searchResults.size())) {
  2774. return {
  2775. _searchResults[_searchedSelected]->item()->history(),
  2776. _searchResults[_searchedSelected]->item()->fullId()
  2777. };
  2778. }
  2779. }
  2780. return RowDescriptor();
  2781. }();
  2782. if (!row.key) {
  2783. return;
  2784. }
  2785. _menuRow = row;
  2786. if (_pressButton != Qt::LeftButton) {
  2787. mousePressReleased(e->globalPos(), _pressButton, e->modifiers());
  2788. }
  2789. _menu = base::make_unique_q<Ui::PopupMenu>(
  2790. this,
  2791. row.fullId ? st::defaultPopupMenu : st::popupMenuExpandedSeparator);
  2792. if (row.fullId) {
  2793. if (session().supportMode()) {
  2794. fillSupportSearchMenu(_menu.get());
  2795. } else {
  2796. fillArchiveSearchMenu(_menu.get());
  2797. }
  2798. } else {
  2799. const auto addAction = Ui::Menu::CreateAddActionCallback(_menu);
  2800. Window::FillDialogsEntryMenu(
  2801. _controller,
  2802. Dialogs::EntryState{
  2803. .key = row.key,
  2804. .section = Dialogs::EntryState::Section::ContextMenu,
  2805. .filterId = _filterId,
  2806. },
  2807. addAction);
  2808. }
  2809. QObject::connect(_menu.get(), &QObject::destroyed, [=] {
  2810. if (_menuRow.key) {
  2811. updateDialogRow(base::take(_menuRow));
  2812. }
  2813. if (!fromMouse) {
  2814. return;
  2815. }
  2816. const auto globalPosition = QCursor::pos();
  2817. if (rect().contains(mapFromGlobal(globalPosition))) {
  2818. setMouseTracking(true);
  2819. selectByMouse(globalPosition);
  2820. }
  2821. });
  2822. if (_menu->empty()) {
  2823. _menu = nullptr;
  2824. } else {
  2825. _menu->popup(e->globalPos());
  2826. e->accept();
  2827. }
  2828. }
  2829. void InnerWidget::parentGeometryChanged() {
  2830. const auto globalPosition = QCursor::pos();
  2831. if (rect().contains(mapFromGlobal(globalPosition))) {
  2832. setMouseTracking(true);
  2833. if (_mouseSelection) {
  2834. selectByMouse(globalPosition);
  2835. }
  2836. }
  2837. }
  2838. bool InnerWidget::processTouchEvent(not_null<QTouchEvent*> e) {
  2839. const auto point = e->touchPoints().empty()
  2840. ? std::optional<QPoint>()
  2841. : e->touchPoints().front().screenPos().toPoint();
  2842. switch (e->type()) {
  2843. case QEvent::TouchBegin: {
  2844. if (!point) {
  2845. return false;
  2846. }
  2847. selectByMouse(*point);
  2848. if (isUserpicPressOnWide() && scheduleChatPreview(*point)) {
  2849. _chatPreviewTouchGlobal = point;
  2850. } else if (!_dragging) {
  2851. _touchDragStartGlobal = point;
  2852. _touchDragPinnedTimer.callOnce(QApplication::startDragTime());
  2853. }
  2854. } break;
  2855. case QEvent::TouchUpdate: {
  2856. if (!point) {
  2857. return false;
  2858. }
  2859. if (_chatPreviewTouchGlobal) {
  2860. const auto delta = (*_chatPreviewTouchGlobal - *point);
  2861. if (delta.manhattanLength() >= QApplication::startDragDistance()) {
  2862. cancelChatPreview();
  2863. }
  2864. }
  2865. if (_touchDragStartGlobal && _dragging) {
  2866. updateReorderPinned(mapFromGlobal(*point));
  2867. return _dragging != nullptr;
  2868. } else if (_touchDragStartGlobal) {
  2869. const auto delta = (*_touchDragStartGlobal - *point);
  2870. if (delta.manhattanLength() >= QApplication::startDragDistance()) {
  2871. if (_touchDragPinnedTimer.isActive()) {
  2872. _touchDragPinnedTimer.cancel();
  2873. _touchDragStartGlobal = {};
  2874. _touchDragNowGlobal = {};
  2875. } else {
  2876. dragPinnedFromTouch();
  2877. }
  2878. } else {
  2879. _touchDragNowGlobal = point;
  2880. }
  2881. }
  2882. } break;
  2883. case QEvent::TouchEnd:
  2884. case QEvent::TouchCancel: {
  2885. if (_chatPreviewTouchGlobal) {
  2886. cancelChatPreview();
  2887. }
  2888. if (_touchDragStartGlobal) {
  2889. _touchDragStartGlobal = {};
  2890. return finishReorderOnRelease();
  2891. }
  2892. } break;
  2893. }
  2894. return false;
  2895. }
  2896. void InnerWidget::dragPinnedFromTouch() {
  2897. Expects(_touchDragStartGlobal.has_value());
  2898. const auto global = *_touchDragStartGlobal;
  2899. _touchDragPinnedTimer.cancel();
  2900. selectByMouse(global);
  2901. if (!_selected || _dragging || _state != WidgetState::Default) {
  2902. return;
  2903. }
  2904. _dragStart = mapFromGlobal(global);
  2905. _dragging = _selected;
  2906. const auto now = mapFromGlobal(_touchDragNowGlobal.value_or(global));
  2907. startReorderPinned(now);
  2908. updateReorderPinned(now);
  2909. }
  2910. bool InnerWidget::hasChatTypeFilter() const {
  2911. return !_searchResults.empty()
  2912. && (_searchState.tab == ChatSearchTab::MyMessages);
  2913. }
  2914. void InnerWidget::searchRequested(bool loading) {
  2915. _searchWaiting = false;
  2916. _searchLoading = loading;
  2917. if (loading) {
  2918. clearSearchResults(true);
  2919. clearPreviewResults();
  2920. }
  2921. refresh(true);
  2922. }
  2923. void InnerWidget::applySearchState(SearchState state) {
  2924. if (_searchState == state) {
  2925. return;
  2926. }
  2927. auto withSameQuery = state;
  2928. withSameQuery.query = _searchState.query;
  2929. const auto otherChanged = (_searchState != withSameQuery);
  2930. const auto ignoreInChat = (state.tab == ChatSearchTab::MyMessages)
  2931. || (state.tab == ChatSearchTab::PublicPosts);
  2932. const auto sublist = ignoreInChat ? nullptr : state.inChat.sublist();
  2933. const auto peer = ignoreInChat ? nullptr : state.inChat.peer();
  2934. if (const auto migrateFrom = peer ? peer->migrateFrom() : nullptr) {
  2935. _searchInMigrated = peer->owner().history(migrateFrom);
  2936. } else {
  2937. _searchInMigrated = nullptr;
  2938. }
  2939. if (peer && peer->isSelf()) {
  2940. const auto reactions = &peer->owner().reactions();
  2941. _searchTags = std::make_unique<SearchTags>(
  2942. &peer->owner(),
  2943. reactions->myTagsValue(sublist),
  2944. state.tags);
  2945. _searchTags->repaintRequests() | rpl::start_with_next([=] {
  2946. const auto height = _searchTags->height();
  2947. update(0, 0, width(), height);
  2948. }, _searchTags->lifetime());
  2949. _searchTags->menuRequests(
  2950. ) | rpl::start_with_next([=](Data::ReactionId id) {
  2951. HistoryView::ShowTagInListMenu(
  2952. &_menu,
  2953. _lastMousePosition.value_or(QCursor::pos()),
  2954. this,
  2955. id,
  2956. _controller);
  2957. }, _searchTags->lifetime());
  2958. _searchTags->heightValue() | rpl::skip(
  2959. 1
  2960. ) | rpl::start_with_next([=] {
  2961. refresh();
  2962. moveSearchIn();
  2963. }, _searchTags->lifetime());
  2964. } else {
  2965. _searchTags = nullptr;
  2966. state.tags.clear();
  2967. }
  2968. _searchFromShown = ignoreInChat
  2969. ? nullptr
  2970. : sublist
  2971. ? sublist->peer().get()
  2972. : state.fromPeer;
  2973. if (state.inChat) {
  2974. onHashtagFilterUpdate(QStringView());
  2975. }
  2976. if (state.filter != _searchState.filter) {
  2977. _chatTypeFilterWidth = 0;
  2978. update();
  2979. }
  2980. _searchState = std::move(state);
  2981. _searchHashOrCashtag = IsHashOrCashtagSearchQuery(_searchState.query);
  2982. _searchWithPostsPreview = computeSearchWithPostsPreview();
  2983. updateSearchIn();
  2984. moveSearchIn();
  2985. auto newFilter = _searchState.query;
  2986. const auto mentionsSearch = (newFilter == u"@"_q);
  2987. const auto words = mentionsSearch
  2988. ? QStringList(newFilter)
  2989. : TextUtilities::PrepareSearchWords(newFilter);
  2990. newFilter = words.isEmpty() ? QString() : words.join(' ');
  2991. if (newFilter != _filter || otherChanged) {
  2992. _filter = newFilter;
  2993. if (_filter.isEmpty()
  2994. && !_searchState.fromPeer
  2995. && _searchState.tags.empty()) {
  2996. clearFilter();
  2997. } else {
  2998. setState(WidgetState::Filtered);
  2999. _filterResults.clear();
  3000. _filterResultsGlobal.clear();
  3001. const auto append = [&](not_null<IndexedList*> list) {
  3002. const auto results = list->filtered(words);
  3003. auto top = filteredHeight();
  3004. auto i = _filterResults.insert(
  3005. end(_filterResults),
  3006. begin(results),
  3007. end(results));
  3008. for (const auto e = end(_filterResults); i != e; ++i) {
  3009. i->top = top;
  3010. i->row->recountHeight(_narrowRatio, _filterId);
  3011. top += i->row->height();
  3012. }
  3013. };
  3014. if (_searchState.filterChatsList() && !words.isEmpty()) {
  3015. if (_savedSublists) {
  3016. const auto owner = &session().data();
  3017. append(owner->savedMessages().chatsList()->indexed());
  3018. } else if (_openedForum) {
  3019. append(_openedForum->topicsList()->indexed());
  3020. } else {
  3021. const auto owner = &session().data();
  3022. append(owner->chatsList()->indexed());
  3023. const auto id = Data::Folder::kId;
  3024. if (const auto add = owner->folderLoaded(id)) {
  3025. append(add->chatsList()->indexed());
  3026. }
  3027. append(owner->contactsNoChatsList());
  3028. }
  3029. }
  3030. }
  3031. clearMouseSelection(true);
  3032. }
  3033. if (_state != WidgetState::Default) {
  3034. _searchWaiting = true;
  3035. _searchRequests.fire(otherChanged
  3036. ? SearchRequestDelay::Instant
  3037. : SearchRequestDelay::Delayed);
  3038. if (_searchWaiting) {
  3039. refresh(true);
  3040. }
  3041. }
  3042. }
  3043. void InnerWidget::onHashtagFilterUpdate(QStringView newFilter) {
  3044. if (newFilter.isEmpty()
  3045. || newFilter.at(0) != '#'
  3046. || _searchState.inChat) {
  3047. _hashtagFilter = QString();
  3048. if (!_hashtagResults.empty()) {
  3049. _hashtagResults.clear();
  3050. refresh(true);
  3051. clearMouseSelection(true);
  3052. }
  3053. return;
  3054. }
  3055. _hashtagFilter = newFilter.toString();
  3056. if (cRecentSearchHashtags().isEmpty() && cRecentWriteHashtags().isEmpty()) {
  3057. session().local().readRecentHashtagsAndBots();
  3058. }
  3059. auto &recent = cRecentSearchHashtags();
  3060. _hashtagResults.clear();
  3061. if (!recent.isEmpty()) {
  3062. _hashtagResults.reserve(qMin(recent.size(), kHashtagResultsLimit));
  3063. for (const auto &tag : recent) {
  3064. if (tag.first.startsWith(base::StringViewMid(_hashtagFilter, 1), Qt::CaseInsensitive)
  3065. && tag.first.size() + 1 != newFilter.size()) {
  3066. _hashtagResults.push_back(std::make_unique<HashtagResult>(tag.first));
  3067. if (_hashtagResults.size() == kHashtagResultsLimit) break;
  3068. }
  3069. }
  3070. }
  3071. refresh(true);
  3072. clearMouseSelection(true);
  3073. }
  3074. void InnerWidget::appendToFiltered(Key key) {
  3075. for (const auto &row : _filterResults) {
  3076. if (row.key() == key) {
  3077. return;
  3078. }
  3079. }
  3080. auto row = std::make_unique<Row>(key, 0, 0);
  3081. row->recountHeight(_narrowRatio, _filterId);
  3082. const auto &[i, ok] = _filterResultsGlobal.emplace(key, std::move(row));
  3083. const auto height = filteredHeight();
  3084. _filterResults.emplace_back(i->second.get());
  3085. _filterResults.back().top = height;
  3086. trackResultsHistory(key.owningHistory());
  3087. }
  3088. InnerWidget::~InnerWidget() {
  3089. session().data().stories().decrementPreloadingMainSources();
  3090. clearSearchResults();
  3091. }
  3092. void InnerWidget::clearSearchResults(bool clearPeerSearchResults) {
  3093. if (clearPeerSearchResults) {
  3094. _peerSearchResults.clear();
  3095. }
  3096. _searchResults.clear();
  3097. _searchedCount = _searchedMigratedCount = 0;
  3098. }
  3099. void InnerWidget::clearPreviewResults() {
  3100. _previewResults.clear();
  3101. _previewCount = 0;
  3102. }
  3103. void InnerWidget::trackResultsHistory(not_null<History*> history) {
  3104. if (!_trackedHistories.emplace(history).second) {
  3105. return;
  3106. }
  3107. const auto channel = history->peer->asChannel();
  3108. if (!channel || channel->isBroadcast()) {
  3109. return;
  3110. }
  3111. channel->flagsValue(
  3112. ) | rpl::skip(
  3113. 1
  3114. ) | rpl::filter([=](const ChannelData::Flags::Change &change) {
  3115. return (change.diff & ChannelDataFlag::Forum);
  3116. }) | rpl::start_with_next([=] {
  3117. for (const auto &row : _searchResults) {
  3118. if (row->item()->history()->peer == channel) {
  3119. row->invalidateTopic();
  3120. }
  3121. }
  3122. auto removed = false;
  3123. for (auto i = begin(_filterResultsGlobal)
  3124. ; i != end(_filterResultsGlobal);) {
  3125. if (const auto topic = i->first.topic()) {
  3126. if (topic->channel() == channel) {
  3127. removed = true;
  3128. _filterResults.erase(
  3129. ranges::remove(
  3130. _filterResults,
  3131. i->first,
  3132. &FilterResult::key),
  3133. end(_filterResults));
  3134. i = _filterResultsGlobal.erase(i);
  3135. continue;
  3136. }
  3137. }
  3138. ++i;
  3139. }
  3140. if (removed) {
  3141. refresh();
  3142. clearMouseSelection(true);
  3143. }
  3144. update();
  3145. }, _trackedLifetime);
  3146. if (const auto forum = channel->forum()) {
  3147. forum->topicDestroyed(
  3148. ) | rpl::start_with_next([=](not_null<Data::ForumTopic*> topic) {
  3149. auto removed = false;
  3150. const auto sfrom = ranges::remove(
  3151. _searchResults,
  3152. topic.get(),
  3153. &FakeRow::topic);
  3154. if (sfrom != end(_searchResults)) {
  3155. _searchResults.erase(sfrom, end(_searchResults));
  3156. removed = true;
  3157. }
  3158. const auto ffrom = ranges::remove(
  3159. _filterResults,
  3160. Key(topic),
  3161. &FilterResult::key);
  3162. if (ffrom != end(_filterResults)) {
  3163. _filterResults.erase(ffrom, end(_filterResults));
  3164. removed = true;
  3165. }
  3166. _filterResultsGlobal.erase(Key(topic));
  3167. if (removed) {
  3168. refresh();
  3169. clearMouseSelection(true);
  3170. }
  3171. if (_chatPreviewRow.key.topic() == topic) {
  3172. _chatPreviewRow = {};
  3173. }
  3174. }, _trackedLifetime);
  3175. }
  3176. }
  3177. Data::Thread *InnerWidget::updateFromParentDrag(QPoint globalPosition) {
  3178. selectByMouse(globalPosition);
  3179. const auto fromRow = [](Row *row) {
  3180. return row ? row->thread() : nullptr;
  3181. };
  3182. if (_state == WidgetState::Default) {
  3183. return fromRow(_selected);
  3184. } else if (_state == WidgetState::Filtered) {
  3185. if (base::in_range(_filteredSelected, 0, _filterResults.size())) {
  3186. return fromRow(_filterResults[_filteredSelected].row);
  3187. } else if (base::in_range(_peerSearchSelected, 0, _peerSearchResults.size())) {
  3188. return session().data().history(
  3189. _peerSearchResults[_peerSearchSelected]->peer);
  3190. } else if (base::in_range(_previewSelected, 0, _previewResults.size())) {
  3191. if (const auto item = _previewResults[_previewSelected]->item()) {
  3192. if (const auto topic = item->topic()) {
  3193. return topic;
  3194. }
  3195. return item->history();
  3196. }
  3197. } else if (base::in_range(_searchedSelected, 0, _searchResults.size())) {
  3198. if (const auto item = _searchResults[_searchedSelected]->item()) {
  3199. if (const auto topic = item->topic()) {
  3200. return topic;
  3201. }
  3202. return item->history();
  3203. }
  3204. }
  3205. }
  3206. return nullptr;
  3207. }
  3208. void InnerWidget::setLoadMoreCallback(Fn<void()> callback) {
  3209. _loadMoreCallback = std::move(callback);
  3210. }
  3211. void InnerWidget::setLoadMoreFilteredCallback(Fn<void()> callback) {
  3212. _loadMoreFilteredCallback = std::move(callback);
  3213. }
  3214. auto InnerWidget::chosenRow() const -> rpl::producer<ChosenRow> {
  3215. return _chosenRow.events();
  3216. }
  3217. rpl::producer<> InnerWidget::updated() const {
  3218. return _updated.events();
  3219. }
  3220. rpl::producer<int> InnerWidget::scrollByDeltaRequests() const {
  3221. return _draggingScroll.scrolls();
  3222. }
  3223. rpl::producer<> InnerWidget::listBottomReached() const {
  3224. return _listBottomReached.events();
  3225. }
  3226. rpl::producer<ChatSearchTab> InnerWidget::changeSearchTabRequests() const {
  3227. return _changeSearchTabRequests.events();
  3228. }
  3229. auto InnerWidget::changeSearchFilterRequests() const
  3230. -> rpl::producer<ChatTypeFilter>{
  3231. return _changeSearchFilterRequests.events();
  3232. }
  3233. rpl::producer<> InnerWidget::cancelSearchRequests() const {
  3234. return _cancelSearchRequests.events();
  3235. }
  3236. rpl::producer<> InnerWidget::cancelSearchFromRequests() const {
  3237. return _cancelSearchFromRequests.events();
  3238. }
  3239. rpl::producer<> InnerWidget::changeSearchFromRequests() const {
  3240. return _changeSearchFromRequests.events();
  3241. }
  3242. rpl::producer<Ui::ScrollToRequest> InnerWidget::mustScrollTo() const {
  3243. return _mustScrollTo.events();
  3244. }
  3245. rpl::producer<Ui::ScrollToRequest> InnerWidget::dialogMoved() const {
  3246. return _dialogMoved.events();
  3247. }
  3248. rpl::producer<SearchRequestDelay> InnerWidget::searchRequests() const {
  3249. return _searchRequests.events();
  3250. }
  3251. rpl::producer<QString> InnerWidget::completeHashtagRequests() const {
  3252. return _completeHashtagRequests.events();
  3253. }
  3254. rpl::producer<> InnerWidget::refreshHashtagsRequests() const {
  3255. return _refreshHashtagsRequests.events();
  3256. }
  3257. void InnerWidget::visibleTopBottomUpdated(
  3258. int visibleTop,
  3259. int visibleBottom) {
  3260. _visibleTop = visibleTop;
  3261. _visibleBottom = visibleBottom;
  3262. preloadRowsData();
  3263. const auto loadTill = _visibleTop
  3264. + PreloadHeightsCount * (_visibleBottom - _visibleTop);
  3265. if (_state == WidgetState::Filtered && loadTill >= peerSearchOffset()) {
  3266. if (_loadMoreFilteredCallback) {
  3267. _loadMoreFilteredCallback();
  3268. }
  3269. }
  3270. if (loadTill >= height()) {
  3271. if (_loadMoreCallback) {
  3272. _loadMoreCallback();
  3273. }
  3274. }
  3275. }
  3276. void InnerWidget::itemRemoved(not_null<const HistoryItem*> item) {
  3277. int wasCount = _searchResults.size();
  3278. for (auto i = _searchResults.begin(); i != _searchResults.end();) {
  3279. if ((*i)->item() == item) {
  3280. i = _searchResults.erase(i);
  3281. if (item->history() == _searchInMigrated) {
  3282. if (_searchedMigratedCount > 0) --_searchedMigratedCount;
  3283. } else {
  3284. if (_searchedCount > 0) --_searchedCount;
  3285. }
  3286. } else {
  3287. ++i;
  3288. }
  3289. }
  3290. if (wasCount != _searchResults.size()) {
  3291. refresh();
  3292. }
  3293. }
  3294. bool InnerWidget::uniqueSearchResults() const {
  3295. return _controller->uniqueChatsInSearchResults();
  3296. }
  3297. bool InnerWidget::hasHistoryInResults(not_null<History*> history) const {
  3298. using Result = std::unique_ptr<FakeRow>;
  3299. const auto inSearchResults = ranges::find(
  3300. _searchResults,
  3301. history,
  3302. [](const Result &result) { return result->item()->history(); }
  3303. ) != end(_searchResults);
  3304. if (inSearchResults) {
  3305. return true;
  3306. }
  3307. const auto inFilteredResults = ranges::find(
  3308. _filterResults,
  3309. Key(history),
  3310. &FilterResult::key
  3311. ) != end(_filterResults);
  3312. if (inFilteredResults) {
  3313. return true;
  3314. }
  3315. const auto inPeerSearchResults = ranges::find(
  3316. _peerSearchResults,
  3317. history->peer,
  3318. [](const auto &result) { return result->peer; }
  3319. ) != end(_peerSearchResults);
  3320. if (inPeerSearchResults) {
  3321. return true;
  3322. }
  3323. return false;
  3324. }
  3325. void InnerWidget::searchReceived(
  3326. std::vector<not_null<HistoryItem*>> messages,
  3327. HistoryItem *inject,
  3328. SearchRequestType type,
  3329. int fullCount) {
  3330. _searchWaiting = false;
  3331. _searchLoading = false;
  3332. const auto uniquePeers = uniqueSearchResults();
  3333. const auto withPreview = _searchWithPostsPreview;
  3334. const auto toPreview = withPreview && type.posts;
  3335. if (type.start && !type.migrated && (!withPreview || !type.posts)) {
  3336. clearSearchResults(false);
  3337. }
  3338. if (!withPreview || toPreview) {
  3339. clearPreviewResults();
  3340. }
  3341. const auto key = (!_openedForum || _searchState.inChat.topic())
  3342. ? _searchState.inChat
  3343. : Key(_openedForum->history());
  3344. if (inject
  3345. && (!_searchState.inChat
  3346. || inject->history() == _searchState.inChat.history())) {
  3347. Assert(_searchResults.empty());
  3348. Assert(!toPreview);
  3349. const auto index = int(_searchResults.size());
  3350. _searchResults.push_back(
  3351. std::make_unique<FakeRow>(
  3352. key,
  3353. inject,
  3354. [=] { repaintSearchResult(index); }));
  3355. trackResultsHistory(inject->history());
  3356. ++fullCount;
  3357. }
  3358. auto &results = toPreview ? _previewResults : _searchResults;
  3359. for (const auto &item : messages) {
  3360. const auto history = item->history();
  3361. if (toPreview || !uniquePeers || !hasHistoryInResults(history)) {
  3362. const auto index = int(results.size());
  3363. const auto repaint = toPreview
  3364. ? Fn<void()>([=] { repaintSearchResult(index); })
  3365. : [=] { repaintPreviewResult(index); };
  3366. results.push_back(
  3367. std::make_unique<FakeRow>(key, item, repaint));
  3368. trackResultsHistory(history);
  3369. if (!toPreview && uniquePeers && !history->unreadCountKnown()) {
  3370. history->owner().histories().requestDialogEntry(history);
  3371. } else if (toPreview && results.size() >= kPreviewPostsLimit) {
  3372. break;
  3373. }
  3374. }
  3375. }
  3376. if (type.migrated) {
  3377. _searchedMigratedCount = fullCount;
  3378. } else if (!withPreview || !toPreview) {
  3379. _searchedCount = fullCount;
  3380. } else {
  3381. _previewCount = fullCount;
  3382. }
  3383. refresh();
  3384. }
  3385. void InnerWidget::peerSearchReceived(
  3386. const QString &query,
  3387. const QVector<MTPPeer> &my,
  3388. const QVector<MTPPeer> &result) {
  3389. if (_state != WidgetState::Filtered) {
  3390. return;
  3391. }
  3392. _peerSearchQuery = query.toLower().trimmed();
  3393. _peerSearchResults.clear();
  3394. _peerSearchResults.reserve(result.size());
  3395. for (const auto &mtpPeer : my) {
  3396. if (const auto peer = session().data().peerLoaded(peerFromMTP(mtpPeer))) {
  3397. appendToFiltered(peer->owner().history(peer));
  3398. } else {
  3399. LOG(("API Error: "
  3400. "user %1 was not loaded in InnerWidget::peopleReceived()"
  3401. ).arg(peerFromMTP(mtpPeer).value));
  3402. }
  3403. }
  3404. for (const auto &mtpPeer : result) {
  3405. if (const auto peer = session().data().peerLoaded(peerFromMTP(mtpPeer))) {
  3406. if (const auto history = peer->owner().historyLoaded(peer)) {
  3407. if (history->inChatList()) {
  3408. continue; // skip existing chats
  3409. }
  3410. }
  3411. _peerSearchResults.push_back(std::make_unique<PeerSearchResult>(
  3412. peer));
  3413. } else {
  3414. LOG(("API Error: "
  3415. "user %1 was not loaded in InnerWidget::peopleReceived()"
  3416. ).arg(peerFromMTP(mtpPeer).value));
  3417. }
  3418. }
  3419. refresh();
  3420. }
  3421. Data::Folder *InnerWidget::shownFolder() const {
  3422. return _openedFolder;
  3423. }
  3424. Data::Forum *InnerWidget::shownForum() const {
  3425. return _openedForum;
  3426. }
  3427. bool InnerWidget::needCollapsedRowsRefresh() const {
  3428. const auto archive = !_shownList->empty()
  3429. ? _shownList->begin()->get()->folder()
  3430. : nullptr;
  3431. const auto collapsedHasArchive = !_collapsedRows.empty()
  3432. && (_collapsedRows.back()->folder != nullptr);
  3433. const auto archiveIsCollapsed = (archive != nullptr)
  3434. && session().settings().archiveCollapsed();
  3435. const auto archiveIsInMainMenu = (archive != nullptr)
  3436. && session().settings().archiveInMainMenu();
  3437. return archiveIsInMainMenu
  3438. ? (collapsedHasArchive || !_skipTopDialog)
  3439. : archiveIsCollapsed
  3440. ? (!collapsedHasArchive || !_skipTopDialog)
  3441. : (collapsedHasArchive || _skipTopDialog);
  3442. }
  3443. void InnerWidget::editOpenedFilter() {
  3444. if (_filterId > 0) {
  3445. EditExistingFilter(_controller, _filterId);
  3446. }
  3447. }
  3448. void InnerWidget::refresh(bool toTop) {
  3449. if (!_geometryInited) {
  3450. return;
  3451. } else if (needCollapsedRowsRefresh()) {
  3452. return refreshWithCollapsedRows(toTop);
  3453. }
  3454. refreshEmpty();
  3455. if (_searchTags) {
  3456. _searchTagsLeft = st::dialogsFilterSkip
  3457. + st::dialogsFilterPadding.x();
  3458. _searchTags->resizeToWidth(width() - 2 * _searchTagsLeft);
  3459. }
  3460. auto h = 0;
  3461. if (_state == WidgetState::Default) {
  3462. if (_shownList->empty()) {
  3463. h = st::dialogsEmptyHeight;
  3464. } else {
  3465. h = dialogsOffset() + _shownList->height();
  3466. }
  3467. } else if (_state == WidgetState::Filtered) {
  3468. if (_searchEmpty && !_searchEmpty->isHidden()) {
  3469. h = searchedOffset() + st::recentPeersEmptyHeightMin;
  3470. _searchEmpty->setMinimalHeight(st::recentPeersEmptyHeightMin);
  3471. _searchEmpty->move(0, h - st::recentPeersEmptyHeightMin);
  3472. } else if (_loadingAnimation) {
  3473. h = searchedOffset() + _loadingAnimation->height();
  3474. } else {
  3475. h = searchedOffset() + (_searchResults.size() * _st->height);
  3476. }
  3477. }
  3478. resize(width(), h);
  3479. if (toTop) {
  3480. stopReorderPinned();
  3481. jumpToTop();
  3482. preloadRowsData();
  3483. }
  3484. update();
  3485. }
  3486. void InnerWidget::refreshEmpty() {
  3487. if (_state == WidgetState::Filtered) {
  3488. const auto empty = _filterResults.empty()
  3489. && _searchResults.empty()
  3490. && _peerSearchResults.empty()
  3491. && _hashtagResults.empty();
  3492. if (_searchLoading || _searchWaiting || !empty) {
  3493. if (_searchEmpty) {
  3494. _searchEmpty->hide();
  3495. }
  3496. } else if (_searchEmptyState != _searchState) {
  3497. _searchEmptyState = _searchState;
  3498. _searchEmpty = MakeSearchEmpty(this, _searchState, [=] {
  3499. _changeSearchFilterRequests.fire(ChatTypeFilter::All);
  3500. });
  3501. if (_controller->session().data().chatsListLoaded()) {
  3502. _searchEmpty->animate();
  3503. }
  3504. } else if (_searchEmpty) {
  3505. _searchEmpty->show();
  3506. }
  3507. if ((!_searchLoading && !_searchWaiting) || !empty) {
  3508. _loadingAnimation.destroy();
  3509. } else if (!_loadingAnimation) {
  3510. _loadingAnimation = Ui::CreateLoadingDialogRowWidget(
  3511. this,
  3512. *_st,
  3513. 2);
  3514. _loadingAnimation->resizeToWidth(width());
  3515. _loadingAnimation->move(0, searchedOffset());
  3516. _loadingAnimation->show();
  3517. }
  3518. } else {
  3519. _searchEmpty.destroy();
  3520. _loadingAnimation.destroy();
  3521. _searchEmptyState = {};
  3522. }
  3523. const auto data = &session().data();
  3524. const auto state = !_shownList->empty()
  3525. ? EmptyState::None
  3526. : _savedSublists
  3527. ? (data->savedMessages().chatsList()->loaded()
  3528. ? EmptyState::EmptySavedSublists
  3529. : EmptyState::Loading)
  3530. : _openedForum
  3531. ? (_openedForum->topicsList()->loaded()
  3532. ? EmptyState::EmptyForum
  3533. : EmptyState::Loading)
  3534. : (!_filterId && data->contactsLoaded().current())
  3535. ? EmptyState::NoContacts
  3536. : (_filterId > 0) && data->chatsList()->loaded()
  3537. ? EmptyState::EmptyFolder
  3538. : EmptyState::Loading;
  3539. if (state == EmptyState::None) {
  3540. _emptyState = state;
  3541. _empty.destroy();
  3542. return;
  3543. } else if (_emptyState == state) {
  3544. _empty->setVisible(_state == WidgetState::Default);
  3545. return;
  3546. }
  3547. _emptyState = state;
  3548. auto phrase = (state == EmptyState::NoContacts)
  3549. ? tr::lng_no_chats()
  3550. : (state == EmptyState::EmptyFolder)
  3551. ? tr::lng_no_chats_filter()
  3552. : (state == EmptyState::EmptyForum)
  3553. ? tr::lng_forum_no_topics()
  3554. : (state == EmptyState::EmptySavedSublists)
  3555. ? tr::lng_no_saved_sublists()
  3556. : tr::lng_contacts_loading();
  3557. auto link = (state == EmptyState::NoContacts)
  3558. ? tr::lng_add_contact_button()
  3559. : (state == EmptyState::EmptyFolder)
  3560. ? tr::lng_filters_context_edit()
  3561. : (state == EmptyState::EmptyForum)
  3562. ? tr::lng_forum_create_topic()
  3563. : rpl::single(QString());
  3564. auto full = rpl::combine(
  3565. std::move(phrase),
  3566. std::move(link)
  3567. ) | rpl::map([](const QString &phrase, const QString &link) {
  3568. auto result = Ui::Text::WithEntities(phrase);
  3569. if (!link.isEmpty()) {
  3570. result.append("\n\n").append(Ui::Text::Link(link));
  3571. }
  3572. return result;
  3573. });
  3574. _empty.create(this, std::move(full), st::dialogsEmptyLabel);
  3575. resizeEmpty();
  3576. _empty->overrideLinkClickHandler([=] {
  3577. if (_emptyState == EmptyState::NoContacts) {
  3578. _controller->showAddContact();
  3579. } else if (_emptyState == EmptyState::EmptyFolder) {
  3580. editOpenedFilter();
  3581. } else if (_emptyState == EmptyState::EmptyForum) {
  3582. _controller->show(
  3583. Box(NewForumTopicBox, _controller, _openedForum->history()));
  3584. }
  3585. });
  3586. _empty->setVisible(_state == WidgetState::Default);
  3587. }
  3588. void InnerWidget::resizeEmpty() {
  3589. if (_empty) {
  3590. const auto skip = st::dialogsEmptySkip;
  3591. _empty->resizeToWidth(width() - 2 * skip);
  3592. _empty->move(skip, (st::dialogsEmptyHeight - _empty->height()) / 2);
  3593. }
  3594. if (_searchEmpty) {
  3595. _searchEmpty->resizeToWidth(width());
  3596. _searchEmpty->move(0, searchedOffset());
  3597. }
  3598. if (_loadingAnimation) {
  3599. _loadingAnimation->resizeToWidth(width());
  3600. _loadingAnimation->move(0, searchedOffset());
  3601. }
  3602. }
  3603. void InnerWidget::clearMouseSelection(bool clearSelection) {
  3604. _mouseSelection = false;
  3605. _lastMousePosition = std::nullopt;
  3606. _lastRowLocalMouseX = -1;
  3607. if (clearSelection) {
  3608. if (_state == WidgetState::Default) {
  3609. _collapsedSelected = -1;
  3610. _selected = nullptr;
  3611. } else if (_state == WidgetState::Filtered) {
  3612. _filteredSelected
  3613. = _peerSearchSelected
  3614. = _previewSelected
  3615. = _searchedSelected
  3616. = _hashtagSelected = -1;
  3617. }
  3618. setCursor(style::cur_default);
  3619. }
  3620. }
  3621. WidgetState InnerWidget::state() const {
  3622. return _state;
  3623. }
  3624. bool InnerWidget::hasFilteredResults() const {
  3625. return !_filterResults.empty() && _hashtagResults.empty();
  3626. }
  3627. auto InnerWidget::searchTagsChanges() const
  3628. -> rpl::producer<std::vector<Data::ReactionId>> {
  3629. return _searchTags
  3630. ? _searchTags->selectedChanges()
  3631. : rpl::never<std::vector<Data::ReactionId>>();
  3632. }
  3633. void InnerWidget::updateSearchIn() {
  3634. if (!_searchState.inChat
  3635. && _searchHashOrCashtag == HashOrCashtag::None) {
  3636. _searchIn = nullptr;
  3637. return;
  3638. } else if (!_searchIn) {
  3639. _searchIn = std::make_unique<ChatSearchIn>(this);
  3640. _searchIn->show();
  3641. _searchIn->changeFromRequests() | rpl::start_to_stream(
  3642. _changeSearchFromRequests,
  3643. _searchIn->lifetime());
  3644. _searchIn->cancelFromRequests() | rpl::start_to_stream(
  3645. _cancelSearchFromRequests,
  3646. _searchIn->lifetime());
  3647. _searchIn->cancelInRequests() | rpl::start_to_stream(
  3648. _cancelSearchRequests,
  3649. _searchIn->lifetime());
  3650. _searchIn->tabChanges() | rpl::start_to_stream(
  3651. _changeSearchTabRequests,
  3652. _searchIn->lifetime());
  3653. }
  3654. const auto sublist = _searchState.inChat.sublist();
  3655. const auto topic = _searchState.inChat.topic();
  3656. const auto peer = _searchState.inChat.owningHistory()
  3657. ? _searchState.inChat.owningHistory()->peer.get()
  3658. : _openedForum
  3659. ? _openedForum->channel().get()
  3660. : nullptr;
  3661. const auto topicIcon = !topic
  3662. ? nullptr
  3663. : topic->iconId()
  3664. ? Ui::MakeEmojiThumbnail(
  3665. &topic->owner(),
  3666. Data::SerializeCustomEmojiId(topic->iconId()))
  3667. : Ui::MakeEmojiThumbnail(
  3668. &topic->owner(),
  3669. Data::TopicIconEmojiEntity({
  3670. .title = (topic->isGeneral()
  3671. ? Data::ForumGeneralIconTitle()
  3672. : topic->title()),
  3673. .colorId = (topic->isGeneral()
  3674. ? Data::ForumGeneralIconColor(st::windowSubTextFg->c)
  3675. : topic->colorId()),
  3676. }));
  3677. const auto peerIcon = peer
  3678. ? Ui::MakeUserpicThumbnail(peer)
  3679. : sublist
  3680. ? Ui::MakeUserpicThumbnail(sublist->peer())
  3681. : nullptr;
  3682. const auto myIcon = Ui::MakeIconThumbnail(st::menuIconChats);
  3683. const auto publicIcon = (_searchHashOrCashtag != HashOrCashtag::None)
  3684. ? Ui::MakeIconThumbnail(st::menuIconChannel)
  3685. : nullptr;
  3686. const auto peerTabType = (peer && peer->isBroadcast())
  3687. ? ChatSearchPeerTabType::Channel
  3688. : (peer && (peer->isChat() || peer->isMegagroup()))
  3689. ? ChatSearchPeerTabType::Group
  3690. : ChatSearchPeerTabType::Chat;
  3691. const auto fromImage = _searchFromShown
  3692. ? Ui::MakeUserpicThumbnail(_searchFromShown)
  3693. : nullptr;
  3694. const auto fromName = _searchFromShown
  3695. ? _searchFromShown->shortName()
  3696. : QString();
  3697. _searchIn->apply({
  3698. { ChatSearchTab::ThisTopic, topicIcon },
  3699. { ChatSearchTab::ThisPeer, peerIcon },
  3700. { ChatSearchTab::MyMessages, myIcon },
  3701. { ChatSearchTab::PublicPosts, publicIcon },
  3702. }, _searchState.tab, peerTabType, fromImage, fromName);
  3703. }
  3704. void InnerWidget::repaintSearchResult(int index) {
  3705. rtlupdate(
  3706. 0,
  3707. searchedOffset() + index * _st->height,
  3708. width(),
  3709. _st->height);
  3710. }
  3711. void InnerWidget::repaintPreviewResult(int index) {
  3712. rtlupdate(
  3713. 0,
  3714. previewOffset() + index * _st->height,
  3715. width(),
  3716. _st->height);
  3717. }
  3718. bool InnerWidget::computeSearchWithPostsPreview() const {
  3719. return (_searchHashOrCashtag != HashOrCashtag::None)
  3720. && (_searchState.tab == ChatSearchTab::MyMessages);
  3721. }
  3722. void InnerWidget::clearFilter() {
  3723. if (_state == WidgetState::Filtered || _searchState.inChat) {
  3724. if (_searchState.inChat) {
  3725. setState(WidgetState::Filtered);
  3726. } else {
  3727. setState(WidgetState::Default);
  3728. }
  3729. _hashtagResults.clear();
  3730. _filterResults.clear();
  3731. _filterResultsGlobal.clear();
  3732. _peerSearchResults.clear();
  3733. _searchResults.clear();
  3734. _previewResults.clear();
  3735. _trackedHistories.clear();
  3736. _trackedLifetime.destroy();
  3737. _filter = QString();
  3738. refresh(true);
  3739. }
  3740. }
  3741. void InnerWidget::setState(WidgetState state) {
  3742. _state = state;
  3743. }
  3744. void InnerWidget::selectSkip(int32 direction) {
  3745. clearMouseSelection();
  3746. if (_state == WidgetState::Default) {
  3747. const auto skip = _skipTopDialog ? 1 : 0;
  3748. if (_collapsedRows.empty() && _shownList->size() <= skip) {
  3749. return;
  3750. }
  3751. if (_collapsedSelected < 0 && !_selected) {
  3752. if (!_collapsedRows.empty()) {
  3753. _collapsedSelected = 0;
  3754. } else {
  3755. _selected = (_shownList->cbegin() + skip)->get();
  3756. }
  3757. } else {
  3758. auto cur = (_collapsedSelected >= 0)
  3759. ? _collapsedSelected
  3760. : int(_collapsedRows.size()
  3761. + (_shownList->cfind(_selected)
  3762. - _shownList->cbegin()
  3763. - skip));
  3764. cur = std::clamp(
  3765. cur + direction,
  3766. 0,
  3767. static_cast<int>(_collapsedRows.size()
  3768. + _shownList->size()
  3769. - skip
  3770. - 1));
  3771. if (cur < _collapsedRows.size()) {
  3772. _collapsedSelected = cur;
  3773. _selected = nullptr;
  3774. } else {
  3775. _collapsedSelected = -1;
  3776. _selected = *(_shownList->cbegin() + skip + cur - _collapsedRows.size());
  3777. }
  3778. }
  3779. scrollToDefaultSelected();
  3780. } else if (_state == WidgetState::Filtered) {
  3781. if (_hashtagResults.empty()
  3782. && _filterResults.empty()
  3783. && _peerSearchResults.empty()
  3784. && _previewResults.empty()
  3785. && _searchResults.empty()) {
  3786. return;
  3787. }
  3788. if ((_hashtagSelected < 0 || _hashtagSelected >= _hashtagResults.size())
  3789. && (_filteredSelected < 0 || _filteredSelected >= _filterResults.size())
  3790. && (_peerSearchSelected < 0 || _peerSearchSelected >= _peerSearchResults.size())
  3791. && (_previewSelected < 0 || _previewSelected >= _previewResults.size())
  3792. && (_searchedSelected < 0 || _searchedSelected >= _searchResults.size())) {
  3793. if (_hashtagResults.empty() && _filterResults.empty() && _peerSearchResults.empty() && _previewResults.empty()) {
  3794. _searchedSelected = 0;
  3795. } else if (_hashtagResults.empty() && _filterResults.empty() && _peerSearchResults.empty()) {
  3796. _previewSelected = 0;
  3797. } else if (_hashtagResults.empty() && _filterResults.empty()) {
  3798. _peerSearchSelected = 0;
  3799. } else if (_hashtagResults.empty()) {
  3800. _filteredSelected = 0;
  3801. } else {
  3802. _hashtagSelected = 0;
  3803. }
  3804. } else {
  3805. int32 cur = base::in_range(_hashtagSelected, 0, _hashtagResults.size())
  3806. ? _hashtagSelected
  3807. : base::in_range(_filteredSelected, 0, _filterResults.size())
  3808. ? (_hashtagResults.size() + _filteredSelected)
  3809. : base::in_range(_peerSearchSelected, 0, _peerSearchResults.size())
  3810. ? (_peerSearchSelected + _filterResults.size() + _hashtagResults.size())
  3811. : base::in_range(_previewSelected, 0, _previewResults.size())
  3812. ? (_previewSelected + _peerSearchResults.size() + _filterResults.size() + _hashtagResults.size())
  3813. : (_searchedSelected + _previewResults.size() + _peerSearchResults.size() + _filterResults.size() + _hashtagResults.size());
  3814. cur = std::clamp(
  3815. cur + direction,
  3816. 0,
  3817. static_cast<int>(_hashtagResults.size()
  3818. + _filterResults.size()
  3819. + _peerSearchResults.size()
  3820. + _previewResults.size()
  3821. + _searchResults.size()) - 1);
  3822. if (cur < _hashtagResults.size()) {
  3823. _hashtagSelected = cur;
  3824. _filteredSelected = _peerSearchSelected = _previewSelected = _searchedSelected = -1;
  3825. } else if (cur < _hashtagResults.size() + _filterResults.size()) {
  3826. _filteredSelected = cur - _hashtagResults.size();
  3827. _hashtagSelected = _peerSearchSelected = _previewSelected = _searchedSelected = -1;
  3828. } else if (cur < _hashtagResults.size() + _filterResults.size() + _peerSearchResults.size()) {
  3829. _peerSearchSelected = cur - _hashtagResults.size() - _filterResults.size();
  3830. _hashtagSelected = _filteredSelected = _previewSelected = _searchedSelected = -1;
  3831. } else if (cur < _hashtagResults.size() + _filterResults.size() + _peerSearchResults.size() + _previewResults.size()) {
  3832. _previewSelected = cur - _hashtagResults.size() - _filterResults.size() - _peerSearchResults.size();
  3833. _hashtagSelected = _filteredSelected = _peerSearchSelected = _searchedSelected = -1;
  3834. } else {
  3835. _searchedSelected = cur - _hashtagResults.size() - _filterResults.size() - _peerSearchResults.size() - _previewResults.size();
  3836. _hashtagSelected = _filteredSelected = _peerSearchSelected = _previewSelected = -1;
  3837. }
  3838. }
  3839. if (base::in_range(_hashtagSelected, 0, _hashtagResults.size())) {
  3840. const auto from = _hashtagSelected * st::mentionHeight;
  3841. scrollToItem(from, st::mentionHeight);
  3842. } else if (base::in_range(_filteredSelected, 0, _filterResults.size())) {
  3843. const auto &result = _filterResults[_filteredSelected];
  3844. const auto from = filteredOffset() + result.top;
  3845. scrollToItem(from, result.row->height());
  3846. } else if (base::in_range(_peerSearchSelected, 0, _peerSearchResults.size())) {
  3847. const auto from = peerSearchOffset()
  3848. + _peerSearchSelected * st::dialogsRowHeight
  3849. + (_peerSearchSelected ? 0 : -st::searchedBarHeight);
  3850. const auto height = st::dialogsRowHeight
  3851. + (_peerSearchSelected ? 0 : st::searchedBarHeight);
  3852. scrollToItem(from, height);
  3853. } else if (base::in_range(_previewSelected, 0, _previewResults.size())) {
  3854. const auto from = previewOffset()
  3855. + _previewSelected * _st->height
  3856. + (_previewSelected ? 0 : -st::searchedBarHeight);
  3857. const auto height = _st->height
  3858. + (_previewSelected ? 0 : st::searchedBarHeight);
  3859. scrollToItem(from, height);
  3860. } else {
  3861. const auto from = searchedOffset()
  3862. + _searchedSelected * _st->height
  3863. + (_searchedSelected ? 0 : -st::searchedBarHeight);
  3864. const auto height = _st->height
  3865. + (_searchedSelected ? 0 : st::searchedBarHeight);
  3866. scrollToItem(from, height);
  3867. }
  3868. }
  3869. update();
  3870. }
  3871. void InnerWidget::scrollToEntry(const RowDescriptor &entry) {
  3872. if (_state == WidgetState::Default) {
  3873. if (auto row = _shownList->getRow(entry.key)) {
  3874. scrollToItem(dialogsOffset() + row->top(), row->height());
  3875. }
  3876. } else if (_state == WidgetState::Filtered) {
  3877. for (auto i = 0, c = int(_previewResults.size()); i != c; ++i) {
  3878. if (isSearchResultActive(_previewResults[i].get(), entry)) {
  3879. const auto from = previewOffset() + i * _st->height;
  3880. scrollToItem(from, _st->height);
  3881. return;
  3882. }
  3883. }
  3884. for (auto i = 0, c = int(_searchResults.size()); i != c; ++i) {
  3885. if (isSearchResultActive(_searchResults[i].get(), entry)) {
  3886. const auto from = searchedOffset() + i * _st->height;
  3887. scrollToItem(from, _st->height);
  3888. return;
  3889. }
  3890. }
  3891. for (auto i = 0, c = int(_filterResults.size()); i != c; ++i) {
  3892. auto &result = _filterResults[i];
  3893. if (result.key() == entry.key) {
  3894. const auto from = filteredOffset() + result.top;
  3895. scrollToItem(from, result.row->height());
  3896. return;
  3897. }
  3898. }
  3899. }
  3900. }
  3901. void InnerWidget::selectSkipPage(int32 pixels, int32 direction) {
  3902. clearMouseSelection();
  3903. int toSkip = pixels / _st->height;
  3904. if (_state != WidgetState::Default) {
  3905. selectSkip(direction * toSkip);
  3906. return;
  3907. }
  3908. const auto skip = _skipTopDialog ? 1 : 0;
  3909. if (!_selected) {
  3910. if (direction > 0 && _shownList->size() > skip) {
  3911. _selected = (_shownList->cbegin() + skip)->get();
  3912. _collapsedSelected = -1;
  3913. } else {
  3914. return;
  3915. }
  3916. }
  3917. if (direction > 0) {
  3918. for (auto i = _shownList->cfind(_selected), end = _shownList->cend()
  3919. ; i != end && (toSkip--)
  3920. ; ++i) {
  3921. _selected = *i;
  3922. }
  3923. } else {
  3924. for (auto i = _shownList->cfind(_selected), b = _shownList->cbegin()
  3925. ; i != b && (*i)->index() > skip && (toSkip--)
  3926. ;) {
  3927. _selected = *(--i);
  3928. }
  3929. if (toSkip && !_collapsedRows.empty()) {
  3930. _collapsedSelected = std::max(int(_collapsedRows.size()) - toSkip, 0);
  3931. _selected = nullptr;
  3932. }
  3933. }
  3934. scrollToDefaultSelected();
  3935. update();
  3936. }
  3937. void InnerWidget::scrollToItem(int top, int height) {
  3938. _mustScrollTo.fire({ top, top + height });
  3939. }
  3940. void InnerWidget::scrollToDefaultSelected() {
  3941. Expects(_state == WidgetState::Default);
  3942. if (_collapsedSelected >= 0) {
  3943. const auto from = _collapsedSelected * st::dialogsImportantBarHeight;
  3944. scrollToItem(from, st::dialogsImportantBarHeight);
  3945. } else if (_selected) {
  3946. const auto from = dialogsOffset() + _selected->top();
  3947. scrollToItem(from, _selected->height());
  3948. }
  3949. }
  3950. void InnerWidget::preloadRowsData() {
  3951. if (!parentWidget()) {
  3952. return;
  3953. }
  3954. auto yFrom = _visibleTop;
  3955. auto yTo = _visibleTop + (_visibleBottom - _visibleTop) * (PreloadHeightsCount + 1);
  3956. if (_state == WidgetState::Default) {
  3957. auto otherStart = _shownList->size() * _st->height;
  3958. if (yFrom < otherStart) {
  3959. for (auto i = _shownList->findByY(yFrom), end = _shownList->cend()
  3960. ; i != end
  3961. ; ++i) {
  3962. if (((*i)->index() * _st->height) >= yTo) {
  3963. break;
  3964. }
  3965. (*i)->entry()->chatListPreloadData();
  3966. }
  3967. yFrom = 0;
  3968. } else {
  3969. yFrom -= otherStart;
  3970. }
  3971. yTo -= otherStart;
  3972. } else if (_state == WidgetState::Filtered) {
  3973. auto from = (yFrom - filteredOffset()) / _st->height;
  3974. if (from < 0) from = 0;
  3975. if (from < _filterResults.size()) {
  3976. const auto to = std::min(
  3977. ((yTo - filteredOffset()) / _st->height) + 1,
  3978. int(_filterResults.size()));
  3979. for (; from < to; ++from) {
  3980. _filterResults[from].key().entry()->chatListPreloadData();
  3981. }
  3982. }
  3983. from = (yFrom - peerSearchOffset()) / st::dialogsRowHeight;
  3984. if (from < 0) from = 0;
  3985. if (from < _peerSearchResults.size()) {
  3986. const auto to = std::min(
  3987. ((yTo - peerSearchOffset()) / st::dialogsRowHeight) + 1,
  3988. int(_peerSearchResults.size()));
  3989. for (; from < to; ++from) {
  3990. _peerSearchResults[from]->peer->loadUserpic();
  3991. }
  3992. }
  3993. from = (yFrom - previewOffset()) / _st->height;
  3994. if (from < 0) from = 0;
  3995. if (from < _previewResults.size()) {
  3996. const auto to = std::min(
  3997. ((yTo - previewOffset()) / _st->height) + 1,
  3998. int(_previewResults.size()));
  3999. for (; from < to; ++from) {
  4000. _previewResults[from]->item()->history()->peer->loadUserpic();
  4001. }
  4002. }
  4003. from = (yFrom - searchedOffset()) / _st->height;
  4004. if (from < 0) from = 0;
  4005. if (from < _searchResults.size()) {
  4006. const auto to = std::min(
  4007. ((yTo - searchedOffset()) / _st->height) + 1,
  4008. int(_searchResults.size()));
  4009. for (; from < to; ++from) {
  4010. _searchResults[from]->item()->history()->peer->loadUserpic();
  4011. }
  4012. }
  4013. }
  4014. }
  4015. bool InnerWidget::chooseCollapsedRow(Qt::KeyboardModifiers modifiers) {
  4016. if (_state != WidgetState::Default) {
  4017. return false;
  4018. } else if ((_collapsedSelected < 0)
  4019. || (_collapsedSelected >= _collapsedRows.size())) {
  4020. return false;
  4021. }
  4022. const auto &row = _collapsedRows[_collapsedSelected];
  4023. Assert(row->folder != nullptr);
  4024. _controller->openFolder(row->folder);
  4025. return true;
  4026. }
  4027. void InnerWidget::switchToFilter(FilterId filterId) {
  4028. if (_controller->windowId().type != Window::SeparateType::Primary) {
  4029. return;
  4030. }
  4031. const auto &list = session().data().chatsFilters().list();
  4032. const auto filterIt = filterId
  4033. ? ranges::find(list, filterId, &Data::ChatFilter::id)
  4034. : end(list);
  4035. const auto found = (filterIt != end(list));
  4036. if (!found) {
  4037. filterId = 0;
  4038. }
  4039. if (_filterId == filterId) {
  4040. jumpToTop();
  4041. return;
  4042. }
  4043. saveChatsFilterScrollState(_filterId);
  4044. if (_openedFolder) {
  4045. _filterId = filterId;
  4046. refreshShownList();
  4047. } else {
  4048. clearSelection();
  4049. stopReorderPinned();
  4050. _filterId = filterId;
  4051. refreshShownList();
  4052. refreshWithCollapsedRows(true);
  4053. }
  4054. refreshEmpty();
  4055. {
  4056. const auto skip = found
  4057. // Don't save a scroll state for very flexible chat filters.
  4058. && (filterIt->flags() & (Data::ChatFilter::Flag::NoRead));
  4059. if (!skip) {
  4060. restoreChatsFilterScrollState(filterId);
  4061. }
  4062. }
  4063. }
  4064. void InnerWidget::jumpToTop() {
  4065. _mustScrollTo.fire({ 0, -1 });
  4066. }
  4067. void InnerWidget::saveChatsFilterScrollState(FilterId filterId) {
  4068. _chatsFilterScrollStates[filterId] = -y();
  4069. }
  4070. void InnerWidget::restoreChatsFilterScrollState(FilterId filterId) {
  4071. const auto it = _chatsFilterScrollStates.find(filterId);
  4072. if (it != end(_chatsFilterScrollStates)) {
  4073. _mustScrollTo.fire({ std::max(it->second, 0), -1 });
  4074. }
  4075. }
  4076. QImage *InnerWidget::cacheChatsFilterTag(
  4077. const Data::ChatFilter &filter,
  4078. uint8 more,
  4079. bool active) {
  4080. if (!filter.id() && !more) {
  4081. return nullptr;
  4082. }
  4083. const auto key = SerializeFilterTagsKey(filter.id(), more, active);
  4084. auto &entry = _chatsFilterTags[key];
  4085. if (!entry.frame.isNull()) {
  4086. if (!entry.context.loading) {
  4087. return &entry.frame;
  4088. }
  4089. for (const auto &[k, emoji] : entry.context.emoji) {
  4090. if (!emoji->ready()) {
  4091. return &entry.frame; // Still waiting for emoji.
  4092. }
  4093. }
  4094. }
  4095. auto roundedText = TextWithEntities();
  4096. auto colorIndex = -1;
  4097. if (filter.id()) {
  4098. roundedText = filter.title().text;
  4099. roundedText.text = roundedText.text.toUpper();
  4100. if (filter.colorIndex()) {
  4101. colorIndex = *(filter.colorIndex());
  4102. }
  4103. } else if (more > 0) {
  4104. roundedText.text = QChar('+') + QString::number(more);
  4105. colorIndex = st::colorIndexBlue;
  4106. }
  4107. if (roundedText.empty() || colorIndex < 0) {
  4108. return nullptr;
  4109. }
  4110. const auto color = Ui::EmptyUserpic::UserpicColor(colorIndex).color2;
  4111. entry.context.color = color->c;
  4112. entry.context.active = active;
  4113. entry.context.textContext = Core::TextContext({ .session = &session() });
  4114. entry.frame = Ui::ChatsFilterTag(roundedText, entry.context);
  4115. return &entry.frame;
  4116. }
  4117. bool InnerWidget::chooseHashtag() {
  4118. if (_state != WidgetState::Filtered) {
  4119. return false;
  4120. } else if ((_hashtagSelected < 0)
  4121. || (_hashtagSelected >= _hashtagResults.size())) {
  4122. return false;
  4123. }
  4124. const auto &hashtag = _hashtagResults[_hashtagSelected];
  4125. if (_hashtagDeleteSelected) {
  4126. auto recent = cRecentSearchHashtags();
  4127. for (auto i = recent.begin(); i != recent.cend();) {
  4128. if (i->first == hashtag->tag) {
  4129. i = recent.erase(i);
  4130. } else {
  4131. ++i;
  4132. }
  4133. }
  4134. cSetRecentSearchHashtags(recent);
  4135. session().local().writeRecentHashtagsAndBots();
  4136. _refreshHashtagsRequests.fire({});
  4137. selectByMouse(QCursor::pos());
  4138. } else {
  4139. session().local().saveRecentSearchHashtags('#' + hashtag->tag);
  4140. _completeHashtagRequests.fire_copy(hashtag->tag);
  4141. }
  4142. return true;
  4143. }
  4144. ChosenRow InnerWidget::computeChosenRow() const {
  4145. if (_state == WidgetState::Default) {
  4146. if ((_collapsedSelected >= 0)
  4147. && (_collapsedSelected < _collapsedRows.size())) {
  4148. const auto &row = _collapsedRows[_collapsedSelected];
  4149. Assert(row->folder != nullptr);
  4150. return {
  4151. .key = row->folder,
  4152. .message = Data::UnreadMessagePosition,
  4153. };
  4154. } else if (_selected) {
  4155. return {
  4156. .key = _selected->key(),
  4157. .message = Data::UnreadMessagePosition,
  4158. };
  4159. }
  4160. } else if (_state == WidgetState::Filtered) {
  4161. if (base::in_range(_filteredSelected, 0, _filterResults.size())) {
  4162. return {
  4163. .key = _filterResults[_filteredSelected].key(),
  4164. .message = Data::UnreadMessagePosition,
  4165. .filteredRow = true,
  4166. };
  4167. } else if (base::in_range(_peerSearchSelected, 0, _peerSearchResults.size())) {
  4168. const auto peer = _peerSearchResults[_peerSearchSelected]->peer;
  4169. return {
  4170. .key = session().data().history(peer),
  4171. .message = Data::UnreadMessagePosition
  4172. };
  4173. } else if (base::in_range(_previewSelected, 0, _previewResults.size())) {
  4174. const auto result = _previewResults[_previewSelected].get();
  4175. const auto topic = result->topic();
  4176. const auto item = result->item();
  4177. return {
  4178. .key = (topic ? (Entry*)topic : (Entry*)item->history()),
  4179. .message = item->position()
  4180. };
  4181. } else if (base::in_range(_searchedSelected, 0, _searchResults.size())) {
  4182. const auto result = _searchResults[_searchedSelected].get();
  4183. const auto topic = result->topic();
  4184. const auto item = result->item();
  4185. return {
  4186. .key = (topic ? (Entry*)topic : (Entry*)item->history()),
  4187. .message = item->position()
  4188. };
  4189. }
  4190. }
  4191. return ChosenRow();
  4192. }
  4193. bool InnerWidget::isUserpicPress() const {
  4194. return (_lastRowLocalMouseX >= 0)
  4195. && (_lastRowLocalMouseX < _st->nameLeft)
  4196. && (_collapsedSelected < 0
  4197. || _collapsedSelected >= _collapsedRows.size());
  4198. }
  4199. bool InnerWidget::isUserpicPressOnWide() const {
  4200. return isUserpicPress() && (width() > _narrowWidth);
  4201. }
  4202. bool InnerWidget::chooseRow(
  4203. Qt::KeyboardModifiers modifiers,
  4204. MsgId pressedTopicRootId) {
  4205. if (chooseHashtag()) {
  4206. return true;
  4207. } else if (_selectedMorePosts) {
  4208. if (_searchHashOrCashtag != HashOrCashtag::None) {
  4209. _changeSearchTabRequests.fire(ChatSearchTab::PublicPosts);
  4210. }
  4211. return true;
  4212. } else if (_selectedChatTypeFilter) {
  4213. _menu = base::make_unique_q<Ui::PopupMenu>(
  4214. this,
  4215. st::popupMenuWithIcons);
  4216. for (const auto tab : {
  4217. ChatTypeFilter::All,
  4218. ChatTypeFilter::Private,
  4219. ChatTypeFilter::Groups,
  4220. ChatTypeFilter::Channels,
  4221. }) {
  4222. _menu->addAction(ChatTypeFilterLabel(tab), [=] {
  4223. _changeSearchFilterRequests.fire_copy(tab);
  4224. }, (tab == _searchState.filter)
  4225. ? &st::mediaPlayerMenuCheck
  4226. : nullptr);
  4227. }
  4228. _menu->popup(QCursor::pos());
  4229. return true;
  4230. }
  4231. const auto modifyChosenRow = [&](
  4232. ChosenRow row,
  4233. Qt::KeyboardModifiers modifiers) {
  4234. row.newWindow = (modifiers & Qt::ControlModifier);
  4235. row.userpicClick = isUserpicPressOnWide();
  4236. return row;
  4237. };
  4238. auto chosen = modifyChosenRow(computeChosenRow(), modifiers);
  4239. if (chosen.key) {
  4240. if (IsServerMsgId(chosen.message.fullId.msg)) {
  4241. session().local().saveRecentSearchHashtags(_filter);
  4242. }
  4243. if (!chosen.message.fullId) {
  4244. if (const auto history = chosen.key.history()) {
  4245. if (const auto forum = history->peer->forum()) {
  4246. if (pressedTopicRootId) {
  4247. chosen.message.fullId = {
  4248. history->peer->id,
  4249. pressedTopicRootId,
  4250. };
  4251. }
  4252. }
  4253. }
  4254. }
  4255. _chosenRow.fire_copy(chosen);
  4256. return true;
  4257. }
  4258. return false;
  4259. }
  4260. RowDescriptor InnerWidget::chatListEntryBefore(
  4261. const RowDescriptor &which) const {
  4262. if (!which.key) {
  4263. return RowDescriptor();
  4264. }
  4265. if (_state == WidgetState::Default) {
  4266. if (const auto row = _shownList->getRow(which.key)) {
  4267. const auto i = _shownList->cfind(row);
  4268. if (i != _shownList->cbegin()) {
  4269. return RowDescriptor(
  4270. (*(i - 1))->key(),
  4271. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4272. }
  4273. }
  4274. return RowDescriptor();
  4275. }
  4276. const auto whichThread = which.key.thread();
  4277. if (!whichThread) {
  4278. return RowDescriptor();
  4279. }
  4280. if (!_searchResults.empty()) {
  4281. for (auto b = _searchResults.cbegin(), i = b + 1, e = _searchResults.cend(); i != e; ++i) {
  4282. if (isSearchResultActive(i->get(), which)) {
  4283. const auto j = i - 1;
  4284. return RowDescriptor(
  4285. (*j)->item()->history(),
  4286. (*j)->item()->fullId());
  4287. }
  4288. }
  4289. if (isSearchResultActive(_searchResults[0].get(), which)) {
  4290. if (_peerSearchResults.empty()) {
  4291. if (_filterResults.empty()) {
  4292. return RowDescriptor();
  4293. }
  4294. return RowDescriptor(
  4295. _filterResults.back().key(),
  4296. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4297. }
  4298. return RowDescriptor(
  4299. session().data().history(_peerSearchResults.back()->peer),
  4300. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4301. }
  4302. }
  4303. if (const auto history = whichThread->asHistory()) {
  4304. if (!_peerSearchResults.empty()
  4305. && _peerSearchResults[0]->peer == history->peer) {
  4306. if (_filterResults.empty()) {
  4307. return RowDescriptor();
  4308. }
  4309. return RowDescriptor(
  4310. _filterResults.back().key(),
  4311. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4312. }
  4313. if (!_peerSearchResults.empty()) {
  4314. for (auto b = _peerSearchResults.cbegin(), i = b + 1, e = _peerSearchResults.cend(); i != e; ++i) {
  4315. if ((*i)->peer == history->peer) {
  4316. return RowDescriptor(
  4317. session().data().history((*(i - 1))->peer),
  4318. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4319. }
  4320. }
  4321. }
  4322. }
  4323. if (_filterResults.empty() || _filterResults[0].key() == which.key) {
  4324. return RowDescriptor();
  4325. }
  4326. for (auto b = _filterResults.cbegin(), i = b + 1, e = _filterResults.cend(); i != e; ++i) {
  4327. if (i->key() == which.key) {
  4328. return RowDescriptor(
  4329. (i - 1)->key(),
  4330. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4331. }
  4332. }
  4333. return RowDescriptor();
  4334. }
  4335. RowDescriptor InnerWidget::chatListEntryAfter(
  4336. const RowDescriptor &which) const {
  4337. if (!which.key) {
  4338. return RowDescriptor();
  4339. }
  4340. if (_state == WidgetState::Default) {
  4341. if (const auto row = _shownList->getRow(which.key)) {
  4342. const auto i = _shownList->cfind(row) + 1;
  4343. if (i != _shownList->cend()) {
  4344. return RowDescriptor(
  4345. (*i)->key(),
  4346. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4347. }
  4348. }
  4349. return RowDescriptor();
  4350. }
  4351. const auto whichThread = which.key.thread();
  4352. if (!whichThread) {
  4353. return RowDescriptor();
  4354. }
  4355. for (auto i = _searchResults.cbegin(), e = _searchResults.cend(); i != e; ++i) {
  4356. if (isSearchResultActive(i->get(), which)) {
  4357. if (++i != e) {
  4358. return RowDescriptor(
  4359. (*i)->item()->history(),
  4360. (*i)->item()->fullId());
  4361. }
  4362. return RowDescriptor();
  4363. }
  4364. }
  4365. if (const auto history = whichThread->asHistory()) {
  4366. for (auto i = _peerSearchResults.cbegin(), e = _peerSearchResults.cend(); i != e; ++i) {
  4367. if ((*i)->peer == history->peer) {
  4368. ++i;
  4369. if (i != e) {
  4370. return RowDescriptor(
  4371. session().data().history((*i)->peer),
  4372. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4373. } else if (!_searchResults.empty()) {
  4374. return RowDescriptor(
  4375. _searchResults.front()->item()->history(),
  4376. _searchResults.front()->item()->fullId());
  4377. }
  4378. return RowDescriptor();
  4379. }
  4380. }
  4381. }
  4382. for (auto i = _filterResults.cbegin(), e = _filterResults.cend(); i != e; ++i) {
  4383. if ((*i).key() == which.key) {
  4384. ++i;
  4385. if (i != e) {
  4386. return RowDescriptor(
  4387. (*i).key(),
  4388. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4389. } else if (!_peerSearchResults.empty()) {
  4390. return RowDescriptor(
  4391. session().data().history(_peerSearchResults.front()->peer),
  4392. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4393. } else if (!_searchResults.empty()) {
  4394. return RowDescriptor(
  4395. _searchResults.front()->item()->history(),
  4396. _searchResults.front()->item()->fullId());
  4397. }
  4398. return RowDescriptor();
  4399. }
  4400. }
  4401. return RowDescriptor();
  4402. }
  4403. RowDescriptor InnerWidget::chatListEntryFirst() const {
  4404. if (_state == WidgetState::Default) {
  4405. const auto i = _shownList->cbegin();
  4406. if (i != _shownList->cend()) {
  4407. return RowDescriptor(
  4408. (*i)->key(),
  4409. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4410. }
  4411. return RowDescriptor();
  4412. } else if (!_filterResults.empty()) {
  4413. return RowDescriptor(
  4414. _filterResults.front().key(),
  4415. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4416. } else if (!_peerSearchResults.empty()) {
  4417. return RowDescriptor(
  4418. session().data().history(_peerSearchResults.front()->peer),
  4419. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4420. } else if (!_searchResults.empty()) {
  4421. return RowDescriptor(
  4422. _searchResults.front()->item()->history(),
  4423. _searchResults.front()->item()->fullId());
  4424. }
  4425. return RowDescriptor();
  4426. }
  4427. RowDescriptor InnerWidget::chatListEntryLast() const {
  4428. if (_state == WidgetState::Default) {
  4429. const auto i = _shownList->cend();
  4430. if (i != _shownList->cbegin()) {
  4431. return RowDescriptor(
  4432. (*(i - 1))->key(),
  4433. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4434. }
  4435. return RowDescriptor();
  4436. } else if (!_searchResults.empty()) {
  4437. return RowDescriptor(
  4438. _searchResults.back()->item()->history(),
  4439. _searchResults.back()->item()->fullId());
  4440. } else if (!_peerSearchResults.empty()) {
  4441. return RowDescriptor(
  4442. session().data().history(_peerSearchResults.back()->peer),
  4443. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4444. } else if (!_filterResults.empty()) {
  4445. return RowDescriptor(
  4446. _filterResults.back().key(),
  4447. FullMsgId(PeerId(), ShowAtUnreadMsgId));
  4448. }
  4449. return RowDescriptor();
  4450. }
  4451. void InnerWidget::setupOnlineStatusCheck() {
  4452. session().changes().peerUpdates(
  4453. Data::PeerUpdate::Flag::OnlineStatus
  4454. | Data::PeerUpdate::Flag::GroupCall
  4455. | Data::PeerUpdate::Flag::MessagesTTL
  4456. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  4457. const auto &peer = update.peer;
  4458. if (const auto user = peer->asUser()) {
  4459. if (user->isSelf()) {
  4460. return;
  4461. }
  4462. if (const auto history = session().data().historyLoaded(user)) {
  4463. updateRowCornerStatusShown(history);
  4464. }
  4465. } else if (const auto group = peer->asMegagroup()) {
  4466. if (const auto history = session().data().historyLoaded(group)) {
  4467. updateRowCornerStatusShown(history);
  4468. }
  4469. } else if (peer->messagesTTL()) {
  4470. if (const auto history = session().data().historyLoaded(peer)) {
  4471. updateRowCornerStatusShown(history);
  4472. }
  4473. }
  4474. }, lifetime());
  4475. }
  4476. void InnerWidget::repaintDialogRowCornerStatus(not_null<History*> history) {
  4477. const auto user = history->peer->isUser();
  4478. const auto size = user
  4479. ? st::dialogsOnlineBadgeSize
  4480. : st::dialogsCallBadgeSize;
  4481. const auto stroke = st::dialogsOnlineBadgeStroke;
  4482. const auto skip = user
  4483. ? st::dialogsOnlineBadgeSkip
  4484. : st::dialogsCallBadgeSkip;
  4485. const auto updateRect = QRect(
  4486. _st->photoSize - skip.x() - size,
  4487. _st->photoSize - skip.y() - size,
  4488. size,
  4489. size
  4490. ).marginsAdded(
  4491. { stroke, stroke, stroke, stroke }
  4492. ).translated(
  4493. st::defaultDialogRow.padding.left(),
  4494. st::defaultDialogRow.padding.top()
  4495. );
  4496. const auto ttlUpdateRect = !history->peer->messagesTTL()
  4497. ? QRect()
  4498. : Dialogs::CornerBadgeTTLRect(
  4499. _st->photoSize
  4500. ).translated(
  4501. st::defaultDialogRow.padding.left(),
  4502. st::defaultDialogRow.padding.top()
  4503. );
  4504. updateDialogRow(
  4505. RowDescriptor(
  4506. history,
  4507. FullMsgId()),
  4508. updateRect.united(ttlUpdateRect),
  4509. UpdateRowSection::Default | UpdateRowSection::Filtered);
  4510. }
  4511. void InnerWidget::updateRowCornerStatusShown(not_null<History*> history) {
  4512. const auto repaint = [=] {
  4513. repaintDialogRowCornerStatus(history);
  4514. };
  4515. repaint();
  4516. const auto findRow = [&](not_null<History*> history)
  4517. -> std::pair<Row*, int> {
  4518. if (state() == WidgetState::Default) {
  4519. const auto row = _shownList->getRow({ history });
  4520. return { row, row ? defaultRowTop(row) : 0 };
  4521. }
  4522. const auto i = ranges::find(
  4523. _filterResults,
  4524. Key(history),
  4525. &FilterResult::key);
  4526. const auto index = (i - begin(_filterResults));
  4527. const auto row = (i == end(_filterResults)) ? nullptr : i->row.get();
  4528. return { row, filteredOffset() + index * _st->height };
  4529. };
  4530. if (const auto &[row, top] = findRow(history); row != nullptr) {
  4531. const auto visible = (top < _visibleBottom)
  4532. && (top + _st->height > _visibleTop);
  4533. row->updateCornerBadgeShown(
  4534. history->peer,
  4535. visible ? Fn<void()>(crl::guard(this, repaint)) : nullptr);
  4536. }
  4537. }
  4538. RowDescriptor InnerWidget::resolveChatNext(RowDescriptor from) const {
  4539. const auto row = from.key ? from : _controller->activeChatEntryCurrent();
  4540. return row.key
  4541. ? computeJump(
  4542. chatListEntryAfter(row),
  4543. JumpSkip::NextOrEnd)
  4544. : row;
  4545. }
  4546. RowDescriptor InnerWidget::resolveChatPrevious(RowDescriptor from) const {
  4547. const auto row = from.key ? from : _controller->activeChatEntryCurrent();
  4548. return row.key
  4549. ? computeJump(
  4550. chatListEntryBefore(row),
  4551. JumpSkip::PreviousOrBegin)
  4552. : row;
  4553. }
  4554. void InnerWidget::setupShortcuts() {
  4555. Shortcuts::Requests(
  4556. ) | rpl::filter([=] {
  4557. return isActiveWindow()
  4558. && !_controller->isLayerShown()
  4559. && !_controller->window().locked()
  4560. && !_childListShown.current().shown
  4561. && !_chatPreviewRow.key;
  4562. }) | rpl::start_with_next([=](not_null<Shortcuts::Request*> request) {
  4563. using Command = Shortcuts::Command;
  4564. const auto row = _controller->activeChatEntryCurrent();
  4565. // Those should be computed before the call to request->handle.
  4566. const auto previous = row.key
  4567. ? computeJump(
  4568. chatListEntryBefore(row),
  4569. JumpSkip::PreviousOrBegin)
  4570. : row;
  4571. const auto next = row.key
  4572. ? computeJump(
  4573. chatListEntryAfter(row),
  4574. JumpSkip::NextOrEnd)
  4575. : row;
  4576. const auto first = [&] {
  4577. const auto to = chatListEntryFirst();
  4578. const auto jump = computeJump(to, JumpSkip::NextOrOriginal);
  4579. return (to == row || jump == row || to == previous) ? to : jump;
  4580. }();
  4581. const auto last = [&] {
  4582. const auto to = chatListEntryLast();
  4583. const auto jump = computeJump(to, JumpSkip::PreviousOrOriginal);
  4584. return (to == row || jump == row || to == next) ? to : jump;
  4585. }();
  4586. if (row.key) {
  4587. request->check(Command::ChatPrevious) && request->handle([=] {
  4588. return jumpToDialogRow(previous);
  4589. });
  4590. request->check(Command::ChatNext) && request->handle([=] {
  4591. return jumpToDialogRow(next);
  4592. });
  4593. } else if (_state == WidgetState::Default
  4594. ? !_shownList->empty()
  4595. : !_filterResults.empty()) {
  4596. request->check(Command::ChatNext) && request->handle([=] {
  4597. return jumpToDialogRow(first);
  4598. });
  4599. }
  4600. request->check(Command::ChatFirst) && request->handle([=] {
  4601. return jumpToDialogRow(first);
  4602. });
  4603. request->check(Command::ChatLast) && request->handle([=] {
  4604. return jumpToDialogRow(last);
  4605. });
  4606. request->check(Command::ChatSelf) && request->handle([=] {
  4607. _controller->showThread(
  4608. session().data().history(session().user()),
  4609. ShowAtUnreadMsgId,
  4610. Window::SectionShow::Way::ClearStack);
  4611. return true;
  4612. });
  4613. request->check(Command::ShowArchive) && request->handle([=] {
  4614. const auto folder = session().data().folderLoaded(
  4615. Data::Folder::kId);
  4616. if (folder && !folder->chatsList()->empty()) {
  4617. const auto controller = _controller;
  4618. controller->openFolder(folder);
  4619. // Calling openFolder() could've destroyed this widget.
  4620. controller->window().hideSettingsAndLayer();
  4621. return true;
  4622. }
  4623. return false;
  4624. });
  4625. if (session().data().chatsFilters().has()) {
  4626. const auto filters = &session().data().chatsFilters();
  4627. const auto filtersCount = int(filters->list().size());
  4628. auto &&folders = ranges::views::zip(
  4629. Shortcuts::kShowFolder,
  4630. ranges::views::ints(0, ranges::unreachable));
  4631. for (const auto &[command, index] : folders) {
  4632. const auto select = (command == Command::ShowFolderLast)
  4633. ? (filtersCount - 1)
  4634. : std::clamp(index, 0, filtersCount - 1);
  4635. request->check(command) && request->handle([=] {
  4636. if (select <= filtersCount) {
  4637. _controller->setActiveChatsFilter(
  4638. filters->lookupId(select));
  4639. }
  4640. return true;
  4641. });
  4642. }
  4643. }
  4644. static const auto kPinned = {
  4645. Command::ChatPinned1,
  4646. Command::ChatPinned2,
  4647. Command::ChatPinned3,
  4648. Command::ChatPinned4,
  4649. Command::ChatPinned5,
  4650. Command::ChatPinned6,
  4651. Command::ChatPinned7,
  4652. Command::ChatPinned8,
  4653. };
  4654. auto &&pinned = ranges::views::zip(
  4655. kPinned,
  4656. ranges::views::ints(0, ranges::unreachable));
  4657. for (const auto &[command, index] : pinned) {
  4658. request->check(command) && request->handle([=, index = index] {
  4659. const auto list = (_filterId
  4660. ? session().data().chatsFilters().chatsList(_filterId)
  4661. : session().data().chatsList()
  4662. )->indexed();
  4663. const auto count = Dialogs::PinnedDialogsCount(
  4664. _filterId,
  4665. list);
  4666. if (index >= count) {
  4667. return false;
  4668. }
  4669. const auto skip = Dialogs::FixedOnTopDialogsCount(list);
  4670. const auto row = *(list->cbegin() + skip + index);
  4671. return jumpToDialogRow({ row->key(), FullMsgId() });
  4672. });
  4673. }
  4674. request->check(Command::FolderNext) && request->handle([=] {
  4675. using namespace Window;
  4676. return CheckAndJumpToNearChatsFilter(_controller, true, true);
  4677. });
  4678. request->check(Command::FolderPrevious) && request->handle([=] {
  4679. using namespace Window;
  4680. return CheckAndJumpToNearChatsFilter(_controller, false, true);
  4681. });
  4682. request->check(Command::ReadChat) && request->handle([=] {
  4683. const auto thread = _selected ? _selected->thread() : nullptr;
  4684. if (!thread) {
  4685. return false;
  4686. }
  4687. if (Window::IsUnreadThread(thread)) {
  4688. Window::MarkAsReadThread(thread);
  4689. }
  4690. return true;
  4691. });
  4692. (!_openedForum)
  4693. && request->check(Command::ArchiveChat)
  4694. && request->handle([=] {
  4695. const auto thread = _selected ? _selected->thread() : nullptr;
  4696. if (!thread) {
  4697. return false;
  4698. }
  4699. const auto history = thread->owningHistory();
  4700. const auto isArchived = history->folder()
  4701. && (history->folder()->id() == Data::Folder::kId);
  4702. Window::ToggleHistoryArchived(
  4703. _controller->uiShow(),
  4704. history,
  4705. !isArchived);
  4706. return true;
  4707. });
  4708. request->check(Command::ShowContacts) && request->handle([=] {
  4709. _controller->show(PrepareContactsBox(_controller));
  4710. return true;
  4711. });
  4712. if (session().supportMode() && row.key.history()) {
  4713. request->check(
  4714. Command::SupportScrollToCurrent
  4715. ) && request->handle([=] {
  4716. scrollToEntry(row);
  4717. return true;
  4718. });
  4719. }
  4720. }, lifetime());
  4721. }
  4722. RowDescriptor InnerWidget::computeJump(
  4723. const RowDescriptor &to,
  4724. JumpSkip skip) const {
  4725. auto result = to;
  4726. if (result.key) {
  4727. const auto down = (skip == JumpSkip::NextOrEnd)
  4728. || (skip == JumpSkip::NextOrOriginal);
  4729. const auto needSkip = [&] {
  4730. return (result.key.folder() != nullptr)
  4731. || (session().supportMode()
  4732. && !result.key.entry()->chatListBadgesState().unread);
  4733. };
  4734. while (needSkip()) {
  4735. const auto next = down
  4736. ? chatListEntryAfter(result)
  4737. : chatListEntryBefore(result);
  4738. if (next.key) {
  4739. result = next;
  4740. } else {
  4741. if (skip == JumpSkip::PreviousOrOriginal
  4742. || skip == JumpSkip::NextOrOriginal) {
  4743. result = to;
  4744. }
  4745. break;
  4746. }
  4747. }
  4748. }
  4749. return result;
  4750. }
  4751. bool InnerWidget::jumpToDialogRow(RowDescriptor to) {
  4752. if (to == chatListEntryLast()) {
  4753. _listBottomReached.fire({});
  4754. }
  4755. if (uniqueSearchResults()) {
  4756. to.fullId = FullMsgId();
  4757. }
  4758. return _controller->jumpToChatListEntry(to);
  4759. }
  4760. rpl::producer<UserId> InnerWidget::openBotMainAppRequests() const {
  4761. return _openBotMainAppRequests.events();
  4762. }
  4763. void InnerWidget::setSwipeContextData(
  4764. int64 key,
  4765. std::optional<Ui::Controls::SwipeContextData> data) {
  4766. if (!key) {
  4767. return;
  4768. }
  4769. if (!data) {
  4770. _quickActions.remove(key);
  4771. return;
  4772. }
  4773. const auto context = ensureQuickAction(key);
  4774. context->data = base::take(*data);
  4775. if (context->data.msgBareId) {
  4776. constexpr auto kStartAnimateThreshold = 0.32;
  4777. constexpr auto kResetAnimateThreshold = 0.24;
  4778. if (context->data.ratio > kStartAnimateThreshold) {
  4779. if (context->icon
  4780. && !context->icon->frameIndex()
  4781. && !context->icon->animating()) {
  4782. context->icon->animate(
  4783. [=] { update(); },
  4784. 0,
  4785. context->icon->framesCount());
  4786. }
  4787. } else if (context->data.ratio < kResetAnimateThreshold) {
  4788. if (context->icon
  4789. && context->icon->frameIndex()) {
  4790. context->icon->jumpTo(0, [=] { update(); });
  4791. }
  4792. }
  4793. update();
  4794. }
  4795. }
  4796. not_null<Ui::QuickActionContext*> InnerWidget::ensureQuickAction(int64 key) {
  4797. Expects(key != 0);
  4798. const auto it = _quickActions.find(key);
  4799. if (it == _quickActions.end()) {
  4800. return _quickActions.emplace(
  4801. key,
  4802. std::make_unique<Ui::QuickActionContext>()).first->second.get();
  4803. } else {
  4804. return it->second.get();
  4805. }
  4806. }
  4807. int64 InnerWidget::calcSwipeKey(int top) {
  4808. top -= dialogsOffset();
  4809. for (auto it = _shownList->begin(); it != _shownList->end(); ++it) {
  4810. const auto row = it->get();
  4811. const auto from = row->top();
  4812. const auto to = from + row->height();
  4813. if (top >= from && top < to) {
  4814. if (const auto peer = row->key().peer()) {
  4815. return peer->id.value;
  4816. }
  4817. return 0;
  4818. }
  4819. }
  4820. return 0;
  4821. }
  4822. void InnerWidget::prepareQuickAction(
  4823. int64 key,
  4824. Dialogs::Ui::QuickDialogAction action) {
  4825. Expects(key != 0);
  4826. const auto context = ensureQuickAction(key);
  4827. const auto peer = session().data().peer(PeerId(key));
  4828. auto name = ResolveQuickDialogLottieIconName(peer, action, _filterId);
  4829. context->icon = Lottie::MakeIcon({
  4830. .name = std::move(name),
  4831. .sizeOverride = Size(st::dialogsQuickActionSize),
  4832. });
  4833. context->action = action;
  4834. }
  4835. } // namespace Dialogs