input_field.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "ui/widgets/fields/input_field.h"
  8. #include "ui/text/text.h"
  9. #include "ui/text/text_renderer.h" // kQuoteCollapsedLines
  10. #include "ui/widgets/fields/custom_field_object.h"
  11. #include "ui/widgets/labels.h"
  12. #include "ui/widgets/popup_menu.h"
  13. #include "ui/emoji_config.h"
  14. #include "ui/ui_utility.h"
  15. #include "ui/painter.h"
  16. #include "ui/qt_object_factory.h"
  17. #include "ui/qt_weak_factory.h"
  18. #include "ui/integration.h"
  19. #include "base/invoke_queued.h"
  20. #include "base/random.h"
  21. #include "base/platform/base_platform_info.h"
  22. #include "base/qt_signal_producer.h"
  23. #include "emoji_suggestions_helper.h"
  24. #include "base/qthelp_regex.h"
  25. #include "base/qt/qt_common_adapters.h"
  26. #include "styles/style_widgets.h"
  27. #include "styles/palette.h"
  28. #include <QtCore/QMimeData>
  29. #include <QtCore/QRegularExpression>
  30. #include <QtGui/QClipboard>
  31. #include <QtGui/QTextBlock>
  32. #include <QtGui/QTextDocumentFragment>
  33. #include <QtGui/QRawFont>
  34. #include <QtWidgets/QApplication>
  35. #include <QtWidgets/QCommonStyle>
  36. #include <QtWidgets/QScrollBar>
  37. #include <QtWidgets/QTextEdit>
  38. #include <QShortcut>
  39. namespace Ui {
  40. namespace {
  41. constexpr auto kInstantReplaceRandomId = QTextFormat::UserProperty;
  42. constexpr auto kInstantReplaceWhatId = QTextFormat::UserProperty + 1;
  43. constexpr auto kInstantReplaceWithId = QTextFormat::UserProperty + 2;
  44. constexpr auto kReplaceTagId = QTextFormat::UserProperty + 3;
  45. constexpr auto kTagProperty = QTextFormat::UserProperty + 4;
  46. constexpr auto kCustomEmojiText = QTextFormat::UserProperty + 5;
  47. constexpr auto kCustomEmojiLink = QTextFormat::UserProperty + 6;
  48. constexpr auto kCustomEmojiId = QTextFormat::UserProperty + 7;
  49. constexpr auto kQuoteFormatId = QTextFormat::UserProperty + 8;
  50. constexpr auto kQuoteId = QTextFormat::UserProperty + 9;
  51. constexpr auto kPreLanguage = QTextFormat::UserProperty + 10;
  52. constexpr auto kCollapsedQuoteFormat = QTextFormat::UserObject + 1;
  53. constexpr auto kCustomEmojiFormat = QTextFormat::UserObject + 2;
  54. const auto kObjectReplacementCh = QChar(QChar::ObjectReplacementCharacter);
  55. const auto kObjectReplacement = QString::fromRawData(
  56. &kObjectReplacementCh,
  57. 1);
  58. const auto &kTagBold = InputField::kTagBold;
  59. const auto &kTagItalic = InputField::kTagItalic;
  60. const auto &kTagUnderline = InputField::kTagUnderline;
  61. const auto &kTagStrikeOut = InputField::kTagStrikeOut;
  62. const auto &kTagCode = InputField::kTagCode;
  63. const auto &kTagPre = InputField::kTagPre;
  64. const auto &kTagBlockquote = InputField::kTagBlockquote;
  65. const auto &kTagBlockquoteCollapsed = InputField::kTagBlockquoteCollapsed;
  66. const auto &kTagSpoiler = InputField::kTagSpoiler;
  67. const auto kTagCheckLinkMeta = u"^:/:/:^"_q;
  68. const auto kSoftLine = QChar::LineSeparator;
  69. const auto kHardLine = QChar::ParagraphSeparator;
  70. // We need unique tags otherwise same custom emoji would join in a single
  71. // QTextCharFormat with the same properties, including kCustomEmojiText.
  72. auto GlobalCustomEmojiCounter = 0;
  73. class InputDocument : public QTextDocument {
  74. public:
  75. InputDocument(QObject *parent, const style::InputField &st);
  76. protected:
  77. QVariant loadResource(int type, const QUrl &name) override;
  78. private:
  79. const style::InputField &_st;
  80. std::map<QUrl, QVariant> _emojiCache;
  81. rpl::lifetime _lifetime;
  82. };
  83. InputDocument::InputDocument(QObject *parent, const style::InputField &st)
  84. : QTextDocument(parent)
  85. , _st(st) {
  86. Emoji::Updated(
  87. ) | rpl::start_with_next([=] {
  88. _emojiCache.clear();
  89. }, _lifetime);
  90. }
  91. QVariant InputDocument::loadResource(int type, const QUrl &name) {
  92. if (type != QTextDocument::ImageResource
  93. || name.scheme() != qstr("emoji")) {
  94. return QTextDocument::loadResource(type, name);
  95. }
  96. const auto i = _emojiCache.find(name);
  97. if (i != _emojiCache.end()) {
  98. return i->second;
  99. }
  100. auto result = [&] {
  101. if (const auto emoji = Emoji::FromUrl(name.toDisplayString())) {
  102. const auto height = std::max(
  103. _st.style.font->height * style::DevicePixelRatio(),
  104. Emoji::GetSizeNormal());
  105. return QVariant(Emoji::SinglePixmap(emoji, height));
  106. }
  107. return QVariant();
  108. }();
  109. _emojiCache.emplace(name, result);
  110. return result;
  111. }
  112. [[nodiscard]] bool IsNewline(QChar ch) {
  113. return (ch == '\r')
  114. || (ch == '\n')
  115. || (ch == QChar(0xfdd0)) // QTextBeginningOfFrame
  116. || (ch == QChar(0xfdd1)) // QTextEndOfFrame
  117. || (ch == QChar(QChar::ParagraphSeparator))
  118. || (ch == QChar(QChar::LineSeparator));
  119. }
  120. [[nodiscard]] bool IsTagPre(QStringView tag) {
  121. return tag.startsWith(kTagPre);
  122. }
  123. [[nodiscard]] bool IsBlockTag(QStringView tag) {
  124. return (tag == kTagBlockquote)
  125. || (tag == kTagBlockquoteCollapsed)
  126. || IsTagPre(tag);
  127. }
  128. [[nodiscard]] QStringView FindBlockTag(QStringView tag) {
  129. for (const auto &tag : TextUtilities::SplitTags(tag)) {
  130. if (IsBlockTag(tag)) {
  131. return tag;
  132. }
  133. }
  134. return QStringView();
  135. }
  136. [[nodiscard]] bool HasBlockTag(QStringView tag) {
  137. return !FindBlockTag(tag).isEmpty();
  138. }
  139. [[nodiscard]] bool HasBlockTag(const QTextBlock &block) {
  140. return HasBlockTag(
  141. block.blockFormat().property(kQuoteFormatId).toString());
  142. }
  143. [[nodiscard]] bool HasSpoilerTag(QStringView tag) {
  144. return ranges::contains(TextUtilities::SplitTags(tag), kTagSpoiler);
  145. }
  146. [[nodiscard]] bool StartsWithPre(not_null<QTextDocument*> document) {
  147. const auto format = document->firstBlock().blockFormat();
  148. const auto tag = format.property(kQuoteFormatId).toString();
  149. return IsTagPre(FindBlockTag(tag));
  150. }
  151. [[nodiscard]] QString WithBlockTagRemoved(QStringView tag) {
  152. auto list = TextUtilities::SplitTags(tag);
  153. list.erase(ranges::remove_if(list, IsBlockTag), list.end());
  154. return list.isEmpty() ? QString() : TextUtilities::JoinTag(list);
  155. }
  156. [[nodiscard]] QTextBlock FindBlock(
  157. not_null<QTextDocument*> document,
  158. int id) {
  159. auto block = document->firstBlock();
  160. for (; block.isValid(); block = block.next()) {
  161. if (block.blockFormat().property(kQuoteId).toInt() == id) {
  162. return block;
  163. }
  164. }
  165. return QTextBlock();
  166. }
  167. [[nodiscard]] TextWithTags ShiftLeftBlockTag(TextWithTags text) {
  168. while (!text.tags.isEmpty() && text.tags.front().length <= 0) {
  169. text.tags.erase(text.tags.begin());
  170. }
  171. if (text.tags.isEmpty()
  172. || text.empty()
  173. || !IsNewline(text.text.front())) {
  174. return text;
  175. }
  176. auto &tag = text.tags.front();
  177. if (tag.offset > 0 || !HasBlockTag(tag.id)) {
  178. return text;
  179. }
  180. auto stripped = WithBlockTagRemoved(tag.id);
  181. if (tag.length == 1) {
  182. if (stripped.isEmpty()) {
  183. text.tags.erase(text.tags.begin());
  184. } else {
  185. tag.id = stripped;
  186. }
  187. } else {
  188. ++tag.offset;
  189. --tag.length;
  190. if (!stripped.isEmpty()) {
  191. text.tags.insert(
  192. text.tags.begin(),
  193. TextWithTags::Tag{ 0, 1, stripped });
  194. }
  195. }
  196. return text;
  197. }
  198. [[nodiscard]] TextWithTags ShiftRightBlockTag(TextWithTags text) {
  199. while (!text.tags.isEmpty() && text.tags.back().length <= 0) {
  200. text.tags.pop_back();
  201. }
  202. if (text.tags.isEmpty()
  203. || text.empty()
  204. || !IsNewline(text.text.back())) {
  205. return text;
  206. }
  207. auto &tag = text.tags.back();
  208. if (tag.offset + tag.length < text.text.size() || !HasBlockTag(tag.id)) {
  209. return text;
  210. }
  211. auto stripped = WithBlockTagRemoved(tag.id);
  212. if (tag.length == 1) {
  213. if (stripped.isEmpty()) {
  214. text.tags.pop_back();
  215. } else {
  216. tag.id = stripped;
  217. }
  218. } else {
  219. --tag.length;
  220. if (!stripped.isEmpty()) {
  221. text.tags.push_back({ int(text.text.size()) - 1, 1, stripped });
  222. }
  223. }
  224. return text;
  225. }
  226. [[nodiscard]] bool IsValidMarkdownLink(QStringView link) {
  227. return (link.indexOf('.') >= 0) || (link.indexOf(':') >= 0);
  228. }
  229. [[nodiscard]] bool IsCustomEmojiLink(QStringView link) {
  230. return link.startsWith(InputField::kCustomEmojiTagStart);
  231. }
  232. [[nodiscard]] QString MakeUniqueCustomEmojiLink(QStringView link) {
  233. if (!IsCustomEmojiLink(link)) {
  234. return link.toString();
  235. }
  236. const auto index = link.indexOf('?');
  237. return u"%1?%2"_q
  238. .arg((index < 0) ? link : base::StringViewMid(link, 0, index))
  239. .arg(++GlobalCustomEmojiCounter);
  240. }
  241. [[nodiscard]] QString DefaultTagMimeProcessor(QStringView mimeTag) {
  242. // By default drop formatting in InputField-s.
  243. return {};
  244. }
  245. [[nodiscard]] uint64 CustomEmojiIdFromLink(QStringView link) {
  246. const auto skip = InputField::kCustomEmojiTagStart.size();
  247. const auto index = link.indexOf('?', skip + 1);
  248. return base::StringViewMid(
  249. link,
  250. skip,
  251. (index <= skip) ? -1 : (index - skip)
  252. ).toULongLong();
  253. }
  254. [[nodiscard]] QString CheckFullTextTag(
  255. const TextWithTags &textWithTags,
  256. const QString &tag) {
  257. auto resultLink = QString();
  258. const auto checkingLink = (tag == kTagCheckLinkMeta);
  259. const auto &text = textWithTags.text;
  260. auto from = 0;
  261. auto till = int(text.size());
  262. const auto adjust = [&] {
  263. for (; from != till; ++from) {
  264. if (!IsNewline(text[from]) && !Text::IsSpace(text[from])) {
  265. break;
  266. }
  267. }
  268. };
  269. for (const auto &existing : textWithTags.tags) {
  270. adjust();
  271. if (existing.offset > from) {
  272. return QString();
  273. }
  274. auto found = false;
  275. for (const auto &single : TextUtilities::SplitTags(existing.id)) {
  276. const auto normalized = IsTagPre(single)
  277. ? QStringView(kTagCode)
  278. : single;
  279. if (checkingLink && IsValidMarkdownLink(single)) {
  280. if (resultLink.isEmpty()) {
  281. resultLink = single.toString();
  282. found = true;
  283. break;
  284. } else if (QStringView(resultLink) == single) {
  285. found = true;
  286. break;
  287. }
  288. return QString();
  289. } else if (!checkingLink && QStringView(tag) == normalized) {
  290. found = true;
  291. break;
  292. }
  293. }
  294. if (!found) {
  295. return QString();
  296. }
  297. from = std::clamp(existing.offset + existing.length, from, till);
  298. }
  299. while (till != from) {
  300. if (!IsNewline(text[till - 1]) && !Text::IsSpace(text[till - 1])) {
  301. break;
  302. }
  303. --till;
  304. }
  305. return (from < till) ? QString() : checkingLink ? resultLink : tag;
  306. }
  307. [[nodiscard]] bool HasFullTextTag(
  308. const TextWithTags &textWithTags,
  309. const QString &tag) {
  310. return !CheckFullTextTag(textWithTags, tag).isEmpty();
  311. }
  312. [[nodiscard]] QString ReadPreLanguageName(
  313. const QString &text,
  314. int preStart,
  315. int preLength) {
  316. auto view = QStringView(text).mid(preStart, preLength);
  317. static const auto expression = QRegularExpression(
  318. "^([a-zA-Z0-9\\+\\-]+)[\\r\\n]");
  319. const auto m = expression.match(view);
  320. return m.hasMatch() ? m.captured(1).toLower() : QString();
  321. }
  322. class RangeAccumulator {
  323. public:
  324. explicit RangeAccumulator(std::vector<InputFieldTextRange> &ranges)
  325. : _ranges(ranges) {
  326. }
  327. ~RangeAccumulator() {
  328. finish();
  329. }
  330. void add(int offset, int length) {
  331. if (_count > 0 && _ranges[_count - 1].till >= offset) {
  332. accumulate_max(_ranges[_count - 1].till, offset + length);
  333. return;
  334. }
  335. if (_count == _ranges.size()) {
  336. _ranges.push_back({ offset, offset + length });
  337. } else {
  338. _ranges[_count] = { offset, offset + length };
  339. }
  340. ++_count;
  341. }
  342. void finish() {
  343. if (_count < _ranges.size()) {
  344. _ranges.resize(_count);
  345. }
  346. }
  347. private:
  348. std::vector<InputFieldTextRange> &_ranges;
  349. int _count = 0;
  350. };
  351. class TagAccumulator {
  352. public:
  353. explicit TagAccumulator(TextWithTags::Tags &tags) : _tags(tags) {
  354. }
  355. [[nodiscard]] bool changed() const {
  356. return _changed;
  357. }
  358. [[nodiscard]] QString currentTag() const {
  359. return _currentTagId;
  360. }
  361. void feed(const QString &randomTagId, int currentPosition) {
  362. if (randomTagId == _currentTagId) {
  363. return;
  364. }
  365. if (!_currentTagId.isEmpty()) {
  366. const auto tag = TextWithTags::Tag{
  367. _currentStart,
  368. currentPosition - _currentStart,
  369. _currentTagId
  370. };
  371. if (tag.length > 0) {
  372. if (_currentTag >= _tags.size()) {
  373. _changed = true;
  374. _tags.push_back(tag);
  375. } else if (_tags[_currentTag] != tag) {
  376. _changed = true;
  377. _tags[_currentTag] = tag;
  378. }
  379. ++_currentTag;
  380. }
  381. }
  382. _currentTagId = randomTagId;
  383. _currentStart = currentPosition;
  384. }
  385. void finish() {
  386. if (_currentTag < _tags.size()) {
  387. _tags.resize(_currentTag);
  388. _changed = true;
  389. }
  390. }
  391. private:
  392. TextWithTags::Tags &_tags;
  393. bool _changed = false;
  394. int _currentTag = 0;
  395. int _currentStart = 0;
  396. QString _currentTagId;
  397. };
  398. struct TagStartExpression {
  399. QString tag;
  400. QString goodBefore;
  401. QString badAfter;
  402. QString badBefore;
  403. QString goodAfter;
  404. };
  405. constexpr auto kTagBoldIndex = 0;
  406. constexpr auto kTagItalicIndex = 1;
  407. //constexpr auto kTagUnderlineIndex = 2;
  408. constexpr auto kTagStrikeOutIndex = 2;
  409. constexpr auto kTagCodeIndex = 3;
  410. constexpr auto kTagPreIndex = 4;
  411. constexpr auto kTagSpoilerIndex = 5;
  412. constexpr auto kInvalidPosition = std::numeric_limits<int>::max() / 2;
  413. class TagSearchItem {
  414. public:
  415. enum class Edge {
  416. Open,
  417. Close,
  418. };
  419. int matchPosition(Edge edge) const {
  420. return (_position >= 0) ? _position : kInvalidPosition;
  421. }
  422. void applyOffset(int offset) {
  423. if (_position < offset) {
  424. _position = -1;
  425. }
  426. accumulate_max(_offset, offset);
  427. }
  428. void fill(
  429. const QString &text,
  430. Edge edge,
  431. const TagStartExpression &expression) {
  432. const auto length = text.size();
  433. const auto &tag = expression.tag;
  434. const auto tagLength = tag.size();
  435. const auto isGoodBefore = [&](QChar ch) {
  436. return expression.goodBefore.isEmpty()
  437. || (expression.goodBefore.indexOf(ch) >= 0);
  438. };
  439. const auto isBadAfter = [&](QChar ch) {
  440. return !expression.badAfter.isEmpty()
  441. && (expression.badAfter.indexOf(ch) >= 0);
  442. };
  443. const auto isBadBefore = [&](QChar ch) {
  444. return !expression.badBefore.isEmpty()
  445. && (expression.badBefore.indexOf(ch) >= 0);
  446. };
  447. const auto isGoodAfter = [&](QChar ch) {
  448. return expression.goodAfter.isEmpty()
  449. || (expression.goodAfter.indexOf(ch) >= 0);
  450. };
  451. const auto check = [&](Edge edge) {
  452. if (_position > 0) {
  453. const auto before = text[_position - 1];
  454. if ((edge == Edge::Open && !isGoodBefore(before))
  455. || (edge == Edge::Close && isBadBefore(before))) {
  456. return false;
  457. }
  458. }
  459. if (_position + tagLength < length) {
  460. const auto after = text[_position + tagLength];
  461. if ((edge == Edge::Open && isBadAfter(after))
  462. || (edge == Edge::Close && !isGoodAfter(after))) {
  463. return false;
  464. }
  465. }
  466. return true;
  467. };
  468. const auto edgeIndex = static_cast<int>(edge);
  469. if (_position >= 0) {
  470. if (_checked[edgeIndex]) {
  471. return;
  472. } else if (check(edge)) {
  473. _checked[edgeIndex] = true;
  474. return;
  475. } else {
  476. _checked = { { false, false } };
  477. }
  478. }
  479. while (true) {
  480. _position = text.indexOf(tag, _offset);
  481. if (_position < 0) {
  482. _offset = _position = kInvalidPosition;
  483. break;
  484. }
  485. _offset = _position + tagLength;
  486. if (check(edge)) {
  487. break;
  488. } else {
  489. continue;
  490. }
  491. }
  492. if (_position == kInvalidPosition) {
  493. _checked = { { true, true } };
  494. } else {
  495. _checked = { { false, false } };
  496. _checked[edgeIndex] = true;
  497. }
  498. }
  499. private:
  500. int _offset = 0;
  501. int _position = -1;
  502. std::array<bool, 2> _checked = { { false, false } };
  503. };
  504. const std::vector<TagStartExpression> &TagStartExpressions() {
  505. static auto cached = std::vector<TagStartExpression> {
  506. {
  507. kTagBold,
  508. TextUtilities::MarkdownBoldGoodBefore(),
  509. TextUtilities::MarkdownBoldBadAfter(),
  510. TextUtilities::MarkdownBoldBadAfter(),
  511. TextUtilities::MarkdownBoldGoodBefore()
  512. },
  513. {
  514. kTagItalic,
  515. TextUtilities::MarkdownItalicGoodBefore(),
  516. TextUtilities::MarkdownItalicBadAfter(),
  517. TextUtilities::MarkdownItalicBadAfter(),
  518. TextUtilities::MarkdownItalicGoodBefore()
  519. },
  520. //{
  521. // kTagUnderline,
  522. // TextUtilities::MarkdownUnderlineGoodBefore(),
  523. // TextUtilities::MarkdownUnderlineBadAfter(),
  524. // TextUtilities::MarkdownUnderlineBadAfter(),
  525. // TextUtilities::MarkdownUnderlineGoodBefore()
  526. //},
  527. {
  528. kTagStrikeOut,
  529. TextUtilities::MarkdownStrikeOutGoodBefore(),
  530. TextUtilities::MarkdownStrikeOutBadAfter(),
  531. TextUtilities::MarkdownStrikeOutBadAfter(),
  532. QString(),
  533. },
  534. {
  535. kTagCode,
  536. TextUtilities::MarkdownCodeGoodBefore(),
  537. TextUtilities::MarkdownCodeBadAfter(),
  538. TextUtilities::MarkdownCodeBadAfter(),
  539. TextUtilities::MarkdownCodeGoodBefore()
  540. },
  541. {
  542. kTagPre,
  543. TextUtilities::MarkdownPreGoodBefore(),
  544. TextUtilities::MarkdownPreBadAfter(),
  545. TextUtilities::MarkdownPreBadAfter(),
  546. TextUtilities::MarkdownPreGoodBefore()
  547. },
  548. {
  549. kTagSpoiler,
  550. TextUtilities::MarkdownSpoilerGoodBefore(),
  551. TextUtilities::MarkdownSpoilerBadAfter(),
  552. TextUtilities::MarkdownSpoilerBadAfter(),
  553. TextUtilities::MarkdownSpoilerGoodBefore()
  554. },
  555. };
  556. return cached;
  557. }
  558. const std::map<QString, int> &TagIndices() {
  559. static auto cached = std::map<QString, int> {
  560. { kTagBold, kTagBoldIndex },
  561. { kTagItalic, kTagItalicIndex },
  562. //{ kTagUnderline, kTagUnderlineIndex },
  563. { kTagStrikeOut, kTagStrikeOutIndex },
  564. { kTagCode, kTagCodeIndex },
  565. { kTagPre, kTagPreIndex },
  566. { kTagSpoiler, kTagSpoilerIndex },
  567. };
  568. return cached;
  569. }
  570. bool DoesTagFinishByNewline(const QString &tag) {
  571. return (tag == kTagCode);
  572. }
  573. class MarkdownTagAccumulator {
  574. public:
  575. using Edge = TagSearchItem::Edge;
  576. MarkdownTagAccumulator(std::vector<InputField::MarkdownTag> *tags)
  577. : _tags(tags)
  578. , _expressions(TagStartExpressions())
  579. , _tagIndices(TagIndices())
  580. , _items(_expressions.size()) {
  581. }
  582. // Here we use the fact that text either contains only emoji
  583. // { adjustedTextLength = text.size() * (emojiLength - 1) }
  584. // or contains no emoji at all and can have tag edges in the middle
  585. // { adjustedTextLength = 0 }.
  586. //
  587. // Otherwise we would have to pass emoji positions inside text.
  588. void feed(
  589. const QString &text,
  590. int adjustedTextLength,
  591. const QString &textTag) {
  592. if (!_tags) {
  593. return;
  594. }
  595. const auto guard = gsl::finally([&] {
  596. _currentInternalLength += text.size();
  597. _currentAdjustedLength += adjustedTextLength;
  598. });
  599. if (!textTag.isEmpty()) {
  600. finishTags();
  601. return;
  602. }
  603. for (auto &item : _items) {
  604. item = TagSearchItem();
  605. }
  606. auto tryFinishTag = _currentTag;
  607. while (true) {
  608. for (; tryFinishTag != _currentFreeTag; ++tryFinishTag) {
  609. auto &tag = (*_tags)[tryFinishTag];
  610. if (tag.internalLength >= 0) {
  611. continue;
  612. }
  613. const auto i = _tagIndices.find(tag.tag);
  614. Assert(i != end(_tagIndices));
  615. const auto tagIndex = i->second;
  616. const auto atLeastOffset =
  617. tag.internalStart
  618. + tag.tag.size()
  619. + 1
  620. - _currentInternalLength;
  621. _items[tagIndex].applyOffset(atLeastOffset);
  622. fillItem(
  623. tagIndex,
  624. text,
  625. Edge::Close);
  626. if (finishByNewline(tryFinishTag, text, tagIndex)) {
  627. continue;
  628. }
  629. const auto position = matchPosition(tagIndex, Edge::Close);
  630. if (position < kInvalidPosition) {
  631. const auto till = position + tag.tag.size();
  632. finishTag(tryFinishTag, till, true);
  633. _items[tagIndex].applyOffset(till);
  634. }
  635. }
  636. for (auto i = 0, count = int(_items.size()); i != count; ++i) {
  637. fillItem(i, text, Edge::Open);
  638. }
  639. const auto min = minIndex(Edge::Open);
  640. if (min < 0) {
  641. return;
  642. }
  643. startTag(matchPosition(min, Edge::Open), _expressions[min].tag);
  644. }
  645. }
  646. void finish() {
  647. if (!_tags) {
  648. return;
  649. }
  650. finishTags();
  651. if (_currentTag < _tags->size()) {
  652. _tags->resize(_currentTag);
  653. }
  654. }
  655. private:
  656. void finishTag(int index, int offsetFromAccumulated, bool closed) {
  657. Expects(_tags != nullptr);
  658. Expects(index >= 0 && index < _tags->size());
  659. auto &tag = (*_tags)[index];
  660. if (tag.internalLength < 0) {
  661. tag.internalLength = _currentInternalLength
  662. + offsetFromAccumulated
  663. - tag.internalStart;
  664. tag.adjustedLength = _currentAdjustedLength
  665. + offsetFromAccumulated
  666. - tag.adjustedStart;
  667. tag.closed = closed;
  668. }
  669. if (index == _currentTag) {
  670. ++_currentTag;
  671. }
  672. }
  673. bool finishByNewline(
  674. int index,
  675. const QString &text,
  676. int tagIndex) {
  677. Expects(_tags != nullptr);
  678. Expects(index >= 0 && index < _tags->size());
  679. auto &tag = (*_tags)[index];
  680. if (!DoesTagFinishByNewline(tag.tag)) {
  681. return false;
  682. }
  683. const auto endPosition = newlinePosition(
  684. text,
  685. std::max(0, tag.internalStart + 1 - _currentInternalLength));
  686. if (matchPosition(tagIndex, Edge::Close) <= endPosition) {
  687. return false;
  688. }
  689. finishTag(index, endPosition, false);
  690. return true;
  691. }
  692. void finishTags() {
  693. while (_currentTag != _currentFreeTag) {
  694. finishTag(_currentTag, 0, false);
  695. }
  696. }
  697. void startTag(int offsetFromAccumulated, const QString &tag) {
  698. Expects(_tags != nullptr);
  699. const auto newTag = InputField::MarkdownTag{
  700. _currentInternalLength + offsetFromAccumulated,
  701. -1,
  702. _currentAdjustedLength + offsetFromAccumulated,
  703. -1,
  704. false,
  705. tag
  706. };
  707. if (_currentFreeTag < _tags->size()) {
  708. (*_tags)[_currentFreeTag] = newTag;
  709. } else {
  710. _tags->push_back(newTag);
  711. }
  712. ++_currentFreeTag;
  713. }
  714. void fillItem(int index, const QString &text, Edge edge) {
  715. Expects(index >= 0 && index < _items.size());
  716. _items[index].fill(text, edge, _expressions[index]);
  717. }
  718. int matchPosition(int index, Edge edge) const {
  719. Expects(index >= 0 && index < _items.size());
  720. return _items[index].matchPosition(edge);
  721. }
  722. int newlinePosition(const QString &text, int offset) const {
  723. const auto length = text.size();
  724. if (offset < length) {
  725. const auto begin = text.data();
  726. const auto end = begin + length;
  727. for (auto ch = begin + offset; ch != end; ++ch) {
  728. if (IsNewline(*ch)) {
  729. return (ch - begin);
  730. }
  731. }
  732. }
  733. return kInvalidPosition;
  734. }
  735. int minIndex(Edge edge) const {
  736. auto result = -1;
  737. auto minPosition = kInvalidPosition;
  738. for (auto i = 0, count = int(_items.size()); i != count; ++i) {
  739. const auto position = matchPosition(i, edge);
  740. if (position < minPosition) {
  741. minPosition = position;
  742. result = i;
  743. }
  744. }
  745. return result;
  746. }
  747. int minIndexForFinish(const std::vector<int> &indices) const {
  748. const auto tagIndex = indices[0];
  749. auto result = -1;
  750. auto minPosition = kInvalidPosition;
  751. for (auto i : indices) {
  752. const auto edge = (i == tagIndex) ? Edge::Close : Edge::Open;
  753. const auto position = matchPosition(i, edge);
  754. if (position < minPosition) {
  755. minPosition = position;
  756. result = i;
  757. }
  758. }
  759. return result;
  760. }
  761. std::vector<InputField::MarkdownTag> *_tags = nullptr;
  762. const std::vector<TagStartExpression> &_expressions;
  763. const std::map<QString, int> &_tagIndices;
  764. std::vector<TagSearchItem> _items;
  765. int _currentTag = 0;
  766. int _currentFreeTag = 0;
  767. int _currentInternalLength = 0;
  768. int _currentAdjustedLength = 0;
  769. };
  770. template <typename Iterator>
  771. QString AccumulateText(Iterator begin, Iterator end) {
  772. auto result = QString();
  773. result.reserve(end - begin);
  774. for (auto i = end; i != begin;) {
  775. result.push_back(*--i);
  776. }
  777. return result;
  778. }
  779. QTextImageFormat PrepareEmojiFormat(EmojiPtr emoji, int lineHeight) {
  780. const auto factor = style::DevicePixelRatio();
  781. const auto size = Emoji::GetSizeNormal();
  782. const auto width = size + st::emojiPadding * factor * 2;
  783. const auto height = std::max(lineHeight * factor, size);
  784. auto result = QTextImageFormat();
  785. result.setWidth(width / factor);
  786. result.setHeight(height / factor);
  787. result.setName(emoji->toUrl());
  788. result.setVerticalAlignment(QTextCharFormat::AlignTop);
  789. return result;
  790. }
  791. [[nodiscard]] QTextCharFormat PrepareTagFormat(
  792. const style::InputField &st,
  793. QStringView tag) {
  794. auto result = QTextCharFormat();
  795. auto font = st.style.font;
  796. auto color = std::optional<QColor>();
  797. auto bg = std::optional<QColor>();
  798. auto replaceWhat = QString();
  799. auto replaceWith = QString();
  800. const auto applyOne = [&](QStringView tag) {
  801. if (IsCustomEmojiLink(tag)) {
  802. replaceWhat = tag.toString();
  803. replaceWith = MakeUniqueCustomEmojiLink(tag);
  804. result.setObjectType(kCustomEmojiFormat);
  805. result.setProperty(kCustomEmojiLink, replaceWith);
  806. result.setProperty(
  807. kCustomEmojiId,
  808. CustomEmojiIdFromLink(replaceWith));
  809. result.setVerticalAlignment(QTextCharFormat::AlignTop);
  810. } else if (IsValidMarkdownLink(tag)) {
  811. color = st::defaultTextPalette.linkFg->c;
  812. } else if (tag == kTagBold) {
  813. font = font->bold();
  814. } else if (tag == kTagItalic) {
  815. font = font->italic();
  816. } else if (tag == kTagUnderline) {
  817. font = font->underline();
  818. } else if (tag == kTagStrikeOut) {
  819. font = font->strikeout();
  820. } else if (tag == kTagCode || IsTagPre(tag)) {
  821. color = st::defaultTextPalette.monoFg->c;
  822. font = font->monospace();
  823. }
  824. };
  825. for (const auto &tag : TextUtilities::SplitTags(tag)) {
  826. applyOne(tag);
  827. }
  828. result.setFont(font);
  829. result.setForeground(color.value_or(st.textFg->c));
  830. auto value = tag.toString();
  831. result.setProperty(
  832. kTagProperty,
  833. (replaceWhat.isEmpty()
  834. ? value
  835. : value.replace(replaceWhat, replaceWith)));
  836. if (bg) {
  837. result.setBackground(*bg);
  838. } else {
  839. result.setBackground(QBrush());
  840. }
  841. return result;
  842. }
  843. [[nodiscard]] int CollapsedQuoteCutoff(const style::InputField &st) {
  844. return (Text::kQuoteCollapsedLines + 0.8) * st.style.font->height;
  845. }
  846. void SetBlockMargins(QTextBlockFormat &format, const style::QuoteStyle &st) {
  847. format.setLeftMargin(st.padding.left());
  848. format.setTopMargin(st.padding.top()
  849. + st.header
  850. + st.verticalSkip
  851. + st.verticalSkip // Those are overlapping margins, not paddings :(
  852. + st.padding.bottom());
  853. format.setRightMargin(st.padding.right());
  854. format.setBottomMargin(st.padding.bottom()
  855. + st.verticalSkip
  856. + st.verticalSkip // Those are overlapping margins, not paddings :(
  857. + st.padding.top());
  858. }
  859. [[nodiscard]] QRect ExtendForPaint(QRect rect, const style::QuoteStyle &st) {
  860. return rect.marginsAdded(
  861. st.padding + QMargins(0, st.header, 0, 0)
  862. ).translated(st.padding.left(), 0);
  863. }
  864. [[nodiscard]] QTextBlockFormat PrepareBlockFormat(
  865. const style::InputField &st,
  866. QStringView tag = {},
  867. int quoteId = -1) {
  868. static auto AutoincrementId = 0;
  869. auto result = QTextBlockFormat();
  870. if (tag != kTagBlockquoteCollapsed) {
  871. result.setLineHeight(
  872. st.style.font->height,
  873. QTextBlockFormat::FixedHeight);
  874. }
  875. const auto id = (quoteId < 0) ? ++AutoincrementId : quoteId;
  876. if (tag == kTagBlockquote || tag == kTagBlockquoteCollapsed) {
  877. result.setProperty(kQuoteFormatId, tag.toString());
  878. result.setProperty(kQuoteId, id);
  879. SetBlockMargins(result, st.style.blockquote);
  880. } else if (IsTagPre(tag)) {
  881. result.setProperty(kQuoteFormatId, tag.toString());
  882. result.setProperty(kQuoteId, id);
  883. result.setProperty(kPreLanguage, tag.mid(kTagPre.size()).toString());
  884. SetBlockMargins(result, st.style.pre);
  885. }
  886. return result;
  887. }
  888. void RemoveDocumentTags(
  889. const style::InputField &st,
  890. not_null<QTextDocument*> document,
  891. int from,
  892. int end) {
  893. auto cursor = QTextCursor(document);
  894. auto blocksCheckedTill = from;
  895. while (blocksCheckedTill < end) {
  896. auto block = document->findBlock(blocksCheckedTill);
  897. const auto till = block.position() + block.length();
  898. if (from <= block.position() && till <= end + 1) {
  899. const auto format = block.blockFormat();
  900. const auto id = format.property(kQuoteFormatId).toString();
  901. if (!id.isEmpty()) {
  902. cursor.setPosition(blocksCheckedTill);
  903. cursor.setBlockFormat(PrepareBlockFormat(st));
  904. }
  905. }
  906. blocksCheckedTill = till;
  907. }
  908. cursor.setPosition(from);
  909. cursor.setPosition(end, QTextCursor::KeepAnchor);
  910. auto format = QTextCharFormat();
  911. format.setProperty(kTagProperty, QString());
  912. format.setProperty(kReplaceTagId, QString());
  913. format.setForeground(st.textFg);
  914. format.setBackground(QBrush());
  915. format.setFont(st.style.font);
  916. cursor.mergeCharFormat(format);
  917. }
  918. [[nodiscard]] QString TagWithoutCustomEmoji(QStringView tag) {
  919. auto tags = TextUtilities::SplitTags(tag);
  920. for (auto i = tags.begin(); i != tags.end();) {
  921. if (IsCustomEmojiLink(*i)) {
  922. i = tags.erase(i);
  923. } else {
  924. ++i;
  925. }
  926. }
  927. return TextUtilities::JoinTag(tags);
  928. }
  929. void RemoveCustomEmojiTag(
  930. const style::InputField &st,
  931. not_null<QTextDocument*> document,
  932. const QString &existingTags,
  933. int from,
  934. int end) {
  935. auto cursor = QTextCursor(document);
  936. cursor.setPosition(from);
  937. cursor.setPosition(end, QTextCursor::KeepAnchor);
  938. auto format = PrepareTagFormat(st, TagWithoutCustomEmoji(existingTags));
  939. format.setProperty(kCustomEmojiLink, QString());
  940. format.setProperty(kCustomEmojiId, QString());
  941. cursor.mergeCharFormat(format);
  942. }
  943. void ApplyTagFormat(QTextCharFormat &to, const QTextCharFormat &from) {
  944. if (from.hasProperty(kTagProperty)) {
  945. to.setProperty(
  946. kTagProperty,
  947. TagWithoutCustomEmoji(from.property(kTagProperty).toString()));
  948. }
  949. to.setProperty(kReplaceTagId, from.property(kReplaceTagId));
  950. to.setFont(from.font());
  951. if (from.hasProperty(QTextFormat::ForegroundBrush)) {
  952. to.setForeground(from.brushProperty(QTextFormat::ForegroundBrush));
  953. }
  954. if (from.hasProperty(QTextFormat::BackgroundBrush)) {
  955. to.setBackground(from.brushProperty(QTextFormat::BackgroundBrush));
  956. }
  957. }
  958. [[nodiscard]] bool IsCollapsedQuoteFragment(const QTextFragment &fragment) {
  959. return (fragment.charFormat().objectType() == kCollapsedQuoteFormat)
  960. && (fragment.text() == kObjectReplacement);
  961. }
  962. [[nodiscard]] int FindCollapsedQuoteObject(const QTextBlock &block) {
  963. for (auto fragmentIt = block.begin(); !fragmentIt.atEnd(); ++fragmentIt) {
  964. auto fragment = fragmentIt.fragment();
  965. if (IsCollapsedQuoteFragment(fragment)) {
  966. return fragment.position();
  967. }
  968. }
  969. return -1;
  970. }
  971. [[nodiscard]] TextWithTags PrepareForInsert(TextWithTags data) {
  972. auto &text = data.text;
  973. auto length = int(data.text.size());
  974. const auto newline = [&](int position) {
  975. return IsNewline(text.at(position));
  976. };
  977. const auto force = [&](int position, QChar ch) {
  978. if (text.at(position) != ch) {
  979. // Don't detach unnecessary.
  980. text[position] = ch;
  981. }
  982. };
  983. for (auto i = 0, length = int(data.text.size()); i != length; ++i) {
  984. if (newline(i)) {
  985. force(i, kSoftLine);
  986. }
  987. }
  988. for (auto i = data.tags.begin(); i != data.tags.end();) {
  989. auto &tagStart = *i;
  990. const auto &id = tagStart.id;
  991. auto from = std::min(tagStart.offset, length);
  992. auto till = std::min(tagStart.offset + tagStart.length, length);
  993. if (from >= till) {
  994. i = data.tags.erase(i);
  995. continue;
  996. }
  997. const auto block = FindBlockTag(id);
  998. if (block.isEmpty()) {
  999. ++i;
  1000. continue;
  1001. }
  1002. auto j = i + 1;
  1003. for (; j != data.tags.end(); ++j) {
  1004. auto &next = *j;
  1005. if (next.offset > till || FindBlockTag(next.id) != block) {
  1006. break;
  1007. }
  1008. till = std::min(next.offset + next.length, length);
  1009. }
  1010. auto &tagEnd = *(j - 1);
  1011. if (from > 0 && newline(from - 1)) {
  1012. force(from - 1, kHardLine);
  1013. } else if (newline(from)) {
  1014. force(from, kHardLine);
  1015. ++from;
  1016. ++tagStart.offset;
  1017. } else if (from > 0) {
  1018. data.text.insert(from, kHardLine);
  1019. ++length;
  1020. for (auto &tag : data.tags) {
  1021. if (tag.offset >= from) {
  1022. ++tag.offset;
  1023. } else if (tag.offset + tag.length > from) {
  1024. ++tag.length;
  1025. }
  1026. }
  1027. ++from;
  1028. ++till;
  1029. }
  1030. if (till < length && newline(till)) {
  1031. force(till, kHardLine);
  1032. } else if (newline(till - 1)) {
  1033. force(till - 1, kHardLine);
  1034. --till;
  1035. --tagEnd.length;
  1036. } else if (till < length) {
  1037. data.text.insert(till, kHardLine);
  1038. ++length;
  1039. for (auto &tag : data.tags) {
  1040. if (tag.offset >= till) {
  1041. ++tag.offset;
  1042. } else if (tag.offset + tag.length > till) {
  1043. ++tag.length;
  1044. }
  1045. }
  1046. }
  1047. i = j;
  1048. }
  1049. return data;
  1050. }
  1051. [[nodiscard]] QString FullTag(
  1052. const QTextCharFormat &ch,
  1053. const QTextBlockFormat &block) {
  1054. auto simple = WithBlockTagRemoved(ch.property(kTagProperty).toString());
  1055. auto quote = block.property(kQuoteFormatId).toString();
  1056. return quote.isEmpty()
  1057. ? simple
  1058. : simple.isEmpty()
  1059. ? quote
  1060. : TextUtilities::TagWithAdded(simple, quote);
  1061. }
  1062. [[nodiscard]] TextWithTags WrapInQuote(
  1063. TextWithTags text,
  1064. const QString &blockTag) {
  1065. auto from = 0, till = int(text.text.size());
  1066. for (auto i = text.tags.begin(); from < till;) {
  1067. if (i == text.tags.end()) {
  1068. if (from < till) {
  1069. text.tags.push_back({ from, till - from, blockTag });
  1070. }
  1071. break;
  1072. } else if (i->offset > from) {
  1073. i = text.tags.insert(
  1074. i,
  1075. { from, i->offset - from, blockTag });
  1076. ++i;
  1077. }
  1078. i->id = TextUtilities::TagWithAdded(i->id, blockTag);
  1079. from = i->offset + i->length;
  1080. ++i;
  1081. }
  1082. return text;
  1083. }
  1084. // Returns the position of the first inserted tag or "changedEnd" value if none found.
  1085. int ProcessInsertedTags(
  1086. const style::InputField &st,
  1087. not_null<QTextDocument*> document,
  1088. int changedPosition,
  1089. int changedEnd,
  1090. const TextWithTags::Tags &tags,
  1091. bool tagsReplaceExisting,
  1092. Fn<QString(QStringView)> processor) {
  1093. auto firstTagStart = changedEnd;
  1094. auto applyNoTagFrom = tagsReplaceExisting ? changedPosition : changedEnd;
  1095. for (const auto &tag : tags) {
  1096. int tagFrom = changedPosition + tag.offset;
  1097. int tagTo = tagFrom + tag.length;
  1098. accumulate_max(tagFrom, changedPosition);
  1099. accumulate_min(tagTo, changedEnd);
  1100. auto tagId = processor ? processor(tag.id) : tag.id;
  1101. if (tagTo > tagFrom && !tagId.isEmpty()) {
  1102. accumulate_min(firstTagStart, tagFrom);
  1103. PrepareFormattingOptimization(document);
  1104. if (applyNoTagFrom < tagFrom) {
  1105. RemoveDocumentTags(
  1106. st,
  1107. document,
  1108. applyNoTagFrom,
  1109. tagFrom);
  1110. }
  1111. QTextCursor c(document);
  1112. c.setPosition(tagFrom);
  1113. c.setPosition(tagTo, QTextCursor::KeepAnchor);
  1114. if (const auto block = FindBlockTag(tag.id); !block.isEmpty()) {
  1115. c.setBlockFormat(PrepareBlockFormat(st, block));
  1116. } else if (tagsReplaceExisting) {
  1117. const auto block = c.block();
  1118. const auto blockStart = block.position();
  1119. if (blockStart >= changedPosition
  1120. && blockStart + block.length() - 1 <= changedEnd) {
  1121. c.setBlockFormat(PrepareBlockFormat(st));
  1122. }
  1123. }
  1124. c.mergeCharFormat(PrepareTagFormat(st, tagId));
  1125. applyNoTagFrom = tagTo;
  1126. }
  1127. }
  1128. if (applyNoTagFrom < changedEnd) {
  1129. RemoveDocumentTags(st, document, applyNoTagFrom, changedEnd);
  1130. }
  1131. return firstTagStart;
  1132. }
  1133. // When inserting a part of text inside a tag we need to have
  1134. // a way to know if the insertion replaced the end of the tag
  1135. // or it was strictly inside (in the middle) of the tag.
  1136. bool WasInsertTillTheEndOfTag(
  1137. QTextBlock block,
  1138. QTextBlock::iterator fragmentIt,
  1139. int insertionEnd) {
  1140. const auto format = fragmentIt.fragment().charFormat();
  1141. const auto insertTagName = format.property(kTagProperty);
  1142. while (true) {
  1143. for (; !fragmentIt.atEnd(); ++fragmentIt) {
  1144. const auto fragment = fragmentIt.fragment();
  1145. const auto position = fragment.position();
  1146. const auto outsideInsertion = (position >= insertionEnd);
  1147. if (outsideInsertion) {
  1148. const auto format = fragment.charFormat();
  1149. const auto tag = format.property(kTagProperty).toString();
  1150. return TagWithoutCustomEmoji(tag)
  1151. != TagWithoutCustomEmoji(insertTagName.toString());
  1152. }
  1153. const auto end = position + fragment.length();
  1154. const auto notFullFragmentInserted = (end > insertionEnd);
  1155. if (notFullFragmentInserted) {
  1156. return false;
  1157. }
  1158. }
  1159. block = block.next();
  1160. if (block.isValid()) {
  1161. fragmentIt = block.begin();
  1162. } else {
  1163. break;
  1164. }
  1165. }
  1166. // Insertion goes till the end of the text => not strictly inside a tag.
  1167. return true;
  1168. }
  1169. struct FormattingAction {
  1170. enum class Type {
  1171. Invalid,
  1172. InsertEmoji,
  1173. InsertCustomEmoji,
  1174. RemoveCustomEmoji,
  1175. TildeFont,
  1176. RemoveTag,
  1177. RemoveNewline,
  1178. ClearInstantReplace,
  1179. FixLineHeight,
  1180. FixPreTag,
  1181. CollapseBlockquote,
  1182. CutCollapsedBefore,
  1183. CutCollapsedAfter,
  1184. MakeCollapsedBlockquote,
  1185. RemoveBlockquote,
  1186. };
  1187. Type type = Type::Invalid;
  1188. EmojiPtr emoji = nullptr;
  1189. bool isTilde = false;
  1190. QString tildeTag;
  1191. QString existingTags;
  1192. QString customEmojiText;
  1193. QString customEmojiLink;
  1194. int intervalStart = 0;
  1195. int intervalEnd = 0;
  1196. int quoteId = 0;
  1197. };
  1198. } // namespace
  1199. // kTagUnderline is not used for Markdown.
  1200. const QString InputField::kTagBold = u"**"_q;
  1201. const QString InputField::kTagItalic = u"__"_q;
  1202. const QString InputField::kTagUnderline = u"^^"_q;
  1203. const QString InputField::kTagStrikeOut = u"~~"_q;
  1204. const QString InputField::kTagCode = u"`"_q;
  1205. const QString InputField::kTagPre = u"```"_q;
  1206. const QString InputField::kTagSpoiler = u"||"_q;
  1207. const QString InputField::kTagBlockquote = u">"_q;
  1208. const QString InputField::kTagBlockquoteCollapsed = u">^"_q;
  1209. const QString InputField::kCustomEmojiTagStart = u"custom-emoji://"_q;
  1210. const int InputField::kCollapsedQuoteFormat = ::Ui::kCollapsedQuoteFormat;
  1211. const int InputField::kCustomEmojiFormat = ::Ui::kCustomEmojiFormat;
  1212. const int InputField::kCustomEmojiId = ::Ui::kCustomEmojiId;
  1213. const int InputField::kCustomEmojiLink = ::Ui::kCustomEmojiLink;
  1214. const int InputField::kQuoteId = ::Ui::kQuoteId;
  1215. class InputField::Inner final : public QTextEdit {
  1216. public:
  1217. Inner(not_null<InputField*> parent) : QTextEdit(parent) {
  1218. }
  1219. protected:
  1220. bool viewportEvent(QEvent *e) override {
  1221. return outer()->viewportEventInner(e);
  1222. }
  1223. void focusInEvent(QFocusEvent *e) override {
  1224. return outer()->focusInEventInner(e);
  1225. }
  1226. void focusOutEvent(QFocusEvent *e) override {
  1227. return outer()->focusOutEventInner(e);
  1228. }
  1229. void keyPressEvent(QKeyEvent *e) override {
  1230. return outer()->keyPressEventInner(e);
  1231. }
  1232. void contextMenuEvent(QContextMenuEvent *e) override {
  1233. return outer()->contextMenuEventInner(e);
  1234. }
  1235. void dropEvent(QDropEvent *e) override {
  1236. return outer()->dropEventInner(e);
  1237. }
  1238. void inputMethodEvent(QInputMethodEvent *e) override {
  1239. return outer()->inputMethodEventInner(e);
  1240. }
  1241. void paintEvent(QPaintEvent *e) override {
  1242. return outer()->paintEventInner(e);
  1243. }
  1244. void mousePressEvent(QMouseEvent *e) override {
  1245. return outer()->mousePressEventInner(e);
  1246. }
  1247. void mouseReleaseEvent(QMouseEvent *e) override {
  1248. return outer()->mouseReleaseEventInner(e);
  1249. }
  1250. void mouseMoveEvent(QMouseEvent *e) override {
  1251. return outer()->mouseMoveEventInner(e);
  1252. }
  1253. void leaveEvent(QEvent *e) override {
  1254. return outer()->leaveEventInner(e);
  1255. }
  1256. bool canInsertFromMimeData(const QMimeData *source) const override {
  1257. return outer()->canInsertFromMimeDataInner(source);
  1258. }
  1259. void insertFromMimeData(const QMimeData *source) override {
  1260. return outer()->insertFromMimeDataInner(source);
  1261. }
  1262. QMimeData *createMimeDataFromSelection() const override {
  1263. return outer()->createMimeDataFromSelectionInner();
  1264. }
  1265. private:
  1266. not_null<InputField*> outer() const {
  1267. return static_cast<InputField*>(parentWidget());
  1268. }
  1269. friend class InputField;
  1270. };
  1271. void InsertEmojiAtCursor(QTextCursor cursor, EmojiPtr emoji) {
  1272. const auto currentFormat = cursor.charFormat();
  1273. const auto blockFormat = cursor.blockFormat();
  1274. const auto type = blockFormat.lineHeightType();
  1275. const auto height = (type == QTextBlockFormat::FixedHeight)
  1276. ? blockFormat.lineHeight()
  1277. : QFontMetrics(cursor.charFormat().font()).height();
  1278. auto format = PrepareEmojiFormat(emoji, height);
  1279. ApplyTagFormat(format, currentFormat);
  1280. cursor.insertText(kObjectReplacement, format);
  1281. }
  1282. void InsertCustomEmojiAtCursor(
  1283. not_null<InputField*> field,
  1284. QTextCursor cursor,
  1285. const QString &text,
  1286. const QString &link) {
  1287. const auto currentFormat = cursor.charFormat();
  1288. const auto unique = MakeUniqueCustomEmojiLink(link);
  1289. auto format = QTextCharFormat();
  1290. format.setObjectType(kCustomEmojiFormat);
  1291. format.setProperty(kCustomEmojiText, text);
  1292. format.setProperty(kCustomEmojiLink, unique);
  1293. format.setProperty(kCustomEmojiId, CustomEmojiIdFromLink(link));
  1294. format.setVerticalAlignment(QTextCharFormat::AlignTop);
  1295. format.setFont(field->st().style.font);
  1296. format.setForeground(field->st().textFg);
  1297. format.setBackground(QBrush());
  1298. ApplyTagFormat(format, currentFormat);
  1299. format.setProperty(kTagProperty, TextUtilities::TagWithAdded(
  1300. format.property(kTagProperty).toString(),
  1301. unique));
  1302. cursor.insertText(kObjectReplacement, format);
  1303. }
  1304. [[nodiscard]] QTextCharFormat PrepareCollapsedQuoteFormat(int quoteId) {
  1305. auto result = QTextCharFormat();
  1306. result.setObjectType(kCollapsedQuoteFormat);
  1307. result.setProperty(kTagProperty, kTagBlockquoteCollapsed);
  1308. result.setProperty(kQuoteId, quoteId);
  1309. result.setVerticalAlignment(QTextCharFormat::AlignNormal);
  1310. return result;
  1311. }
  1312. void InstantReplaces::add(const QString &what, const QString &with) {
  1313. auto node = &reverseMap;
  1314. for (auto i = what.end(), b = what.begin(); i != b;) {
  1315. node = &node->tail.emplace(*--i, Node()).first->second;
  1316. }
  1317. node->text = with;
  1318. accumulate_max(maxLength, int(what.size()));
  1319. }
  1320. const InstantReplaces &InstantReplaces::Default() {
  1321. static const auto result = [] {
  1322. auto result = InstantReplaces();
  1323. result.add("--", QString(1, QChar(8212)));
  1324. result.add("<<", QString(1, QChar(171)));
  1325. result.add(">>", QString(1, QChar(187)));
  1326. result.add(
  1327. ":shrug:",
  1328. QChar(175) + QString("\\_(") + QChar(12484) + ")_/" + QChar(175));
  1329. result.add(":o ", QString(1, QChar(0xD83D)) + QChar(0xDE28));
  1330. result.add("xD ", QString(1, QChar(0xD83D)) + QChar(0xDE06));
  1331. const auto &replacements = Emoji::internal::GetAllReplacements();
  1332. for (const auto &one : replacements) {
  1333. const auto with = Emoji::QStringFromUTF16(one.emoji);
  1334. const auto what = Emoji::QStringFromUTF16(one.replacement);
  1335. result.add(what, with);
  1336. }
  1337. const auto &pairs = Emoji::internal::GetReplacementPairs();
  1338. for (const auto &[what, index] : pairs) {
  1339. const auto emoji = Emoji::internal::ByIndex(index);
  1340. Assert(emoji != nullptr);
  1341. result.add(what, emoji->text());
  1342. }
  1343. return result;
  1344. }();
  1345. return result;
  1346. }
  1347. const InstantReplaces &InstantReplaces::TextOnly() {
  1348. static const auto result = [] {
  1349. auto result = InstantReplaces();
  1350. result.add("--", QString(1, QChar(8212)));
  1351. result.add("<<", QString(1, QChar(171)));
  1352. result.add(">>", QString(1, QChar(187)));
  1353. result.add(
  1354. ":shrug:",
  1355. QChar(175) + QString("\\_(") + QChar(12484) + ")_/" + QChar(175));
  1356. return result;
  1357. }();
  1358. return result;
  1359. }
  1360. bool MarkdownEnabledState::disabled() const {
  1361. return v::is<MarkdownDisabled>(data);
  1362. }
  1363. bool MarkdownEnabledState::enabledForTag(QStringView tag) const {
  1364. const auto yes = std::get_if<MarkdownEnabled>(&data);
  1365. return yes
  1366. && (yes->tagsSubset.empty() || yes->tagsSubset.contains(tag));
  1367. }
  1368. InputField::InputField(
  1369. QWidget *parent,
  1370. const style::InputField &st,
  1371. rpl::producer<QString> placeholder,
  1372. const QString &value)
  1373. : InputField(
  1374. parent,
  1375. st,
  1376. Mode::SingleLine,
  1377. std::move(placeholder),
  1378. { value, {} }) {
  1379. }
  1380. InputField::InputField(
  1381. QWidget *parent,
  1382. const style::InputField &st,
  1383. Mode mode,
  1384. rpl::producer<QString> placeholder,
  1385. const QString &value)
  1386. : InputField(
  1387. parent,
  1388. st,
  1389. mode,
  1390. std::move(placeholder),
  1391. { value, {} }) {
  1392. }
  1393. InputField::InputField(
  1394. QWidget *parent,
  1395. const style::InputField &st,
  1396. Mode mode,
  1397. rpl::producer<QString> placeholder,
  1398. const TextWithTags &value)
  1399. : RpWidget(parent)
  1400. , _st(st)
  1401. , _mode(mode)
  1402. , _minHeight(st.heightMin)
  1403. , _maxHeight(st.heightMax)
  1404. , _inner(std::make_unique<Inner>(this))
  1405. , _lastTextWithTags(value)
  1406. , _placeholderFull(std::move(placeholder)) {
  1407. _inner->setDocument(CreateChild<InputDocument>(_inner.get(), _st));
  1408. _inner->setAcceptRichText(false);
  1409. resize(_st.width, _minHeight);
  1410. { // In case of default fonts all those should be zero.
  1411. const auto metrics = QFontMetricsF(_st.style.font->f);
  1412. const auto realAscent = int(base::SafeRound(metrics.ascent()));
  1413. const auto ascentAdd = _st.style.font->ascent - realAscent;
  1414. //const auto realHeight = int(base::SafeRound(metrics.height()));
  1415. //const auto heightAdd = _font->height - realHeight - ascentAdd;
  1416. //_customFontMargins = QMargins(0, ascentAdd, 0, heightAdd);
  1417. _customFontMargins = QMargins(0, ascentAdd, 0, -ascentAdd);
  1418. // We move _inner down by ascentAdd for the first line to look
  1419. // at the same vertical position as in the default font.
  1420. //
  1421. // But we don't want to get vertical scroll in case the field
  1422. // fits pixel-perfect with the default font, so we allow the
  1423. // bottom margin to be the same shift, but negative.
  1424. if (_mode != Mode::SingleLine) {
  1425. const auto metrics = QFontMetricsF(_st.style.font->f);
  1426. const auto leading = qMax(metrics.leading(), qreal(0.0));
  1427. const auto adjustment = (metrics.ascent() + leading)
  1428. - ((_st.style.font->height * 4) / 5);
  1429. _placeholderCustomFontSkip = int(base::SafeRound(-adjustment));
  1430. }
  1431. }
  1432. if (_st.textBg->c.alphaF() >= 1. && !_st.borderRadius) {
  1433. setAttribute(Qt::WA_OpaquePaintEvent);
  1434. }
  1435. _inner->setFont(_st.style.font->f);
  1436. _inner->setAlignment(_st.textAlign);
  1437. if (_mode == Mode::SingleLine) {
  1438. _inner->setWordWrapMode(QTextOption::NoWrap);
  1439. }
  1440. _placeholderFull.value(
  1441. ) | rpl::start_with_next([=](const QString &text) {
  1442. refreshPlaceholder(text);
  1443. }, lifetime());
  1444. style::PaletteChanged(
  1445. ) | rpl::start_with_next([=] {
  1446. updatePalette();
  1447. }, lifetime());
  1448. {
  1449. auto cursor = _inner->textCursor();
  1450. _defaultCharFormat = cursor.charFormat();
  1451. updatePalette();
  1452. cursor.setCharFormat(_defaultCharFormat);
  1453. cursor.setBlockFormat(PrepareBlockFormat(_st));
  1454. _inner->setTextCursor(cursor);
  1455. }
  1456. _inner->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  1457. _inner->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  1458. _inner->setFrameStyle(int(QFrame::NoFrame) | QFrame::Plain);
  1459. _inner->viewport()->setAutoFillBackground(false);
  1460. _inner->setContentsMargins(0, 0, 0, 0);
  1461. _inner->document()->setDocumentMargin(0);
  1462. setAttribute(Qt::WA_AcceptTouchEvents);
  1463. _inner->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);
  1464. _touchTimer.setCallback([=] { _touchRightButton = true; });
  1465. base::qt_signal_producer(
  1466. _inner->document(),
  1467. &QTextDocument::contentsChange
  1468. ) | rpl::start_with_next([=](int position, int removed, int added) {
  1469. documentContentsChanged(position, removed, added);
  1470. }, lifetime());
  1471. base::qt_signal_producer(
  1472. _inner.get(),
  1473. &QTextEdit::undoAvailable
  1474. ) | rpl::start_with_next([=](bool undoAvailable) {
  1475. _undoAvailable = undoAvailable;
  1476. Integration::Instance().textActionsUpdated();
  1477. }, lifetime());
  1478. base::qt_signal_producer(
  1479. _inner.get(),
  1480. &QTextEdit::redoAvailable
  1481. ) | rpl::start_with_next([=](bool redoAvailable) {
  1482. _redoAvailable = redoAvailable;
  1483. Integration::Instance().textActionsUpdated();
  1484. }, lifetime());
  1485. base::qt_signal_producer(
  1486. _inner.get(),
  1487. &QTextEdit::cursorPositionChanged
  1488. ) | rpl::start_with_next([=] {
  1489. auto cursor = textCursor();
  1490. if (!cursor.hasSelection() && !cursor.position()) {
  1491. cursor.setCharFormat(_defaultCharFormat);
  1492. setTextCursor(cursor);
  1493. }
  1494. if (_customObject) {
  1495. _customObject->refreshSpoilerShown({
  1496. cursor.selectionStart(),
  1497. cursor.selectionEnd(),
  1498. });
  1499. }
  1500. }, lifetime());
  1501. base::qt_signal_producer(
  1502. _inner.get(),
  1503. &Inner::selectionChanged
  1504. ) | rpl::start_with_next([] {
  1505. Integration::Instance().textActionsUpdated();
  1506. }, lifetime());
  1507. setupMarkdownShortcuts();
  1508. const auto bar = _inner->verticalScrollBar();
  1509. _scrollTop = bar->value();
  1510. connect(bar, &QScrollBar::valueChanged, [=] {
  1511. _scrollTop = bar->value();
  1512. });
  1513. setCursor(style::cur_text);
  1514. heightAutoupdated();
  1515. if (!value.text.isEmpty()) {
  1516. setTextWithTags(value, HistoryAction::Clear);
  1517. }
  1518. startBorderAnimation();
  1519. startPlaceholderAnimation();
  1520. finishAnimating();
  1521. }
  1522. std::vector<InputField::MarkdownAction> InputField::MarkdownActions() {
  1523. return {
  1524. { QKeySequence::Bold, kTagBold },
  1525. { QKeySequence::Italic, kTagItalic },
  1526. { QKeySequence::Underline, kTagUnderline },
  1527. { kStrikeOutSequence, kTagStrikeOut },
  1528. { kMonospaceSequence, kTagCode },
  1529. { kBlockquoteSequence, kTagBlockquote },
  1530. { kSpoilerSequence, kTagSpoiler },
  1531. { kClearFormatSequence, QString() },
  1532. { kEditLinkSequence, QString(), MarkdownActionType::EditLink },
  1533. };
  1534. }
  1535. void InputField::setupMarkdownShortcuts() {
  1536. for (const auto &action : MarkdownActions()) {
  1537. auto shortcut = std::make_unique<QShortcut>(
  1538. action.sequence,
  1539. _inner.get(),
  1540. nullptr,
  1541. nullptr,
  1542. Qt::WidgetShortcut);
  1543. QObject::connect(shortcut.get(), &QShortcut::activated, [=] {
  1544. executeMarkdownAction(action);
  1545. });
  1546. _markdownShortcuts.push_back(std::move(shortcut));
  1547. }
  1548. }
  1549. bool InputField::executeMarkdownAction(MarkdownAction action) {
  1550. if (_markdownEnabledState.disabled()) {
  1551. return false;
  1552. } else if (action.type == MarkdownActionType::EditLink) {
  1553. if (!_editLinkCallback) {
  1554. return false;
  1555. }
  1556. const auto cursor = textCursor();
  1557. editMarkdownLink({
  1558. cursor.selectionStart(),
  1559. cursor.selectionEnd()
  1560. });
  1561. } else if (action.tag.isEmpty()) {
  1562. clearSelectionMarkdown();
  1563. } else if (!_markdownEnabledState.enabledForTag(action.tag)
  1564. || (action.tag == kTagCode
  1565. && !_markdownEnabledState.enabledForTag(kTagPre))) {
  1566. return false;
  1567. } else {
  1568. toggleSelectionMarkdown(action.tag);
  1569. }
  1570. return true;
  1571. }
  1572. const rpl::variable<int> &InputField::scrollTop() const {
  1573. return _scrollTop;
  1574. }
  1575. int InputField::scrollTopMax() const {
  1576. return _inner->verticalScrollBar()->maximum();
  1577. }
  1578. void InputField::scrollTo(int top) {
  1579. _inner->verticalScrollBar()->setValue(top);
  1580. }
  1581. bool InputField::menuShown() const {
  1582. return _contextMenu != nullptr;
  1583. }
  1584. rpl::producer<bool> InputField::menuShownValue() const {
  1585. return _menuShownChanges.events_starting_with(menuShown());
  1586. }
  1587. void InputField::setPreCache(Fn<not_null<Text::QuotePaintCache*>()> make) {
  1588. _preCache = std::move(make);
  1589. update();
  1590. }
  1591. void InputField::setBlockquoteCache(
  1592. Fn<not_null<Text::QuotePaintCache*>()> make) {
  1593. _blockquoteCache = std::move(make);
  1594. update();
  1595. }
  1596. bool InputField::viewportEventInner(QEvent *e) {
  1597. if (e->type() == QEvent::TouchBegin
  1598. || e->type() == QEvent::TouchUpdate
  1599. || e->type() == QEvent::TouchEnd
  1600. || e->type() == QEvent::TouchCancel) {
  1601. const auto ev = static_cast<QTouchEvent*>(e);
  1602. if (ev->device()->type() == base::TouchDevice::TouchScreen) {
  1603. handleTouchEvent(ev);
  1604. return false;
  1605. }
  1606. } else if (e->type() == QEvent::Paint && _customObject) {
  1607. _customObject->setNow(crl::now());
  1608. }
  1609. return _inner->QTextEdit::viewportEvent(e);
  1610. }
  1611. void InputField::updatePalette() {
  1612. auto p = _inner->palette();
  1613. p.setColor(QPalette::Text, _st.textFg->c);
  1614. p.setColor(QPalette::Highlight, st::msgInBgSelected->c);
  1615. p.setColor(QPalette::HighlightedText, st::historyTextInFgSelected->c);
  1616. _inner->setPalette(p);
  1617. _defaultCharFormat.merge(PrepareTagFormat(_st, QString()));
  1618. auto cursor = textCursor();
  1619. const auto document = _inner->document();
  1620. auto block = document->begin();
  1621. const auto end = document->end();
  1622. for (; block != end; block = block.next()) {
  1623. auto till = block.position();
  1624. for (auto i = block.begin(); !i.atEnd();) {
  1625. for (; !i.atEnd(); ++i) {
  1626. const auto fragment = i.fragment();
  1627. if (!fragment.isValid() || fragment.position() < till) {
  1628. continue;
  1629. }
  1630. till = fragment.position() + fragment.length();
  1631. auto format = fragment.charFormat();
  1632. const auto tag = format.property(kTagProperty).toString();
  1633. const auto updatedFormat = PrepareTagFormat(_st, tag);
  1634. format.setForeground(updatedFormat.foreground());
  1635. format.setBackground(updatedFormat.background());
  1636. cursor.setPosition(fragment.position());
  1637. cursor.setPosition(till, QTextCursor::KeepAnchor);
  1638. cursor.mergeCharFormat(format);
  1639. i = block.begin();
  1640. break;
  1641. }
  1642. }
  1643. }
  1644. cursor = textCursor();
  1645. if (!cursor.hasSelection()) {
  1646. auto format = cursor.charFormat();
  1647. format.merge(PrepareTagFormat(
  1648. _st,
  1649. TagWithoutCustomEmoji(
  1650. format.property(kTagProperty).toString())));
  1651. cursor.setCharFormat(format);
  1652. setTextCursor(cursor);
  1653. }
  1654. }
  1655. void InputField::setExtendedContextMenu(
  1656. rpl::producer<ExtendedContextMenu> value) {
  1657. std::move(
  1658. value
  1659. ) | rpl::start_with_next([=](auto pair) {
  1660. auto &[menu, e] = pair;
  1661. contextMenuEventInner(e.get(), std::move(menu));
  1662. }, lifetime());
  1663. }
  1664. void InputField::setInstantReplaces(const InstantReplaces &replaces) {
  1665. _mutableInstantReplaces = replaces;
  1666. }
  1667. void InputField::setInstantReplacesEnabled(rpl::producer<bool> enabled) {
  1668. std::move(
  1669. enabled
  1670. ) | rpl::start_with_next([=](bool value) {
  1671. _instantReplacesEnabled = value;
  1672. }, lifetime());
  1673. }
  1674. void InputField::setMarkdownReplacesEnabled(bool enabled) {
  1675. setMarkdownReplacesEnabled(
  1676. rpl::single(MarkdownEnabledState{ MarkdownEnabled() }));
  1677. }
  1678. void InputField::setMarkdownReplacesEnabled(
  1679. rpl::producer<MarkdownEnabledState> enabled) {
  1680. std::move(
  1681. enabled
  1682. ) | rpl::start_with_next([=](MarkdownEnabledState state) {
  1683. if (_markdownEnabledState != state) {
  1684. _markdownEnabledState = state;
  1685. if (_markdownEnabledState.disabled()) {
  1686. _lastMarkdownTags = {};
  1687. } else {
  1688. handleContentsChanged();
  1689. }
  1690. }
  1691. }, lifetime());
  1692. }
  1693. void InputField::setTagMimeProcessor(Fn<QString(QStringView)> processor) {
  1694. _tagMimeProcessor = std::move(processor);
  1695. }
  1696. void InputField::setCustomTextContext(
  1697. Text::MarkedContext context,
  1698. Fn<bool()> pausedEmoji,
  1699. Fn<bool()> pausedSpoiler) {
  1700. _customObject = std::make_unique<CustomFieldObject>(
  1701. this,
  1702. std::move(context),
  1703. std::move(pausedEmoji),
  1704. std::move(pausedSpoiler));
  1705. _inner->document()->documentLayout()->registerHandler(
  1706. kCustomEmojiFormat,
  1707. _customObject.get());
  1708. _inner->document()->documentLayout()->registerHandler(
  1709. kCollapsedQuoteFormat,
  1710. _customObject.get());
  1711. }
  1712. void InputField::customEmojiRepaint() {
  1713. if (_customEmojiRepaintScheduled) {
  1714. return;
  1715. }
  1716. _customEmojiRepaintScheduled = true;
  1717. _inner->update();
  1718. }
  1719. void InputField::paintEventInner(QPaintEvent *e) {
  1720. _customEmojiRepaintScheduled = false;
  1721. paintQuotes(e);
  1722. _inner->QTextEdit::paintEvent(e);
  1723. }
  1724. void InputField::paintQuotes(QPaintEvent *e) {
  1725. if (!_blockquoteCache || !_preCache) {
  1726. return;
  1727. }
  1728. const auto clip = e->rect();
  1729. auto p = std::optional<QPainter>();
  1730. const auto ensurePainter = [&] {
  1731. if (!p) {
  1732. p.emplace(_inner->viewport());
  1733. }
  1734. };
  1735. auto shift = std::optional<QPoint>();
  1736. const auto ensureShift = [&] {
  1737. if (!shift) {
  1738. shift.emplace(
  1739. -_inner->horizontalScrollBar()->value(),
  1740. -_inner->verticalScrollBar()->value());
  1741. }
  1742. };
  1743. const auto document = _inner->document();
  1744. const auto documentLayout = document->documentLayout();
  1745. const auto collapsedCutoff = CollapsedQuoteCutoff(_st);
  1746. auto textSpoilerIt = begin(_spoilerRangesText);
  1747. const auto textSpoilerEnd = end(_spoilerRangesText);
  1748. auto textSpoiler = (TextRange*)nullptr;
  1749. const auto textSpoilerAdjust = [&](int position, int till) {
  1750. if (position >= till) {
  1751. textSpoiler = nullptr;
  1752. return;
  1753. }
  1754. while (textSpoilerIt != textSpoilerEnd
  1755. && textSpoilerIt->till <= position) {
  1756. ++textSpoilerIt;
  1757. }
  1758. textSpoiler = (textSpoilerIt != textSpoilerEnd
  1759. && textSpoilerIt->from < till)
  1760. ? &*textSpoilerIt
  1761. : nullptr;
  1762. };
  1763. auto emojiSpoilerIt = begin(_spoilerRangesEmoji);
  1764. const auto emojiSpoilerEnd = end(_spoilerRangesEmoji);
  1765. auto emojiSpoiler = (TextRange*)nullptr;
  1766. const auto emojiSpoilerAdjust = [&](int position, int till) {
  1767. if (position >= till) {
  1768. emojiSpoiler = nullptr;
  1769. return;
  1770. }
  1771. while (emojiSpoilerIt != emojiSpoilerEnd
  1772. && emojiSpoilerIt->till <= position) {
  1773. ++emojiSpoilerIt;
  1774. }
  1775. emojiSpoiler = (emojiSpoilerIt != emojiSpoilerEnd
  1776. && emojiSpoilerIt->from < till)
  1777. ? &*emojiSpoilerIt
  1778. : nullptr;
  1779. };
  1780. const auto spoilersAdjust = [&](int position, int till) {
  1781. textSpoilerAdjust(position, till);
  1782. emojiSpoilerAdjust(position, till);
  1783. };
  1784. _spoilerRects.resize(0);
  1785. auto lineStart = 0;
  1786. const auto addSpoiler = [&](QRectF rect, bool blockquote) {
  1787. auto normal = rect.toRect();
  1788. if (lineStart < _spoilerRects.size()) {
  1789. auto &last = _spoilerRects.back();
  1790. if (last.geometry.intersects(normal)) {
  1791. Assert(last.blockquote == blockquote);
  1792. last.geometry = last.geometry.united(normal);
  1793. return;
  1794. }
  1795. }
  1796. _spoilerRects.push_back({ normal, blockquote });
  1797. };
  1798. const auto finishSpoilersLine = [&] {
  1799. if (lineStart == _spoilerRects.size()) {
  1800. return;
  1801. }
  1802. ranges::sort(
  1803. _spoilerRects.begin() + lineStart,
  1804. _spoilerRects.end(),
  1805. ranges::less(),
  1806. [](const SpoilerRect &r) { return r.geometry.x(); });
  1807. auto i = _spoilerRects.begin() + lineStart;
  1808. auto j = i + 1;
  1809. while (j != end(_spoilerRects)) {
  1810. if (i->geometry.x() + i->geometry.width() >= j->geometry.x()) {
  1811. i->geometry = i->geometry.united(j->geometry);
  1812. j = _spoilerRects.erase(j);
  1813. } else {
  1814. i = j++;
  1815. }
  1816. }
  1817. lineStart = int(_spoilerRects.size());
  1818. };
  1819. auto block = document->firstBlock();
  1820. while (block.isValid()) {
  1821. auto belowClip = false;
  1822. auto blockRect = std::optional<QRectF>();
  1823. const auto ensureBlockRect = [&] {
  1824. if (!blockRect) {
  1825. blockRect.emplace(documentLayout->blockBoundingRect(block));
  1826. }
  1827. };
  1828. const auto blockPosition = block.position();
  1829. const auto format = block.blockFormat();
  1830. const auto id = format.property(kQuoteFormatId).toString();
  1831. const auto blockquote = (id == kTagBlockquote);
  1832. const auto collapsed = (id == kTagBlockquoteCollapsed);
  1833. const auto pre = !collapsed && IsTagPre(id);
  1834. spoilersAdjust(blockPosition, blockPosition + block.length());
  1835. if (textSpoiler || emojiSpoiler) {
  1836. ensureShift();
  1837. ensureBlockRect();
  1838. const auto fullShift = blockRect->topLeft() + *shift;
  1839. if (fullShift.y() >= clip.y() + clip.height()) {
  1840. belowClip = true;
  1841. } else if (fullShift.y() + blockRect->height() > clip.y()) {
  1842. const auto blockLayout = block.layout();
  1843. const auto lines = std::max(blockLayout->lineCount(), 0);
  1844. for (auto i = 0; i != lines; ++i) {
  1845. const auto line = blockLayout->lineAt(i);
  1846. const auto top = fullShift.y() + line.y();
  1847. const auto height = line.height();
  1848. if (top + height <= clip.y()) {
  1849. continue;
  1850. } else if (top >= clip.y() + clip.height()) {
  1851. belowClip = true;
  1852. break;
  1853. }
  1854. const auto lineFrom = blockPosition + line.textStart();
  1855. const auto lineTill = lineFrom + line.textLength();
  1856. textSpoilerAdjust(lineFrom, lineTill);
  1857. while (textSpoiler) {
  1858. const auto from = std::max(textSpoiler->from, lineFrom);
  1859. const auto runs = line.glyphRuns(
  1860. std::max(textSpoiler->from, lineFrom) - blockPosition,
  1861. std::min(textSpoiler->till, lineTill) - from);
  1862. for (const auto &run : runs) {
  1863. const auto runRect = run.boundingRect();
  1864. addSpoiler(
  1865. QRectF(
  1866. fullShift.x() + runRect.x(),
  1867. top,
  1868. runRect.width(),
  1869. height),
  1870. blockquote);
  1871. }
  1872. textSpoilerAdjust(textSpoiler->till, lineTill);
  1873. }
  1874. emojiSpoilerAdjust(lineFrom, lineTill);
  1875. while (emojiSpoiler) {
  1876. const auto from = std::max(emojiSpoiler->from, lineFrom);
  1877. const auto till = std::min(emojiSpoiler->till, lineTill);
  1878. const auto x = line.cursorToX(from - blockPosition);
  1879. const auto width = line.cursorToX(till - blockPosition) - x;
  1880. addSpoiler(
  1881. QRectF(
  1882. fullShift.x() + std::min(x, x + width),
  1883. top,
  1884. std::abs(width),
  1885. height),
  1886. blockquote);
  1887. emojiSpoilerAdjust(emojiSpoiler->till, lineTill);
  1888. }
  1889. finishSpoilersLine();
  1890. }
  1891. }
  1892. }
  1893. const auto st = pre
  1894. ? &_st.style.pre
  1895. : (blockquote || collapsed)
  1896. ? &_st.style.blockquote
  1897. : nullptr;
  1898. if (st) {
  1899. if (!shift) {
  1900. shift.emplace(
  1901. -_inner->horizontalScrollBar()->value(),
  1902. -_inner->verticalScrollBar()->value());
  1903. }
  1904. if (!blockRect) {
  1905. blockRect.emplace(documentLayout->blockBoundingRect(block));
  1906. }
  1907. const auto rect = blockRect->toRect();
  1908. const auto added = pre
  1909. ? QMargins(0, 0, 0, st->verticalSkip)
  1910. : QMargins();
  1911. const auto target = ExtendForPaint(
  1912. rect.marginsAdded(added),
  1913. *st
  1914. ).translated(*shift);
  1915. if (target.intersects(clip)) {
  1916. ensurePainter();
  1917. const auto cache = pre ? _preCache() : _blockquoteCache();
  1918. const auto collapsible = !pre
  1919. && !collapsed
  1920. && (rect.height() > collapsedCutoff);
  1921. Text::ValidateQuotePaintCache(*cache, *st);
  1922. Text::FillQuotePaint(*p, target, *cache, *st, {
  1923. .expandIcon = collapsed,
  1924. .collapseIcon = collapsible,
  1925. });
  1926. if (!pre) {
  1927. _blockquoteBg = cache->bg;
  1928. }
  1929. if (st->header > 0) {
  1930. const auto font = _st.style.font->monospace();
  1931. const auto topleft = target.topLeft();
  1932. const auto position = topleft + st->headerPosition;
  1933. const auto baseline = position + QPoint(0, font->ascent);
  1934. p->setFont(font);
  1935. p->setPen(st::defaultTextPalette.monoFg);
  1936. p->drawText(
  1937. baseline,
  1938. format.property(kPreLanguage).toString());
  1939. }
  1940. }
  1941. }
  1942. if (belowClip) {
  1943. break;
  1944. }
  1945. block = block.next();
  1946. }
  1947. }
  1948. void InputField::setDocumentMargin(float64 margin) {
  1949. _settingDocumentMargin = true;
  1950. document()->setDocumentMargin(margin);
  1951. _settingDocumentMargin = false;
  1952. }
  1953. void InputField::setAdditionalMargin(int margin) {
  1954. setAdditionalMargins({ margin, margin, margin, margin });
  1955. }
  1956. void InputField::setAdditionalMargins(QMargins margins) {
  1957. _additionalMargins = margins;
  1958. QResizeEvent e(size(), size());
  1959. QCoreApplication::sendEvent(this, &e);
  1960. }
  1961. void InputField::setMaxLength(int length) {
  1962. if (_maxLength != length) {
  1963. _maxLength = length;
  1964. if (_maxLength > 0) {
  1965. const auto document = _inner->document();
  1966. _correcting = true;
  1967. QTextCursor(document).joinPreviousEditBlock();
  1968. const auto guard = gsl::finally([&] {
  1969. _correcting = false;
  1970. QTextCursor(document).endEditBlock();
  1971. handleContentsChanged();
  1972. });
  1973. auto cursor = QTextCursor(document);
  1974. cursor.movePosition(QTextCursor::End);
  1975. chopByMaxLength(0, cursor.position());
  1976. }
  1977. }
  1978. }
  1979. void InputField::setMinHeight(int height) {
  1980. _minHeight = height;
  1981. }
  1982. void InputField::setMaxHeight(int height) {
  1983. _maxHeight = height;
  1984. }
  1985. void InputField::insertTag(const QString &text, QString tagId) {
  1986. auto cursor = textCursor();
  1987. const auto position = cursor.position();
  1988. const auto document = _inner->document();
  1989. auto block = document->findBlock(position);
  1990. for (auto iter = block.begin(); !iter.atEnd(); ++iter) {
  1991. auto fragment = iter.fragment();
  1992. Assert(fragment.isValid());
  1993. const auto fragmentPosition = fragment.position();
  1994. const auto fragmentEnd = (fragmentPosition + fragment.length());
  1995. if (fragmentPosition >= position || fragmentEnd < position) {
  1996. continue;
  1997. }
  1998. const auto format = fragment.charFormat();
  1999. if (format.isImageFormat()) {
  2000. continue;
  2001. }
  2002. auto mentionInCommand = false;
  2003. const auto fragmentText = fragment.text();
  2004. for (auto i = position - fragmentPosition; i > 0; --i) {
  2005. const auto previous = fragmentText[i - 1];
  2006. if (previous == '@' || previous == '#' || previous == '/') {
  2007. if ((i == position - fragmentPosition
  2008. || (previous == '/'
  2009. ? fragmentText[i].isLetterOrNumber()
  2010. : fragmentText[i].isLetter())
  2011. || previous == '#') &&
  2012. (i < 2 || !(fragmentText[i - 2].isLetterOrNumber()
  2013. || fragmentText[i - 2] == '_'))) {
  2014. cursor.setPosition(fragmentPosition + i - 1);
  2015. auto till = fragmentPosition + i;
  2016. for (; (till < fragmentEnd && till < position); ++till) {
  2017. const auto ch = fragmentText[till - fragmentPosition];
  2018. if (!ch.isLetterOrNumber() && ch != '_' && ch != '@') {
  2019. break;
  2020. }
  2021. }
  2022. if (till < fragmentEnd
  2023. && fragmentText[till - fragmentPosition] == ' ') {
  2024. ++till;
  2025. }
  2026. cursor.setPosition(till, QTextCursor::KeepAnchor);
  2027. break;
  2028. } else if ((i == position - fragmentPosition
  2029. || fragmentText[i].isLetter())
  2030. && fragmentText[i - 1] == '@'
  2031. && (i > 2)
  2032. && (fragmentText[i - 2].isLetterOrNumber()
  2033. || fragmentText[i - 2] == '_')
  2034. && !mentionInCommand) {
  2035. mentionInCommand = true;
  2036. --i;
  2037. continue;
  2038. }
  2039. break;
  2040. }
  2041. if (position - fragmentPosition - i > 127
  2042. || (!mentionInCommand
  2043. && (position - fragmentPosition - i > 63))
  2044. || (!fragmentText[i - 1].isLetterOrNumber()
  2045. && fragmentText[i - 1] != '_')) {
  2046. break;
  2047. }
  2048. }
  2049. break;
  2050. }
  2051. if (tagId.isEmpty()) {
  2052. cursor.insertText(text + ' ', _defaultCharFormat);
  2053. } else {
  2054. _insertedTags.clear();
  2055. _insertedTags.push_back({ 0, int(text.size()), tagId });
  2056. _insertedTagsAreFromMime = false;
  2057. cursor.insertText(text + ' ');
  2058. _insertedTags.clear();
  2059. }
  2060. }
  2061. bool InputField::heightAutoupdated() {
  2062. if (_minHeight < 0
  2063. || _maxHeight < 0
  2064. || _inHeightCheck
  2065. || _mode == Mode::SingleLine) {
  2066. return false;
  2067. }
  2068. _inHeightCheck = true;
  2069. const auto guard = gsl::finally([&] { _inHeightCheck = false; });
  2070. SendPendingMoveResizeEvents(this);
  2071. const auto contentHeight = int(std::ceil(document()->size().height()))
  2072. + _st.textMargins.top()
  2073. + _st.textMargins.bottom()
  2074. + _additionalMargins.top()
  2075. + _additionalMargins.bottom();
  2076. const auto newHeight = std::clamp(contentHeight, _minHeight, _maxHeight);
  2077. if (height() != newHeight) {
  2078. resize(width(), newHeight);
  2079. return true;
  2080. }
  2081. return false;
  2082. }
  2083. void InputField::checkContentHeight() {
  2084. if (heightAutoupdated()) {
  2085. _heightChanges.fire({});
  2086. }
  2087. }
  2088. void InputField::handleTouchEvent(QTouchEvent *e) {
  2089. switch (e->type()) {
  2090. case QEvent::TouchBegin: {
  2091. if (_touchPress || e->touchPoints().isEmpty()) {
  2092. return;
  2093. }
  2094. _touchTimer.callOnce(QApplication::startDragTime());
  2095. _touchPress = true;
  2096. _touchMove = _touchRightButton = false;
  2097. _touchStart = e->touchPoints().cbegin()->screenPos().toPoint();
  2098. } break;
  2099. case QEvent::TouchUpdate: {
  2100. if (!e->touchPoints().isEmpty()) {
  2101. touchUpdate(e->touchPoints().cbegin()->screenPos().toPoint());
  2102. }
  2103. } break;
  2104. case QEvent::TouchEnd: {
  2105. touchFinish();
  2106. } break;
  2107. case QEvent::TouchCancel: {
  2108. _touchPress = false;
  2109. _touchTimer.cancel();
  2110. } break;
  2111. }
  2112. }
  2113. void InputField::touchUpdate(QPoint globalPosition) {
  2114. if (_touchPress
  2115. && !_touchMove
  2116. && ((globalPosition - _touchStart).manhattanLength()
  2117. >= QApplication::startDragDistance())) {
  2118. _touchMove = true;
  2119. }
  2120. }
  2121. void InputField::touchFinish() {
  2122. if (!_touchPress) {
  2123. return;
  2124. }
  2125. const auto weak = MakeWeak(this);
  2126. if (!_touchMove && window()) {
  2127. QPoint mapped(mapFromGlobal(_touchStart));
  2128. if (_touchRightButton) {
  2129. QContextMenuEvent contextEvent(
  2130. QContextMenuEvent::Mouse,
  2131. mapped,
  2132. _touchStart);
  2133. contextMenuEvent(&contextEvent);
  2134. } else {
  2135. QGuiApplication::inputMethod()->show();
  2136. }
  2137. }
  2138. if (weak) {
  2139. _touchTimer.cancel();
  2140. _touchPress
  2141. = _touchMove
  2142. = _touchRightButton
  2143. = _mousePressedInTouch = false;
  2144. }
  2145. }
  2146. void InputField::paintSurrounding(
  2147. QPainter &p,
  2148. QRect clip,
  2149. float64 errorDegree,
  2150. float64 focusedDegree) {
  2151. if (_st.borderRadius > 0) {
  2152. paintRoundSurrounding(p, clip, errorDegree, focusedDegree);
  2153. } else {
  2154. paintFlatSurrounding(p, clip, errorDegree, focusedDegree);
  2155. }
  2156. }
  2157. void InputField::paintRoundSurrounding(
  2158. QPainter &p,
  2159. QRect clip,
  2160. float64 errorDegree,
  2161. float64 focusedDegree) {
  2162. const auto divide = _st.borderDenominator ? _st.borderDenominator : 1;
  2163. const auto border = _st.border / float64(divide);
  2164. const auto borderHalf = border / 2.;
  2165. auto pen = anim::pen(_st.borderFg, _st.borderFgActive, focusedDegree);
  2166. pen.setWidthF(border);
  2167. p.setPen(pen);
  2168. p.setBrush(anim::brush(_st.textBg, _st.textBgActive, focusedDegree));
  2169. PainterHighQualityEnabler hq(p);
  2170. const auto radius = _st.borderRadius - borderHalf;
  2171. p.drawRoundedRect(
  2172. QRectF(0, 0, width(), height()).marginsRemoved(
  2173. QMarginsF(borderHalf, borderHalf, borderHalf, borderHalf)),
  2174. radius,
  2175. radius);
  2176. }
  2177. void InputField::paintFlatSurrounding(
  2178. QPainter &p,
  2179. QRect clip,
  2180. float64 errorDegree,
  2181. float64 focusedDegree) {
  2182. if (_st.textBg->c.alphaF() > 0.) {
  2183. p.fillRect(clip, _st.textBg);
  2184. }
  2185. if (_st.border) {
  2186. p.fillRect(0, height() - _st.border, width(), _st.border, _st.borderFg);
  2187. }
  2188. const auto borderShownDegree = _a_borderShown.value(1.);
  2189. const auto borderOpacity = _a_borderOpacity.value(_borderVisible ? 1. : 0.);
  2190. if (_st.borderActive && (borderOpacity > 0.)) {
  2191. auto borderStart = std::clamp(_borderAnimationStart, 0, width());
  2192. auto borderFrom = qRound(borderStart * (1. - borderShownDegree));
  2193. auto borderTo = borderStart + qRound((width() - borderStart) * borderShownDegree);
  2194. if (borderTo > borderFrom) {
  2195. auto borderFg = anim::brush(_st.borderFgActive, _st.borderFgError, errorDegree);
  2196. p.setOpacity(borderOpacity);
  2197. p.fillRect(borderFrom, height() - _st.borderActive, borderTo - borderFrom, _st.borderActive, borderFg);
  2198. p.setOpacity(1);
  2199. }
  2200. }
  2201. }
  2202. void InputField::paintEvent(QPaintEvent *e) {
  2203. auto p = QPainter(this);
  2204. const auto r = rect().intersected(e->rect());
  2205. const auto errorDegree = _a_error.value(_error ? 1. : 0.);
  2206. const auto focusedDegree = _a_focused.value(_focused ? 1. : 0.);
  2207. paintSurrounding(p, r, errorDegree, focusedDegree);
  2208. const auto skip = int(base::SafeRound(_inner->document()->documentMargin()));
  2209. const auto margins = _st.textMargins
  2210. + _st.placeholderMargins
  2211. + QMargins(skip, skip + _placeholderCustomFontSkip, skip, 0)
  2212. + _additionalMargins
  2213. + _customFontMargins;
  2214. if (_st.placeholderScale > 0. && !_placeholderPath.isEmpty()) {
  2215. auto placeholderShiftDegree = _a_placeholderShifted.value(_placeholderShifted ? 1. : 0.);
  2216. p.save();
  2217. p.setClipRect(r);
  2218. auto placeholderTop = anim::interpolate(0, _st.placeholderShift, placeholderShiftDegree);
  2219. QRect r(rect().marginsRemoved(margins));
  2220. r.moveTop(r.top() + placeholderTop);
  2221. if (style::RightToLeft()) r.moveLeft(width() - r.left() - r.width());
  2222. auto placeholderScale = 1. - (1. - _st.placeholderScale) * placeholderShiftDegree;
  2223. auto placeholderFg = anim::color(_st.placeholderFg, _st.placeholderFgActive, focusedDegree);
  2224. placeholderFg = anim::color(placeholderFg, _st.placeholderFgError, errorDegree);
  2225. PainterHighQualityEnabler hq(p);
  2226. p.setPen(Qt::NoPen);
  2227. p.setBrush(placeholderFg);
  2228. p.translate(r.topLeft());
  2229. p.scale(placeholderScale, placeholderScale);
  2230. p.drawPath(_placeholderPath);
  2231. p.restore();
  2232. } else if (!_placeholder.isEmpty()) {
  2233. const auto placeholderHiddenDegree = _a_placeholderShifted.value(_placeholderShifted ? 1. : 0.);
  2234. if (placeholderHiddenDegree < 1.) {
  2235. p.setOpacity(1. - placeholderHiddenDegree);
  2236. p.save();
  2237. p.setClipRect(r);
  2238. const auto placeholderLeft = anim::interpolate(0, -_st.placeholderShift, placeholderHiddenDegree);
  2239. p.setFont(_st.placeholderFont);
  2240. p.setPen(anim::pen(_st.placeholderFg, _st.placeholderFgActive, focusedDegree));
  2241. if (_st.placeholderAlign == style::al_topleft && _placeholderAfterSymbols > 0) {
  2242. const auto skipWidth = placeholderSkipWidth();
  2243. p.drawText(
  2244. margins.left() + skipWidth,
  2245. margins.top() + _st.placeholderFont->ascent,
  2246. _placeholder);
  2247. } else {
  2248. auto r = rect().marginsRemoved(margins);
  2249. r.moveLeft(r.left() + placeholderLeft);
  2250. if (style::RightToLeft()) r.moveLeft(width() - r.left() - r.width());
  2251. p.drawText(r, _placeholder, _st.placeholderAlign);
  2252. }
  2253. p.restore();
  2254. }
  2255. }
  2256. RpWidget::paintEvent(e);
  2257. }
  2258. int InputField::placeholderSkipWidth() const {
  2259. if (!_placeholderAfterSymbols) {
  2260. return 0;
  2261. }
  2262. const auto &text = getTextWithTags().text;
  2263. auto result = _st.style.font->width(
  2264. text.mid(0, _placeholderAfterSymbols));
  2265. if (_placeholderAfterSymbols > text.size()) {
  2266. result += _st.style.font->spacew;
  2267. }
  2268. return result;
  2269. }
  2270. void InputField::startBorderAnimation() {
  2271. auto borderVisible = (_error || _focused);
  2272. if (_borderVisible != borderVisible) {
  2273. _borderVisible = borderVisible;
  2274. if (_borderVisible) {
  2275. if (_a_borderOpacity.animating()) {
  2276. _a_borderOpacity.start([this] { update(); }, 0., 1., _st.duration);
  2277. } else {
  2278. _a_borderShown.start([this] { update(); }, 0., 1., _st.duration);
  2279. }
  2280. } else {
  2281. _a_borderOpacity.start([this] { update(); }, 1., 0., _st.duration);
  2282. }
  2283. }
  2284. }
  2285. void InputField::focusInEvent(QFocusEvent *e) {
  2286. _borderAnimationStart = (e->reason() == Qt::MouseFocusReason)
  2287. ? mapFromGlobal(QCursor::pos()).x()
  2288. : (width() / 2);
  2289. InvokeQueued(this, [=] {
  2290. if (QWidget::hasFocus()) {
  2291. focusInner();
  2292. }
  2293. });
  2294. }
  2295. void InputField::mousePressEvent(QMouseEvent *e) {
  2296. _borderAnimationStart = e->pos().x();
  2297. InvokeQueued(this, [=] { focusInner(); });
  2298. }
  2299. void InputField::mousePressEventInner(QMouseEvent *e) {
  2300. if (_touchPress && e->button() == Qt::LeftButton) {
  2301. _mousePressedInTouch = true;
  2302. _touchStart = e->globalPos();
  2303. } else {
  2304. _selectedActionQuoteId = lookupActionQuoteId(e->pos());
  2305. _pressedActionQuoteId = _selectedActionQuoteId;
  2306. updateCursorShape();
  2307. }
  2308. if (_pressedActionQuoteId <= 0) {
  2309. _inner->QTextEdit::mousePressEvent(e);
  2310. }
  2311. }
  2312. void InputField::editPreLanguage(int quoteId, QStringView tag) {
  2313. Expects(IsTagPre(tag));
  2314. if (!_editLanguageCallback) {
  2315. return;
  2316. }
  2317. const auto apply = crl::guard(this, [=](QString language) {
  2318. auto block = FindBlock(document(), quoteId);
  2319. if (block.isValid()) {
  2320. const auto id = kTagPre + language;
  2321. _insertedTags = { { block.position(), block.length() - 1, id } };
  2322. auto cursor = QTextCursor(document());
  2323. cursor.setPosition(block.position());
  2324. cursor.setBlockFormat(PrepareBlockFormat(_st, id));
  2325. _insertedTags.clear();
  2326. }
  2327. });
  2328. _editLanguageCallback(tag.mid(kTagPre.size()).toString(), apply);
  2329. }
  2330. void InputField::trippleEnterExitBlock(QTextCursor &cursor) {
  2331. const auto block = cursor.block();
  2332. if (!HasBlockTag(block)) {
  2333. return;
  2334. }
  2335. const auto document = cursor.document();
  2336. const auto position = cursor.position();
  2337. const auto blockFrom = block.position();
  2338. const auto blockTill = blockFrom + block.length();
  2339. if (blockTill - blockFrom <= 3
  2340. || (position != blockFrom + 3 && position != blockTill - 1)) {
  2341. return;
  2342. } else if (document->characterAt(position - 1) != kSoftLine
  2343. || document->characterAt(position - 2) != kSoftLine
  2344. || document->characterAt(position - 3) != kSoftLine) {
  2345. return;
  2346. }
  2347. const auto before = (position == blockFrom + 3);
  2348. cursor.setPosition(position - 3, QTextCursor::KeepAnchor);
  2349. cursor.insertText(
  2350. QString(QChar(kHardLine)),
  2351. before ? cursor.charFormat() : _defaultCharFormat);
  2352. if (before) {
  2353. cursor.setPosition(cursor.position() - 1);
  2354. }
  2355. cursor.setBlockFormat(PrepareBlockFormat(_st));
  2356. if (before) {
  2357. setTextCursor(cursor);
  2358. }
  2359. }
  2360. void InputField::toggleBlockquoteCollapsed(
  2361. int quoteId,
  2362. QStringView tag,
  2363. TextRange range) {
  2364. if (!_customObject) {
  2365. return;
  2366. }
  2367. const auto collapsed = (tag == kTagBlockquoteCollapsed);
  2368. auto text = getTextWithTagsPart(range.from, range.till);
  2369. for (auto i = text.tags.begin(); i != text.tags.end();) {
  2370. auto without = WithBlockTagRemoved(i->id);
  2371. if (without.isEmpty()) {
  2372. i = text.tags.erase(i);
  2373. } else {
  2374. i->id = std::move(without);
  2375. ++i;
  2376. }
  2377. }
  2378. if (!collapsed) {
  2379. _customObject->setCollapsedText(quoteId, std::move(text));
  2380. }
  2381. _insertedTagsDelayClear = true;
  2382. const auto now = collapsed ? kTagBlockquote : kTagBlockquoteCollapsed;
  2383. auto cursor = QTextCursor(document());
  2384. cursor.beginEditBlock();
  2385. cursor.setPosition(range.from);
  2386. cursor.setPosition(range.till, QTextCursor::KeepAnchor);
  2387. cursor.removeSelectedText();
  2388. cursor.setBlockFormat(PrepareBlockFormat(_st, now, quoteId));
  2389. if (collapsed) {
  2390. insertWithTags(
  2391. { range.from, range.from },
  2392. WrapInQuote(std::move(text), kTagBlockquote));
  2393. } else {
  2394. cursor.insertText(
  2395. kObjectReplacement,
  2396. PrepareCollapsedQuoteFormat(quoteId));
  2397. const auto now = cursor.position();
  2398. cursor.movePosition(QTextCursor::End);
  2399. if (cursor.position() == now) {
  2400. cursor.insertBlock(PrepareBlockFormat(_st), _defaultCharFormat);
  2401. } else {
  2402. cursor.setPosition(now + 1);
  2403. }
  2404. }
  2405. cursor.endEditBlock();
  2406. _insertedTagsDelayClear = false;
  2407. _insertedTags.clear();
  2408. _realInsertPosition = -1;
  2409. setTextCursor(cursor);
  2410. }
  2411. void InputField::blockActionClicked(int quoteId) {
  2412. auto block = FindBlock(document(), quoteId);
  2413. const auto format = block.blockFormat();
  2414. const auto tag = format.property(kQuoteFormatId).toString();
  2415. const auto blockTag = FindBlockTag(tag);
  2416. if (IsTagPre(blockTag)) {
  2417. editPreLanguage(quoteId, blockTag);
  2418. } else {
  2419. toggleBlockquoteCollapsed(
  2420. quoteId,
  2421. blockTag,
  2422. { block.position(), block.position() + block.length() - 1 });
  2423. }
  2424. }
  2425. void InputField::mouseReleaseEventInner(QMouseEvent *e) {
  2426. _selectedActionQuoteId = lookupActionQuoteId(e->pos());
  2427. const auto taken = std::exchange(_pressedActionQuoteId, -1);
  2428. if (taken > 0 && taken == _selectedActionQuoteId) {
  2429. blockActionClicked(taken);
  2430. }
  2431. updateCursorShape();
  2432. if (_mousePressedInTouch) {
  2433. touchFinish();
  2434. } else {
  2435. _inner->QTextEdit::mouseReleaseEvent(e);
  2436. }
  2437. }
  2438. void InputField::mouseMoveEventInner(QMouseEvent *e) {
  2439. if (_mousePressedInTouch) {
  2440. touchUpdate(e->globalPos());
  2441. }
  2442. _selectedActionQuoteId = lookupActionQuoteId(e->pos());
  2443. updateCursorShape();
  2444. _inner->QTextEdit::mouseMoveEvent(e);
  2445. }
  2446. int InputField::lookupActionQuoteId(QPoint point) const {
  2447. auto shift = std::optional<QPoint>();
  2448. const auto document = _inner->document();
  2449. const auto layout = document->documentLayout();
  2450. const auto collapsedCutoff = CollapsedQuoteCutoff(_st);
  2451. auto block = document->firstBlock();
  2452. while (block.isValid()) {
  2453. const auto format = block.blockFormat();
  2454. const auto id = format.property(kQuoteFormatId).toString();
  2455. const auto collapsed = (id == kTagBlockquoteCollapsed);
  2456. const auto pre = !collapsed && IsTagPre(id);
  2457. const auto st = pre
  2458. ? &_st.style.pre
  2459. : (id == kTagBlockquote || collapsed)
  2460. ? &_st.style.blockquote
  2461. : nullptr;
  2462. if (st) {
  2463. if (!shift) {
  2464. shift.emplace(
  2465. -_inner->horizontalScrollBar()->value(),
  2466. -_inner->verticalScrollBar()->value());
  2467. }
  2468. const auto rect = layout->blockBoundingRect(block).toRect();
  2469. const auto added = IsTagPre(id)
  2470. ? QMargins(0, 0, 0, st->verticalSkip)
  2471. : QMargins();
  2472. const auto target = ExtendForPaint(
  2473. rect.marginsAdded(added),
  2474. *st
  2475. ).translated(*shift);
  2476. if (pre
  2477. && QRect(
  2478. target.x(),
  2479. target.y(),
  2480. target.width(),
  2481. st->header).contains(point)) {
  2482. return format.property(kQuoteId).toInt();
  2483. } else if (!pre
  2484. && (collapsed || rect.height() > collapsedCutoff)) {
  2485. const auto right = target.x() + target.width();
  2486. const auto bottom = target.y() + target.height();
  2487. const auto w = st->expand.width() + st->expandPosition.x();
  2488. const auto h = st->expand.height() + st->expandPosition.y();
  2489. if (QRect(right - w, bottom - h, w, h).contains(point)) {
  2490. return format.property(kQuoteId).toInt();
  2491. }
  2492. }
  2493. }
  2494. block = block.next();
  2495. }
  2496. return 0;
  2497. }
  2498. void InputField::updateCursorShape() {
  2499. const auto check = (_pressedActionQuoteId < 0)
  2500. ? _selectedActionQuoteId
  2501. : _pressedActionQuoteId;
  2502. _inner->viewport()->setCursor(check > 0
  2503. ? style::cur_pointer
  2504. : style::cur_text);
  2505. }
  2506. void InputField::leaveEventInner(QEvent *e) {
  2507. _selectedActionQuoteId = 0;
  2508. _inner->viewport()->setCursor(style::cur_text);
  2509. _inner->QTextEdit::leaveEvent(e);
  2510. }
  2511. void InputField::focusInner() {
  2512. auto borderStart = _borderAnimationStart;
  2513. _inner->setFocus();
  2514. _borderAnimationStart = borderStart;
  2515. }
  2516. int InputField::borderAnimationStart() const {
  2517. return _borderAnimationStart;
  2518. }
  2519. void InputField::contextMenuEvent(QContextMenuEvent *e) {
  2520. _inner->contextMenuEvent(e);
  2521. }
  2522. void InputField::focusInEventInner(QFocusEvent *e) {
  2523. _borderAnimationStart = (e->reason() == Qt::MouseFocusReason)
  2524. ? mapFromGlobal(QCursor::pos()).x()
  2525. : (width() / 2);
  2526. setFocused(true);
  2527. _inner->QTextEdit::focusInEvent(e);
  2528. _focusedChanges.fire(true);
  2529. }
  2530. void InputField::focusOutEventInner(QFocusEvent *e) {
  2531. setFocused(false);
  2532. _inner->QTextEdit::focusOutEvent(e);
  2533. _focusedChanges.fire(false);
  2534. }
  2535. void InputField::setFocused(bool focused) {
  2536. if (_focused != focused) {
  2537. _focused = focused;
  2538. _a_focused.start([this] { update(); }, _focused ? 0. : 1., _focused ? 1. : 0., _st.duration);
  2539. startPlaceholderAnimation();
  2540. startBorderAnimation();
  2541. }
  2542. }
  2543. QSize InputField::sizeHint() const {
  2544. return geometry().size();
  2545. }
  2546. QSize InputField::minimumSizeHint() const {
  2547. return geometry().size();
  2548. }
  2549. bool InputField::hasText() const {
  2550. const auto document = _inner->document();
  2551. const auto from = document->begin();
  2552. const auto till = document->end();
  2553. if (from == till) {
  2554. return false;
  2555. }
  2556. for (auto item = from.begin(); !item.atEnd(); ++item) {
  2557. const auto fragment = item.fragment();
  2558. if (!fragment.isValid()) {
  2559. continue;
  2560. } else if (!fragment.text().isEmpty()) {
  2561. return true;
  2562. }
  2563. }
  2564. return (from.next() != till);
  2565. }
  2566. QString InputField::getTextPart(
  2567. int start,
  2568. int end,
  2569. TagList &outTagsList,
  2570. bool &outTagsChanged,
  2571. std::vector<MarkdownTag> *outMarkdownTags) const {
  2572. Expects((start == 0 && end < 0) || outMarkdownTags == nullptr);
  2573. if (end >= 0 && end <= start) {
  2574. outTagsChanged = !outTagsList.isEmpty();
  2575. outTagsList.clear();
  2576. return {};
  2577. }
  2578. if (start < 0) {
  2579. start = 0;
  2580. }
  2581. const auto full = (start == 0 && end < 0);
  2582. auto textSpoilers = std::optional<RangeAccumulator>();
  2583. auto emojiSpoilers = std::optional<RangeAccumulator>();
  2584. if (full) {
  2585. textSpoilers.emplace(_spoilerRangesText);
  2586. emojiSpoilers.emplace(_spoilerRangesEmoji);
  2587. }
  2588. auto lastTag = QString();
  2589. TagAccumulator tagAccumulator(outTagsList);
  2590. MarkdownTagAccumulator markdownTagAccumulator(outMarkdownTags);
  2591. const auto newline = outMarkdownTags ? QString(1, '\n') : QString();
  2592. const auto document = _inner->document();
  2593. const auto from = full ? document->begin() : document->findBlock(start);
  2594. auto till = (end < 0) ? document->end() : document->findBlock(end);
  2595. if (till.isValid()) {
  2596. till = till.next();
  2597. }
  2598. auto possibleLength = 0;
  2599. for (auto block = from; block != till; block = block.next()) {
  2600. possibleLength += block.length();
  2601. }
  2602. auto result = QString();
  2603. result.reserve(possibleLength);
  2604. if (!full && end < 0) {
  2605. end = possibleLength;
  2606. }
  2607. for (auto block = from; block != till;) {
  2608. // Only full blocks add block tags.
  2609. const auto blockFormat = full
  2610. ? block.blockFormat()
  2611. : (start > block.position()
  2612. || end + 1 < block.position() + block.length())
  2613. ? QTextBlockFormat()
  2614. : block.blockFormat();
  2615. for (auto item = block.begin(); !item.atEnd(); ++item) {
  2616. const auto fragment = item.fragment();
  2617. if (!fragment.isValid()) {
  2618. continue;
  2619. }
  2620. const auto fragmentPosition = full ? 0 : fragment.position();
  2621. const auto fragmentEnd = full
  2622. ? 0
  2623. : (fragmentPosition + fragment.length());
  2624. const auto format = fragment.charFormat();
  2625. if (!full) {
  2626. if (fragmentPosition == end) {
  2627. const auto tag = FullTag(format, blockFormat);
  2628. tagAccumulator.feed(tag, result.size());
  2629. break;
  2630. } else if (fragmentPosition > end) {
  2631. break;
  2632. } else if (fragmentEnd <= start) {
  2633. continue;
  2634. }
  2635. }
  2636. const auto emojiText = [&] {
  2637. if (format.isImageFormat()) {
  2638. const auto imageName = format.toImageFormat().name();
  2639. if (const auto emoji = Emoji::FromUrl(imageName)) {
  2640. return emoji->text();
  2641. }
  2642. }
  2643. return format.property(kCustomEmojiText).toString();
  2644. }();
  2645. auto text = [&] {
  2646. const auto result = fragment.text();
  2647. if (!full) {
  2648. if (fragmentPosition < start) {
  2649. return result.mid(start - fragmentPosition, end - start);
  2650. } else if (fragmentEnd > end) {
  2651. return result.mid(0, end - fragmentPosition);
  2652. }
  2653. }
  2654. return result;
  2655. }();
  2656. if (full || !text.isEmpty()) {
  2657. lastTag = FullTag(format, blockFormat);
  2658. tagAccumulator.feed(lastTag, result.size());
  2659. if (textSpoilers && HasSpoilerTag(lastTag)) {
  2660. const auto offset = fragment.position();
  2661. const auto length = fragment.length();
  2662. if (!emojiText.isEmpty()) {
  2663. emojiSpoilers->add(offset, length);
  2664. } else {
  2665. textSpoilers->add(offset, length);
  2666. }
  2667. }
  2668. }
  2669. auto begin = text.data();
  2670. auto ch = begin;
  2671. auto adjustedLength = text.size();
  2672. for (const auto end = begin + text.size(); ch != end; ++ch) {
  2673. if (IsNewline(*ch) && ch->unicode() != '\r') {
  2674. *ch = QLatin1Char('\n');
  2675. } else switch (ch->unicode()) {
  2676. case QChar::ObjectReplacementCharacter: {
  2677. if (ch > begin) {
  2678. result.append(begin, ch - begin);
  2679. }
  2680. const auto tag = blockFormat.property(kQuoteFormatId);
  2681. const auto quote = FindBlockTag(tag.toString());
  2682. if (quote == kTagBlockquoteCollapsed) {
  2683. auto collapsed = _customObject
  2684. ? _customObject->collapsedText(
  2685. blockFormat.property(kQuoteId).toInt())
  2686. : TextWithTags();
  2687. adjustedLength += collapsed.text.size() - 1;
  2688. auto from = int(result.size());
  2689. tagAccumulator.feed(kTagBlockquoteCollapsed, from);
  2690. for (const auto &tag : collapsed.tags) {
  2691. tagAccumulator.feed(
  2692. TextUtilities::TagWithAdded(
  2693. tag.id,
  2694. kTagBlockquoteCollapsed),
  2695. from + tag.offset);
  2696. tagAccumulator.feed(
  2697. kTagBlockquoteCollapsed,
  2698. from + tag.offset + tag.length);
  2699. }
  2700. result.append(collapsed.text);
  2701. } else {
  2702. adjustedLength += emojiText.size() - 1;
  2703. if (!emojiText.isEmpty()) {
  2704. result.append(emojiText);
  2705. }
  2706. }
  2707. begin = ch + 1;
  2708. } break;
  2709. }
  2710. }
  2711. if (ch > begin) {
  2712. result.append(begin, ch - begin);
  2713. }
  2714. if (full || !text.isEmpty()) {
  2715. markdownTagAccumulator.feed(text, adjustedLength, lastTag);
  2716. }
  2717. }
  2718. block = block.next();
  2719. if (block != till) {
  2720. tagAccumulator.feed(
  2721. TagWithoutCustomEmoji(
  2722. FullTag(block.charFormat(), QTextBlockFormat())),
  2723. result.size());
  2724. result.append('\n');
  2725. markdownTagAccumulator.feed(newline, 1, lastTag);
  2726. }
  2727. }
  2728. tagAccumulator.feed(QString(), result.size());
  2729. tagAccumulator.finish();
  2730. markdownTagAccumulator.finish();
  2731. outTagsChanged = tagAccumulator.changed();
  2732. return result;
  2733. }
  2734. bool InputField::isUndoAvailable() const {
  2735. return _undoAvailable;
  2736. }
  2737. bool InputField::isRedoAvailable() const {
  2738. return _redoAvailable;
  2739. }
  2740. void InputField::processFormatting(int insertPosition, int insertEnd) {
  2741. // Tilde formatting.
  2742. const auto ratio = style::DevicePixelRatio();
  2743. const auto processTilde = (_st.style.font->f.pixelSize() * ratio == 13)
  2744. && (_st.style.font->f.family() == qstr("Open Sans"));
  2745. auto isTildeFragment = false;
  2746. auto tildeFixedFont = _st.style.font->semibold()->f;
  2747. // First tag handling (the one we inserted text to).
  2748. bool startTagFound = false;
  2749. bool breakTagOnNotLetter = false;
  2750. auto document = _inner->document();
  2751. // Apply inserted tags.
  2752. const auto insertedTagsProcessor = _insertedTagsAreFromMime
  2753. ? (_tagMimeProcessor ? _tagMimeProcessor : DefaultTagMimeProcessor)
  2754. : nullptr;
  2755. const auto breakTagOnNotLetterTill = ProcessInsertedTags(
  2756. _st,
  2757. document,
  2758. insertPosition,
  2759. insertEnd,
  2760. _insertedTags,
  2761. _insertedTagsReplace,
  2762. insertedTagsProcessor);
  2763. using ActionType = FormattingAction::Type;
  2764. while (true) {
  2765. FormattingAction action;
  2766. auto blockTag = QString();
  2767. auto checkedTill = insertPosition;
  2768. auto fromBlock = document->findBlock(insertPosition);
  2769. auto tillBlock = document->findBlock(insertEnd);
  2770. if (tillBlock.isValid()) tillBlock = tillBlock.next();
  2771. for (auto block = fromBlock; block != tillBlock; block = block.next()) {
  2772. const auto blockFormat = block.blockFormat();
  2773. blockTag = FindBlockTag(
  2774. blockFormat.property(kQuoteFormatId).toString()).toString();
  2775. if (blockTag == kTagBlockquoteCollapsed) {
  2776. const auto id = blockFormat.property(kQuoteId).toInt();
  2777. if (!_customObject || !id || block.length() == 1) {
  2778. action.type = ActionType::RemoveBlockquote;
  2779. action.intervalStart = block.position();
  2780. break;
  2781. }
  2782. auto collapsedObjectPosition = FindCollapsedQuoteObject(block);
  2783. if (collapsedObjectPosition < 0) {
  2784. action.type = ActionType::CollapseBlockquote;
  2785. action.quoteId = id;
  2786. action.intervalStart = block.position();
  2787. action.intervalEnd = block.position() + block.length() - 1;
  2788. break;
  2789. } else if (collapsedObjectPosition > block.position()) {
  2790. action.type = ActionType::CutCollapsedBefore;
  2791. action.quoteId = id;
  2792. action.intervalStart = block.position();
  2793. action.intervalEnd = collapsedObjectPosition;
  2794. break;
  2795. } else if (collapsedObjectPosition + 2 < block.position() + block.length()) {
  2796. action.type = ActionType::CutCollapsedAfter;
  2797. action.intervalStart = collapsedObjectPosition + 1;
  2798. break;
  2799. }
  2800. continue;
  2801. } else if (blockFormat.lineHeightType() != QTextBlockFormat::FixedHeight
  2802. && blockTag != kTagBlockquoteCollapsed) {
  2803. action.intervalStart = block.position();
  2804. action.type = ActionType::FixLineHeight;
  2805. break;
  2806. }
  2807. for (auto fragmentIt = block.begin(); !fragmentIt.atEnd(); ++fragmentIt) {
  2808. auto fragment = fragmentIt.fragment();
  2809. Assert(fragment.isValid());
  2810. const auto fragmentPosition = fragment.position();
  2811. const auto fragmentEnd = fragmentPosition + fragment.length();
  2812. if (insertPosition > fragmentEnd) {
  2813. // In case insertPosition == fragmentEnd we still
  2814. // need to fill startTagFound / breakTagOnNotLetter.
  2815. // This can happen if we inserted a newline after
  2816. // a text fragment with some formatting tag, like Bold.
  2817. continue;
  2818. }
  2819. int changedPositionInFragment = insertPosition - fragmentPosition; // Can be negative.
  2820. int changedEndInFragment = insertEnd - fragmentPosition;
  2821. if (changedEndInFragment < 0) {
  2822. break;
  2823. }
  2824. auto format = fragment.charFormat();
  2825. if (!format.hasProperty(kTagProperty)) {
  2826. action.type = ActionType::RemoveTag;
  2827. action.intervalStart = fragmentPosition;
  2828. action.intervalEnd = fragmentEnd;
  2829. break;
  2830. } else if (IsTagPre(blockTag)
  2831. && blockTag != format.property(kTagProperty).toString()
  2832. && format.objectType() != kCustomEmojiFormat) {
  2833. action.type = ActionType::FixPreTag;
  2834. action.intervalStart = fragmentPosition;
  2835. action.intervalEnd = fragmentEnd;
  2836. break;
  2837. }
  2838. if (processTilde) {
  2839. const auto formatFont = format.font();
  2840. if (!tildeFixedFont.styleName().isEmpty()
  2841. && formatFont.styleName().isEmpty()) {
  2842. tildeFixedFont.setStyleName(QString());
  2843. }
  2844. isTildeFragment = (format.font() == tildeFixedFont);
  2845. }
  2846. auto fragmentText = fragment.text();
  2847. auto *textStart = fragmentText.constData();
  2848. auto *textEnd = textStart + fragmentText.size();
  2849. if (_customObject
  2850. && format.objectType() == kCustomEmojiFormat) {
  2851. if (fragmentText == kObjectReplacement) {
  2852. checkedTill = fragmentEnd;
  2853. continue;
  2854. }
  2855. action.type = ActionType::InsertCustomEmoji;
  2856. action.intervalStart = fragmentPosition;
  2857. action.intervalEnd = fragmentPosition
  2858. + fragmentText.size();
  2859. action.customEmojiText = fragmentText;
  2860. action.customEmojiLink = format.property(
  2861. kCustomEmojiLink).toString();
  2862. break;
  2863. } else if (_customObject
  2864. && format.objectType() == kCollapsedQuoteFormat) {
  2865. action.type = ActionType::MakeCollapsedBlockquote;
  2866. action.quoteId = format.property(kQuoteId).toInt();
  2867. action.intervalStart = fragmentPosition;
  2868. action.intervalEnd = fragmentPosition + fragmentText.size();
  2869. break;
  2870. }
  2871. const auto with = format.property(kInstantReplaceWithId);
  2872. if (with.isValid()) {
  2873. const auto string = with.toString();
  2874. if (fragmentText != string) {
  2875. action.type = ActionType::ClearInstantReplace;
  2876. action.intervalStart = fragmentPosition
  2877. + (fragmentText.startsWith(string)
  2878. ? string.size()
  2879. : 0);
  2880. action.intervalEnd = fragmentPosition
  2881. + fragmentText.size();
  2882. break;
  2883. }
  2884. }
  2885. if (format.hasProperty(kCustomEmojiLink)
  2886. && !format.property(kCustomEmojiLink).toString().isEmpty()) {
  2887. action.type = ActionType::RemoveCustomEmoji;
  2888. action.existingTags = format.property(kTagProperty).toString();
  2889. action.intervalStart = fragmentPosition;
  2890. action.intervalEnd = fragmentPosition
  2891. + fragmentText.size();
  2892. break;
  2893. }
  2894. if (!startTagFound) {
  2895. startTagFound = true;
  2896. auto tagName = format.property(kTagProperty).toString();
  2897. if (!tagName.isEmpty()) {
  2898. breakTagOnNotLetter = WasInsertTillTheEndOfTag(
  2899. block,
  2900. fragmentIt,
  2901. insertEnd);
  2902. }
  2903. }
  2904. auto *ch = textStart + qMax(changedPositionInFragment, 0);
  2905. for (; ch < textEnd; ++ch) {
  2906. const auto removeNewline = (_mode != Mode::MultiLine)
  2907. && IsNewline(*ch);
  2908. if (removeNewline) {
  2909. if (action.type == ActionType::Invalid) {
  2910. action.type = ActionType::RemoveNewline;
  2911. action.intervalStart = fragmentPosition + (ch - textStart);
  2912. action.intervalEnd = action.intervalStart + 1;
  2913. }
  2914. break;
  2915. }
  2916. auto emojiLength = 0;
  2917. if (const auto emoji = Emoji::Find(ch, textEnd, &emojiLength)) {
  2918. // Replace emoji if no current action is prepared.
  2919. if (action.type == ActionType::Invalid) {
  2920. action.type = ActionType::InsertEmoji;
  2921. action.emoji = emoji;
  2922. action.intervalStart = fragmentPosition + (ch - textStart);
  2923. action.intervalEnd = action.intervalStart + emojiLength;
  2924. }
  2925. if (emojiLength > 1) {
  2926. _emojiSurrogateAmount += emojiLength - 1;
  2927. }
  2928. break;
  2929. }
  2930. if (breakTagOnNotLetter && !ch->isLetterOrNumber()) {
  2931. // Remove tag name till the end if no current action is prepared.
  2932. if (action.type != ActionType::Invalid) {
  2933. break;
  2934. }
  2935. breakTagOnNotLetter = false;
  2936. if (fragmentPosition + (ch - textStart) < breakTagOnNotLetterTill) {
  2937. action.type = ActionType::RemoveTag;
  2938. action.intervalStart = fragmentPosition + (ch - textStart);
  2939. action.intervalEnd = breakTagOnNotLetterTill;
  2940. break;
  2941. }
  2942. }
  2943. if (processTilde) { // Tilde symbol fix in OpenSans.
  2944. bool tilde = (ch->unicode() == '~');
  2945. if ((tilde && !isTildeFragment) || (!tilde && isTildeFragment)) {
  2946. if (action.type == ActionType::Invalid) {
  2947. action.type = ActionType::TildeFont;
  2948. action.intervalStart = fragmentPosition + (ch - textStart);
  2949. action.intervalEnd = action.intervalStart + 1;
  2950. action.tildeTag = format.property(kTagProperty).toString();
  2951. action.isTilde = tilde;
  2952. } else {
  2953. ++action.intervalEnd;
  2954. }
  2955. } else if (action.type == ActionType::TildeFont) {
  2956. break;
  2957. }
  2958. }
  2959. if (ch + 1 < textEnd && ch->isHighSurrogate() && (ch + 1)->isLowSurrogate()) {
  2960. ++ch;
  2961. }
  2962. }
  2963. if (action.type != ActionType::Invalid) {
  2964. break;
  2965. }
  2966. checkedTill = fragmentEnd;
  2967. }
  2968. if (action.type != ActionType::Invalid) {
  2969. break;
  2970. } else if (_mode != Mode::MultiLine
  2971. && block.next() != document->end()) {
  2972. action.type = ActionType::RemoveNewline;
  2973. action.intervalStart = block.next().position() - 1;
  2974. action.intervalEnd = action.intervalStart + 1;
  2975. break;
  2976. } else if (breakTagOnNotLetter) {
  2977. // In case we need to break on not letter and we didn't
  2978. // find any non letter symbol, we found it here - a newline.
  2979. breakTagOnNotLetter = false;
  2980. if (checkedTill < breakTagOnNotLetterTill) {
  2981. action.type = ActionType::RemoveTag;
  2982. action.intervalStart = checkedTill;
  2983. action.intervalEnd = breakTagOnNotLetterTill;
  2984. break;
  2985. }
  2986. }
  2987. }
  2988. if (action.type != ActionType::Invalid) {
  2989. PrepareFormattingOptimization(document);
  2990. if (action.type == ActionType::CollapseBlockquote) {
  2991. toggleBlockquoteCollapsed(
  2992. action.quoteId,
  2993. kTagBlockquote,
  2994. { action.intervalStart, action.intervalEnd });
  2995. continue;
  2996. }
  2997. auto cursor = QTextCursor(document);
  2998. if (action.type == ActionType::CutCollapsedBefore) {
  2999. auto realCursor = textCursor();
  3000. const auto wasAtEdge = !realCursor.hasSelection()
  3001. && realCursor.position() == action.intervalEnd;
  3002. cursor.setPosition(action.intervalEnd);
  3003. if (action.intervalEnd > 0
  3004. && IsNewline(
  3005. document->characterAt(action.intervalEnd - 1))) {
  3006. cursor.setPosition(
  3007. action.intervalEnd - 1,
  3008. QTextCursor::KeepAnchor);
  3009. cursor.insertText(
  3010. QString(QChar(kHardLine)),
  3011. _defaultCharFormat);
  3012. } else {
  3013. cursor.insertBlock(
  3014. PrepareBlockFormat(
  3015. _st,
  3016. kTagBlockquoteCollapsed,
  3017. action.quoteId),
  3018. _defaultCharFormat);
  3019. }
  3020. cursor.setPosition(action.intervalStart);
  3021. cursor.setBlockFormat(PrepareBlockFormat(_st));
  3022. if (wasAtEdge) {
  3023. realCursor.setPosition(action.intervalEnd);
  3024. _formattingCursorUpdate = realCursor;
  3025. }
  3026. continue;
  3027. }
  3028. cursor.setPosition(action.intervalStart);
  3029. if (action.type == ActionType::FixLineHeight) {
  3030. cursor.setBlockFormat(PrepareBlockFormat(_st));
  3031. continue;
  3032. } else if (action.type == ActionType::CutCollapsedAfter) {
  3033. if (IsNewline(document->characterAt(action.intervalStart))) {
  3034. cursor.setPosition(
  3035. action.intervalStart + 1,
  3036. QTextCursor::KeepAnchor);
  3037. cursor.insertText(
  3038. QString(QChar(kHardLine)),
  3039. _defaultCharFormat);
  3040. } else {
  3041. cursor.insertBlock(
  3042. PrepareBlockFormat(_st),
  3043. _defaultCharFormat);
  3044. ++insertEnd;
  3045. }
  3046. continue;
  3047. } else if (action.type == ActionType::RemoveBlockquote) {
  3048. cursor.setBlockFormat(PrepareBlockFormat(_st));
  3049. continue;
  3050. } else if (action.type == ActionType::MakeCollapsedBlockquote) {
  3051. auto text = _customObject->collapsedText(action.quoteId);
  3052. if (text.text.isEmpty()) {
  3053. cursor.setPosition(action.intervalEnd);
  3054. cursor.removeSelectedText();
  3055. } else {
  3056. const auto blockFormat = PrepareBlockFormat(
  3057. _st,
  3058. kTagBlockquoteCollapsed);
  3059. const auto id = blockFormat.property(kQuoteId).toInt();
  3060. _customObject->setCollapsedText(id, std::move(text));
  3061. const auto format = PrepareCollapsedQuoteFormat(id);
  3062. auto bBlock = document->findBlock(action.intervalStart);
  3063. if (bBlock.position() != action.intervalStart) {
  3064. cursor.insertText(QString(QChar(kHardLine)), format);
  3065. ++action.intervalStart;
  3066. ++action.intervalEnd;
  3067. }
  3068. cursor.setBlockFormat(blockFormat);
  3069. cursor.setBlockCharFormat(format);
  3070. const auto after = action.intervalEnd + 1;
  3071. auto eBlock = document->findBlock(after);
  3072. if (eBlock.position() != after) {
  3073. cursor.setPosition(action.intervalEnd);
  3074. cursor.insertBlock(
  3075. PrepareBlockFormat(_st),
  3076. _defaultCharFormat);
  3077. }
  3078. cursor.setPosition(action.intervalStart);
  3079. cursor.setPosition(
  3080. action.intervalEnd,
  3081. QTextCursor::KeepAnchor);
  3082. cursor.setCharFormat(format);
  3083. }
  3084. }
  3085. cursor.setPosition(action.intervalEnd, QTextCursor::KeepAnchor);
  3086. if (action.type == ActionType::InsertEmoji
  3087. || action.type == ActionType::InsertCustomEmoji) {
  3088. if (action.type == ActionType::InsertEmoji) {
  3089. InsertEmojiAtCursor(cursor, action.emoji);
  3090. } else {
  3091. InsertCustomEmojiAtCursor(
  3092. this,
  3093. cursor,
  3094. action.customEmojiText,
  3095. action.customEmojiLink);
  3096. }
  3097. insertPosition = action.intervalStart + 1;
  3098. if (insertEnd >= action.intervalEnd) {
  3099. insertEnd -= action.intervalEnd
  3100. - action.intervalStart
  3101. - 1;
  3102. }
  3103. } else if (action.type == ActionType::RemoveTag) {
  3104. RemoveDocumentTags(
  3105. _st,
  3106. document,
  3107. action.intervalStart,
  3108. action.intervalEnd);
  3109. } else if (action.type == ActionType::FixPreTag) {
  3110. cursor.setCharFormat(PrepareTagFormat(_st, blockTag));
  3111. } else if (action.type == ActionType::RemoveCustomEmoji) {
  3112. RemoveCustomEmojiTag(
  3113. _st,
  3114. document,
  3115. action.existingTags,
  3116. action.intervalStart,
  3117. action.intervalEnd);
  3118. } else if (action.type == ActionType::TildeFont) {
  3119. auto format = QTextCharFormat();
  3120. format.setFont(action.isTilde
  3121. ? tildeFixedFont
  3122. : PrepareTagFormat(_st, action.tildeTag).font());
  3123. cursor.mergeCharFormat(format);
  3124. insertPosition = action.intervalEnd;
  3125. } else if (action.type == ActionType::ClearInstantReplace) {
  3126. auto format = _defaultCharFormat;
  3127. ApplyTagFormat(format, cursor.charFormat());
  3128. cursor.setCharFormat(format);
  3129. } else if (action.type == ActionType::RemoveNewline) {
  3130. cursor.insertText(u" "_q);
  3131. insertPosition = action.intervalStart;
  3132. }
  3133. } else {
  3134. break;
  3135. }
  3136. }
  3137. }
  3138. void InputField::forceProcessContentsChanges() {
  3139. PostponeCall(this, [=] {
  3140. handleContentsChanged();
  3141. });
  3142. }
  3143. void InputField::documentContentsChanged(
  3144. int position,
  3145. int charsRemoved,
  3146. int charsAdded) {
  3147. if (_correcting) {
  3148. return;
  3149. }
  3150. // In case of input method events Qt emits
  3151. // document content change signals for a whole
  3152. // text block where the even took place.
  3153. // This breaks our wysiwyg markup, so we adjust
  3154. // the parameters to match the real change.
  3155. if (_inputMethodCommit.has_value()
  3156. && charsAdded > _inputMethodCommit->size()
  3157. && charsRemoved > 0) {
  3158. const auto inBlockBefore = charsAdded - _inputMethodCommit->size();
  3159. if (charsRemoved >= inBlockBefore) {
  3160. charsAdded -= inBlockBefore;
  3161. charsRemoved -= inBlockBefore;
  3162. position += inBlockBefore;
  3163. }
  3164. }
  3165. const auto document = _inner->document();
  3166. // Qt bug workaround https://bugreports.qt.io/browse/QTBUG-49062
  3167. if (!position) {
  3168. auto cursor = QTextCursor(document);
  3169. cursor.movePosition(QTextCursor::End);
  3170. if (position + charsAdded > cursor.position()) {
  3171. const auto delta = position + charsAdded - cursor.position();
  3172. if (charsRemoved >= delta) {
  3173. charsAdded -= delta;
  3174. charsRemoved -= delta;
  3175. }
  3176. }
  3177. }
  3178. const auto insertPosition = (_realInsertPosition >= 0)
  3179. ? _realInsertPosition
  3180. : position;
  3181. const auto insertLength = (_realInsertPosition >= 0)
  3182. ? _realCharsAdded
  3183. : charsAdded;
  3184. _correcting = true;
  3185. QTextCursor(document).joinPreviousEditBlock();
  3186. chopByMaxLength(insertPosition, insertLength);
  3187. if (document->availableRedoSteps() == 0) {
  3188. const auto pageSize = document->pageSize();
  3189. processFormatting(insertPosition, insertPosition + insertLength);
  3190. if (document->pageSize() != pageSize) {
  3191. document->setPageSize(pageSize);
  3192. }
  3193. }
  3194. if (document->isEmpty()) {
  3195. textCursor().setBlockFormat(PrepareBlockFormat(_st));
  3196. }
  3197. updateRootFrameFormat();
  3198. _correcting = false;
  3199. QTextCursor(document).endEditBlock();
  3200. if (_formattingCursorUpdate) {
  3201. setTextCursor(*base::take(_formattingCursorUpdate));
  3202. ensureCursorVisible();
  3203. }
  3204. handleContentsChanged();
  3205. const auto added = charsAdded - _emojiSurrogateAmount;
  3206. _documentContentsChanges.fire({ position, charsRemoved, added });
  3207. _emojiSurrogateAmount = 0;
  3208. }
  3209. void InputField::updateRootFrameFormat() {
  3210. const auto document = _inner->document();
  3211. auto format = document->rootFrame()->frameFormat();
  3212. const auto propertyId = QTextFrameFormat::FrameTopMargin;
  3213. const auto topMargin = format.property(propertyId).toInt();
  3214. const auto wantedTopMargin = StartsWithPre(document)
  3215. ? (_st.style.pre.padding.top()
  3216. + _st.style.pre.header
  3217. + _st.style.pre.verticalSkip)
  3218. : _requestedDocumentTopMargin;
  3219. if (_settingDocumentMargin) {
  3220. _requestedDocumentTopMargin = topMargin;
  3221. } else if (topMargin != wantedTopMargin) {
  3222. const auto value = QVariant::fromValue(1. * wantedTopMargin);
  3223. format.setProperty(propertyId, value);
  3224. document->rootFrame()->setFrameFormat(format);
  3225. }
  3226. }
  3227. void InputField::chopByMaxLength(int insertPosition, int insertLength) {
  3228. Expects(_correcting);
  3229. if (_maxLength < 0) {
  3230. return;
  3231. }
  3232. auto cursor = QTextCursor(document());
  3233. cursor.movePosition(QTextCursor::End);
  3234. const auto fullSize = cursor.position();
  3235. const auto toRemove = fullSize - _maxLength;
  3236. if (toRemove > 0) {
  3237. if (toRemove > insertLength) {
  3238. if (insertLength) {
  3239. cursor.setPosition(insertPosition);
  3240. cursor.setPosition(
  3241. (insertPosition + insertLength),
  3242. QTextCursor::KeepAnchor);
  3243. cursor.removeSelectedText();
  3244. }
  3245. cursor.setPosition(fullSize - (toRemove - insertLength));
  3246. cursor.setPosition(fullSize, QTextCursor::KeepAnchor);
  3247. cursor.removeSelectedText();
  3248. } else {
  3249. cursor.setPosition(
  3250. insertPosition + (insertLength - toRemove));
  3251. cursor.setPosition(
  3252. insertPosition + insertLength,
  3253. QTextCursor::KeepAnchor);
  3254. cursor.removeSelectedText();
  3255. }
  3256. }
  3257. }
  3258. void InputField::handleContentsChanged() {
  3259. setErrorShown(false);
  3260. auto tagsChanged = false;
  3261. const auto currentText = getTextPart(
  3262. 0,
  3263. -1,
  3264. _lastTextWithTags.tags,
  3265. tagsChanged,
  3266. _markdownEnabledState.disabled() ? nullptr : &_lastMarkdownTags);
  3267. //highlightMarkdown();
  3268. if (_spoilerRangesText.empty() && _spoilerRangesEmoji.empty()) {
  3269. _spoilerOverlay = nullptr;
  3270. } else if (_customObject) {
  3271. if (!_spoilerOverlay) {
  3272. _spoilerOverlay = _customObject->createSpoilerOverlay();
  3273. _spoilerOverlay->setGeometry(_inner->rect());
  3274. }
  3275. const auto cursor = textCursor();
  3276. _customObject->refreshSpoilerShown({
  3277. cursor.selectionStart(),
  3278. cursor.selectionEnd(),
  3279. });
  3280. }
  3281. if (tagsChanged || (_lastTextWithTags.text != currentText)) {
  3282. _lastTextWithTags.text = currentText;
  3283. const auto weak = MakeWeak(this);
  3284. _changes.fire({});
  3285. if (!weak) {
  3286. return;
  3287. }
  3288. checkContentHeight();
  3289. }
  3290. startPlaceholderAnimation();
  3291. if (_lastTextWithTags.text.isEmpty()) {
  3292. if (const auto object = _customObject.get()) {
  3293. object->clearEmoji();
  3294. }
  3295. }
  3296. Integration::Instance().textActionsUpdated();
  3297. }
  3298. void InputField::highlightMarkdown() {
  3299. // Highlighting may interfere with markdown parsing -> inaccurate.
  3300. // For debug.
  3301. auto from = 0;
  3302. auto applyColor = [&](int a, int b, QColor color) {
  3303. auto cursor = textCursor();
  3304. cursor.setPosition(a);
  3305. cursor.setPosition(b, QTextCursor::KeepAnchor);
  3306. auto format = QTextCharFormat();
  3307. format.setForeground(color);
  3308. cursor.mergeCharFormat(format);
  3309. from = b;
  3310. };
  3311. for (const auto &tag : _lastMarkdownTags) {
  3312. if (tag.internalStart > from) {
  3313. applyColor(from, tag.internalStart, QColor(0, 0, 0));
  3314. } else if (tag.internalStart < from) {
  3315. continue;
  3316. }
  3317. applyColor(
  3318. tag.internalStart,
  3319. tag.internalStart + tag.internalLength,
  3320. (tag.closed
  3321. ? QColor(0, 128, 0)
  3322. : QColor(128, 0, 0)));
  3323. }
  3324. auto cursor = textCursor();
  3325. cursor.movePosition(QTextCursor::End);
  3326. if (const auto till = cursor.position(); till > from) {
  3327. applyColor(from, till, QColor(0, 0, 0));
  3328. }
  3329. }
  3330. void InputField::setDisplayFocused(bool focused) {
  3331. setFocused(focused);
  3332. finishAnimating();
  3333. }
  3334. void InputField::selectAll() {
  3335. auto cursor = _inner->textCursor();
  3336. cursor.setPosition(0);
  3337. cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  3338. _inner->setTextCursor(cursor);
  3339. }
  3340. void InputField::finishAnimating() {
  3341. _a_focused.stop();
  3342. _a_error.stop();
  3343. _a_placeholderShifted.stop();
  3344. _a_borderShown.stop();
  3345. _a_borderOpacity.stop();
  3346. update();
  3347. }
  3348. void InputField::setPlaceholderHidden(bool forcePlaceholderHidden) {
  3349. _forcePlaceholderHidden = forcePlaceholderHidden;
  3350. startPlaceholderAnimation();
  3351. }
  3352. void InputField::startPlaceholderAnimation() {
  3353. const auto textLength = [&] {
  3354. return getTextWithTags().text.size() + _lastPreEditText.size();
  3355. };
  3356. const auto placeholderShifted = _forcePlaceholderHidden
  3357. || (_focused && _st.placeholderScale > 0.)
  3358. || (textLength() > _placeholderAfterSymbols);
  3359. if (_placeholderShifted != placeholderShifted) {
  3360. _placeholderShifted = placeholderShifted;
  3361. _a_placeholderShifted.start(
  3362. [=] { update(); },
  3363. _placeholderShifted ? 0. : 1.,
  3364. _placeholderShifted ? 1. : 0.,
  3365. _st.duration);
  3366. }
  3367. }
  3368. QMimeData *InputField::createMimeDataFromSelectionInner() const {
  3369. const auto cursor = _inner->textCursor();
  3370. const auto start = cursor.selectionStart();
  3371. const auto end = cursor.selectionEnd();
  3372. return TextUtilities::MimeDataFromText((end > start)
  3373. ? getTextWithTagsPart(start, end)
  3374. : TextWithTags()
  3375. ).release();
  3376. }
  3377. void InputField::customUpDown(bool isCustom) {
  3378. _customUpDown = isCustom;
  3379. }
  3380. void InputField::customTab(bool isCustom) {
  3381. _customTab = isCustom;
  3382. }
  3383. void InputField::setSubmitSettings(SubmitSettings settings) {
  3384. _submitSettings = settings;
  3385. }
  3386. not_null<QTextDocument*> InputField::document() {
  3387. return _inner->document();
  3388. }
  3389. not_null<const QTextDocument*> InputField::document() const {
  3390. return _inner->document();
  3391. }
  3392. void InputField::setTextCursor(const QTextCursor &cursor) {
  3393. return _inner->setTextCursor(cursor);
  3394. }
  3395. QTextCursor InputField::textCursor() const {
  3396. return _inner->textCursor();
  3397. }
  3398. void InputField::setCursorPosition(int pos) {
  3399. auto cursor = _inner->textCursor();
  3400. cursor.setPosition(pos);
  3401. _inner->setTextCursor(cursor);
  3402. }
  3403. void InputField::setText(const QString &text) {
  3404. setTextWithTags({ text, {} });
  3405. }
  3406. void InputField::setTextWithTags(
  3407. const TextWithTags &textWithTags,
  3408. HistoryAction historyAction) {
  3409. auto prepared = PrepareForInsert(textWithTags);
  3410. _insertedTags = prepared.tags;
  3411. _insertedTagsAreFromMime = false;
  3412. _realInsertPosition = 0;
  3413. _realCharsAdded = prepared.text.size();
  3414. const auto document = _inner->document();
  3415. auto cursor = QTextCursor(document);
  3416. if (historyAction == HistoryAction::Clear) {
  3417. document->setUndoRedoEnabled(false);
  3418. if (const auto object = _customObject.get()) {
  3419. object->clearEmoji();
  3420. object->clearQuotes();
  3421. }
  3422. cursor.beginEditBlock();
  3423. } else if (historyAction == HistoryAction::MergeEntry) {
  3424. cursor.joinPreviousEditBlock();
  3425. } else {
  3426. cursor.beginEditBlock();
  3427. }
  3428. cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
  3429. cursor.insertText(prepared.text, _defaultCharFormat);
  3430. cursor.movePosition(QTextCursor::End);
  3431. cursor.endEditBlock();
  3432. if (historyAction == HistoryAction::Clear) {
  3433. document->setUndoRedoEnabled(true);
  3434. }
  3435. _insertedTags.clear();
  3436. _realInsertPosition = -1;
  3437. finishAnimating();
  3438. }
  3439. TextWithTags InputField::getTextWithTagsPart(int start, int end) const {
  3440. auto changed = false;
  3441. auto result = TextWithTags();
  3442. result.text = getTextPart(start, end, result.tags, changed);
  3443. return result;
  3444. }
  3445. TextWithTags InputField::getTextWithAppliedMarkdown() const {
  3446. if (_markdownEnabledState.disabled() || _lastMarkdownTags.empty()) {
  3447. return getTextWithTags();
  3448. }
  3449. const auto &originalText = _lastTextWithTags.text;
  3450. const auto &originalTags = _lastTextWithTags.tags;
  3451. // Ignore tags that partially intersect some http-links.
  3452. // This will allow sending http://test.com/__test__/test correctly.
  3453. const auto links = TextUtilities::ParseEntities(
  3454. originalText,
  3455. 0).entities;
  3456. auto result = TextWithTags();
  3457. result.text.reserve(originalText.size());
  3458. result.tags.reserve(originalTags.size() + _lastMarkdownTags.size());
  3459. auto removed = 0;
  3460. auto originalTag = originalTags.begin();
  3461. const auto originalTagsEnd = originalTags.end();
  3462. const auto addOriginalTagsUpTill = [&](int offset) {
  3463. while (originalTag != originalTagsEnd
  3464. && originalTag->offset + originalTag->length <= offset) {
  3465. result.tags.push_back(*originalTag++);
  3466. result.tags.back().offset -= removed;
  3467. }
  3468. };
  3469. auto from = 0;
  3470. const auto addOriginalTextUpTill = [&](int offset) {
  3471. if (offset > from) {
  3472. result.text.append(base::StringViewMid(originalText, from, offset - from));
  3473. }
  3474. };
  3475. auto link = links.begin();
  3476. const auto linksEnd = links.end();
  3477. for (const auto &tag : _lastMarkdownTags) {
  3478. const auto tagLength = int(tag.tag.size());
  3479. if (!tag.closed || tag.adjustedStart < from) {
  3480. continue;
  3481. }
  3482. auto entityLength = tag.adjustedLength - 2 * tagLength;
  3483. if (entityLength <= 0) {
  3484. continue;
  3485. }
  3486. addOriginalTagsUpTill(tag.adjustedStart);
  3487. const auto tagAdjustedEnd = tag.adjustedStart + tag.adjustedLength;
  3488. if (originalTag != originalTagsEnd
  3489. && originalTag->offset < tagAdjustedEnd) {
  3490. continue;
  3491. }
  3492. while (link != linksEnd
  3493. && link->offset() + link->length() <= tag.adjustedStart) {
  3494. ++link;
  3495. }
  3496. if (link != linksEnd
  3497. && link->offset() < tagAdjustedEnd
  3498. && (link->offset() + link->length() > tagAdjustedEnd
  3499. || link->offset() < tag.adjustedStart)) {
  3500. continue;
  3501. }
  3502. addOriginalTextUpTill(tag.adjustedStart);
  3503. auto tagId = tag.tag;
  3504. auto entityStart = tag.adjustedStart + tagLength;
  3505. if (tagId == kTagPre) {
  3506. // Remove redundant newlines for pre.
  3507. // If ``` is on a separate line add only one newline.
  3508. const auto languageName = ReadPreLanguageName(
  3509. originalText,
  3510. entityStart,
  3511. entityLength);
  3512. if (!languageName.isEmpty()) {
  3513. // ```language-name{\n}code
  3514. entityStart += languageName.size() + 1;
  3515. entityLength -= languageName.size() + 1;
  3516. tagId += languageName;
  3517. } else if (IsNewline(originalText[entityStart])
  3518. && (result.text.isEmpty()
  3519. || IsNewline(result.text[result.text.size() - 1]))) {
  3520. ++entityStart;
  3521. --entityLength;
  3522. }
  3523. const auto entityEnd = entityStart + entityLength;
  3524. if (IsNewline(originalText[entityEnd - 1])
  3525. && (originalText.size() <= entityEnd + tagLength
  3526. || IsNewline(originalText[entityEnd + tagLength]))) {
  3527. --entityLength;
  3528. }
  3529. }
  3530. if (entityLength > 0) {
  3531. // Add tag text and entity.
  3532. result.tags.push_back(TextWithTags::Tag{
  3533. int(result.text.size()),
  3534. entityLength,
  3535. tagId });
  3536. result.text.append(base::StringViewMid(
  3537. originalText,
  3538. entityStart,
  3539. entityLength));
  3540. }
  3541. from = tag.adjustedStart + tag.adjustedLength;
  3542. removed += (tag.adjustedLength - entityLength);
  3543. }
  3544. addOriginalTagsUpTill(originalText.size());
  3545. addOriginalTextUpTill(originalText.size());
  3546. return result;
  3547. }
  3548. void InputField::clear() {
  3549. _inner->clear();
  3550. startPlaceholderAnimation();
  3551. if (const auto object = _customObject.get()) {
  3552. object->clearEmoji();
  3553. }
  3554. }
  3555. bool InputField::hasFocus() const {
  3556. return _inner->hasFocus();
  3557. }
  3558. void InputField::setFocus() {
  3559. _inner->setFocus();
  3560. }
  3561. void InputField::clearFocus() {
  3562. _inner->clearFocus();
  3563. }
  3564. void InputField::ensureCursorVisible() {
  3565. _inner->ensureCursorVisible();
  3566. }
  3567. not_null<QTextEdit*> InputField::rawTextEdit() {
  3568. return _inner.get();
  3569. }
  3570. not_null<const QTextEdit*> InputField::rawTextEdit() const {
  3571. return _inner.get();
  3572. }
  3573. bool InputField::ShouldSubmit(
  3574. SubmitSettings settings,
  3575. Qt::KeyboardModifiers modifiers) {
  3576. const auto shift = modifiers.testFlag(Qt::ShiftModifier);
  3577. const auto ctrl = modifiers.testFlag(Qt::ControlModifier)
  3578. || modifiers.testFlag(Qt::MetaModifier);
  3579. return (ctrl && shift)
  3580. || (ctrl
  3581. && settings != SubmitSettings::None
  3582. && settings != SubmitSettings::Enter)
  3583. || (!ctrl
  3584. && !shift
  3585. && settings != SubmitSettings::None
  3586. && settings != SubmitSettings::CtrlEnter);
  3587. }
  3588. void InputField::keyPressEventInner(QKeyEvent *e) {
  3589. const auto shift = e->modifiers().testFlag(Qt::ShiftModifier);
  3590. const auto alt = e->modifiers().testFlag(Qt::AltModifier);
  3591. const auto macmeta = Platform::IsMac()
  3592. && e->modifiers().testFlag(Qt::ControlModifier)
  3593. && !e->modifiers().testFlag(Qt::MetaModifier)
  3594. && !e->modifiers().testFlag(Qt::AltModifier);
  3595. const auto ctrl = e->modifiers().testFlag(Qt::ControlModifier)
  3596. || e->modifiers().testFlag(Qt::MetaModifier);
  3597. const auto enterSubmit = (_mode != Mode::MultiLine)
  3598. || ShouldSubmit(_submitSettings, e->modifiers());
  3599. const auto enter = (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return);
  3600. const auto backspace = (e->key() == Qt::Key_Backspace);
  3601. if (e->key() == Qt::Key_Left
  3602. || e->key() == Qt::Key_Right
  3603. || e->key() == Qt::Key_Up
  3604. || e->key() == Qt::Key_Down
  3605. || e->key() == Qt::Key_Home
  3606. || e->key() == Qt::Key_End) {
  3607. _reverseMarkdownReplacement = false;
  3608. }
  3609. if (backspace && macmeta) {
  3610. QTextCursor tc(textCursor()), start(tc);
  3611. start.movePosition(QTextCursor::StartOfLine);
  3612. tc.setPosition(start.position(), QTextCursor::KeepAnchor);
  3613. tc.removeSelectedText();
  3614. } else if (backspace
  3615. && e->modifiers() == 0
  3616. && revertFormatReplace()) {
  3617. e->accept();
  3618. } else if (backspace && jumpOutOfBlockByBackspace()) {
  3619. e->accept();
  3620. } else if (enter && enterSubmit) {
  3621. _submits.fire(e->modifiers());
  3622. } else if (e->key() == Qt::Key_Escape) {
  3623. e->ignore();
  3624. _cancelled.fire({});
  3625. } else if (e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab) {
  3626. if (alt || ctrl) {
  3627. e->ignore();
  3628. } else if (_customTab) {
  3629. _tabbed.fire({});
  3630. } else if (!focusNextPrevChild(e->key() == Qt::Key_Tab && !shift)) {
  3631. e->ignore();
  3632. }
  3633. } else if (e->key() == Qt::Key_Search || e == QKeySequence::Find) {
  3634. e->ignore();
  3635. } else if (handleMarkdownKey(e)) {
  3636. e->accept();
  3637. } else if (_customUpDown && (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down || e->key() == Qt::Key_PageUp || e->key() == Qt::Key_PageDown)) {
  3638. e->ignore();
  3639. #ifdef Q_OS_MAC
  3640. } else if (e->key() == Qt::Key_E && e->modifiers().testFlag(Qt::ControlModifier)) {
  3641. const auto cursor = textCursor();
  3642. const auto start = cursor.selectionStart();
  3643. const auto end = cursor.selectionEnd();
  3644. if (end > start) {
  3645. QGuiApplication::clipboard()->setText(
  3646. getTextWithTagsPart(start, end).text,
  3647. QClipboard::FindBuffer);
  3648. }
  3649. #endif // Q_OS_MAC
  3650. } else {
  3651. const auto text = e->text();
  3652. auto cursor = textCursor();
  3653. const auto oldPosition = cursor.position();
  3654. const auto oldSelection = cursor.hasSelection();
  3655. const auto oldModifiers = e->modifiers();
  3656. const auto allowedModifiers = (enter && ctrl)
  3657. ? (~Qt::ControlModifier)
  3658. : (enter && shift)
  3659. ? (~Qt::ShiftModifier)
  3660. : oldModifiers;
  3661. const auto changeModifiers = (oldModifiers & ~allowedModifiers) != 0;
  3662. if (changeModifiers) {
  3663. e->setModifiers(oldModifiers & allowedModifiers);
  3664. }
  3665. // If we enable this, the Undo/Redo will work through Key_Space
  3666. // insertions, because they will be in edit blocks with the following
  3667. // text char format changes. But this will make every entered letter
  3668. // have a separate Undo block without grouping input together.
  3669. //
  3670. //const auto createEditBlock = (e != QKeySequence::Undo)
  3671. // && (e != QKeySequence::Redo);
  3672. const auto createEditBlock = enter
  3673. || backspace
  3674. || (e->key() == Qt::Key_Space)
  3675. || (e->key() == Qt::Key_Delete);
  3676. if (createEditBlock) {
  3677. cursor.beginEditBlock();
  3678. }
  3679. if (e == QKeySequence::InsertParagraphSeparator) {
  3680. // qtbase commit dbb9579566f3accd8aa5fe61db9692991117afd3 introduced
  3681. // special logic for repeated 'Enter' key presses, which drops the
  3682. // block format instead of inserting a newline in case the block format
  3683. // is non-trivial. For custom fonts we use non-trivial block formats
  3684. // always for the entire QTextEdit, so we revert that logic and simply
  3685. // insert a newline as it was before Qt 6.X.Y where this was added.
  3686. // Also we insert a kSoftLine instead of a block, because we want
  3687. // newlines to belong to the same block by default (blockquotes).
  3688. if (!cursor.hasSelection() && !HasBlockTag(cursor.block())) {
  3689. cursor.insertText(QString(QChar(kHardLine)));
  3690. } else {
  3691. cursor.insertText(QString(QChar(kSoftLine)));
  3692. trippleEnterExitBlock(cursor);
  3693. }
  3694. e->accept();
  3695. } else {
  3696. _inner->QTextEdit::keyPressEvent(e);
  3697. }
  3698. if (createEditBlock) {
  3699. cursor.endEditBlock();
  3700. }
  3701. _inner->ensureCursorVisible();
  3702. if (changeModifiers) {
  3703. e->setModifiers(oldModifiers);
  3704. }
  3705. auto updatedCursor = textCursor();
  3706. if (updatedCursor.position() == oldPosition) {
  3707. const auto shift = e->modifiers().testFlag(Qt::ShiftModifier);
  3708. bool check = false;
  3709. if (e->key() == Qt::Key_PageUp || e->key() == Qt::Key_Up) {
  3710. updatedCursor.movePosition(QTextCursor::Start, shift ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
  3711. check = true;
  3712. } else if (e->key() == Qt::Key_PageDown || e->key() == Qt::Key_Down) {
  3713. updatedCursor.movePosition(QTextCursor::End, shift ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
  3714. check = true;
  3715. } else if (!oldSelection
  3716. && (e->key() == Qt::Key_Left
  3717. || e->key() == Qt::Key_Right
  3718. || e->key() == Qt::Key_Backspace)) {
  3719. e->ignore();
  3720. }
  3721. if (check) {
  3722. if (oldPosition == updatedCursor.position()) {
  3723. if (shift || !exitQuoteWithNewBlock(e->key())) {
  3724. e->ignore();
  3725. }
  3726. } else {
  3727. setTextCursor(updatedCursor);
  3728. }
  3729. }
  3730. }
  3731. if (!processMarkdownReplaces(text)) {
  3732. processInstantReplaces(text);
  3733. }
  3734. }
  3735. }
  3736. bool InputField::exitQuoteWithNewBlock(int key) {
  3737. const auto up = (key == Qt::Key_Up);
  3738. if (!up && key != Qt::Key_Down) {
  3739. return false;
  3740. }
  3741. auto cursor = textCursor();
  3742. if (cursor.hasSelection()
  3743. || !cursor.blockFormat().hasProperty(kQuoteFormatId)) {
  3744. return false;
  3745. }
  3746. if (up) {
  3747. cursor.beginEditBlock();
  3748. cursor.insertText(QString(QChar(kHardLine)), _defaultCharFormat);
  3749. cursor.movePosition(QTextCursor::Start);
  3750. cursor.setBlockFormat(PrepareBlockFormat(_st));
  3751. cursor.setCharFormat(_defaultCharFormat);
  3752. cursor.endEditBlock();
  3753. setTextCursor(cursor);
  3754. checkContentHeight();
  3755. } else {
  3756. cursor.insertBlock(PrepareBlockFormat(_st), _defaultCharFormat);
  3757. }
  3758. _inner->ensureCursorVisible();
  3759. return true;
  3760. }
  3761. TextWithTags InputField::getTextWithTagsSelected() const {
  3762. const auto cursor = textCursor();
  3763. const auto start = cursor.selectionStart();
  3764. const auto end = cursor.selectionEnd();
  3765. return (end > start) ? getTextWithTagsPart(start, end) : TextWithTags();
  3766. }
  3767. bool InputField::handleMarkdownKey(QKeyEvent *e) {
  3768. if (_markdownEnabledState.disabled()) {
  3769. return false;
  3770. }
  3771. const auto matches = [&](const QKeySequence &sequence) {
  3772. const auto searchKey = (e->modifiers() | e->key())
  3773. & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier);
  3774. const auto events = QKeySequence(searchKey);
  3775. return sequence.matches(events) == QKeySequence::ExactMatch;
  3776. };
  3777. for (const auto &action : MarkdownActions()) {
  3778. if (matches(action.sequence)) {
  3779. return executeMarkdownAction(action);
  3780. }
  3781. }
  3782. return false;
  3783. }
  3784. auto InputField::selectionEditLinkData(EditLinkSelection selection) const
  3785. -> EditLinkData {
  3786. Expects(_editLinkCallback != nullptr);
  3787. const auto position = (selection.from == selection.till
  3788. && selection.from > 0)
  3789. ? (selection.from - 1)
  3790. : selection.from;
  3791. const auto link = [&] {
  3792. return (position != selection.till)
  3793. ? CheckFullTextTag(
  3794. getTextWithTagsPart(position, selection.till),
  3795. kTagCheckLinkMeta)
  3796. : QString();
  3797. }();
  3798. const auto simple = EditLinkData{
  3799. selection.from,
  3800. selection.till,
  3801. QString()
  3802. };
  3803. if (!_editLinkCallback(selection, {}, link, EditLinkAction::Check)) {
  3804. return simple;
  3805. }
  3806. Assert(!link.isEmpty());
  3807. struct State {
  3808. QTextBlock block;
  3809. QTextBlock::iterator i;
  3810. };
  3811. const auto document = _inner->document();
  3812. const auto skipInvalid = [&](State &state) {
  3813. if (state.block == document->end()) {
  3814. return false;
  3815. }
  3816. while (state.i.atEnd()) {
  3817. state.block = state.block.next();
  3818. if (state.block == document->end()) {
  3819. return false;
  3820. }
  3821. state.i = state.block.begin();
  3822. }
  3823. return true;
  3824. };
  3825. const auto moveToNext = [&](State &state) {
  3826. Expects(state.block != document->end());
  3827. Expects(!state.i.atEnd());
  3828. ++state.i;
  3829. };
  3830. const auto moveToPrevious = [&](State &state) {
  3831. Expects(state.block != document->end());
  3832. Expects(!state.i.atEnd());
  3833. while (state.i == state.block.begin()) {
  3834. if (state.block == document->begin()) {
  3835. state.block = document->end();
  3836. return false;
  3837. }
  3838. state.block = state.block.previous();
  3839. state.i = state.block.end();
  3840. }
  3841. --state.i;
  3842. return true;
  3843. };
  3844. const auto stateTag = [&](const State &state) {
  3845. const auto format = state.i.fragment().charFormat();
  3846. return format.property(kTagProperty).toString();
  3847. };
  3848. const auto stateTagHasLink = [&](const State &state) {
  3849. const auto tag = stateTag(state);
  3850. return (tag == link)
  3851. || TextUtilities::SplitTags(tag).contains(QStringView(link));
  3852. };
  3853. const auto stateStart = [&](const State &state) {
  3854. return state.i.fragment().position();
  3855. };
  3856. const auto stateEnd = [&](const State &state) {
  3857. const auto fragment = state.i.fragment();
  3858. return fragment.position() + fragment.length();
  3859. };
  3860. auto state = State{ document->findBlock(position) };
  3861. if (state.block != document->end()) {
  3862. state.i = state.block.begin();
  3863. }
  3864. for (; skipInvalid(state); moveToNext(state)) {
  3865. const auto fragmentStart = stateStart(state);
  3866. const auto fragmentEnd = stateEnd(state);
  3867. if (fragmentEnd <= position) {
  3868. continue;
  3869. } else if (fragmentStart >= selection.till) {
  3870. break;
  3871. }
  3872. if (stateTagHasLink(state)) {
  3873. auto start = fragmentStart;
  3874. auto finish = fragmentEnd;
  3875. auto copy = state;
  3876. while (moveToPrevious(copy) && stateTagHasLink(copy)) {
  3877. start = stateStart(copy);
  3878. }
  3879. while (skipInvalid(state) && stateTagHasLink(state)) {
  3880. finish = stateEnd(state);
  3881. moveToNext(state);
  3882. }
  3883. return { start, finish, link };
  3884. }
  3885. }
  3886. return simple;
  3887. }
  3888. auto InputField::editLinkSelection(QContextMenuEvent *e) const
  3889. -> EditLinkSelection {
  3890. const auto cursor = textCursor();
  3891. if (!cursor.hasSelection() && e->reason() == QContextMenuEvent::Mouse) {
  3892. const auto clickCursor = _inner->cursorForPosition(
  3893. _inner->viewport()->mapFromGlobal(e->globalPos()));
  3894. if (!clickCursor.isNull() && !clickCursor.hasSelection()) {
  3895. return {
  3896. clickCursor.position(),
  3897. clickCursor.position()
  3898. };
  3899. }
  3900. }
  3901. return {
  3902. cursor.selectionStart(),
  3903. cursor.selectionEnd()
  3904. };
  3905. }
  3906. void InputField::editMarkdownLink(EditLinkSelection selection) {
  3907. if (!_editLinkCallback) {
  3908. return;
  3909. }
  3910. const auto data = selectionEditLinkData(selection);
  3911. auto text = getTextWithTagsPart(data.from, data.till);
  3912. for (auto i = text.tags.begin(); i != text.tags.end();) {
  3913. auto all = TextUtilities::SplitTags(i->id);
  3914. for (auto j = all.begin(); j != all.end();) {
  3915. if (IsValidMarkdownLink(*j)) {
  3916. j = all.erase(j);
  3917. } else {
  3918. ++j;
  3919. }
  3920. }
  3921. if (all.empty()) {
  3922. i = text.tags.erase(i);
  3923. } else {
  3924. i->id = TextUtilities::JoinTag(all);
  3925. ++i;
  3926. }
  3927. }
  3928. _editLinkCallback(selection, text, data.link, EditLinkAction::Edit);
  3929. }
  3930. void InputField::inputMethodEventInner(QInputMethodEvent *e) {
  3931. const auto preedit = e->preeditString();
  3932. if (_lastPreEditText != preedit) {
  3933. _lastPreEditText = preedit;
  3934. startPlaceholderAnimation();
  3935. }
  3936. _inputMethodCommit = e->commitString();
  3937. const auto weak = MakeWeak(this);
  3938. _inner->QTextEdit::inputMethodEvent(e);
  3939. if (weak && _inputMethodCommit.has_value()) {
  3940. const auto text = *base::take(_inputMethodCommit);
  3941. if (!processMarkdownReplaces(text)) {
  3942. processInstantReplaces(text);
  3943. }
  3944. }
  3945. }
  3946. const InstantReplaces &InputField::instantReplaces() const {
  3947. return _mutableInstantReplaces;
  3948. }
  3949. // Disable markdown instant replacement.
  3950. bool InputField::processMarkdownReplaces(const QString &appended) {
  3951. //if (appended.size() != 1 || !_markdownEnabled) {
  3952. // return false;
  3953. //}
  3954. //const auto ch = appended[0];
  3955. //if (ch == '`') {
  3956. // return processMarkdownReplace(kTagCode)
  3957. // || processMarkdownReplace(kTagPre);
  3958. //} else if (ch == '*') {
  3959. // return processMarkdownReplace(kTagBold);
  3960. //} else if (ch == '_') {
  3961. // return processMarkdownReplace(kTagItalic);
  3962. //}
  3963. return false;
  3964. }
  3965. //bool InputField::processMarkdownReplace(const QString &tag) {
  3966. // const auto position = textCursor().position();
  3967. // const auto tagLength = tag.size();
  3968. // const auto start = [&] {
  3969. // for (const auto &possible : _lastMarkdownTags) {
  3970. // const auto end = possible.start + possible.length;
  3971. // if (possible.start + 2 * tagLength >= position) {
  3972. // return MarkdownTag();
  3973. // } else if (end >= position || end + tagLength == position) {
  3974. // if (possible.tag == tag) {
  3975. // return possible;
  3976. // }
  3977. // }
  3978. // }
  3979. // return MarkdownTag();
  3980. // }();
  3981. // if (start.tag.isEmpty()) {
  3982. // return false;
  3983. // }
  3984. // return commitMarkdownReplacement(start.start, position, tag, tag);
  3985. //}
  3986. void InputField::processInstantReplaces(const QString &appended) {
  3987. const auto &replaces = instantReplaces();
  3988. if (appended.size() != 1
  3989. || !_instantReplacesEnabled
  3990. || !replaces.maxLength) {
  3991. return;
  3992. }
  3993. const auto it = replaces.reverseMap.tail.find(appended[0]);
  3994. if (it == end(replaces.reverseMap.tail)) {
  3995. return;
  3996. }
  3997. const auto position = textCursor().position();
  3998. for (const auto &tag : _lastMarkdownTags) {
  3999. if (tag.internalStart < position
  4000. && tag.internalStart + tag.internalLength >= position
  4001. && (tag.tag == kTagCode || IsTagPre(tag.tag))) {
  4002. return;
  4003. }
  4004. }
  4005. const auto typed = getTextWithTagsPart(
  4006. std::max(position - replaces.maxLength, 0),
  4007. position - 1).text;
  4008. auto node = &it->second;
  4009. auto i = typed.size();
  4010. do {
  4011. if (!node->text.isEmpty()) {
  4012. applyInstantReplace(typed.mid(i) + appended, node->text);
  4013. return;
  4014. } else if (!i) {
  4015. return;
  4016. }
  4017. const auto it = node->tail.find(typed[--i]);
  4018. if (it == end(node->tail)) {
  4019. return;
  4020. }
  4021. node = &it->second;
  4022. } while (true);
  4023. }
  4024. void InputField::applyInstantReplace(
  4025. const QString &what,
  4026. const QString &with) {
  4027. const auto length = int(what.size());
  4028. const auto cursor = textCursor();
  4029. const auto position = cursor.position();
  4030. if (cursor.hasSelection()) {
  4031. return;
  4032. } else if (position < length) {
  4033. return;
  4034. }
  4035. commitInstantReplacement(
  4036. position - length,
  4037. position,
  4038. with,
  4039. QString(),
  4040. what,
  4041. true);
  4042. }
  4043. void InputField::commitInstantReplacement(
  4044. int from,
  4045. int till,
  4046. const QString &with,
  4047. const QString &customEmojiData) {
  4048. commitInstantReplacement(
  4049. from,
  4050. till,
  4051. with,
  4052. customEmojiData,
  4053. std::nullopt,
  4054. false);
  4055. }
  4056. void InputField::commitInstantReplacement(
  4057. int from,
  4058. int till,
  4059. const QString &with,
  4060. const QString &customEmojiData,
  4061. std::optional<QString> checkOriginal,
  4062. bool checkIfInMonospace) {
  4063. const auto original = getTextWithTagsPart(from, till).text;
  4064. if (checkOriginal
  4065. && checkOriginal->compare(original, Qt::CaseInsensitive) != 0) {
  4066. return;
  4067. }
  4068. auto cursor = textCursor();
  4069. if (checkIfInMonospace) {
  4070. const auto currentTag = cursor.charFormat().property(
  4071. kTagProperty
  4072. ).toString();
  4073. for (const auto &tag : TextUtilities::SplitTags(currentTag)) {
  4074. if (tag == kTagCode || IsTagPre(tag)) {
  4075. return;
  4076. }
  4077. }
  4078. }
  4079. cursor.setPosition(from);
  4080. cursor.setPosition(till, QTextCursor::KeepAnchor);
  4081. const auto link = customEmojiData.isEmpty()
  4082. ? QString()
  4083. : CustomEmojiLink(customEmojiData);
  4084. const auto unique = link.isEmpty()
  4085. ? QString()
  4086. : MakeUniqueCustomEmojiLink(link);
  4087. auto format = [&]() -> QTextCharFormat {
  4088. auto emojiLength = 0;
  4089. const auto emoji = Emoji::Find(with, &emojiLength);
  4090. if (!emoji || with.size() != emojiLength) {
  4091. return _defaultCharFormat;
  4092. } else if (!customEmojiData.isEmpty()) {
  4093. auto result = QTextCharFormat();
  4094. result.setObjectType(kCustomEmojiFormat);
  4095. result.setProperty(kCustomEmojiText, with);
  4096. result.setProperty(kCustomEmojiLink, unique);
  4097. result.setProperty(kCustomEmojiId, CustomEmojiIdFromLink(link));
  4098. result.setVerticalAlignment(QTextCharFormat::AlignTop);
  4099. return result;
  4100. }
  4101. const auto use = Integration::Instance().defaultEmojiVariant(
  4102. emoji);
  4103. return PrepareEmojiFormat(use, _st.style.font);
  4104. }();
  4105. const auto replacement = (format.isImageFormat()
  4106. || format.objectType() == kCustomEmojiFormat)
  4107. ? kObjectReplacement
  4108. : with;
  4109. format.setProperty(kInstantReplaceWhatId, original);
  4110. format.setProperty(kInstantReplaceWithId, replacement);
  4111. format.setProperty(
  4112. kInstantReplaceRandomId,
  4113. base::RandomValue<uint32>());
  4114. ApplyTagFormat(format, cursor.charFormat());
  4115. if (!unique.isEmpty()) {
  4116. format.setProperty(kTagProperty, TextUtilities::TagWithAdded(
  4117. format.property(kTagProperty).toString(),
  4118. unique));
  4119. }
  4120. cursor.insertText(replacement, format);
  4121. }
  4122. #if 0
  4123. bool InputField::commitMarkdownReplacement(
  4124. int from,
  4125. int till,
  4126. const QString &tag,
  4127. const QString &edge) {
  4128. const auto end = [&] {
  4129. auto cursor = QTextCursor(document());
  4130. cursor.movePosition(QTextCursor::End);
  4131. return cursor.position();
  4132. }();
  4133. // In case of 'pre' tag extend checked text by one symbol.
  4134. // So that we'll know if we need to insert additional newlines.
  4135. // "Test ```test``` Test" should become three-line text.
  4136. const auto blocktag = (tag == kTagPre);
  4137. const auto extendLeft = (blocktag && from > 0) ? 1 : 0;
  4138. const auto extendRight = (blocktag && till < end) ? 1 : 0;
  4139. const auto extended = getTextWithTagsPart(
  4140. from - extendLeft,
  4141. till + extendRight).text;
  4142. const auto outer = base::StringViewMid(
  4143. extended,
  4144. extendLeft,
  4145. extended.size() - extendLeft - extendRight);
  4146. if ((outer.size() <= 2 * edge.size())
  4147. || (!edge.isEmpty()
  4148. && !(outer.startsWith(edge) && outer.endsWith(edge)))) {
  4149. return false;
  4150. }
  4151. // In case of 'pre' tag check if we need to remove one of two newlines.
  4152. // "Test\n```\ntest\n```" should become two-line text + newline.
  4153. const auto innerRight = edge.size();
  4154. const auto checkIfTwoNewlines = blocktag
  4155. && (extendLeft > 0)
  4156. && IsNewline(extended[0]);
  4157. const auto innerLeft = [&] {
  4158. const auto simple = edge.size();
  4159. if (!checkIfTwoNewlines) {
  4160. return simple;
  4161. }
  4162. const auto last = outer.size() - innerRight;
  4163. for (auto check = simple; check != last; ++check) {
  4164. const auto ch = outer.at(check);
  4165. if (IsNewline(ch)) {
  4166. return check + 1;
  4167. } else if (!Text::IsSpace(ch)) {
  4168. break;
  4169. }
  4170. }
  4171. return simple;
  4172. }();
  4173. const auto innerLength = outer.size() - innerLeft - innerRight;
  4174. // Prepare the final "insert" replacement for the "outer" text part.
  4175. const auto newlineleft = blocktag
  4176. && (extendLeft > 0)
  4177. && !IsNewline(extended[0])
  4178. && !IsNewline(outer.at(innerLeft));
  4179. const auto newlineright = blocktag
  4180. && (!extendRight || !IsNewline(extended[extended.size() - 1]))
  4181. && !IsNewline(outer.at(outer.size() - innerRight - 1));
  4182. const auto insert = (newlineleft ? "\n" : "")
  4183. + outer.mid(innerLeft, innerLength).toString()
  4184. + (newlineright ? "\n" : "");
  4185. // Trim inserted tag, so that all newlines are left outside.
  4186. _insertedTags.clear();
  4187. auto tagFrom = newlineleft ? 1 : 0;
  4188. auto tagTill = insert.size() - (newlineright ? 1 : 0);
  4189. for (; tagFrom != tagTill; ++tagFrom) {
  4190. const auto ch = insert.at(tagFrom);
  4191. if (!IsNewline(ch)) {
  4192. break;
  4193. }
  4194. }
  4195. for (; tagTill != tagFrom; --tagTill) {
  4196. const auto ch = insert.at(tagTill - 1);
  4197. if (!IsNewline(ch)) {
  4198. break;
  4199. }
  4200. }
  4201. if (tagTill > tagFrom) {
  4202. _insertedTags.push_back({
  4203. tagFrom,
  4204. int(tagTill - tagFrom),
  4205. tag,
  4206. });
  4207. }
  4208. // Replace.
  4209. auto cursor = _inner->textCursor();
  4210. cursor.setPosition(from);
  4211. cursor.setPosition(till, QTextCursor::KeepAnchor);
  4212. auto format = _defaultCharFormat;
  4213. if (!edge.isEmpty()) {
  4214. format.setProperty(kReplaceTagId, edge);
  4215. _reverseMarkdownReplacement = true;
  4216. }
  4217. _insertedTagsAreFromMime = false;
  4218. cursor.insertText(insert, format);
  4219. _insertedTags.clear();
  4220. cursor.setCharFormat(_defaultCharFormat);
  4221. _inner->setTextCursor(cursor);
  4222. // Fire the tag to the spellchecker.
  4223. _markdownTagApplies.fire({ from, till, -1, -1, false, tag });
  4224. return true;
  4225. }
  4226. #endif
  4227. auto InputField::addMarkdownTag(TextRange range, const QString &tag)
  4228. -> TextRange {
  4229. auto current = getTextWithTagsPart(range.from, range.till);
  4230. auto filled = 0;
  4231. auto tags = TextWithTags::Tags();
  4232. if (!TextUtilities::IsSeparateTag(tag)) {
  4233. for (auto existing : current.tags) {
  4234. if (existing.offset > filled) {
  4235. tags.push_back({ filled, existing.offset - filled, tag });
  4236. }
  4237. existing.id = TextUtilities::TagWithAdded(existing.id, tag);
  4238. tags.push_back(std::move(existing));
  4239. filled = existing.offset + existing.length;
  4240. }
  4241. }
  4242. if (filled < current.text.size()) {
  4243. tags.push_back({ filled, int(current.text.size()) - filled, tag });
  4244. }
  4245. current.tags = TextUtilities::SimplifyTags(std::move(tags));
  4246. const auto result = insertWithTags(range, std::move(current));
  4247. // Fire the tag to the spellchecker.
  4248. _markdownTagApplies.fire(
  4249. { result.from, result.till, -1, -1, false, tag });
  4250. return result;
  4251. }
  4252. auto InputField::insertWithTags(TextRange range, TextWithTags text)
  4253. -> TextRange {
  4254. if (text.empty() || text.tags.isEmpty()) {
  4255. finishMarkdownTagChange(range, PrepareForInsert(std::move(text)));
  4256. return range;
  4257. }
  4258. text = ShiftLeftBlockTag(std::move(text));
  4259. text = ShiftRightBlockTag(std::move(text));
  4260. auto result = range;
  4261. const auto firstTag = text.tags.front();
  4262. const auto lastTag = text.tags.back();
  4263. const auto textLength = int(text.text.size());
  4264. const auto adjustLeft = !firstTag.offset && HasBlockTag(firstTag.id);
  4265. const auto adjustRight = (lastTag.offset + lastTag.length >= textLength)
  4266. && HasBlockTag(lastTag.id);
  4267. auto cursor = QTextCursor(document());
  4268. cursor.movePosition(QTextCursor::End);
  4269. const auto fullLength = cursor.position();
  4270. const auto goodLeft = !adjustLeft
  4271. || !range.from
  4272. || (document()->findBlock(range.from).position() == range.from);
  4273. const auto goodRight = !adjustRight
  4274. || (range.till >= fullLength)
  4275. || (document()->findBlock(range.till + 1).position()
  4276. == range.till + 1);
  4277. const auto leftEdge = goodLeft
  4278. ? TextWithTags()
  4279. : getTextWithTagsPart(range.from - 1, range.from);
  4280. const auto rightEdge = goodRight
  4281. ? TextWithTags()
  4282. : getTextWithTagsPart(range.till, range.till + 1);
  4283. const auto extendLeft = !leftEdge.empty()
  4284. && IsNewline(leftEdge.text.back());
  4285. const auto extendRight = !rightEdge.empty()
  4286. && IsNewline(rightEdge.text.front());
  4287. if (!goodLeft) {
  4288. text.text.insert(0, kHardLine);
  4289. for (auto &tag : text.tags) {
  4290. ++tag.offset;
  4291. }
  4292. if (extendLeft) {
  4293. --range.from;
  4294. } else {
  4295. ++result.from;
  4296. ++result.till;
  4297. }
  4298. }
  4299. if (!goodRight) {
  4300. text.text.push_back(kHardLine);
  4301. if (extendRight) {
  4302. ++range.till;
  4303. }
  4304. }
  4305. finishMarkdownTagChange(range, PrepareForInsert(std::move(text)));
  4306. return result;
  4307. }
  4308. void InputField::removeMarkdownTag(TextRange range, const QString &tag) {
  4309. auto current = getTextWithTagsPart(range.from, range.till);
  4310. auto tags = TagList();
  4311. for (const auto &existing : current.tags) {
  4312. const auto id = TextUtilities::TagWithRemoved(existing.id, tag);
  4313. const auto additional = (tag == kTagPre)
  4314. ? kTagCode
  4315. : (tag == kTagCode)
  4316. ? kTagPre
  4317. : QString();
  4318. const auto removeBlock = (IsTagPre(tag) || tag == kTagCode)
  4319. && IsTagPre(FindBlockTag(id));
  4320. const auto use = removeBlock
  4321. ? WithBlockTagRemoved(id)
  4322. : additional.isEmpty()
  4323. ? id
  4324. : TextUtilities::TagWithRemoved(id, additional);
  4325. if (!use.isEmpty()) {
  4326. tags.push_back({ existing.offset, existing.length, use });
  4327. }
  4328. }
  4329. current.tags = std::move(tags);
  4330. _insertedTagsReplace = true;
  4331. finishMarkdownTagChange(range, PrepareForInsert(std::move(current)));
  4332. _insertedTagsReplace = false;
  4333. }
  4334. void InputField::finishMarkdownTagChange(
  4335. TextRange range,
  4336. const TextWithTags &textWithTags) {
  4337. auto cursor = _inner->textCursor();
  4338. cursor.beginEditBlock();
  4339. cursor.setPosition(range.from);
  4340. cursor.setPosition(range.till, QTextCursor::KeepAnchor);
  4341. _insertedTags = textWithTags.tags;
  4342. _realInsertPosition = range.from;
  4343. _realCharsAdded = textWithTags.text.size();
  4344. cursor.insertText(textWithTags.text);
  4345. cursor.setCharFormat(_defaultCharFormat);
  4346. cursor.endEditBlock();
  4347. if (!_insertedTagsDelayClear) {
  4348. _insertedTags.clear();
  4349. _realInsertPosition = -1;
  4350. }
  4351. _inner->setTextCursor(cursor);
  4352. }
  4353. bool InputField::IsValidMarkdownLink(QStringView link) {
  4354. return ::Ui::IsValidMarkdownLink(link) && !::Ui::IsCustomEmojiLink(link);
  4355. }
  4356. bool InputField::IsCustomEmojiLink(QStringView link) {
  4357. return ::Ui::IsCustomEmojiLink(link);
  4358. }
  4359. QString InputField::CustomEmojiLink(QStringView entityData) {
  4360. return MakeUniqueCustomEmojiLink(u"%1%2"_q
  4361. .arg(kCustomEmojiTagStart)
  4362. .arg(entityData));
  4363. }
  4364. QString InputField::CustomEmojiEntityData(QStringView link) {
  4365. const auto match = qthelp::regex_match(
  4366. "^(\\d+)(\\?|$)",
  4367. base::StringViewMid(link, kCustomEmojiTagStart.size()));
  4368. return match ? match->captured(1) : QString();
  4369. }
  4370. void InputField::commitMarkdownLinkEdit(
  4371. EditLinkSelection selection,
  4372. const TextWithTags &textWithTags,
  4373. const QString &link) {
  4374. if (textWithTags.text.isEmpty()
  4375. || !IsValidMarkdownLink(link)
  4376. || !_editLinkCallback) {
  4377. return;
  4378. }
  4379. auto prepared = PrepareForInsert(textWithTags);
  4380. {
  4381. auto from = 0;
  4382. const auto till = int(prepared.text.size());
  4383. auto &tags = prepared.tags;
  4384. auto i = tags.begin();
  4385. while (from < till) {
  4386. while (i != tags.end() && i->offset <= from) {
  4387. auto all = TextUtilities::SplitTags(i->id);
  4388. auto j = all.begin();
  4389. for (; j != all.end(); ++j) {
  4390. if (IsValidMarkdownLink(*j)) {
  4391. *j = link;
  4392. break;
  4393. }
  4394. }
  4395. if (j == all.end()) {
  4396. all.push_back(link);
  4397. }
  4398. i->id = TextUtilities::JoinTag(all);
  4399. from = i->offset + i->length;
  4400. ++i;
  4401. }
  4402. const auto tagFrom = (i == tags.end())
  4403. ? till
  4404. : i->offset;
  4405. if (from < tagFrom) {
  4406. i = tags.insert(i, { from, tagFrom - from, link });
  4407. from = tagFrom;
  4408. ++i;
  4409. }
  4410. }
  4411. }
  4412. _insertedTags = prepared.tags;
  4413. _insertedTagsAreFromMime = false;
  4414. auto cursor = textCursor();
  4415. const auto editData = selectionEditLinkData(selection);
  4416. cursor.setPosition(editData.from);
  4417. cursor.setPosition(editData.till, QTextCursor::KeepAnchor);
  4418. auto format = _defaultCharFormat;
  4419. _insertedTagsAreFromMime = false;
  4420. const auto text = prepared.text;
  4421. cursor.insertText(
  4422. (editData.from == editData.till) ? (text + QChar(' ')) : text,
  4423. _defaultCharFormat);
  4424. _insertedTags.clear();
  4425. _reverseMarkdownReplacement = false;
  4426. _correcting = true;
  4427. cursor.joinPreviousEditBlock();
  4428. cursor.setCharFormat(_defaultCharFormat);
  4429. cursor.endEditBlock();
  4430. _inner->setTextCursor(cursor);
  4431. _correcting = false;
  4432. }
  4433. void InputField::toggleSelectionMarkdown(const QString &tag) {
  4434. _reverseMarkdownReplacement = false;
  4435. _insertedTagsAreFromMime = false;
  4436. const auto cursor = textCursor();
  4437. auto position = cursor.position();
  4438. auto from = cursor.selectionStart();
  4439. auto till = cursor.selectionEnd();
  4440. if (from >= till) {
  4441. return;
  4442. }
  4443. if (document()->characterAt(from) == kHardLine) {
  4444. ++from;
  4445. }
  4446. if (document()->characterAt(till - 1) == kHardLine) {
  4447. --till;
  4448. }
  4449. auto range = TextRange{ from, till };
  4450. if (tag.isEmpty()) {
  4451. RemoveDocumentTags(_st, document(), from, till);
  4452. } else if (HasFullTextTag(getTextWithTagsSelected(), tag)) {
  4453. removeMarkdownTag(range, tag);
  4454. } else {
  4455. const auto leftForBlock = [&] {
  4456. if (from <= 0) {
  4457. return true;
  4458. }
  4459. const auto text = getTextWithTagsPart(
  4460. from - 1,
  4461. from + 1
  4462. ).text;
  4463. return text.isEmpty()
  4464. || IsNewline(text[0])
  4465. || IsNewline(text[text.size() - 1]);
  4466. }();
  4467. const auto rightForBlock = [&] {
  4468. auto cursor = QTextCursor(document());
  4469. cursor.movePosition(QTextCursor::End);
  4470. if (till >= cursor.position()) {
  4471. return true;
  4472. }
  4473. const auto text = getTextWithTagsPart(
  4474. till - 1,
  4475. till + 1
  4476. ).text;
  4477. return text.isEmpty()
  4478. || IsNewline(text[0])
  4479. || IsNewline(text[text.size() - 1]);
  4480. }();
  4481. const auto useTag = (tag != kTagCode)
  4482. ? tag
  4483. : (leftForBlock && rightForBlock)
  4484. ? kTagPre
  4485. : kTagCode;
  4486. range = addMarkdownTag(range, useTag);
  4487. }
  4488. auto restorePosition = textCursor();
  4489. restorePosition.setPosition(
  4490. (position == till) ? range.from : range.till);
  4491. restorePosition.setPosition(
  4492. (position == till) ? range.till : range.from,
  4493. QTextCursor::KeepAnchor);
  4494. setTextCursor(restorePosition);
  4495. }
  4496. void InputField::clearSelectionMarkdown() {
  4497. toggleSelectionMarkdown(QString());
  4498. }
  4499. bool InputField::revertFormatReplace() {
  4500. const auto cursor = textCursor();
  4501. const auto position = cursor.position();
  4502. if (position <= 0 || cursor.hasSelection()) {
  4503. return false;
  4504. }
  4505. const auto inside = position - 1;
  4506. const auto document = _inner->document();
  4507. const auto block = document->findBlock(inside);
  4508. if (block == document->end()) {
  4509. return false;
  4510. }
  4511. for (auto i = block.begin(); !i.atEnd(); ++i) {
  4512. const auto fragment = i.fragment();
  4513. const auto fragmentStart = fragment.position();
  4514. const auto fragmentEnd = fragmentStart + fragment.length();
  4515. if (fragmentEnd <= inside) {
  4516. continue;
  4517. } else if (fragmentStart > inside || fragmentEnd != position) {
  4518. return false;
  4519. }
  4520. const auto current = fragment.charFormat();
  4521. if (current.hasProperty(kInstantReplaceWithId)) {
  4522. const auto with = current.property(kInstantReplaceWithId);
  4523. const auto string = with.toString();
  4524. if (fragment.text() != string) {
  4525. return false;
  4526. }
  4527. auto replaceCursor = cursor;
  4528. replaceCursor.setPosition(fragmentStart);
  4529. replaceCursor.setPosition(fragmentEnd, QTextCursor::KeepAnchor);
  4530. const auto what = current.property(kInstantReplaceWhatId);
  4531. auto format = _defaultCharFormat;
  4532. ApplyTagFormat(format, current);
  4533. replaceCursor.insertText(what.toString(), format);
  4534. return true;
  4535. } else if (_reverseMarkdownReplacement
  4536. && current.hasProperty(kReplaceTagId)) {
  4537. const auto tag = current.property(kReplaceTagId).toString();
  4538. if (tag.isEmpty()) {
  4539. return false;
  4540. } else if (auto test = i; !(++test).atEnd()) {
  4541. const auto format = test.fragment().charFormat();
  4542. if (format.property(kReplaceTagId).toString() == tag) {
  4543. return false;
  4544. }
  4545. } else if (auto test = block; test.next() != document->end()) {
  4546. const auto begin = test.begin();
  4547. if (begin != test.end()) {
  4548. const auto format = begin.fragment().charFormat();
  4549. if (format.property(kReplaceTagId).toString() == tag) {
  4550. return false;
  4551. }
  4552. }
  4553. }
  4554. const auto first = [&] {
  4555. auto checkBlock = block;
  4556. auto checkLast = i;
  4557. while (true) {
  4558. for (auto j = checkLast; j != checkBlock.begin();) {
  4559. --j;
  4560. const auto format = j.fragment().charFormat();
  4561. if (format.property(kReplaceTagId) != tag) {
  4562. return ++j;
  4563. }
  4564. }
  4565. if (checkBlock == document->begin()) {
  4566. return checkBlock.begin();
  4567. }
  4568. checkBlock = checkBlock.previous();
  4569. checkLast = checkBlock.end();
  4570. }
  4571. }();
  4572. const auto from = first.fragment().position();
  4573. const auto till = fragmentEnd;
  4574. auto replaceCursor = cursor;
  4575. replaceCursor.setPosition(from);
  4576. replaceCursor.setPosition(till, QTextCursor::KeepAnchor);
  4577. replaceCursor.insertText(
  4578. tag + getTextWithTagsPart(from, till).text + tag,
  4579. _defaultCharFormat);
  4580. return true;
  4581. }
  4582. return false;
  4583. }
  4584. return false;
  4585. }
  4586. bool InputField::jumpOutOfBlockByBackspace() {
  4587. auto cursor = textCursor();
  4588. if (cursor.hasSelection()) {
  4589. return false;
  4590. }
  4591. const auto position = cursor.position();
  4592. if (!position) {
  4593. return false;
  4594. }
  4595. const auto block = document()->findBlock(position);
  4596. const auto tagId = block.blockFormat().property(kQuoteFormatId);
  4597. if (block.position() != position || !HasBlockTag(tagId.toString())) {
  4598. return false;
  4599. }
  4600. cursor.setPosition(position - 1);
  4601. setTextCursor(cursor);
  4602. return true;
  4603. }
  4604. void InputField::contextMenuEventInner(QContextMenuEvent *e, QMenu *m) {
  4605. if (const auto menu = m ? m : _inner->createStandardContextMenu()) {
  4606. addMarkdownActions(menu, e);
  4607. _contextMenu = base::make_unique_q<PopupMenu>(this, menu, _st.menu);
  4608. QObject::connect(_contextMenu.get(), &QObject::destroyed, [=] {
  4609. _menuShownChanges.fire(false);
  4610. });
  4611. _menuShownChanges.fire(true);
  4612. _contextMenu->popup(e->globalPos());
  4613. }
  4614. }
  4615. void InputField::addMarkdownActions(
  4616. not_null<QMenu*> menu,
  4617. QContextMenuEvent *e) {
  4618. if (_markdownEnabledState.disabled()) {
  4619. return;
  4620. }
  4621. auto &integration = Integration::Instance();
  4622. const auto formatting = new QAction(
  4623. integration.phraseFormattingTitle(),
  4624. menu);
  4625. addMarkdownMenuAction(menu, formatting);
  4626. const auto submenu = new QMenu(menu);
  4627. formatting->setMenu(submenu);
  4628. const auto textWithTags = getTextWithTagsSelected();
  4629. const auto &text = textWithTags.text;
  4630. const auto &tags = textWithTags.tags;
  4631. const auto hasText = !text.isEmpty();
  4632. const auto hasTags = !tags.isEmpty();
  4633. const auto disabled = (!_editLinkCallback && !hasText);
  4634. formatting->setDisabled(disabled);
  4635. if (disabled) {
  4636. return;
  4637. }
  4638. const auto add = [&](
  4639. const QString &base,
  4640. QKeySequence sequence,
  4641. bool disabled,
  4642. auto callback) {
  4643. const auto add = sequence.isEmpty()
  4644. ? QString()
  4645. : QChar('\t') + sequence.toString(QKeySequence::NativeText);
  4646. const auto action = new QAction(base + add, submenu);
  4647. connect(action, &QAction::triggered, this, callback);
  4648. action->setDisabled(disabled);
  4649. submenu->addAction(action);
  4650. };
  4651. const auto addtag = [&](
  4652. const QString &base,
  4653. QKeySequence sequence,
  4654. const QString &tag) {
  4655. if (!_markdownEnabledState.enabledForTag(tag)) {
  4656. return;
  4657. }
  4658. const auto disabled = !hasText;
  4659. add(base, sequence, disabled, [=] {
  4660. toggleSelectionMarkdown(tag);
  4661. });
  4662. };
  4663. const auto addlink = [&] {
  4664. const auto selection = editLinkSelection(e);
  4665. const auto data = selectionEditLinkData(selection);
  4666. const auto base = data.link.isEmpty()
  4667. ? integration.phraseFormattingLinkCreate()
  4668. : integration.phraseFormattingLinkEdit();
  4669. add(base, kEditLinkSequence, false, [=] {
  4670. editMarkdownLink(selection);
  4671. });
  4672. };
  4673. const auto addclear = [&] {
  4674. const auto disabled = !hasText || !hasTags;
  4675. add(integration.phraseFormattingClear(), kClearFormatSequence, disabled, [=] {
  4676. clearSelectionMarkdown();
  4677. });
  4678. };
  4679. addtag(integration.phraseFormattingBold(), QKeySequence::Bold, kTagBold);
  4680. addtag(integration.phraseFormattingItalic(), QKeySequence::Italic, kTagItalic);
  4681. addtag(integration.phraseFormattingUnderline(), QKeySequence::Underline, kTagUnderline);
  4682. addtag(integration.phraseFormattingStrikeOut(), kStrikeOutSequence, kTagStrikeOut);
  4683. addtag(integration.phraseFormattingBlockquote(), kBlockquoteSequence, kTagBlockquote);
  4684. addtag(integration.phraseFormattingMonospace(), kMonospaceSequence, kTagCode);
  4685. addtag(integration.phraseFormattingSpoiler(), kSpoilerSequence, kTagSpoiler);
  4686. if (_editLinkCallback) {
  4687. submenu->addSeparator();
  4688. addlink();
  4689. }
  4690. submenu->addSeparator();
  4691. addclear();
  4692. }
  4693. void InputField::addMarkdownMenuAction(
  4694. not_null<QMenu*> menu,
  4695. not_null<QAction*> action) {
  4696. const auto actions = menu->actions();
  4697. const auto before = [&] {
  4698. auto seenAfter = false;
  4699. for (const auto action : actions) {
  4700. if (seenAfter) {
  4701. return action;
  4702. } else if (action->objectName() == qstr("edit-delete")) {
  4703. seenAfter = true;
  4704. }
  4705. }
  4706. return (QAction*)nullptr;
  4707. }();
  4708. menu->insertSeparator(before);
  4709. menu->insertAction(before, action);
  4710. }
  4711. void InputField::dropEventInner(QDropEvent *e) {
  4712. _insertedTagsDelayClear = true;
  4713. _inner->QTextEdit::dropEvent(e);
  4714. _insertedTagsDelayClear = false;
  4715. _insertedTags.clear();
  4716. _realInsertPosition = -1;
  4717. window()->raise();
  4718. window()->activateWindow();
  4719. }
  4720. bool InputField::canInsertFromMimeDataInner(const QMimeData *source) const {
  4721. if (source
  4722. && _mimeDataHook
  4723. && _mimeDataHook(source, MimeAction::Check)) {
  4724. return true;
  4725. }
  4726. return _inner->QTextEdit::canInsertFromMimeData(source);
  4727. }
  4728. void InputField::insertFromMimeDataInner(const QMimeData *source) {
  4729. if (source
  4730. && _mimeDataHook
  4731. && _mimeDataHook(source, MimeAction::Insert)) {
  4732. return;
  4733. }
  4734. const auto text = [&] {
  4735. const auto textMime = TextUtilities::TagsTextMimeType();
  4736. const auto tagsMime = TextUtilities::TagsMimeType();
  4737. if (!source->hasFormat(textMime) || !source->hasFormat(tagsMime)) {
  4738. _insertedTags.clear();
  4739. auto result = source->text();
  4740. return result.replace(u"\r\n"_q, u"\n"_q);
  4741. }
  4742. auto result = QString::fromUtf8(source->data(textMime));
  4743. _insertedTags = TextUtilities::DeserializeTags(
  4744. source->data(tagsMime),
  4745. result.size());
  4746. _insertedTagsAreFromMime = true;
  4747. return result;
  4748. }();
  4749. auto cursor = textCursor();
  4750. if (!text.isEmpty()) {
  4751. insertWithTags(
  4752. { cursor.selectionStart(), cursor.selectionEnd() },
  4753. { text, _insertedTags });
  4754. }
  4755. ensureCursorVisible();
  4756. if (!_insertedTagsDelayClear) {
  4757. _insertedTags.clear();
  4758. }
  4759. }
  4760. void InputField::resizeEvent(QResizeEvent *e) {
  4761. refreshPlaceholder(_placeholderFull.current());
  4762. _inner->setGeometry(rect().marginsRemoved(
  4763. _st.textMargins + _additionalMargins + _customFontMargins));
  4764. if (_spoilerOverlay) {
  4765. _spoilerOverlay->setGeometry(_inner->rect());
  4766. }
  4767. _borderAnimationStart = width() / 2;
  4768. RpWidget::resizeEvent(e);
  4769. checkContentHeight();
  4770. }
  4771. void InputField::refreshPlaceholder(const QString &text) {
  4772. const auto margins = _st.textMargins
  4773. + _st.placeholderMargins
  4774. + _additionalMargins
  4775. + _customFontMargins;
  4776. const auto availableWidth = rect().marginsRemoved(margins).width();
  4777. if (_st.placeholderScale > 0.) {
  4778. auto placeholderFont = _st.placeholderFont->f;
  4779. placeholderFont.setStyleStrategy(QFont::PreferMatch);
  4780. const auto metrics = QFontMetrics(placeholderFont);
  4781. _placeholder = metrics.elidedText(text, Qt::ElideRight, availableWidth);
  4782. _placeholderPath = QPainterPath();
  4783. if (!_placeholder.isEmpty()) {
  4784. const auto result = style::FindAdjustResult(placeholderFont);
  4785. const auto ascent = result ? result->iascent : metrics.ascent();
  4786. _placeholderPath.addText(0, ascent, placeholderFont, _placeholder);
  4787. }
  4788. } else {
  4789. _placeholder = _st.placeholderFont->elided(text, availableWidth);
  4790. }
  4791. update();
  4792. }
  4793. void InputField::setPlaceholder(
  4794. rpl::producer<QString> placeholder,
  4795. int afterSymbols) {
  4796. _placeholderFull = std::move(placeholder);
  4797. if (_placeholderAfterSymbols != afterSymbols) {
  4798. _placeholderAfterSymbols = afterSymbols;
  4799. startPlaceholderAnimation();
  4800. }
  4801. }
  4802. void InputField::setEditLinkCallback(
  4803. Fn<bool(
  4804. EditLinkSelection selection,
  4805. TextWithTags text,
  4806. QString link,
  4807. EditLinkAction action)> callback) {
  4808. _editLinkCallback = std::move(callback);
  4809. }
  4810. void InputField::setEditLanguageCallback(
  4811. Fn<void(QString now, Fn<void(QString)> save)> callback) {
  4812. _editLanguageCallback = std::move(callback);
  4813. }
  4814. void InputField::showError() {
  4815. showErrorNoFocus();
  4816. if (!hasFocus()) {
  4817. _inner->setFocus();
  4818. }
  4819. }
  4820. void InputField::showErrorNoFocus() {
  4821. setErrorShown(true);
  4822. }
  4823. void InputField::hideError() {
  4824. setErrorShown(false);
  4825. }
  4826. void InputField::setErrorShown(bool error) {
  4827. if (_error != error) {
  4828. _error = error;
  4829. _a_error.start([this] { update(); }, _error ? 0. : 1., _error ? 1. : 0., _st.duration);
  4830. startBorderAnimation();
  4831. }
  4832. }
  4833. rpl::producer<> InputField::heightChanges() const {
  4834. return _heightChanges.events();
  4835. }
  4836. rpl::producer<bool> InputField::focusedChanges() const {
  4837. return _focusedChanges.events();
  4838. }
  4839. rpl::producer<> InputField::tabbed() const {
  4840. return _tabbed.events();
  4841. }
  4842. rpl::producer<> InputField::cancelled() const {
  4843. return _cancelled.events();
  4844. }
  4845. rpl::producer<> InputField::changes() const {
  4846. return _changes.events();
  4847. }
  4848. rpl::producer<Qt::KeyboardModifiers> InputField::submits() const {
  4849. return _submits.events();
  4850. }
  4851. InputField::~InputField() = default;
  4852. // Optimization: with null page size document does not re-layout
  4853. // on each insertText / mergeCharFormat.
  4854. void PrepareFormattingOptimization(not_null<QTextDocument*> document) {
  4855. if (!document->pageSize().isNull()) {
  4856. document->setPageSize(QSizeF(0, 0));
  4857. }
  4858. }
  4859. int ComputeRealUnicodeCharactersCount(const QString &text) {
  4860. return text.size() - ranges::count(text, true, [](QChar ch) {
  4861. return ch.isHighSurrogate();
  4862. });
  4863. }
  4864. int ComputeFieldCharacterCount(not_null<InputField*> field) {
  4865. return ComputeRealUnicodeCharactersCount(field->getLastText());
  4866. }
  4867. void AddLengthLimitLabel(
  4868. not_null<InputField*> field,
  4869. int limit,
  4870. std::optional<uint> customThreshold,
  4871. int limitLabelTop) {
  4872. struct State {
  4873. rpl::variable<int> length;
  4874. };
  4875. constexpr auto kMinus = QChar(0x2212);
  4876. const auto state = field->lifetime().make_state<State>();
  4877. state->length = rpl::single(
  4878. rpl::empty
  4879. ) | rpl::then(field->changes()) | rpl::map([=] {
  4880. return int(field->getLastText().size());
  4881. });
  4882. const auto allowExceed = std::max(limit / 2, 9);
  4883. field->setMaxLength(limit + allowExceed);
  4884. const auto threshold = !customThreshold
  4885. ? std::min(limit / 2, 9)
  4886. : int(*customThreshold);
  4887. auto warningText = state->length.value() | rpl::map([=](int count) {
  4888. const auto left = limit - count;
  4889. return (left >= threshold)
  4890. ? QString()
  4891. : (left < 0)
  4892. ? (kMinus + QString::number(std::abs(left)))
  4893. : QString::number(left);
  4894. });
  4895. const auto warning = CreateChild<FlatLabel>(
  4896. field.get(),
  4897. std::move(warningText),
  4898. st::defaultInputFieldLimit);
  4899. const auto maxSize = st::defaultInputFieldLimit.style.font->width(
  4900. kMinus + QString::number(allowExceed));
  4901. const auto add = std::max(maxSize - field->st().textMargins.right(), 0);
  4902. if (add) {
  4903. field->setAdditionalMargins({ 0, 0, add, 0 });
  4904. }
  4905. state->length.value() | rpl::map(
  4906. rpl::mappers::_1 > limit
  4907. ) | rpl::start_with_next([=](bool exceeded) {
  4908. warning->setTextColorOverride(exceeded
  4909. ? st::attentionButtonFg->c
  4910. : std::optional<QColor>());
  4911. }, warning->lifetime());
  4912. rpl::combine(
  4913. field->sizeValue(),
  4914. warning->sizeValue()
  4915. ) | rpl::start_with_next([=] {
  4916. // Baseline alignment.
  4917. const auto top = field->st().textMargins.top()
  4918. + field->st().style.font->ascent
  4919. - st::defaultInputFieldLimit.style.font->ascent;
  4920. warning->moveToRight(0, top + limitLabelTop);
  4921. }, warning->lifetime());
  4922. warning->setAttribute(Qt::WA_TransparentForMouseEvents);
  4923. }
  4924. } // namespace Ui