Bez popisu

ViewController.swift 414KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284
  1. //
  2. // ViewController.swift
  3. // Assistant for Google Meet
  4. //
  5. // Created by Dev Mac 1 on 06/04/2026.
  6. //
  7. import Cocoa
  8. import QuartzCore
  9. import AVFoundation
  10. import AVKit
  11. import WebKit
  12. import AuthenticationServices
  13. import StoreKit
  14. import ScreenCaptureKit
  15. private enum SidebarPage: Int {
  16. case joinMeetings = 0
  17. case photo = 1
  18. case video = 2
  19. case widgets = 3
  20. case settings = 4
  21. case aiCompanion = 5
  22. }
  23. private enum ZoomJoinMode: Int {
  24. case id = 0
  25. case url = 1
  26. }
  27. private enum SettingsAction: Int {
  28. case restore = 0
  29. case rateUs = 1
  30. case support = 2
  31. case moreApps = 3
  32. case shareApp = 4
  33. case upgrade = 5
  34. case privacyPolicy = 6
  35. case termsOfServices = 7
  36. }
  37. private enum PremiumPlan: Int {
  38. case weekly = 0
  39. case monthly = 1
  40. case yearly = 2
  41. case lifetime = 3
  42. }
  43. private enum PremiumStoreProduct {
  44. static let weekly = "com.mqldev.meetingsapp.premium.weekly"
  45. static let monthly = "com.mqldev.meetingsapp.premium.monthly"
  46. static let yearly = "com.mqldev.meetingsapp.premium.yearly"
  47. static let lifetime = "com.mqldev.meetingsapp.premium.lifetime"
  48. static let allIDs = [weekly, monthly, yearly, lifetime]
  49. static func productID(for plan: PremiumPlan) -> String {
  50. switch plan {
  51. case .weekly: return weekly
  52. case .monthly: return monthly
  53. case .yearly: return yearly
  54. case .lifetime: return lifetime
  55. }
  56. }
  57. static func plan(for productID: String) -> PremiumPlan? {
  58. switch productID {
  59. case weekly: return .weekly
  60. case monthly: return .monthly
  61. case yearly: return .yearly
  62. case lifetime: return .lifetime
  63. default: return nil
  64. }
  65. }
  66. }
  67. @MainActor
  68. private final class StoreKitCoordinator {
  69. enum PurchaseOutcome {
  70. case success
  71. case cancelled
  72. case pending
  73. case unavailable
  74. case alreadyOwned
  75. case failed(String)
  76. }
  77. private(set) var productsByID: [String: Product] = [:]
  78. private(set) var activeEntitlementProductIDs: Set<String> = []
  79. private(set) var lastProductLoadError: String?
  80. var onEntitlementsChanged: ((Bool) -> Void)?
  81. var hasPremiumAccess: Bool { !activeEntitlementProductIDs.isEmpty }
  82. var hasLifetimeAccess: Bool { activeEntitlementProductIDs.contains(PremiumStoreProduct.lifetime) }
  83. var activeNonLifetimePlan: PremiumPlan? {
  84. activeEntitlementProductIDs
  85. .compactMap { PremiumStoreProduct.plan(for: $0) }
  86. .filter { $0 != .lifetime }
  87. .max(by: { $0.rawValue < $1.rawValue })
  88. }
  89. private var transactionUpdatesTask: Task<Void, Never>?
  90. deinit {
  91. transactionUpdatesTask?.cancel()
  92. }
  93. func start() async {
  94. if transactionUpdatesTask == nil {
  95. transactionUpdatesTask = Task { [weak self] in
  96. await self?.observeTransactionUpdates()
  97. }
  98. }
  99. await refreshProducts()
  100. await refreshEntitlements()
  101. }
  102. func refreshProducts() async {
  103. do {
  104. let products = try await Product.products(for: PremiumStoreProduct.allIDs)
  105. productsByID = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) })
  106. lastProductLoadError = nil
  107. } catch {
  108. productsByID = [:]
  109. lastProductLoadError = error.localizedDescription
  110. }
  111. }
  112. func refreshEntitlements() async {
  113. let previousHasPremiumAccess = hasPremiumAccess
  114. var active = Set<String>()
  115. for await entitlement in Transaction.currentEntitlements {
  116. guard case .verified(let transaction) = entitlement else { continue }
  117. guard PremiumStoreProduct.allIDs.contains(transaction.productID) else { continue }
  118. if Self.isTransactionActive(transaction) {
  119. active.insert(transaction.productID)
  120. }
  121. }
  122. // Some StoreKit test timelines can briefly report empty current entitlements
  123. // even though a latest verified transaction exists for a non-consumable.
  124. // Merge in latest transactions to keep launch access state accurate.
  125. for productID in PremiumStoreProduct.allIDs {
  126. guard let latest = await Transaction.latest(for: productID),
  127. case .verified(let transaction) = latest,
  128. Self.isTransactionActive(transaction) else { continue }
  129. active.insert(productID)
  130. }
  131. activeEntitlementProductIDs = active
  132. let newHasPremiumAccess = hasPremiumAccess
  133. if newHasPremiumAccess != previousHasPremiumAccess {
  134. onEntitlementsChanged?(newHasPremiumAccess)
  135. }
  136. }
  137. func purchase(plan: PremiumPlan) async -> PurchaseOutcome {
  138. let productID = PremiumStoreProduct.productID(for: plan)
  139. if activeEntitlementProductIDs.contains(productID) {
  140. return .alreadyOwned
  141. }
  142. guard let product = productsByID[productID] else {
  143. await refreshProducts()
  144. guard let refreshed = productsByID[productID] else {
  145. if let lastProductLoadError, !lastProductLoadError.isEmpty {
  146. return .failed("Unable to load products: \(lastProductLoadError)")
  147. }
  148. let loadedIDs = productsByID.keys.sorted().joined(separator: ", ")
  149. let debugIDs = loadedIDs.isEmpty ? "none" : loadedIDs
  150. return .failed("Product ID not found in StoreKit response. Requested: \(productID). Loaded IDs: \(debugIDs)")
  151. }
  152. return await purchase(product: refreshed)
  153. }
  154. return await purchase(product: product)
  155. }
  156. func restorePurchases() async -> String {
  157. do {
  158. try await AppStore.sync()
  159. await refreshEntitlements()
  160. if hasPremiumAccess {
  161. return "Purchases restored successfully."
  162. }
  163. return "No previous premium purchase was found for this Apple ID."
  164. } catch {
  165. return "Restore failed: \(error.localizedDescription)"
  166. }
  167. }
  168. private func purchase(product: Product) async -> PurchaseOutcome {
  169. do {
  170. let result = try await product.purchase()
  171. switch result {
  172. case .success(let verificationResult):
  173. guard case .verified(let transaction) = verificationResult else {
  174. return .failed("Purchase verification failed.")
  175. }
  176. await transaction.finish()
  177. await refreshEntitlements()
  178. return .success
  179. case .pending:
  180. return .pending
  181. case .userCancelled:
  182. return .cancelled
  183. @unknown default:
  184. return .failed("Unknown purchase state.")
  185. }
  186. } catch {
  187. return .failed(error.localizedDescription)
  188. }
  189. }
  190. private func observeTransactionUpdates() async {
  191. for await update in Transaction.updates {
  192. guard case .verified(let transaction) = update else { continue }
  193. if PremiumStoreProduct.allIDs.contains(transaction.productID) {
  194. await refreshEntitlements()
  195. }
  196. await transaction.finish()
  197. }
  198. }
  199. private static func isTransactionActive(_ transaction: Transaction) -> Bool {
  200. if transaction.revocationDate != nil { return false }
  201. if let expirationDate = transaction.expirationDate {
  202. return expirationDate > Date()
  203. }
  204. return true
  205. }
  206. }
  207. final class ViewController: NSViewController {
  208. private enum MeetingTranscriptStatus: String, Codable {
  209. case notRequested
  210. case processing
  211. case ready
  212. case failed
  213. }
  214. private enum MeetingTranscriptSource: String, Codable {
  215. case meetApi
  216. case localAudioOpenAI
  217. }
  218. private enum PaywallFooterAction {
  219. case manageSubscription
  220. case restorePurchase
  221. case continueWithFreePlan
  222. case privacyPolicy
  223. case support
  224. case termsOfServices
  225. }
  226. private struct GoogleProfileDisplay {
  227. let name: String
  228. let email: String
  229. let pictureURL: URL?
  230. }
  231. private struct MeetingRecordingSummary: Codable {
  232. let id: String
  233. let title: String
  234. let meetURLString: String
  235. let startedAt: Date
  236. let endedAt: Date
  237. let audioFilePath: String
  238. var transcriptStatusRaw: String?
  239. var transcriptSourceRaw: String?
  240. var transcriptText: String?
  241. var transcriptErrorMessage: String?
  242. }
  243. private struct ActiveMeetingRecordingSession {
  244. let id: String
  245. let title: String
  246. let meetURL: URL
  247. let startedAt: Date
  248. let systemAudioFileURL: URL
  249. let microphoneAudioFileURL: URL
  250. }
  251. private var palette = Palette(isDarkMode: true)
  252. private let typography = Typography()
  253. private let launchContentSize = NSSize(width: 920, height: 690)
  254. private let launchMinContentSize = NSSize(width: 760, height: 600)
  255. private let launchSplashMinimumVisibleDuration: TimeInterval = 2
  256. private let launchSplashTimeout: TimeInterval = 12
  257. private var launchSplashView: LaunchSplashView?
  258. private var launchSplashTimeoutWorkItem: DispatchWorkItem?
  259. private var launchSplashMinimumDelayWorkItem: DispatchWorkItem?
  260. private var launchSplashShownAt: Date?
  261. private var hasDismissedLaunchSplash = false
  262. private var mainContentHost: NSView?
  263. /// Pin constraints for the current page inside `mainContentHost`; deactivated before each swap so relayout never stacks duplicates.
  264. private var mainContentHostPinConstraints: [NSLayoutConstraint] = []
  265. private var sidebarRowViews: [SidebarPage: NSView] = [:]
  266. private var selectedSidebarPage: SidebarPage = .joinMeetings
  267. private var selectedZoomJoinMode: ZoomJoinMode = .id
  268. private var pageCache: [SidebarPage: NSView] = [:]
  269. private var sidebarPageByView = [ObjectIdentifier: SidebarPage]()
  270. private var zoomJoinModeByView = [ObjectIdentifier: ZoomJoinMode]()
  271. private var zoomJoinModeViews: [ZoomJoinMode: NSView] = [:]
  272. private var settingsActionByView = [ObjectIdentifier: SettingsAction]()
  273. private var aiCompanionAudioURLByView = [ObjectIdentifier: URL]()
  274. private var aiCompanionAudioStatusLabelByView = [ObjectIdentifier: NSTextField]()
  275. private var aiCompanionTranscriptMeetingIdByView = [ObjectIdentifier: String]()
  276. private var aiCompanionTranscriptStatusLabelByView = [ObjectIdentifier: NSTextField]()
  277. private var aiCompanionTranscriptCurrentRequestId: UUID?
  278. private var aiCompanionTranscriptWindow: NSWindow?
  279. private weak var aiCompanionTranscriptTextView: NSTextView?
  280. private var aiCompanionTranscriptTaskByMeetingId = [String: Task<Void, Never>]()
  281. private var aiCompanionAudioPlayer: AVPlayer?
  282. private var aiCompanionLocalAudioPlayer: AVAudioPlayer?
  283. private var aiCompanionCurrentlyPlayingURL: URL?
  284. private weak var aiCompanionCurrentlyPlayingButton: NSButton?
  285. private var aiCompanionPlaybackEndObserver: NSObjectProtocol?
  286. private var aiCompanionPlaybackFailedObserver: NSObjectProtocol?
  287. private var aiCompanionTimeControlObserver: NSKeyValueObservation?
  288. private var aiCompanionAudioRequestID = UUID()
  289. private var aiCompanionNoProgressWorkItem: DispatchWorkItem?
  290. private let aiCompanionSpeechSynthesizer = AVSpeechSynthesizer()
  291. private var aiCompanionIsUsingSpeech = false
  292. private var aiCompanionSpeechTextByView = [ObjectIdentifier: String]()
  293. private var aiCompanionCurrentlySpeakingButtonId: ObjectIdentifier?
  294. private var paywallWindow: NSWindow?
  295. private weak var paywallOverlayView: NSView?
  296. private let paywallContentWidth: CGFloat = 520
  297. private let launchWindowLeftOffset: CGFloat = 80
  298. private var selectedPremiumPlan: PremiumPlan = .monthly
  299. private var paywallPlanViews: [PremiumPlan: NSView] = [:]
  300. private var premiumPlanByView = [ObjectIdentifier: PremiumPlan]()
  301. private var paywallFooterActionByView = [ObjectIdentifier: PaywallFooterAction]()
  302. private weak var paywallOfferLabel: NSTextField?
  303. private weak var paywallContinueLabel: NSTextField?
  304. private weak var paywallContinueButton: NSView?
  305. private weak var sidebarPremiumTitleLabel: NSTextField?
  306. private weak var sidebarPremiumIconView: NSImageView?
  307. private weak var sidebarPremiumButtonView: HoverTrackingView?
  308. private weak var instantMeetCardView: HoverSurfaceView?
  309. private weak var instantMeetTitleLabel: NSTextField?
  310. private weak var instantMeetSubtitleLabel: NSTextField?
  311. private weak var joinWithLinkCardView: HoverSurfaceView?
  312. private weak var joinWithLinkTitleLabel: NSTextField?
  313. private weak var joinMeetPrimaryButton: NSButton?
  314. private weak var meetLinkField: NSTextField?
  315. private weak var browseAddressField: NSTextField?
  316. private var inAppBrowserWindowController: InAppBrowserWindowController?
  317. private var embeddedBrowserViewController: InAppBrowserContainerViewController?
  318. private var embeddedBrowserURL: URL?
  319. private var embeddedBrowserPolicy: InAppBrowserURLPolicy = .allowAll
  320. private weak var mainPanelAuthBar: NSView?
  321. private var mainContentHostTopToAuthConstraint: NSLayoutConstraint?
  322. private var mainContentHostTopToPanelConstraint: NSLayoutConstraint?
  323. private let googleOAuth = GoogleOAuthService.shared
  324. private let calendarClient = GoogleCalendarClient()
  325. private let googleMeetClient = GoogleMeetClient()
  326. private let storeKitCoordinator = StoreKitCoordinator()
  327. private var storeKitStartupTask: Task<Void, Never>?
  328. private var paywallPurchaseTask: Task<Void, Never>?
  329. private var paywallPriceLabels: [PremiumPlan: NSTextField] = [:]
  330. private var paywallSubtitleLabels: [PremiumPlan: NSTextField] = [:]
  331. private var paywallContinueEnabled = true
  332. private var paywallUpgradeFlowEnabled = false
  333. private let launchPaywallDelay: TimeInterval = 3
  334. private var hasCompletedInitialStoreKitSync = false
  335. private var hasPresentedLaunchPaywall = false
  336. private var launchPaywallWorkItem: DispatchWorkItem?
  337. private var hasViewAppearedOnce = false
  338. private var lastKnownPremiumAccess = false
  339. private var displayedScheduleMeetings: [ScheduledMeeting] = []
  340. private var appUsageSessionStartDate: Date?
  341. private var hasObservedAppLifecycleForUsage = false
  342. private var premiumUpgradeRatingPromptWorkItem: DispatchWorkItem?
  343. private enum ScheduleFilter: Int {
  344. case all = 0
  345. case today = 1
  346. case week = 2
  347. }
  348. private enum SchedulePageFilter: Int {
  349. case all = 0
  350. case today = 1
  351. case week = 2
  352. case month = 3
  353. case customRange = 4
  354. }
  355. private var scheduleFilter: ScheduleFilter = .all
  356. private weak var scheduleDateHeadingLabel: NSTextField?
  357. private weak var scheduleCardsStack: NSStackView?
  358. private weak var scheduleCardsScrollView: NSScrollView?
  359. private weak var scheduleScrollLeftButton: NSView?
  360. private weak var scheduleScrollRightButton: NSView?
  361. private weak var scheduleFilterDropdown: NSPopUpButton?
  362. private weak var scheduleGoogleAuthButton: NSButton?
  363. private weak var scheduleGoogleAuthHostView: GoogleProfileAuthHostView?
  364. private var scheduleGoogleAuthHostPadWidthConstraint: NSLayoutConstraint?
  365. private var scheduleGoogleAuthHostPadHeightConstraint: NSLayoutConstraint?
  366. private var scheduleGoogleAuthButtonWidthConstraint: NSLayoutConstraint?
  367. private var scheduleGoogleAuthButtonHeightConstraint: NSLayoutConstraint?
  368. private weak var settingsReminderMasterSwitch: NSSwitch?
  369. private weak var settingsReminder1DaySwitch: NSSwitch?
  370. private weak var settingsReminder12HoursSwitch: NSSwitch?
  371. private weak var settingsReminder1HourSwitch: NSSwitch?
  372. /// Circular avatar size when signed in (top-right, Google-style).
  373. private let scheduleGoogleSignedInAvatarSize: CGFloat = 36
  374. private var scheduleGoogleAuthHovering = false
  375. private var scheduleCurrentProfile: GoogleProfileDisplay?
  376. /// Larger copy of the header avatar for the account popover (optional).
  377. private var scheduleProfileMenuAvatar: NSImage?
  378. private var scheduleProfileImageTask: Task<Void, Never>?
  379. private var googleAccountPopover: NSPopover?
  380. private var scheduleCachedMeetings: [ScheduledMeeting] = []
  381. private var aiCompanionLocalRecordings: [MeetingRecordingSummary] = []
  382. private var activeMeetingRecordingSession: ActiveMeetingRecordingSession?
  383. private var activeMeetingAudioRecorder: AVAudioRecorder?
  384. private var activeMeetingSystemAudioStopper: (() async -> Void)?
  385. private var meetingRecordingMonitorTask: Task<Void, Never>?
  386. private weak var aiCompanionStopRecordingButton: NSButton?
  387. private let widgetSnapshotLimit: Int = 3
  388. private var schedulePageFilter: SchedulePageFilter = .all
  389. private var schedulePageFromDate: Date = Calendar.current.startOfDay(for: Date())
  390. private var schedulePageToDate: Date = Calendar.current.startOfDay(for: Date())
  391. private var schedulePageFilteredMeetings: [ScheduledMeeting] = []
  392. private var schedulePageVisibleCount: Int = 0
  393. private let schedulePageBatchSize: Int = 6
  394. private let schedulePageCardsPerRow: Int = 3
  395. private let schedulePageCardSpacing: CGFloat = 20
  396. private let schedulePageCardHeight: CGFloat = 182
  397. /// Match `makeJoinMeetingsContent` vertical rhythm between sections.
  398. private let schedulePageStackSpacing: CGFloat = 14
  399. /// Tighter gap from header block (title + filters) to the date line below.
  400. private let schedulePageHeaderToDateSpacing: CGFloat = 10
  401. /// Join Meetings: gap from “Schedule” row to date heading, and date heading to card strip (keeps cards aligned with the rest of the column).
  402. private let joinPageScheduleHeaderToDateSpacing: CGFloat = 8
  403. private let joinPageDateToMeetingCardsSpacing: CGFloat = 8
  404. /// Match Join Meetings main content insets so the top auth/profile bar lines up with page edges.
  405. private let schedulePageLeadingInset: CGFloat = 28
  406. private let schedulePageTrailingInset: CGFloat = 28
  407. private var schedulePageScrollObservation: NSObjectProtocol?
  408. private weak var schedulePageDateHeadingLabel: NSTextField?
  409. private weak var schedulePageFilterDropdown: NSPopUpButton?
  410. private weak var schedulePageFromDatePicker: NSDatePicker?
  411. private weak var schedulePageToDatePicker: NSDatePicker?
  412. private weak var schedulePageRangeErrorLabel: NSTextField?
  413. private weak var schedulePageCardsStack: NSStackView?
  414. private weak var schedulePageCardsScrollView: NSScrollView?
  415. // MARK: - Calendar page (custom month UI)
  416. private var calendarPageMonthAnchor: Date = Calendar.current.startOfDay(for: Date())
  417. private var calendarPageSelectedDate: Date = Calendar.current.startOfDay(for: Date())
  418. private weak var calendarPageMonthLabel: NSTextField?
  419. private weak var calendarPageGridStack: NSStackView?
  420. private var calendarPageGridHeightConstraint: NSLayoutConstraint?
  421. private weak var calendarPageDaySummaryLabel: NSTextField?
  422. private var calendarPageActionPopover: NSPopover?
  423. private var calendarPageCreatePopover: NSPopover?
  424. private weak var topToastView: NSVisualEffectView?
  425. private var topToastHideWorkItem: DispatchWorkItem?
  426. /// In-app browser navigation: `.allowAll` or `.whitelist(hostSuffixes:)` (e.g. `["google.com"]` matches `meet.google.com`).
  427. private let inAppBrowserDefaultPolicy: InAppBrowserURLPolicy = .allowAll
  428. private let darkModeDefaultsKey = "settings.darkModeEnabled"
  429. private let appUsageAccumulatedSecondsDefaultsKey = "rating.appUsageAccumulatedSeconds"
  430. private let userHasRatedDefaultsKey = "rating.userHasRated"
  431. private let ratingStateMigrationV2DoneDefaultsKey = "rating.stateMigrationV2Done"
  432. private let nonPremiumJoinTrialConsumedDefaultsKey = "join.nonPremiumTrialConsumed"
  433. private let aiCompanionLocalRecordingsDefaultsKey = "aiCompanion.localRecordings"
  434. private let openAIAPIKeyDefaultsKey = "openai.apiKey"
  435. private let openAIAPIKeyPlistKey = "OpenAIAPIKey"
  436. private let ratingEligibleUsageSeconds: TimeInterval = 30 * 60
  437. private let openAITranscriptionClient = OpenAITranscriptionClient()
  438. private var darkModeEnabled: Bool {
  439. get {
  440. let hasValue = UserDefaults.standard.object(forKey: darkModeDefaultsKey) != nil
  441. return hasValue ? UserDefaults.standard.bool(forKey: darkModeDefaultsKey) : systemPrefersDarkMode()
  442. }
  443. set { UserDefaults.standard.set(newValue, forKey: darkModeDefaultsKey) }
  444. }
  445. private var nonPremiumJoinTrialConsumed: Bool {
  446. get { UserDefaults.standard.bool(forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
  447. set { UserDefaults.standard.set(newValue, forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
  448. }
  449. private var shouldGateJoinActionsForNonPremium: Bool {
  450. !storeKitCoordinator.hasPremiumAccess && nonPremiumJoinTrialConsumed
  451. }
  452. private func makeSettingsPopover() -> NSPopover {
  453. let popover = NSPopover()
  454. popover.behavior = .transient
  455. popover.animates = true
  456. let showUpgradeInSettings = storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess
  457. let showRateUsInSettings = shouldShowRateUsInSettings
  458. popover.contentViewController = SettingsMenuViewController(
  459. palette: palette,
  460. typography: typography,
  461. darkModeEnabled: darkModeEnabled,
  462. showRateUsInSettings: showRateUsInSettings,
  463. showUpgradeInSettings: showUpgradeInSettings,
  464. onToggleDarkMode: { [weak self] enabled in
  465. self?.setDarkMode(enabled)
  466. },
  467. onAction: { [weak self] action, sourceView, clickPoint in
  468. self?.handleSettingsAction(action, sourceView: sourceView, clickLocationInSourceView: clickPoint)
  469. }
  470. )
  471. return popover
  472. }
  473. private var settingsPopover: NSPopover?
  474. override func viewDidLoad() {
  475. super.viewDidLoad()
  476. aiCompanionSpeechSynthesizer.delegate = self
  477. loadAiCompanionLocalRecordings()
  478. // Sync toggle + palette with current macOS appearance on launch.
  479. darkModeEnabled = systemPrefersDarkMode()
  480. palette = Palette(isDarkMode: darkModeEnabled)
  481. storeKitCoordinator.onEntitlementsChanged = { [weak self] hasPremiumAccess in
  482. guard let self else { return }
  483. self.handlePremiumAccessChanged(hasPremiumAccess)
  484. }
  485. NotificationCenter.default.post(
  486. name: .statusBarPremiumAccessChanged,
  487. object: nil,
  488. userInfo: ["hasPremiumAccess": storeKitCoordinator.hasPremiumAccess]
  489. )
  490. migrateLegacyRatingStateIfNeeded()
  491. beginUsageTrackingSessionIfNeeded()
  492. observeAppLifecycleForUsageTrackingIfNeeded()
  493. registerWidgetNotificationObservers()
  494. setupRootView()
  495. buildMainLayout()
  496. showLaunchSplashIfNeeded()
  497. startStoreKit()
  498. }
  499. override func viewDidAppear() {
  500. super.viewDidAppear()
  501. DesktopWidgetWindowManager.shared.restore()
  502. hasViewAppearedOnce = true
  503. presentLaunchPaywallIfNeeded()
  504. dismissLaunchSplashIfReady()
  505. applyWindowTitle(for: selectedSidebarPage)
  506. guard let window = view.window else { return }
  507. configureMainWindowChrome(window)
  508. // Ensure launch size is applied even when macOS tries to restore prior window state.
  509. window.isRestorable = false
  510. window.setFrameAutosaveName("")
  511. DispatchQueue.main.async { [weak self, weak window] in
  512. guard let self, let window else { return }
  513. let frameSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchContentSize)).size
  514. var newFrame = window.frame
  515. newFrame.size = frameSize
  516. window.setFrame(newFrame, display: true)
  517. window.center()
  518. if let screen = window.screen ?? NSScreen.main {
  519. var adjustedFrame = window.frame
  520. adjustedFrame.origin.x -= self.launchWindowLeftOffset
  521. let minX = screen.visibleFrame.minX
  522. adjustedFrame.origin.x = max(minX, adjustedFrame.origin.x)
  523. window.setFrame(adjustedFrame, display: true)
  524. }
  525. window.minSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchMinContentSize)).size
  526. }
  527. }
  528. override var representedObject: Any? {
  529. didSet {}
  530. }
  531. deinit {
  532. premiumUpgradeRatingPromptWorkItem?.cancel()
  533. endUsageTrackingSession()
  534. launchSplashTimeoutWorkItem?.cancel()
  535. launchSplashMinimumDelayWorkItem?.cancel()
  536. NotificationCenter.default.removeObserver(self)
  537. if let observer = schedulePageScrollObservation {
  538. NotificationCenter.default.removeObserver(observer)
  539. }
  540. storeKitStartupTask?.cancel()
  541. paywallPurchaseTask?.cancel()
  542. launchPaywallWorkItem?.cancel()
  543. meetingRecordingMonitorTask?.cancel()
  544. }
  545. }
  546. private extension ViewController {
  547. func setupRootView() {
  548. view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  549. view.wantsLayer = true
  550. view.layer?.backgroundColor = palette.pageBackground.cgColor
  551. }
  552. private func makeLaunchSplashTheme() -> LaunchSplashView.Theme {
  553. let borderAlpha: CGFloat = darkModeEnabled ? 0.9 : 0.45
  554. let cardBackground = darkModeEnabled ? palette.sectionCard : palette.tabBarBackground
  555. let cardBorder = darkModeEnabled ? palette.inputBorder : palette.separator
  556. return LaunchSplashView.Theme(
  557. background: palette.pageBackground,
  558. cardBackground: cardBackground,
  559. cardBorder: cardBorder.withAlphaComponent(borderAlpha),
  560. titleText: palette.textPrimary,
  561. subtitleText: palette.textSecondary,
  562. accent: palette.primaryBlue
  563. )
  564. }
  565. private func showLaunchSplashIfNeeded() {
  566. guard launchSplashView == nil else { return }
  567. let splash = LaunchSplashView(frame: .zero)
  568. splash.alphaValue = 1
  569. let displayName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String)?
  570. .trimmingCharacters(in: .whitespacesAndNewlines)
  571. let fallbackName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
  572. let resolvedName = (displayName?.isEmpty == false ? displayName : fallbackName) ?? "Assistant for Google Meet"
  573. splash.configure(appName: resolvedName, appIcon: NSApp.applicationIconImage, theme: makeLaunchSplashTheme())
  574. view.addSubview(splash)
  575. NSLayoutConstraint.activate([
  576. splash.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  577. splash.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  578. splash.topAnchor.constraint(equalTo: view.topAnchor),
  579. splash.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  580. ])
  581. view.layoutSubtreeIfNeeded()
  582. launchSplashView = splash
  583. launchSplashShownAt = Date()
  584. launchSplashTimeoutWorkItem?.cancel()
  585. let timeoutWorkItem = DispatchWorkItem { [weak self] in
  586. self?.dismissLaunchSplash(force: true)
  587. }
  588. launchSplashTimeoutWorkItem = timeoutWorkItem
  589. DispatchQueue.main.asyncAfter(deadline: .now() + launchSplashTimeout, execute: timeoutWorkItem)
  590. }
  591. private func dismissLaunchSplashIfReady() {
  592. guard hasCompletedInitialStoreKitSync else { return }
  593. guard !hasDismissedLaunchSplash else { return }
  594. if let shownAt = launchSplashShownAt {
  595. let elapsed = Date().timeIntervalSince(shownAt)
  596. let remaining = launchSplashMinimumVisibleDuration - elapsed
  597. if remaining > 0 {
  598. launchSplashMinimumDelayWorkItem?.cancel()
  599. let minDelayWorkItem = DispatchWorkItem { [weak self] in
  600. self?.dismissLaunchSplash(force: false)
  601. }
  602. launchSplashMinimumDelayWorkItem = minDelayWorkItem
  603. DispatchQueue.main.asyncAfter(deadline: .now() + remaining, execute: minDelayWorkItem)
  604. return
  605. }
  606. }
  607. dismissLaunchSplash(force: false)
  608. }
  609. private func dismissLaunchSplash(force: Bool) {
  610. guard !hasDismissedLaunchSplash else { return }
  611. guard let splash = launchSplashView else { return }
  612. if !force && !hasCompletedInitialStoreKitSync { return }
  613. hasDismissedLaunchSplash = true
  614. launchSplashTimeoutWorkItem?.cancel()
  615. launchSplashTimeoutWorkItem = nil
  616. launchSplashMinimumDelayWorkItem?.cancel()
  617. launchSplashMinimumDelayWorkItem = nil
  618. let removeSplash: () -> Void = { [weak self] in
  619. splash.removeFromSuperview()
  620. self?.launchSplashView = nil
  621. self?.launchSplashShownAt = nil
  622. }
  623. let fadeOutAndRemove: () -> Void = {
  624. NSAnimationContext.runAnimationGroup({ context in
  625. context.duration = 0.24
  626. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  627. splash.animator().alphaValue = 0
  628. }, completionHandler: removeSplash)
  629. }
  630. if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
  631. splash.completeLoading(duration: 0) {
  632. removeSplash()
  633. }
  634. return
  635. }
  636. splash.completeLoading {
  637. fadeOutAndRemove()
  638. }
  639. }
  640. func systemPrefersDarkMode() -> Bool {
  641. // Use the system-wide appearance setting (not app/window effective appearance).
  642. // When the key is missing, macOS is in Light mode.
  643. let global = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)
  644. let style = global?["AppleInterfaceStyle"] as? String
  645. return style?.lowercased() == "dark"
  646. }
  647. func buildMainLayout() {
  648. let splitContainer = NSStackView()
  649. splitContainer.translatesAutoresizingMaskIntoConstraints = false
  650. splitContainer.orientation = .horizontal
  651. splitContainer.spacing = 14
  652. splitContainer.distribution = .fill
  653. splitContainer.alignment = .top
  654. view.addSubview(splitContainer)
  655. NSLayoutConstraint.activate([
  656. splitContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  657. splitContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  658. splitContainer.topAnchor.constraint(equalTo: view.topAnchor),
  659. splitContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  660. ])
  661. let sidebar = makeSidebar()
  662. let mainPanel = makeMainPanel()
  663. sidebar.setContentHuggingPriority(.required, for: .horizontal)
  664. sidebar.setContentCompressionResistancePriority(.required, for: .horizontal)
  665. mainPanel.setContentHuggingPriority(.defaultLow, for: .horizontal)
  666. mainPanel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  667. splitContainer.addArrangedSubview(sidebar)
  668. splitContainer.addArrangedSubview(mainPanel)
  669. }
  670. @objc private func sidebarItemClicked(_ sender: NSClickGestureRecognizer) {
  671. guard let view = sender.view else { return }
  672. activateSidebarItem(view)
  673. }
  674. private func activateSidebarItem(_ view: NSView) {
  675. guard let page = sidebarPageByView[ObjectIdentifier(view)],
  676. page != selectedSidebarPage || page == .settings else { return }
  677. showSidebarPage(page)
  678. }
  679. @objc private func zoomJoinModeClicked(_ sender: NSClickGestureRecognizer) {
  680. guard let view = sender.view,
  681. let mode = zoomJoinModeByView[ObjectIdentifier(view)],
  682. mode != selectedZoomJoinMode else { return }
  683. selectedZoomJoinMode = mode
  684. updateZoomJoinModeAppearance()
  685. if selectedSidebarPage == .joinMeetings {
  686. pageCache[.joinMeetings] = nil
  687. showSidebarPage(.joinMeetings)
  688. }
  689. }
  690. @objc private func premiumButtonClicked(_ sender: NSClickGestureRecognizer) {
  691. if storeKitCoordinator.hasLifetimeAccess {
  692. openManageSubscriptions()
  693. } else if storeKitCoordinator.hasPremiumAccess {
  694. showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
  695. } else {
  696. showPaywall()
  697. }
  698. }
  699. @objc private func sidebarButtonClicked(_ sender: NSButton) {
  700. guard let page = SidebarPage(rawValue: sender.tag),
  701. page != selectedSidebarPage || page == .settings else { return }
  702. showSidebarPage(page)
  703. }
  704. private func registerWidgetNotificationObservers() {
  705. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenJoinMeetingsPageRequested), name: .widgetOpenJoinMeetingsPage, object: nil)
  706. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSchedulePageRequested), name: .widgetOpenSchedulePage, object: nil)
  707. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenCalendarPageRequested), name: .widgetOpenCalendarPage, object: nil)
  708. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSettingsPageRequested), name: .widgetOpenSettingsPage, object: nil)
  709. NotificationCenter.default.addObserver(self, selector: #selector(widgetSignInRequested), name: .widgetSignInRequested, object: nil)
  710. NotificationCenter.default.addObserver(self, selector: #selector(widgetRefreshRequested), name: .widgetRefreshRequested, object: nil)
  711. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetWebRequested), name: .widgetOpenMeetWebRequested, object: nil)
  712. NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetingLinkRequested(_:)), name: .widgetOpenMeetingLinkRequested, object: nil)
  713. NotificationCenter.default.addObserver(self, selector: #selector(statusBarOpenSidebarPageRequested(_:)), name: .statusBarOpenSidebarPage, object: nil)
  714. NotificationCenter.default.addObserver(self, selector: #selector(statusBarSignOutRequested), name: .statusBarSignOutRequested, object: nil)
  715. }
  716. @objc private func widgetOpenJoinMeetingsPageRequested() { showSidebarPage(.joinMeetings) }
  717. @objc private func widgetOpenSchedulePageRequested() { showSidebarPage(.photo) }
  718. @objc private func widgetOpenCalendarPageRequested() { showSidebarPage(.video) }
  719. @objc private func widgetOpenSettingsPageRequested() { showSidebarPage(.settings) }
  720. @objc private func widgetSignInRequested() { scheduleConnectClicked() }
  721. @objc private func widgetRefreshRequested() { scheduleReloadClicked() }
  722. @objc private func widgetOpenMeetWebRequested() {
  723. guard let url = URL(string: "https://meet.google.com/") else { return }
  724. openInDefaultBrowser(url: url)
  725. }
  726. @objc private func widgetOpenMeetingLinkRequested(_ notification: Notification) {
  727. guard let link = notification.userInfo?["link"] as? String,
  728. let url = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)) else { return }
  729. openInDefaultBrowser(url: url)
  730. }
  731. @objc private func statusBarOpenSidebarPageRequested(_ notification: Notification) {
  732. guard let pageRaw = notification.userInfo?["page"] as? Int,
  733. let page = SidebarPage(rawValue: pageRaw) else { return }
  734. showSidebarPage(page)
  735. }
  736. @objc private func statusBarSignOutRequested() { performGoogleSignOut() }
  737. @objc private func joinMeetClicked(_ sender: Any?) {
  738. guard shouldGateJoinActionsForNonPremium == false else {
  739. showPaywall()
  740. return
  741. }
  742. let rawInput = meetLinkField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  743. guard let url = normalizedMeetJoinURL(from: rawInput) else {
  744. showSimpleAlert(
  745. title: "Invalid Meet link",
  746. message: "Enter a valid Google Meet link or meeting code (for example nkd-grps-duv, meet.google.com/nkd-grps-duv, or https://meet.google.com/nkd-grps-duv)."
  747. )
  748. return
  749. }
  750. beginMeetingRecordingIfConsented(meetingTitle: "Quick Join Meeting", meetingURL: url)
  751. openInDefaultBrowser(url: url)
  752. consumeNonPremiumJoinTrialIfNeeded()
  753. }
  754. @objc private func joinWithLinkCardClicked(_ sender: NSClickGestureRecognizer) {
  755. meetLinkField?.window?.makeFirstResponder(meetLinkField)
  756. }
  757. @objc private func cancelMeetJoinClicked(_ sender: Any?) {
  758. meetLinkField?.stringValue = ""
  759. }
  760. @objc private func browseOpenAddressClicked(_ sender: Any?) {
  761. let raw = browseAddressField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  762. guard raw.isEmpty == false else {
  763. showSimpleAlert(title: "Browse", message: "Enter a web address (for example meet.google.com).")
  764. return
  765. }
  766. let normalized = normalizedURLString(from: raw)
  767. guard let url = URL(string: normalized), url.scheme == "http" || url.scheme == "https" else {
  768. showSimpleAlert(title: "Invalid address", message: "Enter a valid http or https URL.")
  769. return
  770. }
  771. openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
  772. }
  773. @objc private func browseQuickLinkMeetClicked(_ sender: Any?) {
  774. guard let url = URL(string: "https://meet.google.com/") else { return }
  775. openInDefaultBrowser(url: url)
  776. }
  777. @objc private func browseQuickLinkMeetHelpClicked(_ sender: Any?) {
  778. guard let url = URL(string: "https://support.google.com/meet") else { return }
  779. openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
  780. }
  781. @objc private func browseQuickLinkZoomHelpClicked(_ sender: Any?) {
  782. guard let url = URL(string: "https://support.zoom.us") else { return }
  783. openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
  784. }
  785. @objc private func instantMeetClicked(_ sender: NSClickGestureRecognizer) {
  786. guard shouldGateJoinActionsForNonPremium == false else {
  787. showPaywall()
  788. return
  789. }
  790. guard let url = URL(string: "https://meet.google.com/new") else { return }
  791. openInDefaultBrowser(url: url)
  792. consumeNonPremiumJoinTrialIfNeeded()
  793. }
  794. private func consumeNonPremiumJoinTrialIfNeeded() {
  795. guard !storeKitCoordinator.hasPremiumAccess,
  796. !nonPremiumJoinTrialConsumed else { return }
  797. nonPremiumJoinTrialConsumed = true
  798. refreshInstantMeetPremiumState()
  799. }
  800. private func normalizedURLString(from value: String) -> String {
  801. if value.lowercased().hasPrefix("http://") || value.lowercased().hasPrefix("https://") {
  802. return value
  803. }
  804. return "https://\(value)"
  805. }
  806. /// Typical Meet meeting code shape: three hyphen-separated groups (e.g. `nkd-grps-duv`).
  807. private func isValidMeetMeetingCode(_ code: String) -> Bool {
  808. let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)
  809. guard trimmed.isEmpty == false else { return false }
  810. let pattern = "^[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}$"
  811. return trimmed.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
  812. }
  813. /// Accepts `https://meet.google.com/...`, `meet.google.com/...`, or a bare code; returns canonical Meet URL or `nil`.
  814. private func normalizedMeetJoinURL(from rawInput: String) -> URL? {
  815. let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
  816. guard trimmed.isEmpty == false else { return nil }
  817. let lower = trimmed.lowercased()
  818. if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
  819. guard let url = URL(string: trimmed),
  820. let host = url.host?.lowercased(),
  821. host == "meet.google.com" || host.hasSuffix(".meet.google.com") else {
  822. return nil
  823. }
  824. let path = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
  825. guard path.isEmpty == false else { return nil }
  826. let firstSegment = path.split(separator: "/").first.map(String.init) ?? path
  827. guard isValidMeetMeetingCode(firstSegment) else { return nil }
  828. return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
  829. }
  830. if lower.hasPrefix("meet.google.com/") {
  831. let afterHost = trimmed.dropFirst("meet.google.com/".count)
  832. let beforeQuery = String(afterHost).split(separator: "?").first.map(String.init) ?? String(afterHost)
  833. let firstSegment = beforeQuery.split(separator: "/").first.map(String.init) ?? beforeQuery
  834. guard isValidMeetMeetingCode(firstSegment) else { return nil }
  835. return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
  836. }
  837. if isValidMeetMeetingCode(trimmed) {
  838. return URL(string: "https://meet.google.com/\(trimmed.lowercased())")
  839. }
  840. return nil
  841. }
  842. private func openInAppBrowser(with url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
  843. let browserController: InAppBrowserWindowController
  844. if let existing = inAppBrowserWindowController {
  845. browserController = existing
  846. } else {
  847. browserController = InAppBrowserWindowController()
  848. inAppBrowserWindowController = browserController
  849. }
  850. browserController.load(url: url, policy: policy)
  851. browserController.applyDefaultFrameCenteredOnVisibleScreen()
  852. browserController.showWindow(nil)
  853. browserController.window?.makeKeyAndOrderFront(nil)
  854. browserController.window?.orderFrontRegardless()
  855. NSApp.activate(ignoringOtherApps: true)
  856. }
  857. private func openInDefaultBrowser(url: URL) {
  858. NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { [weak self] _, error in
  859. if let error {
  860. DispatchQueue.main.async {
  861. self?.showSimpleAlert(title: "Unable to open browser", message: error.localizedDescription)
  862. }
  863. }
  864. }
  865. }
  866. private func openURLWithRouting(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
  867. let scheme = (url.scheme ?? "").lowercased()
  868. if scheme == "http" || scheme == "https" {
  869. showEmbeddedWebPage(url, policy: policy)
  870. return
  871. }
  872. openInDefaultBrowser(url: url)
  873. }
  874. private func embeddedBrowserController() -> InAppBrowserContainerViewController {
  875. if let existing = embeddedBrowserViewController {
  876. return existing
  877. }
  878. let controller = InAppBrowserContainerViewController()
  879. embeddedBrowserViewController = controller
  880. return controller
  881. }
  882. private func detachEmbeddedBrowserIfNeeded() {
  883. guard let controller = embeddedBrowserViewController, controller.parent === self else { return }
  884. controller.view.removeFromSuperview()
  885. controller.removeFromParent()
  886. }
  887. private func mountMainContentView(_ child: NSView) {
  888. guard let host = mainContentHost else { return }
  889. NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
  890. mainContentHostPinConstraints.removeAll()
  891. host.subviews.forEach { $0.removeFromSuperview() }
  892. child.translatesAutoresizingMaskIntoConstraints = false
  893. host.addSubview(child)
  894. mainContentHostPinConstraints = [
  895. child.leadingAnchor.constraint(equalTo: host.leadingAnchor),
  896. child.trailingAnchor.constraint(equalTo: host.trailingAnchor),
  897. child.topAnchor.constraint(equalTo: host.topAnchor),
  898. child.bottomAnchor.constraint(equalTo: host.bottomAnchor)
  899. ]
  900. NSLayoutConstraint.activate(mainContentHostPinConstraints)
  901. }
  902. private func showEmbeddedWebPage(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
  903. embeddedBrowserURL = url
  904. embeddedBrowserPolicy = policy
  905. let controller = embeddedBrowserController()
  906. _ = controller.view
  907. if controller.parent !== self {
  908. addChild(controller)
  909. }
  910. controller.setNavigationPolicy(policy)
  911. controller.load(url: url)
  912. setEmbeddedBrowserLayoutMode(isEmbedded: true)
  913. applyEmbeddedBrowserWindowTitle(url: url)
  914. mountMainContentView(controller.view)
  915. }
  916. private func setEmbeddedBrowserLayoutMode(isEmbedded: Bool) {
  917. mainPanelAuthBar?.isHidden = isEmbedded
  918. mainContentHostTopToAuthConstraint?.isActive = !isEmbedded
  919. mainContentHostTopToPanelConstraint?.isActive = isEmbedded
  920. }
  921. private func applyEmbeddedBrowserWindowTitle(url: URL) {
  922. if let host = url.host, host.isEmpty == false {
  923. view.window?.title = host
  924. } else {
  925. view.window?.title = "Browser"
  926. }
  927. }
  928. private func openRateUsDestination() {
  929. let configured = (Bundle.main.object(forInfoDictionaryKey: "RateUsURL") as? String)?
  930. .trimmingCharacters(in: .whitespacesAndNewlines)
  931. let placeholder = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String)?
  932. .trimmingCharacters(in: .whitespacesAndNewlines)
  933. let hardcodedRateUsURL = "https://apps.apple.com/pk/app/meeting-app-for-google-meet/id6654920763?mt=12"
  934. var candidateStrings = [String]()
  935. if let configured, !configured.isEmpty {
  936. candidateStrings.append(configured)
  937. if let appID = extractAppleAppID(from: configured) {
  938. candidateStrings.append("macappstore://apps.apple.com/app/id\(appID)")
  939. candidateStrings.append("macappstore://itunes.apple.com/app/id\(appID)")
  940. }
  941. }
  942. candidateStrings.append(hardcodedRateUsURL)
  943. candidateStrings.append("macappstore://apps.apple.com/app/id6654920763")
  944. candidateStrings.append("macappstore://itunes.apple.com/app/id6654920763")
  945. if let placeholder, !placeholder.isEmpty {
  946. candidateStrings.append(placeholder)
  947. }
  948. for candidate in candidateStrings {
  949. guard let url = URL(string: candidate) else { continue }
  950. if NSWorkspace.shared.open(url) {
  951. return
  952. }
  953. }
  954. showSimpleAlert(
  955. title: "Unable to Open Rate Page",
  956. message: "Could not open the App Store rating page. Please try again."
  957. )
  958. requestAppRatingIfEligible(markAsRated: true)
  959. }
  960. private func extractAppleAppID(from urlString: String) -> String? {
  961. guard let match = urlString.range(of: "id[0-9]+", options: .regularExpression) else {
  962. return nil
  963. }
  964. let token = String(urlString[match])
  965. return String(token.dropFirst())
  966. }
  967. private func openInSafari(url: URL) {
  968. guard let safariAppURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Safari") else {
  969. NSWorkspace.shared.open(url)
  970. return
  971. }
  972. let configuration = NSWorkspace.OpenConfiguration()
  973. NSWorkspace.shared.open([url], withApplicationAt: safariAppURL, configuration: configuration) { _, error in
  974. if let error {
  975. self.showSimpleAlert(title: "Unable to Open Safari", message: error.localizedDescription)
  976. }
  977. }
  978. }
  979. private func openManageSubscriptions() {
  980. if let appStoreURL = URL(string: "macappstore://apps.apple.com/account/subscriptions"),
  981. NSWorkspace.shared.open(appStoreURL) {
  982. return
  983. }
  984. guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else {
  985. showSimpleAlert(title: "Unable to Open Subscriptions", message: "The subscriptions URL is invalid.")
  986. return
  987. }
  988. openInDefaultBrowser(url: url)
  989. }
  990. private func openRestoreSubscriptionPage() {
  991. let fallbackURL = "https://support.apple.com/en-us/108096"
  992. let restoreURL = (Bundle.main.object(forInfoDictionaryKey: "RestoreSubscriptionURL") as? String) ?? fallbackURL
  993. guard let url = URL(string: restoreURL) else {
  994. if let fallback = URL(string: fallbackURL) {
  995. NSWorkspace.shared.open(fallback)
  996. }
  997. return
  998. }
  999. NSWorkspace.shared.open(url)
  1000. }
  1001. private func performRestorePurchases() {
  1002. Task { [weak self] in
  1003. guard let self else { return }
  1004. let message = await self.storeKitCoordinator.restorePurchases()
  1005. self.refreshPaywallStoreUI()
  1006. self.showSimpleAlert(title: "Restore Purchases", message: message)
  1007. }
  1008. }
  1009. private func shareAppURL() -> URL? {
  1010. if let configured = Bundle.main.object(forInfoDictionaryKey: "AppShareURL") as? String {
  1011. let trimmed = configured.trimmingCharacters(in: .whitespacesAndNewlines)
  1012. if trimmed.isEmpty == false, let url = URL(string: trimmed) {
  1013. return url
  1014. }
  1015. }
  1016. return nil
  1017. }
  1018. private func shareAppFromSettingsMenu(sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
  1019. let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
  1020. ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
  1021. ?? "Meetings App"
  1022. let message = "Check out \(appName) for managing and joining meetings."
  1023. let appURL = shareAppURL()
  1024. let shareItems: [Any] = appURL.map { [message, $0] } ?? [message]
  1025. let picker = NSSharingServicePicker(items: shareItems)
  1026. let anchorView = sourceView ?? sidebarRowViews[.settings] ?? view
  1027. let anchorPoint = clickLocationInSourceView
  1028. ?? NSPoint(x: anchorView.bounds.midX, y: anchorView.bounds.midY)
  1029. let anchorRect = NSRect(x: anchorPoint.x, y: anchorPoint.y, width: 1, height: 1)
  1030. picker.show(relativeTo: anchorRect, of: anchorView, preferredEdge: .minY)
  1031. let clipboardText = ([message, appURL?.absoluteString].compactMap { $0 }).joined(separator: "\n")
  1032. NSPasteboard.general.clearContents()
  1033. NSPasteboard.general.setString(clipboardText, forType: .string)
  1034. }
  1035. private func showSidebarPage(_ page: SidebarPage) {
  1036. selectedSidebarPage = page
  1037. updateSidebarAppearance()
  1038. applyWindowTitle(for: page)
  1039. setEmbeddedBrowserLayoutMode(isEmbedded: false)
  1040. detachEmbeddedBrowserIfNeeded()
  1041. let child = viewForPage(page)
  1042. mountMainContentView(child)
  1043. }
  1044. private func showSettingsPopover() {
  1045. guard let anchor = sidebarRowViews[.settings] else { return }
  1046. if settingsPopover?.isShown == true {
  1047. settingsPopover?.performClose(nil)
  1048. return
  1049. }
  1050. settingsPopover = makeSettingsPopover()
  1051. if let menu = settingsPopover?.contentViewController as? SettingsMenuViewController {
  1052. menu.setDarkModeEnabled(darkModeEnabled)
  1053. }
  1054. settingsPopover?.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxX)
  1055. }
  1056. private func setDarkMode(_ enabled: Bool) {
  1057. darkModeEnabled = enabled
  1058. NSApp.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
  1059. view.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
  1060. palette = Palette(isDarkMode: enabled)
  1061. launchSplashView?.apply(theme: makeLaunchSplashTheme())
  1062. reloadTheme()
  1063. }
  1064. private func reloadTheme() {
  1065. pageCache.removeAll()
  1066. if let observer = schedulePageScrollObservation {
  1067. NotificationCenter.default.removeObserver(observer)
  1068. }
  1069. schedulePageScrollObservation = nil
  1070. sidebarRowViews.removeAll()
  1071. sidebarPageByView.removeAll()
  1072. zoomJoinModeByView.removeAll()
  1073. zoomJoinModeViews.removeAll()
  1074. settingsActionByView.removeAll()
  1075. paywallPlanViews.removeAll()
  1076. premiumPlanByView.removeAll()
  1077. paywallFooterActionByView.removeAll()
  1078. paywallPriceLabels.removeAll()
  1079. paywallSubtitleLabels.removeAll()
  1080. paywallContinueLabel = nil
  1081. paywallContinueButton = nil
  1082. paywallContinueEnabled = true
  1083. detachEmbeddedBrowserIfNeeded()
  1084. embeddedBrowserViewController = nil
  1085. embeddedBrowserURL = nil
  1086. embeddedBrowserPolicy = .allowAll
  1087. mainPanelAuthBar = nil
  1088. mainContentHostTopToAuthConstraint = nil
  1089. mainContentHostTopToPanelConstraint = nil
  1090. googleAccountPopover?.performClose(nil)
  1091. googleAccountPopover = nil
  1092. NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
  1093. mainContentHostPinConstraints.removeAll()
  1094. mainContentHost = nil
  1095. view.subviews.forEach { $0.removeFromSuperview() }
  1096. setupRootView()
  1097. buildMainLayout()
  1098. showSidebarPage(selectedSidebarPage)
  1099. }
  1100. private func handleSettingsAction(_ action: SettingsAction, sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
  1101. switch action {
  1102. case .restore:
  1103. performRestorePurchases()
  1104. case .rateUs:
  1105. openRateUsDestination()
  1106. case .support:
  1107. openSettingsLink(infoKey: "SupportURL")
  1108. case .privacyPolicy:
  1109. openSettingsLink(infoKey: "PrivacyPolicyURL")
  1110. case .termsOfServices:
  1111. openSettingsLink(infoKey: "TermsOfServiceURL")
  1112. case .moreApps:
  1113. if let moreAppsURL = Bundle.main.object(forInfoDictionaryKey: "MoreAppsURL") as? String,
  1114. let url = URL(string: moreAppsURL) {
  1115. openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
  1116. }
  1117. case .shareApp:
  1118. shareAppFromSettingsMenu(sourceView: sourceView, clickLocationInSourceView: clickLocationInSourceView)
  1119. case .upgrade:
  1120. showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
  1121. }
  1122. }
  1123. private func openSettingsLink(infoKey: String) {
  1124. let defaultURL = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String) ?? "https://example.com/app-link-coming-soon"
  1125. let urlString = (Bundle.main.object(forInfoDictionaryKey: infoKey) as? String) ?? defaultURL
  1126. guard let url = URL(string: urlString) else { return }
  1127. openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
  1128. }
  1129. private func showSimpleAlert(title: String, message: String) {
  1130. let alert = NSAlert()
  1131. alert.messageText = title
  1132. alert.informativeText = message
  1133. alert.addButton(withTitle: "OK")
  1134. alert.runModal()
  1135. }
  1136. private func requestMeetingRecordingConsent(title: String) -> Bool {
  1137. let alert = NSAlert()
  1138. alert.messageText = "Record this meeting locally?"
  1139. alert.informativeText = "With your consent, the app will record meeting audio on this Mac and show it in AI Companion after the meeting."
  1140. alert.addButton(withTitle: "Allow and Continue")
  1141. alert.addButton(withTitle: "Continue Without Recording")
  1142. let response = alert.runModal()
  1143. if response == .alertFirstButtonReturn { return true }
  1144. return false
  1145. }
  1146. private func loadAiCompanionLocalRecordings() {
  1147. guard let raw = UserDefaults.standard.data(forKey: aiCompanionLocalRecordingsDefaultsKey) else {
  1148. aiCompanionLocalRecordings = []
  1149. return
  1150. }
  1151. let decoder = JSONDecoder()
  1152. if let decoded = try? decoder.decode([MeetingRecordingSummary].self, from: raw) {
  1153. aiCompanionLocalRecordings = decoded.sorted(by: { $0.endedAt > $1.endedAt })
  1154. } else {
  1155. aiCompanionLocalRecordings = []
  1156. }
  1157. }
  1158. private func persistAiCompanionLocalRecordings() {
  1159. let encoder = JSONEncoder()
  1160. guard let encoded = try? encoder.encode(aiCompanionLocalRecordings) else { return }
  1161. UserDefaults.standard.set(encoded, forKey: aiCompanionLocalRecordingsDefaultsKey)
  1162. }
  1163. private func configuredOpenAIAPIKey() -> String? {
  1164. let value = UserDefaults.standard.string(forKey: openAIAPIKeyDefaultsKey)?
  1165. .trimmingCharacters(in: .whitespacesAndNewlines)
  1166. if let value, value.isEmpty == false {
  1167. return value
  1168. }
  1169. let plistValue = Bundle.main.object(forInfoDictionaryKey: openAIAPIKeyPlistKey) as? String
  1170. let trimmedPlist = plistValue?.trimmingCharacters(in: .whitespacesAndNewlines)
  1171. if let trimmedPlist, trimmedPlist.isEmpty == false {
  1172. return trimmedPlist
  1173. }
  1174. return nil
  1175. }
  1176. private func aiCompanionTranscriptStatus(for recording: MeetingRecordingSummary) -> MeetingTranscriptStatus {
  1177. guard let raw = recording.transcriptStatusRaw, let status = MeetingTranscriptStatus(rawValue: raw) else {
  1178. return .notRequested
  1179. }
  1180. return status
  1181. }
  1182. private func aiCompanionTranscriptStatusText(for recording: MeetingRecordingSummary) -> String {
  1183. switch aiCompanionTranscriptStatus(for: recording) {
  1184. case .notRequested:
  1185. return "Transcript not requested"
  1186. case .processing:
  1187. return "Transcript processing..."
  1188. case .ready:
  1189. return "Transcript ready"
  1190. case .failed:
  1191. let error = recording.transcriptErrorMessage?.trimmingCharacters(in: .whitespacesAndNewlines)
  1192. if let error, error.isEmpty == false {
  1193. return "Transcript unavailable (tap to retry)"
  1194. }
  1195. return "Transcript unavailable (tap to retry)"
  1196. }
  1197. }
  1198. private func aiCompanionMeetingFromRecording(_ recording: MeetingRecordingSummary) -> ScheduledMeeting? {
  1199. guard let meetURL = URL(string: recording.meetURLString) else { return nil }
  1200. return ScheduledMeeting(
  1201. id: recording.id,
  1202. title: recording.title,
  1203. subtitle: nil,
  1204. startDate: recording.startedAt,
  1205. endDate: recording.endedAt,
  1206. meetURL: meetURL,
  1207. isAllDay: false
  1208. )
  1209. }
  1210. @discardableResult
  1211. private func aiCompanionUpdateRecording(meetingId: String, mutate: (inout MeetingRecordingSummary) -> Void) -> MeetingRecordingSummary? {
  1212. guard let idx = aiCompanionLocalRecordings.firstIndex(where: { $0.id == meetingId }) else { return nil }
  1213. mutate(&aiCompanionLocalRecordings[idx])
  1214. persistAiCompanionLocalRecordings()
  1215. return aiCompanionLocalRecordings[idx]
  1216. }
  1217. private func aiCompanionRefreshTranscriptStatusLabels(forMeetingID meetingId: String) {
  1218. guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else { return }
  1219. let statusText = aiCompanionTranscriptStatusText(for: recording)
  1220. for (buttonId, linkedMeetingId) in aiCompanionTranscriptMeetingIdByView where linkedMeetingId == meetingId {
  1221. aiCompanionTranscriptStatusLabelByView[buttonId]?.stringValue = statusText
  1222. }
  1223. }
  1224. private func localRecordingDirectoryURL() -> URL {
  1225. let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
  1226. ?? URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
  1227. let bundleID = Bundle.main.bundleIdentifier ?? "meetings_app"
  1228. let directory = base.appendingPathComponent(bundleID, isDirectory: true).appendingPathComponent("MeetingRecordings", isDirectory: true)
  1229. try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
  1230. return directory
  1231. }
  1232. private func beginMeetingRecordingIfConsented(meetingTitle: String, meetingURL: URL) {
  1233. meetingRecordingMonitorTask?.cancel()
  1234. meetingRecordingMonitorTask = nil
  1235. if activeMeetingRecordingSession != nil { finishActiveMeetingRecording(cancelMonitoring: false) }
  1236. guard requestMeetingRecordingConsent(title: meetingTitle) else { return }
  1237. let permission = AVCaptureDevice.authorizationStatus(for: .audio)
  1238. switch permission {
  1239. case .authorized:
  1240. startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
  1241. case .notDetermined:
  1242. AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
  1243. DispatchQueue.main.async {
  1244. guard let self else { return }
  1245. if granted {
  1246. self.startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
  1247. } else {
  1248. self.showSimpleAlert(title: "Microphone permission denied", message: "Enable microphone access in System Settings to record meetings locally.")
  1249. }
  1250. }
  1251. }
  1252. case .denied, .restricted:
  1253. showSimpleAlert(title: "Microphone permission required", message: "Enable microphone access in System Settings to record meetings locally.")
  1254. @unknown default:
  1255. break
  1256. }
  1257. }
  1258. private func startAutomaticRecordingFlow(meetingTitle: String, meetingURL: URL) {
  1259. guard let meetingCode = aiCompanionMeetMeetingCode(from: meetingURL), hasGoogleSessionAvailable() else {
  1260. startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
  1261. return
  1262. }
  1263. showTopToast(message: "Recording will start when the meeting starts", isError: false)
  1264. meetingRecordingMonitorTask = Task { [weak self] in
  1265. guard let self else { return }
  1266. defer { self.meetingRecordingMonitorTask = nil }
  1267. do {
  1268. let space = try await self.googleMeetClient.getSpace(
  1269. accessToken: try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window),
  1270. spaceNameOrMeetingCode: "spaces/\(meetingCode)"
  1271. )
  1272. let spaceName = space.name ?? "spaces/\(meetingCode)"
  1273. var hasStarted = false
  1274. var inactivePollCount = 0
  1275. let noStartDeadline = Date().addingTimeInterval(20 * 60)
  1276. while !Task.isCancelled {
  1277. let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  1278. let isActive = try await self.aiCompanionIsMeetingActive(spaceResourceName: spaceName, accessToken: token)
  1279. if isActive {
  1280. inactivePollCount = 0
  1281. if !hasStarted {
  1282. self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
  1283. hasStarted = true
  1284. }
  1285. } else if hasStarted {
  1286. inactivePollCount += 1
  1287. if inactivePollCount >= 1 {
  1288. self.finishActiveMeetingRecording(cancelMonitoring: false)
  1289. break
  1290. }
  1291. } else if Date() > noStartDeadline {
  1292. break
  1293. }
  1294. try await Task.sleep(nanoseconds: 2_000_000_000)
  1295. }
  1296. } catch {
  1297. if self.activeMeetingRecordingSession == nil {
  1298. self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
  1299. }
  1300. }
  1301. }
  1302. }
  1303. private func aiCompanionIsMeetingActive(spaceResourceName: String, accessToken: String) async throws -> Bool {
  1304. let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceResourceName)
  1305. return records.contains { $0.startTime != nil && $0.endTime == nil }
  1306. }
  1307. private func startMeetingRecording(meetingTitle: String, meetingURL: URL) {
  1308. let recordingID = UUID().uuidString
  1309. let outputURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-system.m4a")
  1310. let microphoneURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-mic.m4a")
  1311. activeMeetingRecordingSession = ActiveMeetingRecordingSession(
  1312. id: recordingID,
  1313. title: meetingTitle,
  1314. meetURL: meetingURL,
  1315. startedAt: Date(),
  1316. systemAudioFileURL: outputURL,
  1317. microphoneAudioFileURL: microphoneURL
  1318. )
  1319. pageCache[.aiCompanion] = nil
  1320. if selectedSidebarPage == .aiCompanion { showSidebarPage(.aiCompanion) }
  1321. startMicrophoneRecording(at: microphoneURL, showToast: false)
  1322. if #available(macOS 13.0, *) {
  1323. let systemRecorder = MeetingSystemAudioRecorder(outputURL: outputURL)
  1324. activeMeetingSystemAudioStopper = { [systemRecorder] in
  1325. try? await systemRecorder.stop()
  1326. }
  1327. Task { [weak self] in
  1328. guard let self else { return }
  1329. do {
  1330. try await systemRecorder.start()
  1331. await MainActor.run {
  1332. self.showTopToast(message: "Meeting recording started (meeting + microphone)", isError: false)
  1333. }
  1334. } catch {
  1335. await MainActor.run {
  1336. self.activeMeetingSystemAudioStopper = nil
  1337. self.showTopToast(message: "System audio unavailable. Recording microphone only.", isError: true)
  1338. }
  1339. }
  1340. }
  1341. return
  1342. }
  1343. showTopToast(message: "Meeting recording started (microphone only)", isError: false)
  1344. }
  1345. private func startMicrophoneRecording(at outputURL: URL, showToast: Bool) {
  1346. let settings: [String: Any] = [
  1347. AVFormatIDKey: kAudioFormatMPEG4AAC,
  1348. AVSampleRateKey: 48_000,
  1349. AVNumberOfChannelsKey: 1,
  1350. AVEncoderBitRateKey: 128_000,
  1351. AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
  1352. ]
  1353. do {
  1354. let recorder = try AVAudioRecorder(url: outputURL, settings: settings)
  1355. recorder.prepareToRecord()
  1356. recorder.record()
  1357. activeMeetingAudioRecorder = recorder
  1358. if showToast {
  1359. showTopToast(message: "Meeting recording started (microphone only)", isError: false)
  1360. }
  1361. } catch {
  1362. activeMeetingRecordingSession = nil
  1363. showSimpleAlert(title: "Could not start recording", message: error.localizedDescription)
  1364. }
  1365. }
  1366. private func finishActiveMeetingRecording(cancelMonitoring: Bool = true) {
  1367. if cancelMonitoring {
  1368. meetingRecordingMonitorTask?.cancel()
  1369. meetingRecordingMonitorTask = nil
  1370. }
  1371. guard let session = activeMeetingRecordingSession else { return }
  1372. let stopSystemAudio = activeMeetingSystemAudioStopper
  1373. activeMeetingSystemAudioStopper = nil
  1374. activeMeetingAudioRecorder?.stop()
  1375. activeMeetingAudioRecorder = nil
  1376. activeMeetingRecordingSession = nil
  1377. Task { [weak self] in
  1378. guard let self else { return }
  1379. if let stopSystemAudio { await stopSystemAudio() }
  1380. let finalURL = await self.finalizeMeetingAudioFile(
  1381. systemURL: session.systemAudioFileURL,
  1382. microphoneURL: session.microphoneAudioFileURL,
  1383. recordingID: session.id
  1384. )
  1385. await MainActor.run {
  1386. let summary = MeetingRecordingSummary(
  1387. id: session.id,
  1388. title: session.title,
  1389. meetURLString: session.meetURL.absoluteString,
  1390. startedAt: session.startedAt,
  1391. endedAt: Date(),
  1392. audioFilePath: finalURL.path,
  1393. transcriptStatusRaw: MeetingTranscriptStatus.notRequested.rawValue,
  1394. transcriptSourceRaw: nil,
  1395. transcriptText: nil,
  1396. transcriptErrorMessage: nil
  1397. )
  1398. self.aiCompanionLocalRecordings.insert(summary, at: 0)
  1399. self.aiCompanionLocalRecordings.sort(by: { $0.endedAt > $1.endedAt })
  1400. self.persistAiCompanionLocalRecordings()
  1401. self.aiCompanionStartTranscriptProcessing(forMeetingID: summary.id, requestId: nil, interactiveAuth: false, forceRegenerate: false)
  1402. self.pageCache[.aiCompanion] = nil
  1403. self.showTopToast(message: "Meeting recording saved", isError: false)
  1404. if self.selectedSidebarPage == .aiCompanion {
  1405. self.showSidebarPage(.aiCompanion)
  1406. }
  1407. }
  1408. }
  1409. }
  1410. private func fileSize(at url: URL) -> Int64 {
  1411. let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)
  1412. return attrs?[.size] as? Int64 ?? 0
  1413. }
  1414. private func hasAudioPayload(at url: URL, minBytes: Int64 = 10_000) -> Bool {
  1415. guard FileManager.default.fileExists(atPath: url.path) else { return false }
  1416. return fileSize(at: url) >= minBytes
  1417. }
  1418. private func finalizeMeetingAudioFile(systemURL: URL, microphoneURL: URL, recordingID: String) async -> URL {
  1419. let destinationURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID).m4a")
  1420. let hasSystem = hasAudioPayload(at: systemURL)
  1421. let hasMic = hasAudioPayload(at: microphoneURL)
  1422. if hasSystem && hasMic {
  1423. do {
  1424. try await mixAudioFiles(systemURL: systemURL, microphoneURL: microphoneURL, destinationURL: destinationURL)
  1425. try? FileManager.default.removeItem(at: systemURL)
  1426. try? FileManager.default.removeItem(at: microphoneURL)
  1427. return destinationURL
  1428. } catch {
  1429. // Fall back to best available single track.
  1430. }
  1431. }
  1432. let chosenURL: URL
  1433. if hasSystem {
  1434. chosenURL = systemURL
  1435. } else if hasMic {
  1436. chosenURL = microphoneURL
  1437. } else {
  1438. let systemSize = fileSize(at: systemURL)
  1439. let micSize = fileSize(at: microphoneURL)
  1440. chosenURL = systemSize >= micSize ? systemURL : microphoneURL
  1441. }
  1442. if chosenURL.path != destinationURL.path {
  1443. try? FileManager.default.removeItem(at: destinationURL)
  1444. do {
  1445. try FileManager.default.copyItem(at: chosenURL, to: destinationURL)
  1446. } catch {
  1447. return chosenURL
  1448. }
  1449. }
  1450. try? FileManager.default.removeItem(at: systemURL)
  1451. try? FileManager.default.removeItem(at: microphoneURL)
  1452. return destinationURL
  1453. }
  1454. private func mixAudioFiles(systemURL: URL, microphoneURL: URL, destinationURL: URL) async throws {
  1455. try? FileManager.default.removeItem(at: destinationURL)
  1456. let composition = AVMutableComposition()
  1457. guard let systemTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid),
  1458. let micTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
  1459. throw NSError(domain: "MeetingAudioMix", code: 1, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio composition tracks."])
  1460. }
  1461. let systemAsset = AVURLAsset(url: systemURL)
  1462. let micAsset = AVURLAsset(url: microphoneURL)
  1463. if let src = try await systemAsset.loadTracks(withMediaType: .audio).first {
  1464. let duration = try await systemAsset.load(.duration)
  1465. try systemTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
  1466. }
  1467. if let src = try await micAsset.loadTracks(withMediaType: .audio).first {
  1468. let duration = try await micAsset.load(.duration)
  1469. try micTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
  1470. }
  1471. guard let export = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
  1472. throw NSError(domain: "MeetingAudioMix", code: 2, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio export session."])
  1473. }
  1474. // Give the local microphone a small speech-focused boost while preserving meeting audio.
  1475. let systemMix = AVMutableAudioMixInputParameters(track: systemTrack)
  1476. systemMix.setVolume(1.0, at: .zero)
  1477. let micMix = AVMutableAudioMixInputParameters(track: micTrack)
  1478. micMix.setVolume(1.35, at: .zero)
  1479. let audioMix = AVMutableAudioMix()
  1480. audioMix.inputParameters = [systemMix, micMix]
  1481. export.outputURL = destinationURL
  1482. export.outputFileType = .m4a
  1483. export.audioMix = audioMix
  1484. await withCheckedContinuation { continuation in
  1485. export.exportAsynchronously {
  1486. continuation.resume()
  1487. }
  1488. }
  1489. if export.status != .completed {
  1490. throw export.error ?? NSError(domain: "MeetingAudioMix", code: 3, userInfo: [NSLocalizedDescriptionKey: "Audio mix export failed."])
  1491. }
  1492. }
  1493. private func showTopToast(message: String, isError: Bool) {
  1494. topToastHideWorkItem?.cancel()
  1495. topToastHideWorkItem = nil
  1496. topToastView?.removeFromSuperview()
  1497. topToastView = nil
  1498. let toast = NSVisualEffectView()
  1499. toast.translatesAutoresizingMaskIntoConstraints = false
  1500. toast.material = darkModeEnabled ? .hudWindow : .popover
  1501. toast.blendingMode = .withinWindow
  1502. toast.state = .active
  1503. toast.wantsLayer = true
  1504. toast.layer?.cornerRadius = 10
  1505. toast.layer?.masksToBounds = true
  1506. toast.layer?.borderWidth = 1
  1507. toast.layer?.borderColor = NSColor.white.withAlphaComponent(darkModeEnabled ? 0.10 : 0.18).cgColor
  1508. toast.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.68 : 0.78).cgColor
  1509. toast.alphaValue = 0
  1510. let row = NSStackView()
  1511. row.translatesAutoresizingMaskIntoConstraints = false
  1512. row.orientation = .horizontal
  1513. row.alignment = .centerY
  1514. row.spacing = 8
  1515. row.distribution = .fill
  1516. let icon = NSImageView()
  1517. icon.translatesAutoresizingMaskIntoConstraints = false
  1518. icon.imageScaling = .scaleProportionallyDown
  1519. icon.image = NSImage(
  1520. systemSymbolName: isError ? "xmark.circle.fill" : "checkmark.circle.fill",
  1521. accessibilityDescription: isError ? "Error" : "Success"
  1522. )
  1523. icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
  1524. icon.contentTintColor = isError ? NSColor.systemRed : NSColor.systemGreen
  1525. let label = textLabel(
  1526. message,
  1527. font: NSFont.systemFont(ofSize: 13, weight: .semibold),
  1528. color: NSColor.white
  1529. )
  1530. label.alignment = .left
  1531. label.maximumNumberOfLines = 2
  1532. label.lineBreakMode = .byWordWrapping
  1533. row.addArrangedSubview(icon)
  1534. row.addArrangedSubview(label)
  1535. toast.addSubview(row)
  1536. view.addSubview(toast)
  1537. NSLayoutConstraint.activate([
  1538. toast.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
  1539. toast.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  1540. toast.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -40),
  1541. toast.heightAnchor.constraint(greaterThanOrEqualToConstant: 40),
  1542. icon.widthAnchor.constraint(equalToConstant: 16),
  1543. icon.heightAnchor.constraint(equalToConstant: 16),
  1544. row.leadingAnchor.constraint(equalTo: toast.leadingAnchor, constant: 14),
  1545. row.trailingAnchor.constraint(equalTo: toast.trailingAnchor, constant: -14),
  1546. row.topAnchor.constraint(equalTo: toast.topAnchor, constant: 10),
  1547. row.bottomAnchor.constraint(equalTo: toast.bottomAnchor, constant: -10)
  1548. ])
  1549. topToastView = toast
  1550. NSAnimationContext.runAnimationGroup { context in
  1551. context.duration = 0.18
  1552. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  1553. toast.animator().alphaValue = 1
  1554. }
  1555. let hideWorkItem = DispatchWorkItem { [weak self, weak toast] in
  1556. guard let self, let toast else { return }
  1557. NSAnimationContext.runAnimationGroup({ context in
  1558. context.duration = 0.2
  1559. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  1560. toast.animator().alphaValue = 0
  1561. }, completionHandler: {
  1562. toast.removeFromSuperview()
  1563. if self.topToastView === toast {
  1564. self.topToastView = nil
  1565. }
  1566. })
  1567. }
  1568. topToastHideWorkItem = hideWorkItem
  1569. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: hideWorkItem)
  1570. }
  1571. private func confirmPremiumUpgrade(for targetPlan: PremiumPlan) -> Bool {
  1572. let alert = NSAlert()
  1573. alert.messageText = "Already Premium"
  1574. alert.informativeText = "You are already premium. Do you want to continue with this purchase?"
  1575. alert.addButton(withTitle: "Continue")
  1576. alert.addButton(withTitle: "Cancel")
  1577. return alert.runModal() == .alertFirstButtonReturn
  1578. }
  1579. private func showPaywall(upgradeFlow: Bool = false, preferredPlan: PremiumPlan? = nil) {
  1580. if !Thread.isMainThread {
  1581. DispatchQueue.main.async { [weak self] in
  1582. self?.showPaywall(upgradeFlow: upgradeFlow, preferredPlan: preferredPlan)
  1583. }
  1584. return
  1585. }
  1586. paywallUpgradeFlowEnabled = upgradeFlow
  1587. if let preferredPlan {
  1588. selectedPremiumPlan = preferredPlan
  1589. }
  1590. if let existingOverlay = paywallOverlayView {
  1591. refreshPaywallStoreUI()
  1592. existingOverlay.alphaValue = 1
  1593. view.addSubview(existingOverlay, positioned: .above, relativeTo: nil)
  1594. return
  1595. }
  1596. if let existing = paywallWindow {
  1597. refreshPaywallStoreUI()
  1598. animatePaywallPresentation(existing)
  1599. existing.makeKeyAndOrderFront(nil)
  1600. NSApp.activate(ignoringOtherApps: true)
  1601. return
  1602. }
  1603. let content = makePaywallContent()
  1604. let overlay = NSView()
  1605. overlay.translatesAutoresizingMaskIntoConstraints = false
  1606. overlay.wantsLayer = true
  1607. overlay.layer?.backgroundColor = palette.pageBackground.withAlphaComponent(0.98).cgColor
  1608. overlay.alphaValue = 0
  1609. overlay.addSubview(content)
  1610. view.addSubview(overlay, positioned: .above, relativeTo: nil)
  1611. NSLayoutConstraint.activate([
  1612. overlay.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  1613. overlay.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  1614. overlay.topAnchor.constraint(equalTo: view.topAnchor),
  1615. overlay.bottomAnchor.constraint(equalTo: view.bottomAnchor),
  1616. content.leadingAnchor.constraint(equalTo: overlay.leadingAnchor),
  1617. content.trailingAnchor.constraint(equalTo: overlay.trailingAnchor),
  1618. content.topAnchor.constraint(equalTo: overlay.topAnchor),
  1619. content.bottomAnchor.constraint(equalTo: overlay.bottomAnchor)
  1620. ])
  1621. paywallOverlayView = overlay
  1622. NSAnimationContext.runAnimationGroup { context in
  1623. context.duration = 0.20
  1624. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  1625. overlay.animator().alphaValue = 1
  1626. }
  1627. Task { [weak self] in
  1628. guard let self else { return }
  1629. await self.storeKitCoordinator.refreshProducts()
  1630. self.refreshPaywallStoreUI()
  1631. }
  1632. }
  1633. private func animatePaywallPresentation(_ window: NSWindow) {
  1634. let finalFrame = window.frame
  1635. let targetScreen = window.screen ?? NSScreen.main
  1636. let startY: CGFloat
  1637. if let screen = targetScreen {
  1638. startY = screen.visibleFrame.maxY + 12
  1639. } else {
  1640. startY = finalFrame.origin.y + 120
  1641. }
  1642. let startFrame = NSRect(x: finalFrame.origin.x, y: startY, width: finalFrame.width, height: finalFrame.height)
  1643. window.setFrame(startFrame, display: false)
  1644. window.alphaValue = 0
  1645. NSAnimationContext.runAnimationGroup { context in
  1646. context.duration = 0.28
  1647. context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  1648. window.animator().alphaValue = 1
  1649. window.animator().setFrame(finalFrame, display: true)
  1650. }
  1651. }
  1652. @objc private func closePaywallClicked(_ sender: Any?) {
  1653. if let overlay = paywallOverlayView {
  1654. paywallOverlayView = nil
  1655. paywallUpgradeFlowEnabled = false
  1656. overlay.removeFromSuperview()
  1657. return
  1658. }
  1659. if let win = paywallWindow {
  1660. win.performClose(nil)
  1661. return
  1662. }
  1663. if let gesture = sender as? NSGestureRecognizer, let win = gesture.view?.window {
  1664. win.performClose(nil)
  1665. return
  1666. }
  1667. if let view = sender as? NSView, let win = view.window {
  1668. win.performClose(nil)
  1669. return
  1670. }
  1671. }
  1672. private func dismissPaywallIfPresented() {
  1673. if !Thread.isMainThread {
  1674. DispatchQueue.main.async { [weak self] in
  1675. self?.dismissPaywallIfPresented()
  1676. }
  1677. return
  1678. }
  1679. closePaywallClicked(nil)
  1680. }
  1681. @objc private func paywallFooterLinkClicked(_ sender: NSClickGestureRecognizer) {
  1682. guard let view = sender.view else { return }
  1683. let action = paywallFooterActionByView[ObjectIdentifier(view)]
  1684. let text = (view.subviews.first { $0 is NSTextField } as? NSTextField)?.stringValue ?? "Link"
  1685. guard let action else {
  1686. showSimpleAlert(title: text, message: "\(text) tapped.")
  1687. return
  1688. }
  1689. handlePaywallFooterAction(action)
  1690. }
  1691. private func handlePaywallFooterAction(_ action: PaywallFooterAction) {
  1692. switch action {
  1693. case .manageSubscription:
  1694. openManageSubscriptions()
  1695. case .restorePurchase:
  1696. openRestoreSubscriptionPage()
  1697. case .continueWithFreePlan:
  1698. closePaywallClicked(nil)
  1699. case .privacyPolicy:
  1700. openSettingsLink(infoKey: "PrivacyPolicyURL")
  1701. case .support:
  1702. openSettingsLink(infoKey: "SupportURL")
  1703. case .termsOfServices:
  1704. openSettingsLink(infoKey: "TermsOfServiceURL")
  1705. }
  1706. }
  1707. @objc private func paywallFooterButtonPressed(_ sender: NSButton) {
  1708. guard let action = paywallFooterActionByView[ObjectIdentifier(sender)] else { return }
  1709. handlePaywallFooterAction(action)
  1710. }
  1711. @objc private func paywallPlanClicked(_ sender: NSClickGestureRecognizer) {
  1712. guard let view = sender.view,
  1713. let plan = premiumPlanByView[ObjectIdentifier(view)] else { return }
  1714. selectedPremiumPlan = plan
  1715. updatePaywallPlanSelection()
  1716. }
  1717. @objc private func paywallPlanButtonClicked(_ sender: NSButton) {
  1718. guard let plan = PremiumPlan(rawValue: sender.tag) else { return }
  1719. selectedPremiumPlan = plan
  1720. updatePaywallPlanSelection()
  1721. }
  1722. private func updatePaywallPlanSelection() {
  1723. for (plan, view) in paywallPlanViews {
  1724. applyPaywallPlanStyle(view, isSelected: plan == selectedPremiumPlan)
  1725. }
  1726. paywallOfferLabel?.stringValue = paywallOfferText(for: selectedPremiumPlan)
  1727. }
  1728. private func paywallOfferText(for plan: PremiumPlan) -> String {
  1729. if storeKitCoordinator.hasPremiumAccess {
  1730. if storeKitCoordinator.hasLifetimeAccess {
  1731. return "Lifetime premium is active on this Apple ID."
  1732. }
  1733. if paywallUpgradeFlowEnabled {
  1734. let currentPlanName = storeKitCoordinator.activeNonLifetimePlan?.displayName ?? "Premium"
  1735. if plan == .lifetime {
  1736. return "Current plan: \(currentPlanName). Tap Continue to upgrade to Lifetime."
  1737. }
  1738. return "Current plan: \(currentPlanName). Select Lifetime to upgrade."
  1739. }
  1740. return "Premium is active on this Apple ID."
  1741. }
  1742. let productID = PremiumStoreProduct.productID(for: plan)
  1743. if let product = storeKitCoordinator.productsByID[productID] {
  1744. let pkrPrice = pkrDisplayPrice(product.displayPrice)
  1745. if product.type == .nonConsumable {
  1746. return "\(pkrPrice) one-time purchase"
  1747. }
  1748. if let subscription = product.subscription {
  1749. let billingText = "\(pkrPrice)/\(subscriptionUnitText(subscription.subscriptionPeriod.unit))"
  1750. if let introOffer = subscription.introductoryOffer,
  1751. introOffer.paymentMode == .freeTrial {
  1752. return "Free for \(subscriptionPeriodText(introOffer.period)), then \(billingText)"
  1753. }
  1754. return billingText
  1755. }
  1756. return pkrPrice
  1757. }
  1758. switch plan {
  1759. case .weekly:
  1760. return "PKR 1,100.00/week"
  1761. case .monthly:
  1762. return "PKR 2,500.00/month (3 days free trial)"
  1763. case .yearly:
  1764. return "PKR 9,900.00/year (about 190.38/week)"
  1765. case .lifetime:
  1766. return "PKR 14,900.00 one-time purchase"
  1767. }
  1768. }
  1769. private func pkrDisplayPrice(_ value: String) -> String {
  1770. if value.hasPrefix("PKR ") { return value }
  1771. if value.hasPrefix("Rs ") {
  1772. return "PKR " + value.dropFirst(3)
  1773. }
  1774. if value.contains("PKR") { return value }
  1775. return "PKR \(value)"
  1776. }
  1777. private func subscriptionUnitText(_ unit: Product.SubscriptionPeriod.Unit) -> String {
  1778. switch unit {
  1779. case .day: return "day"
  1780. case .week: return "week"
  1781. case .month: return "month"
  1782. case .year: return "year"
  1783. @unknown default: return "period"
  1784. }
  1785. }
  1786. private func subscriptionPeriodText(_ period: Product.SubscriptionPeriod) -> String {
  1787. let unit = subscriptionUnitText(period.unit)
  1788. if period.value == 1 {
  1789. return "1 \(unit)"
  1790. }
  1791. return "\(period.value) \(unit)s"
  1792. }
  1793. private func freeTrialPackageText(for product: Product) -> String? {
  1794. guard let introOffer = product.subscription?.introductoryOffer,
  1795. introOffer.paymentMode == .freeTrial else {
  1796. return nil
  1797. }
  1798. return "\(subscriptionPeriodText(introOffer.period)) free trial"
  1799. }
  1800. private func startStoreKit() {
  1801. storeKitStartupTask?.cancel()
  1802. storeKitStartupTask = Task { [weak self] in
  1803. guard let self else { return }
  1804. await self.storeKitCoordinator.start()
  1805. self.hasCompletedInitialStoreKitSync = true
  1806. self.refreshPaywallStoreUI()
  1807. self.presentLaunchPaywallIfNeeded()
  1808. self.dismissLaunchSplashIfReady()
  1809. }
  1810. }
  1811. private func refreshPaywallStoreUI() {
  1812. for (plan, label) in paywallPriceLabels {
  1813. let productID = PremiumStoreProduct.productID(for: plan)
  1814. if let product = storeKitCoordinator.productsByID[productID] {
  1815. label.stringValue = pkrDisplayPrice(product.displayPrice)
  1816. }
  1817. }
  1818. for (plan, label) in paywallSubtitleLabels {
  1819. let productID = PremiumStoreProduct.productID(for: plan)
  1820. guard let product = storeKitCoordinator.productsByID[productID],
  1821. let period = product.subscription?.subscriptionPeriod else {
  1822. // Show neutral fallback text when subscription metadata isn't available.
  1823. label.stringValue = "Billed via App Store"
  1824. continue
  1825. }
  1826. let recurringText = "\(pkrDisplayPrice(product.displayPrice))/\(subscriptionUnitText(period.unit))"
  1827. if let trialText = freeTrialPackageText(for: product) {
  1828. label.stringValue = "\(recurringText) • \(trialText)"
  1829. } else {
  1830. label.stringValue = recurringText
  1831. }
  1832. }
  1833. refreshSidebarPremiumButton()
  1834. refreshInstantMeetPremiumState()
  1835. updatePaywallPlanSelection()
  1836. updatePaywallContinueState(isLoading: false)
  1837. }
  1838. private func refreshInstantMeetPremiumState() {
  1839. let isLocked = shouldGateJoinActionsForNonPremium
  1840. let lockedAlpha: CGFloat = 0.6
  1841. instantMeetCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
  1842. instantMeetTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
  1843. instantMeetSubtitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
  1844. instantMeetCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
  1845. instantMeetCardView?.onHoverChanged?(false)
  1846. joinWithLinkCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
  1847. joinWithLinkTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
  1848. meetLinkField?.isEditable = !isLocked
  1849. meetLinkField?.isSelectable = !isLocked
  1850. meetLinkField?.alphaValue = isLocked ? lockedAlpha : 1.0
  1851. joinMeetPrimaryButton?.isEnabled = true
  1852. joinMeetPrimaryButton?.alphaValue = isLocked ? lockedAlpha : 1.0
  1853. joinMeetPrimaryButton?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
  1854. joinWithLinkCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
  1855. }
  1856. private func handlePremiumAccessChanged(_ hasPremiumAccess: Bool) {
  1857. let hadPremiumAccess = lastKnownPremiumAccess
  1858. lastKnownPremiumAccess = hasPremiumAccess
  1859. NotificationCenter.default.post(
  1860. name: .statusBarPremiumAccessChanged,
  1861. object: nil,
  1862. userInfo: ["hasPremiumAccess": hasPremiumAccess]
  1863. )
  1864. premiumUpgradeRatingPromptWorkItem?.cancel()
  1865. refreshPaywallStoreUI()
  1866. refreshScheduleCardsForPremiumStateChange()
  1867. refreshPagesAfterPremiumStateUpdate()
  1868. Task { [weak self] in
  1869. await self?.loadSchedule()
  1870. }
  1871. if !hadPremiumAccess && hasPremiumAccess {
  1872. dismissPaywallIfPresented()
  1873. if selectedSidebarPage != .joinMeetings {
  1874. Task { [weak self] in
  1875. await self?.loadSchedule()
  1876. }
  1877. }
  1878. // Skip delayed review prompt during initial launch entitlement sync.
  1879. // We only want this after a real in-session upgrade.
  1880. if hasCompletedInitialStoreKitSync {
  1881. scheduleRatingPromptAfterPremiumUpgrade()
  1882. }
  1883. MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
  1884. guard let self else { return }
  1885. MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
  1886. }
  1887. }
  1888. if hadPremiumAccess && !hasPremiumAccess {
  1889. MeetingReminderManager.shared.cancelAllReminders()
  1890. DesktopWidgetWindowManager.shared.removeAllInstances()
  1891. showPaywall()
  1892. }
  1893. }
  1894. private func refreshPagesAfterPremiumStateUpdate() {
  1895. pageCache[.joinMeetings] = nil
  1896. pageCache[.photo] = nil
  1897. pageCache[.video] = nil
  1898. pageCache[.widgets] = nil
  1899. pageCache[.settings] = nil
  1900. pageCache[.aiCompanion] = nil
  1901. showSidebarPage(selectedSidebarPage)
  1902. }
  1903. private var userHasRated: Bool {
  1904. UserDefaults.standard.bool(forKey: userHasRatedDefaultsKey)
  1905. }
  1906. private var accumulatedAppUsageSeconds: TimeInterval {
  1907. get {
  1908. UserDefaults.standard.double(forKey: appUsageAccumulatedSecondsDefaultsKey)
  1909. }
  1910. set {
  1911. UserDefaults.standard.set(newValue, forKey: appUsageAccumulatedSecondsDefaultsKey)
  1912. }
  1913. }
  1914. private var totalTrackedUsageSeconds: TimeInterval {
  1915. let liveSessionSeconds: TimeInterval
  1916. if let start = appUsageSessionStartDate {
  1917. liveSessionSeconds = max(0, Date().timeIntervalSince(start))
  1918. } else {
  1919. liveSessionSeconds = 0
  1920. }
  1921. return accumulatedAppUsageSeconds + liveSessionSeconds
  1922. }
  1923. private var hasReachedRatingUsageThreshold: Bool {
  1924. totalTrackedUsageSeconds >= ratingEligibleUsageSeconds
  1925. }
  1926. private var shouldShowRateUsInSettings: Bool {
  1927. true
  1928. }
  1929. private func migrateLegacyRatingStateIfNeeded() {
  1930. let defaults = UserDefaults.standard
  1931. guard !defaults.bool(forKey: ratingStateMigrationV2DoneDefaultsKey) else { return }
  1932. // Legacy behavior marked "rated" immediately after requesting review.
  1933. // Clear once so testing and new logic can run correctly.
  1934. defaults.set(false, forKey: userHasRatedDefaultsKey)
  1935. defaults.set(true, forKey: ratingStateMigrationV2DoneDefaultsKey)
  1936. }
  1937. private func beginUsageTrackingSessionIfNeeded() {
  1938. guard appUsageSessionStartDate == nil else { return }
  1939. appUsageSessionStartDate = Date()
  1940. }
  1941. private func endUsageTrackingSession() {
  1942. guard let start = appUsageSessionStartDate else { return }
  1943. let sessionElapsedSeconds = max(0, Date().timeIntervalSince(start))
  1944. accumulatedAppUsageSeconds += sessionElapsedSeconds
  1945. appUsageSessionStartDate = nil
  1946. }
  1947. private func observeAppLifecycleForUsageTrackingIfNeeded() {
  1948. guard !hasObservedAppLifecycleForUsage else { return }
  1949. hasObservedAppLifecycleForUsage = true
  1950. NotificationCenter.default.addObserver(
  1951. self,
  1952. selector: #selector(applicationDidBecomeActiveForUsageTracking),
  1953. name: NSApplication.didBecomeActiveNotification,
  1954. object: nil
  1955. )
  1956. NotificationCenter.default.addObserver(
  1957. self,
  1958. selector: #selector(applicationWillResignActiveForUsageTracking),
  1959. name: NSApplication.willResignActiveNotification,
  1960. object: nil
  1961. )
  1962. NotificationCenter.default.addObserver(
  1963. self,
  1964. selector: #selector(applicationWillTerminateForUsageTracking),
  1965. name: NSApplication.willTerminateNotification,
  1966. object: nil
  1967. )
  1968. }
  1969. @objc private func applicationDidBecomeActiveForUsageTracking() {
  1970. beginUsageTrackingSessionIfNeeded()
  1971. }
  1972. @objc private func applicationWillResignActiveForUsageTracking() {
  1973. endUsageTrackingSession()
  1974. }
  1975. @objc private func applicationWillTerminateForUsageTracking() {
  1976. endUsageTrackingSession()
  1977. }
  1978. private func scheduleRatingPromptAfterPremiumUpgrade() {
  1979. guard !userHasRated else { return }
  1980. let workItem = DispatchWorkItem { [weak self] in
  1981. self?.requestAppRatingIfEligible(markAsRated: false)
  1982. }
  1983. premiumUpgradeRatingPromptWorkItem = workItem
  1984. DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: workItem)
  1985. }
  1986. private func requestAppRatingIfEligible(markAsRated: Bool) {
  1987. guard storeKitCoordinator.hasPremiumAccess, !userHasRated else { return }
  1988. SKStoreReviewController.requestReview()
  1989. if markAsRated {
  1990. UserDefaults.standard.set(true, forKey: userHasRatedDefaultsKey)
  1991. }
  1992. }
  1993. private func refreshScheduleCardsForPremiumStateChange() {
  1994. if let stack = scheduleCardsStack {
  1995. renderScheduleCards(into: stack, meetings: displayedScheduleMeetings)
  1996. }
  1997. applySchedulePageFiltersAndRender()
  1998. }
  1999. private func refreshSidebarPremiumButton() {
  2000. let isPremium = storeKitCoordinator.hasPremiumAccess
  2001. if isPremium {
  2002. sidebarPremiumTitleLabel?.stringValue = "Manage Subscription"
  2003. sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "crown.fill")
  2004. } else {
  2005. sidebarPremiumTitleLabel?.stringValue = "Get Premium"
  2006. sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "star.fill")
  2007. }
  2008. sidebarPremiumIconView?.contentTintColor = .white
  2009. sidebarPremiumButtonView?.onHoverChanged?(false)
  2010. }
  2011. private func premiumButtonSymbolImage(named symbolName: String) -> NSImage? {
  2012. let configuration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
  2013. return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
  2014. .withSymbolConfiguration(configuration)
  2015. }
  2016. private func presentLaunchPaywallIfNeeded() {
  2017. guard hasCompletedInitialStoreKitSync, hasViewAppearedOnce, !hasPresentedLaunchPaywall else { return }
  2018. hasPresentedLaunchPaywall = true
  2019. if !storeKitCoordinator.hasPremiumAccess {
  2020. launchPaywallWorkItem?.cancel()
  2021. let workItem = DispatchWorkItem { [weak self] in
  2022. guard let self else { return }
  2023. self.launchPaywallWorkItem = nil
  2024. guard !self.storeKitCoordinator.hasPremiumAccess else { return }
  2025. self.showPaywall()
  2026. }
  2027. launchPaywallWorkItem = workItem
  2028. DispatchQueue.main.asyncAfter(deadline: .now() + launchPaywallDelay, execute: workItem)
  2029. }
  2030. }
  2031. @objc private func paywallContinueClicked(_ sender: Any?) {
  2032. startSelectedPlanPurchase()
  2033. }
  2034. private func startSelectedPlanPurchase() {
  2035. guard paywallContinueEnabled else {
  2036. if storeKitCoordinator.hasPremiumAccess {
  2037. showSimpleAlert(title: "Premium Active", message: "This Apple ID already has premium access.")
  2038. } else {
  2039. showSimpleAlert(title: "Please Wait", message: "A purchase is already being processed.")
  2040. }
  2041. return
  2042. }
  2043. if paywallUpgradeFlowEnabled,
  2044. storeKitCoordinator.hasPremiumAccess,
  2045. selectedPremiumPlan != .lifetime,
  2046. !confirmPremiumUpgrade(for: selectedPremiumPlan) {
  2047. return
  2048. }
  2049. paywallPurchaseTask?.cancel()
  2050. updatePaywallContinueState(isLoading: true)
  2051. let selectedPlan = selectedPremiumPlan
  2052. paywallPurchaseTask = Task { [weak self] in
  2053. guard let self else { return }
  2054. let result = await self.storeKitCoordinator.purchase(plan: selectedPlan)
  2055. self.updatePaywallContinueState(isLoading: false)
  2056. self.refreshPaywallStoreUI()
  2057. switch result {
  2058. case .success:
  2059. self.refreshPagesAfterPremiumStateUpdate()
  2060. Task { [weak self] in
  2061. await self?.loadSchedule()
  2062. }
  2063. if selectedPlan == .lifetime, self.storeKitCoordinator.activeNonLifetimePlan != nil {
  2064. self.showSimpleAlert(
  2065. title: "Lifetime Premium Activated",
  2066. message: "You are premium for lifetime now. Please cancel your previous subscription in App Store Subscriptions to avoid future renewal charges."
  2067. )
  2068. } else if selectedPlan == .lifetime {
  2069. self.showSimpleAlert(title: "Purchase Complete", message: "Lifetime premium has been unlocked successfully.")
  2070. } else {
  2071. self.showSimpleAlert(title: "Purchase Complete", message: "Premium has been unlocked successfully.")
  2072. }
  2073. self.dismissPaywallIfPresented()
  2074. self.scheduleRatingPromptAfterPremiumUpgrade()
  2075. case .cancelled:
  2076. break
  2077. case .pending:
  2078. self.showSimpleAlert(title: "Purchase Pending", message: "Your purchase is pending approval. You can continue once it completes.")
  2079. case .unavailable:
  2080. self.showSimpleAlert(title: "Product Not Available", message: "Unable to load this product. Check your StoreKit configuration and product IDs.")
  2081. case .alreadyOwned:
  2082. self.showSimpleAlert(title: "Already Purchased", message: "This plan is already active on your Apple ID.")
  2083. case .failed(let message):
  2084. self.showSimpleAlert(title: "Purchase Failed", message: message)
  2085. }
  2086. }
  2087. }
  2088. private func updatePaywallContinueState(isLoading: Bool) {
  2089. if isLoading {
  2090. paywallContinueEnabled = false
  2091. paywallContinueLabel?.stringValue = "Processing..."
  2092. paywallContinueButton?.alphaValue = 0.75
  2093. return
  2094. }
  2095. if storeKitCoordinator.hasLifetimeAccess {
  2096. paywallContinueEnabled = false
  2097. paywallContinueLabel?.stringValue = "Premium Active"
  2098. paywallContinueButton?.alphaValue = 0.75
  2099. } else if paywallUpgradeFlowEnabled && storeKitCoordinator.hasPremiumAccess {
  2100. paywallContinueEnabled = true
  2101. paywallContinueLabel?.stringValue = "Continue"
  2102. paywallContinueButton?.alphaValue = 1.0
  2103. } else {
  2104. paywallContinueEnabled = true
  2105. paywallContinueLabel?.stringValue = "Continue"
  2106. paywallContinueButton?.alphaValue = 1.0
  2107. }
  2108. }
  2109. private func applyPaywallPlanStyle(_ card: NSView, isSelected: Bool, hovering: Bool = false) {
  2110. let selectedBorder = NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1)
  2111. let idleBorder = palette.inputBorder
  2112. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  2113. let hoverIdleBackground =
  2114. palette.sectionCard.blended(withFraction: 0.10, of: hoverBlend) ?? palette.sectionCard
  2115. let selectedBackground = darkModeEnabled
  2116. ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
  2117. : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
  2118. card.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hoverIdleBackground : palette.sectionCard)).cgColor
  2119. card.layer?.borderColor = (isSelected ? selectedBorder : (hovering ? selectedBorder.withAlphaComponent(0.55) : idleBorder)).cgColor
  2120. card.layer?.borderWidth = isSelected ? 2 : 1
  2121. card.layer?.shadowColor = NSColor.black.cgColor
  2122. card.layer?.shadowOpacity = isSelected ? (darkModeEnabled ? 0.26 : 0.10) : (hovering ? 0.18 : 0.12)
  2123. card.layer?.shadowOffset = CGSize(width: 0, height: -1)
  2124. card.layer?.shadowRadius = isSelected ? (darkModeEnabled ? 10 : 6) : (hovering ? 7 : 5)
  2125. }
  2126. private func viewForPage(_ page: SidebarPage) -> NSView {
  2127. if let cached = pageCache[page] { return cached }
  2128. let built: NSView
  2129. switch page {
  2130. case .joinMeetings:
  2131. built = makeJoinMeetingsContent()
  2132. case .photo:
  2133. built = makeSchedulePageContent()
  2134. case .video:
  2135. built = makeCalendarPageContent()
  2136. case .widgets:
  2137. built = makeWidgetsPageContent()
  2138. case .settings:
  2139. built = makeSettingsPageContent()
  2140. case .aiCompanion:
  2141. built = makeAiCompanionPageContent()
  2142. }
  2143. pageCache[page] = built
  2144. return built
  2145. }
  2146. private func makeWidgetsPageContent() -> NSView {
  2147. let panel = NSView()
  2148. panel.translatesAutoresizingMaskIntoConstraints = false
  2149. let host = makeWidgetsPageHost(canAddWidgets: storeKitCoordinator.hasPremiumAccess) { [weak self] in
  2150. self?.showPaywall()
  2151. }
  2152. panel.addSubview(host)
  2153. NSLayoutConstraint.activate([
  2154. host.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  2155. host.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  2156. host.topAnchor.constraint(equalTo: panel.topAnchor),
  2157. host.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16)
  2158. ])
  2159. // Keep widgets anchored to the top instead of drifting vertically in tall windows.
  2160. host.setContentHuggingPriority(.required, for: .vertical)
  2161. host.setContentCompressionResistancePriority(.required, for: .vertical)
  2162. return panel
  2163. }
  2164. private func makeAiCompanionPageContent() -> NSView {
  2165. // Reset per-card mappings so stale buttons/labels from previous page builds don't linger.
  2166. aiCompanionAudioPlayer?.pause()
  2167. aiCompanionAudioPlayer = nil
  2168. aiCompanionLocalAudioPlayer?.stop()
  2169. aiCompanionLocalAudioPlayer = nil
  2170. aiCompanionCurrentlyPlayingURL = nil
  2171. aiCompanionCurrentlyPlayingButton = nil
  2172. aiCompanionTimeControlObserver = nil
  2173. aiCompanionNoProgressWorkItem?.cancel()
  2174. aiCompanionNoProgressWorkItem = nil
  2175. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2176. aiCompanionIsUsingSpeech = false
  2177. aiCompanionCurrentlySpeakingButtonId = nil
  2178. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2179. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2180. aiCompanionPlaybackEndObserver = nil
  2181. aiCompanionPlaybackFailedObserver = nil
  2182. aiCompanionAudioURLByView.removeAll()
  2183. aiCompanionAudioStatusLabelByView.removeAll()
  2184. aiCompanionSpeechTextByView.removeAll()
  2185. aiCompanionTranscriptMeetingIdByView.removeAll()
  2186. aiCompanionTranscriptStatusLabelByView.removeAll()
  2187. // Keep transcript requests and window state alive across AI Companion page rebuilds.
  2188. // The page is rebuilt while processing starts/completes, and cancelling here interrupts
  2189. // the active request before it can update the transcript view.
  2190. let panel = NSView()
  2191. panel.translatesAutoresizingMaskIntoConstraints = false
  2192. panel.userInterfaceLayoutDirection = .leftToRight
  2193. let scroll = NSScrollView()
  2194. scroll.translatesAutoresizingMaskIntoConstraints = false
  2195. scroll.drawsBackground = false
  2196. scroll.hasHorizontalScroller = false
  2197. scroll.hasVerticalScroller = true
  2198. scroll.autohidesScrollers = true
  2199. scroll.borderType = .noBorder
  2200. scroll.scrollerStyle = .overlay
  2201. scroll.automaticallyAdjustsContentInsets = false
  2202. let clip = TopAlignedClipView()
  2203. clip.drawsBackground = false
  2204. scroll.contentView = clip
  2205. panel.addSubview(scroll)
  2206. let content = NSView()
  2207. content.translatesAutoresizingMaskIntoConstraints = false
  2208. scroll.documentView = content
  2209. let contentStack = NSStackView()
  2210. contentStack.translatesAutoresizingMaskIntoConstraints = false
  2211. contentStack.userInterfaceLayoutDirection = .leftToRight
  2212. contentStack.orientation = .vertical
  2213. contentStack.spacing = 12
  2214. contentStack.alignment = .width
  2215. contentStack.distribution = .fill
  2216. let titleLabel = textLabel("Ai companion", font: typography.pageTitle, color: palette.textPrimary)
  2217. titleLabel.alignment = .left
  2218. contentStack.addArrangedSubview(titleLabel)
  2219. let subtitle = textLabel("Ended meetings with local recordings", font: typography.fieldLabel, color: palette.textSecondary)
  2220. subtitle.alignment = .left
  2221. contentStack.addArrangedSubview(subtitle)
  2222. contentStack.setCustomSpacing(14, after: subtitle)
  2223. titleLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  2224. subtitle.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  2225. if let session = activeMeetingRecordingSession {
  2226. let activeCard = aiCompanionActiveRecordingCard(session: session)
  2227. contentStack.addArrangedSubview(activeCard)
  2228. activeCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  2229. }
  2230. if aiCompanionLocalRecordings.isEmpty {
  2231. let emptyLabel = textLabel(
  2232. "No saved recordings yet. Start a meeting from this app and allow consent to store local audio here.",
  2233. font: typography.fieldLabel,
  2234. color: palette.textMuted
  2235. )
  2236. emptyLabel.alignment = .left
  2237. emptyLabel.maximumNumberOfLines = 2
  2238. emptyLabel.lineBreakMode = .byWordWrapping
  2239. contentStack.addArrangedSubview(emptyLabel)
  2240. emptyLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  2241. } else {
  2242. for recording in aiCompanionLocalRecordings {
  2243. let card = aiCompanionMeetingCard(recording)
  2244. contentStack.addArrangedSubview(card)
  2245. card.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  2246. }
  2247. }
  2248. content.addSubview(contentStack)
  2249. NSLayoutConstraint.activate([
  2250. scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
  2251. scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
  2252. scroll.topAnchor.constraint(equalTo: panel.topAnchor),
  2253. scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),
  2254. content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  2255. content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  2256. content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  2257. content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
  2258. content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
  2259. contentStack.leftAnchor.constraint(equalTo: content.leftAnchor, constant: 28),
  2260. contentStack.rightAnchor.constraint(equalTo: content.rightAnchor, constant: -28),
  2261. contentStack.topAnchor.constraint(equalTo: content.topAnchor, constant: 16),
  2262. content.bottomAnchor.constraint(greaterThanOrEqualTo: contentStack.bottomAnchor, constant: 16)
  2263. ])
  2264. return panel
  2265. }
  2266. private func aiCompanionActiveRecordingCard(session: ActiveMeetingRecordingSession) -> NSView {
  2267. let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
  2268. card.translatesAutoresizingMaskIntoConstraints = false
  2269. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2270. let stack = NSStackView()
  2271. stack.translatesAutoresizingMaskIntoConstraints = false
  2272. stack.userInterfaceLayoutDirection = .leftToRight
  2273. stack.orientation = .vertical
  2274. stack.alignment = .leading
  2275. stack.spacing = 8
  2276. let title = textLabel("Recording in progress: \(session.title)", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
  2277. let started = DateFormatter.localizedString(from: session.startedAt, dateStyle: .medium, timeStyle: .short)
  2278. let status = textLabel("Started: \(started)", font: typography.fieldLabel, color: palette.textSecondary)
  2279. let stopButton = NSButton(title: "Stop Recording", target: self, action: #selector(aiCompanionStopRecordingTapped(_:)))
  2280. stopButton.translatesAutoresizingMaskIntoConstraints = false
  2281. stopButton.isBordered = false
  2282. stopButton.bezelStyle = .inline
  2283. stopButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
  2284. stopButton.contentTintColor = NSColor.systemRed
  2285. stopButton.alignment = .left
  2286. stopButton.setButtonType(.momentaryPushIn)
  2287. aiCompanionStopRecordingButton = stopButton
  2288. stack.addArrangedSubview(title)
  2289. stack.addArrangedSubview(status)
  2290. stack.addArrangedSubview(stopButton)
  2291. card.addSubview(stack)
  2292. NSLayoutConstraint.activate([
  2293. stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
  2294. stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
  2295. stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  2296. stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
  2297. ])
  2298. return card
  2299. }
  2300. private func aiCompanionMeetingCard(_ recording: MeetingRecordingSummary) -> NSView {
  2301. let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
  2302. card.translatesAutoresizingMaskIntoConstraints = false
  2303. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  2304. let stack = NSStackView()
  2305. stack.translatesAutoresizingMaskIntoConstraints = false
  2306. stack.userInterfaceLayoutDirection = .leftToRight
  2307. stack.orientation = .vertical
  2308. stack.alignment = .leading
  2309. stack.spacing = 8
  2310. let title = textLabel(recording.title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
  2311. title.alignment = .left
  2312. title.maximumNumberOfLines = 2
  2313. title.lineBreakMode = .byTruncatingTail
  2314. let dateText = DateFormatter.localizedString(from: recording.endedAt, dateStyle: .medium, timeStyle: .short)
  2315. let dateLabel = textLabel("Saved: \(dateText)", font: typography.fieldLabel, color: palette.textSecondary)
  2316. dateLabel.alignment = .left
  2317. let audioURL = URL(fileURLWithPath: recording.audioFilePath)
  2318. let audioLink = audioURL.lastPathComponent
  2319. let audioButton = NSButton(title: "Play Audio", target: self, action: #selector(aiCompanionAudioTapped(_:)))
  2320. audioButton.translatesAutoresizingMaskIntoConstraints = false
  2321. audioButton.isBordered = false
  2322. audioButton.bezelStyle = .inline
  2323. audioButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
  2324. audioButton.contentTintColor = palette.primaryBlue
  2325. audioButton.alignment = .left
  2326. audioButton.setButtonType(.momentaryPushIn)
  2327. aiCompanionAudioURLByView[ObjectIdentifier(audioButton)] = audioURL
  2328. let trimmedSubtitle: String? = nil
  2329. let speechText = {
  2330. let base = "Ended meeting: \(recording.title)."
  2331. guard let trimmedSubtitle, trimmedSubtitle.isEmpty == false else { return base }
  2332. return "\(base) \(trimmedSubtitle)."
  2333. }()
  2334. aiCompanionSpeechTextByView[ObjectIdentifier(audioButton)] = speechText
  2335. let audioURLLabel = textLabel(audioLink, font: typography.fieldLabel, color: palette.textMuted)
  2336. audioURLLabel.alignment = .left
  2337. audioURLLabel.maximumNumberOfLines = 2
  2338. audioURLLabel.lineBreakMode = .byTruncatingTail
  2339. let audioStatusLabel = textLabel("Not playing", font: typography.fieldLabel, color: palette.textMuted)
  2340. audioStatusLabel.alignment = .left
  2341. audioStatusLabel.maximumNumberOfLines = 1
  2342. audioStatusLabel.lineBreakMode = .byTruncatingTail
  2343. aiCompanionAudioStatusLabelByView[ObjectIdentifier(audioButton)] = audioStatusLabel
  2344. let transcriptButton = NSButton(title: "View transcript", target: self, action: #selector(aiCompanionTranscriptTapped(_:)))
  2345. transcriptButton.translatesAutoresizingMaskIntoConstraints = false
  2346. transcriptButton.isBordered = false
  2347. transcriptButton.bezelStyle = .inline
  2348. transcriptButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
  2349. transcriptButton.contentTintColor = palette.primaryBlue
  2350. transcriptButton.alignment = .left
  2351. transcriptButton.setButtonType(.momentaryPushIn)
  2352. aiCompanionTranscriptMeetingIdByView[ObjectIdentifier(transcriptButton)] = recording.id
  2353. let transcriptStatusLabel = textLabel(aiCompanionTranscriptStatusText(for: recording), font: typography.fieldLabel, color: palette.textMuted)
  2354. transcriptStatusLabel.alignment = .left
  2355. transcriptStatusLabel.maximumNumberOfLines = 2
  2356. transcriptStatusLabel.lineBreakMode = .byTruncatingTail
  2357. aiCompanionTranscriptStatusLabelByView[ObjectIdentifier(transcriptButton)] = transcriptStatusLabel
  2358. stack.addArrangedSubview(title)
  2359. stack.addArrangedSubview(dateLabel)
  2360. stack.addArrangedSubview(audioButton)
  2361. stack.addArrangedSubview(audioURLLabel)
  2362. stack.addArrangedSubview(audioStatusLabel)
  2363. stack.addArrangedSubview(transcriptButton)
  2364. stack.addArrangedSubview(transcriptStatusLabel)
  2365. card.addSubview(stack)
  2366. NSLayoutConstraint.activate([
  2367. stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
  2368. stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
  2369. stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  2370. stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
  2371. ])
  2372. return card
  2373. }
  2374. @objc private func aiCompanionAudioTapped(_ sender: NSButton) {
  2375. let senderId = ObjectIdentifier(sender)
  2376. guard let url = aiCompanionAudioURLByView[senderId] else { return }
  2377. // Toggle play/pause if the same card is tapped.
  2378. if aiCompanionCurrentlyPlayingURL == url {
  2379. if aiCompanionIsUsingSpeech {
  2380. if aiCompanionSpeechSynthesizer.isSpeaking {
  2381. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2382. aiCompanionIsUsingSpeech = false
  2383. sender.title = "Play Audio"
  2384. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Stopped"
  2385. } else {
  2386. aiCompanionStartSpeech(forButtonId: senderId)
  2387. sender.title = "Pause Audio"
  2388. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Speaking..."
  2389. }
  2390. return
  2391. } else if let player = aiCompanionAudioPlayer {
  2392. if player.rate != 0 {
  2393. player.pause()
  2394. sender.title = "Play Audio"
  2395. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
  2396. } else {
  2397. player.play()
  2398. sender.title = "Pause Audio"
  2399. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
  2400. }
  2401. return
  2402. } else if let player = aiCompanionLocalAudioPlayer {
  2403. if player.isPlaying {
  2404. player.pause()
  2405. sender.title = "Play Audio"
  2406. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
  2407. } else {
  2408. player.play()
  2409. sender.title = "Pause Audio"
  2410. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
  2411. }
  2412. return
  2413. }
  2414. }
  2415. // Stop any previous playback and remove observers.
  2416. aiCompanionAudioPlayer?.pause()
  2417. aiCompanionLocalAudioPlayer?.stop()
  2418. aiCompanionLocalAudioPlayer = nil
  2419. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2420. aiCompanionIsUsingSpeech = false
  2421. aiCompanionNoProgressWorkItem?.cancel()
  2422. aiCompanionNoProgressWorkItem = nil
  2423. aiCompanionCurrentlySpeakingButtonId = nil
  2424. aiCompanionTimeControlObserver = nil
  2425. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2426. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2427. aiCompanionPlaybackEndObserver = nil
  2428. aiCompanionPlaybackFailedObserver = nil
  2429. // Revert previous playing UI (if any).
  2430. if let previousButton = aiCompanionCurrentlyPlayingButton {
  2431. let previousId = ObjectIdentifier(previousButton)
  2432. previousButton.title = "Play Audio"
  2433. aiCompanionAudioStatusLabelByView[previousId]?.stringValue = "Not playing"
  2434. }
  2435. aiCompanionCurrentlyPlayingURL = url
  2436. aiCompanionCurrentlyPlayingButton = sender
  2437. sender.title = "Pause Audio"
  2438. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Checking audio..."
  2439. aiCompanionAudioRequestID = UUID()
  2440. let requestID = aiCompanionAudioRequestID
  2441. let urlToCheck = url
  2442. let senderButton = sender
  2443. if urlToCheck.isFileURL {
  2444. guard FileManager.default.fileExists(atPath: urlToCheck.path) else {
  2445. senderButton.title = "Play Audio"
  2446. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Audio file missing"
  2447. return
  2448. }
  2449. do {
  2450. let player = try AVAudioPlayer(contentsOf: urlToCheck)
  2451. player.volume = 1.0
  2452. player.delegate = self
  2453. player.prepareToPlay()
  2454. let didPlay = player.play()
  2455. guard didPlay else {
  2456. senderButton.title = "Play Audio"
  2457. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Could not play recording"
  2458. return
  2459. }
  2460. aiCompanionLocalAudioPlayer = player
  2461. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
  2462. } catch {
  2463. senderButton.title = "Play Audio"
  2464. aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Failed: \(error.localizedDescription)"
  2465. }
  2466. return
  2467. }
  2468. var request = URLRequest(url: urlToCheck)
  2469. request.setValue("bytes=0-0", forHTTPHeaderField: "Range") // lightweight probe
  2470. request.timeoutInterval = 10
  2471. URLSession.shared.dataTask(with: request) { [weak self] _, response, error in
  2472. guard let self else { return }
  2473. DispatchQueue.main.async {
  2474. guard self.aiCompanionAudioRequestID == requestID else { return } // stale tap
  2475. if let error {
  2476. senderButton.title = "Play Audio"
  2477. self.aiCompanionAudioTimeControlObserverResetForFailure()
  2478. self.aiCompanionStartSpeech(forButtonId: senderId)
  2479. return
  2480. }
  2481. guard let http = response as? HTTPURLResponse else {
  2482. senderButton.title = "Play Audio"
  2483. self.aiCompanionAudioTimeControlObserverResetForFailure()
  2484. self.aiCompanionStartSpeech(forButtonId: senderId)
  2485. return
  2486. }
  2487. let mime = http.mimeType?.lowercased() ?? ""
  2488. let okStatus = (200...299).contains(http.statusCode) || http.statusCode == 206
  2489. guard okStatus else {
  2490. senderButton.title = "Play Audio"
  2491. self.aiCompanionAudioTimeControlObserverResetForFailure()
  2492. self.aiCompanionStartSpeech(forButtonId: senderId)
  2493. return
  2494. }
  2495. if !mime.isEmpty && mime.hasPrefix("audio/") == false {
  2496. senderButton.title = "Play Audio"
  2497. self.aiCompanionAudioTimeControlObserverResetForFailure()
  2498. self.aiCompanionStartSpeech(forButtonId: senderId)
  2499. return
  2500. }
  2501. self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Loading..."
  2502. let player = AVPlayer(url: urlToCheck)
  2503. player.volume = 1.0
  2504. self.aiCompanionAudioPlayer = player
  2505. if let item = player.currentItem {
  2506. self.aiCompanionPlaybackEndObserver = NotificationCenter.default.addObserver(
  2507. forName: .AVPlayerItemDidPlayToEndTime,
  2508. object: item,
  2509. queue: .main
  2510. ) { [weak self] _ in
  2511. self?.aiCompanionAudioDidFinish()
  2512. }
  2513. self.aiCompanionPlaybackFailedObserver = NotificationCenter.default.addObserver(
  2514. forName: .AVPlayerItemFailedToPlayToEndTime,
  2515. object: item,
  2516. queue: .main
  2517. ) { [weak self] notification in
  2518. self?.aiCompanionAudioDidFail(notification: notification)
  2519. }
  2520. }
  2521. // Update the UI only when playback actually starts (helps diagnose "playing but no audio").
  2522. self.aiCompanionTimeControlObserver = player.observe(\.timeControlStatus, options: [.initial, .new]) { [weak self] p, _ in
  2523. guard let self else { return }
  2524. guard self.aiCompanionCurrentlyPlayingURL == urlToCheck else { return }
  2525. switch p.timeControlStatus {
  2526. case .playing:
  2527. self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
  2528. case .waitingToPlayAtSpecifiedRate:
  2529. self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Buffering..."
  2530. case .paused:
  2531. self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
  2532. @unknown default:
  2533. self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
  2534. }
  2535. }
  2536. // If the remote file is silent/unplayable, AVPlayer can still report "playing".
  2537. // After a short grace period, fall back to text-to-speech so you can always hear something.
  2538. let startSeconds = player.currentTime().seconds
  2539. player.play()
  2540. let playerRef = player
  2541. let urlRef = urlToCheck
  2542. self.aiCompanionNoProgressWorkItem?.cancel()
  2543. let workItem = DispatchWorkItem { [weak self] in
  2544. guard let self else { return }
  2545. guard self.aiCompanionAudioPlayer === playerRef else { return }
  2546. guard self.aiCompanionCurrentlyPlayingURL == urlRef else { return }
  2547. guard self.aiCompanionIsUsingSpeech == false else { return }
  2548. let nowSeconds = playerRef.currentTime().seconds
  2549. let progressed = startSeconds.isFinite && nowSeconds.isFinite && (nowSeconds - startSeconds) > 0.5
  2550. let actuallyPlaying = playerRef.timeControlStatus == .playing
  2551. if actuallyPlaying == false || progressed == false {
  2552. self.aiCompanionStartSpeech(forButtonId: senderId)
  2553. }
  2554. }
  2555. self.aiCompanionNoProgressWorkItem = workItem
  2556. DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: workItem)
  2557. }
  2558. }.resume()
  2559. }
  2560. @objc private func aiCompanionTranscriptTapped(_ sender: NSButton) {
  2561. let senderId = ObjectIdentifier(sender)
  2562. guard let meetingId = aiCompanionTranscriptMeetingIdByView[senderId] else { return }
  2563. guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
  2564. aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript unavailable (tap to retry)"
  2565. showSimpleAlert(title: "Transcript unavailable", message: "Could not find recording details for this meeting.")
  2566. return
  2567. }
  2568. if aiCompanionTranscriptStatus(for: recording) == .ready,
  2569. let cached = recording.transcriptText?.trimmingCharacters(in: .whitespacesAndNewlines),
  2570. cached.isEmpty == false {
  2571. aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: cached)
  2572. aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = aiCompanionTranscriptStatusText(for: recording)
  2573. return
  2574. }
  2575. aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript processing..."
  2576. let requestId = UUID()
  2577. aiCompanionTranscriptCurrentRequestId = requestId
  2578. aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: "Transcript processing...")
  2579. aiCompanionStartTranscriptProcessing(forMeetingID: meetingId, requestId: requestId, interactiveAuth: true, forceRegenerate: true)
  2580. }
  2581. private func aiCompanionStartTranscriptProcessing(
  2582. forMeetingID meetingId: String,
  2583. requestId: UUID?,
  2584. interactiveAuth: Bool,
  2585. forceRegenerate: Bool
  2586. ) {
  2587. if !forceRegenerate,
  2588. let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }),
  2589. aiCompanionTranscriptStatus(for: recording) == .ready {
  2590. return
  2591. }
  2592. aiCompanionTranscriptTaskByMeetingId[meetingId]?.cancel()
  2593. _ = aiCompanionUpdateRecording(meetingId: meetingId) { recording in
  2594. recording.transcriptStatusRaw = MeetingTranscriptStatus.processing.rawValue
  2595. recording.transcriptErrorMessage = nil
  2596. if forceRegenerate {
  2597. recording.transcriptText = nil
  2598. recording.transcriptSourceRaw = nil
  2599. }
  2600. }
  2601. aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
  2602. if selectedSidebarPage == .aiCompanion {
  2603. pageCache[.aiCompanion] = nil
  2604. showSidebarPage(.aiCompanion)
  2605. }
  2606. let presentingWindow = view.window
  2607. let task = Task { [weak self] in
  2608. guard let self else { return }
  2609. defer { Task { @MainActor [weak self] in self?.aiCompanionTranscriptTaskByMeetingId[meetingId] = nil } }
  2610. do {
  2611. let result = try await self.aiCompanionFetchOrGenerateTranscript(
  2612. meetingId: meetingId,
  2613. interactiveAuth: interactiveAuth,
  2614. presentingWindow: presentingWindow
  2615. )
  2616. await MainActor.run {
  2617. guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
  2618. _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
  2619. recording.transcriptStatusRaw = MeetingTranscriptStatus.ready.rawValue
  2620. recording.transcriptSourceRaw = result.source.rawValue
  2621. recording.transcriptText = result.text
  2622. recording.transcriptErrorMessage = nil
  2623. }
  2624. self.aiCompanionTranscriptTextView?.string = result.text
  2625. self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
  2626. if self.selectedSidebarPage == .aiCompanion {
  2627. self.pageCache[.aiCompanion] = nil
  2628. self.showSidebarPage(.aiCompanion)
  2629. }
  2630. }
  2631. } catch {
  2632. await MainActor.run {
  2633. guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
  2634. let msg = error.localizedDescription.isEmpty ? "Failed to load transcript." : error.localizedDescription
  2635. _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
  2636. recording.transcriptStatusRaw = MeetingTranscriptStatus.failed.rawValue
  2637. recording.transcriptErrorMessage = msg
  2638. }
  2639. self.aiCompanionTranscriptTextView?.string = "Transcript unavailable.\n\n\(msg)"
  2640. self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
  2641. if self.selectedSidebarPage == .aiCompanion {
  2642. self.pageCache[.aiCompanion] = nil
  2643. self.showSidebarPage(.aiCompanion)
  2644. }
  2645. }
  2646. }
  2647. }
  2648. aiCompanionTranscriptTaskByMeetingId[meetingId] = task
  2649. }
  2650. private func aiCompanionFetchOrGenerateTranscript(
  2651. meetingId: String,
  2652. interactiveAuth: Bool,
  2653. presentingWindow: NSWindow?
  2654. ) async throws -> (text: String, source: MeetingTranscriptSource) {
  2655. guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
  2656. throw NSError(domain: "AiCompanionTranscript", code: 10, userInfo: [NSLocalizedDescriptionKey: "Recording not found."])
  2657. }
  2658. if let meeting = aiCompanionMeetingFromRecording(recording) {
  2659. do {
  2660. let accessToken: String
  2661. if interactiveAuth {
  2662. accessToken = try await googleOAuth.validAccessToken(presentingWindow: presentingWindow)
  2663. } else if let token = googleOAuth.loadTokens()?.accessToken {
  2664. accessToken = token
  2665. } else {
  2666. throw NSError(domain: "AiCompanionTranscript", code: 11, userInfo: [NSLocalizedDescriptionKey: "Google account not connected."])
  2667. }
  2668. let text = try await aiCompanionFetchTranscriptText(for: meeting, accessToken: accessToken)
  2669. let cleaned = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  2670. if cleaned.isEmpty == false {
  2671. return (cleaned, .meetApi)
  2672. }
  2673. } catch {
  2674. // Continue to OpenAI fallback below.
  2675. }
  2676. }
  2677. let audioURL = URL(fileURLWithPath: recording.audioFilePath)
  2678. guard FileManager.default.fileExists(atPath: audioURL.path) else {
  2679. throw NSError(domain: "AiCompanionTranscript", code: 12, userInfo: [NSLocalizedDescriptionKey: "Local meeting audio is missing."])
  2680. }
  2681. guard let apiKey = configuredOpenAIAPIKey() else {
  2682. throw NSError(domain: "AiCompanionTranscript", code: 13, userInfo: [NSLocalizedDescriptionKey: "OpenAI API key missing. Add OpenAIAPIKey to Info.plist or openai.apiKey to UserDefaults."])
  2683. }
  2684. let text = try await openAITranscriptionClient.transcribeAudioFile(fileURL: audioURL, apiKey: apiKey)
  2685. let cleaned = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  2686. guard cleaned.isEmpty == false else {
  2687. throw NSError(domain: "AiCompanionTranscript", code: 14, userInfo: [NSLocalizedDescriptionKey: "Generated transcript was empty."])
  2688. }
  2689. return (cleaned, .localAudioOpenAI)
  2690. }
  2691. @objc private func aiCompanionStopRecordingTapped(_ sender: NSButton) {
  2692. finishActiveMeetingRecording()
  2693. }
  2694. private func aiCompanionAudioTimeControlObserverResetForFailure() {
  2695. aiCompanionAudioPlayer?.pause()
  2696. aiCompanionAudioPlayer = nil
  2697. aiCompanionLocalAudioPlayer?.stop()
  2698. aiCompanionLocalAudioPlayer = nil
  2699. aiCompanionTimeControlObserver = nil
  2700. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2701. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2702. aiCompanionPlaybackEndObserver = nil
  2703. aiCompanionPlaybackFailedObserver = nil
  2704. }
  2705. private func aiCompanionStartSpeech(forButtonId buttonId: ObjectIdentifier) {
  2706. // Stop any remote audio playback first.
  2707. aiCompanionAudioPlayer?.pause()
  2708. aiCompanionAudioPlayer = nil
  2709. aiCompanionTimeControlObserver = nil
  2710. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2711. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2712. aiCompanionPlaybackEndObserver = nil
  2713. aiCompanionPlaybackFailedObserver = nil
  2714. aiCompanionNoProgressWorkItem?.cancel()
  2715. aiCompanionNoProgressWorkItem = nil
  2716. aiCompanionIsUsingSpeech = true
  2717. aiCompanionCurrentlySpeakingButtonId = buttonId
  2718. if let button = aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
  2719. button.title = "Pause Audio"
  2720. }
  2721. aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Speaking..."
  2722. let text = aiCompanionSpeechTextByView[buttonId] ?? "Ended meeting."
  2723. let utterance = AVSpeechUtterance(string: text)
  2724. utterance.rate = 0.5
  2725. utterance.volume = 1.0
  2726. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2727. aiCompanionSpeechSynthesizer.speak(utterance)
  2728. }
  2729. private func aiCompanionAudioDidFinish() {
  2730. guard let button = aiCompanionCurrentlyPlayingButton else { return }
  2731. let buttonId = ObjectIdentifier(button)
  2732. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2733. aiCompanionIsUsingSpeech = false
  2734. aiCompanionCurrentlySpeakingButtonId = nil
  2735. button.title = "Play Audio"
  2736. aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"
  2737. aiCompanionAudioPlayer?.pause()
  2738. aiCompanionAudioPlayer = nil
  2739. aiCompanionLocalAudioPlayer?.stop()
  2740. aiCompanionLocalAudioPlayer = nil
  2741. aiCompanionCurrentlyPlayingURL = nil
  2742. aiCompanionCurrentlyPlayingButton = nil
  2743. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2744. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2745. aiCompanionPlaybackEndObserver = nil
  2746. aiCompanionPlaybackFailedObserver = nil
  2747. aiCompanionTimeControlObserver = nil
  2748. }
  2749. private func aiCompanionAudioDidFail(notification: Notification) {
  2750. guard let button = aiCompanionCurrentlyPlayingButton else { return }
  2751. let buttonId = ObjectIdentifier(button)
  2752. aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
  2753. aiCompanionIsUsingSpeech = false
  2754. aiCompanionCurrentlySpeakingButtonId = nil
  2755. button.title = "Play Audio"
  2756. var message = "Failed to play audio"
  2757. if let item = notification.object as? AVPlayerItem, let error = item.error {
  2758. message = "Failed: \(error.localizedDescription)"
  2759. }
  2760. aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = message
  2761. aiCompanionAudioPlayer?.pause()
  2762. aiCompanionAudioPlayer = nil
  2763. aiCompanionLocalAudioPlayer?.stop()
  2764. aiCompanionLocalAudioPlayer = nil
  2765. aiCompanionCurrentlyPlayingURL = nil
  2766. aiCompanionCurrentlyPlayingButton = nil
  2767. if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
  2768. if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
  2769. aiCompanionPlaybackEndObserver = nil
  2770. aiCompanionPlaybackFailedObserver = nil
  2771. aiCompanionTimeControlObserver = nil
  2772. }
  2773. @MainActor
  2774. private func aiCompanionPresentTranscriptWindow(meetingTitle: String, initialText: String) {
  2775. if let window = aiCompanionTranscriptWindow, let textView = aiCompanionTranscriptTextView {
  2776. window.title = "Transcript - \(meetingTitle)"
  2777. textView.string = initialText
  2778. window.makeKeyAndOrderFront(nil)
  2779. NSApp.activate(ignoringOtherApps: true)
  2780. return
  2781. }
  2782. let windowWidth: CGFloat = 640
  2783. let windowHeight: CGFloat = 560
  2784. let window = NSWindow(
  2785. contentRect: NSRect(x: 0, y: 0, width: windowWidth, height: windowHeight),
  2786. styleMask: [.titled, .closable, .resizable],
  2787. backing: .buffered,
  2788. defer: false
  2789. )
  2790. window.isReleasedWhenClosed = false
  2791. window.title = "Transcript - \(meetingTitle)"
  2792. window.center()
  2793. let root = NSView()
  2794. root.translatesAutoresizingMaskIntoConstraints = false
  2795. let scroll = NSScrollView()
  2796. scroll.translatesAutoresizingMaskIntoConstraints = false
  2797. scroll.drawsBackground = false
  2798. scroll.hasVerticalScroller = true
  2799. let textView = NSTextView()
  2800. textView.isEditable = false
  2801. textView.isSelectable = true
  2802. textView.backgroundColor = .clear
  2803. textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
  2804. textView.string = initialText
  2805. textView.textContainer?.widthTracksTextView = true
  2806. scroll.documentView = textView
  2807. root.addSubview(scroll)
  2808. NSLayoutConstraint.activate([
  2809. scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  2810. scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  2811. scroll.topAnchor.constraint(equalTo: root.topAnchor),
  2812. scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor)
  2813. ])
  2814. window.contentView = root
  2815. window.makeKeyAndOrderFront(nil)
  2816. NSApp.activate(ignoringOtherApps: true)
  2817. aiCompanionTranscriptWindow = window
  2818. aiCompanionTranscriptTextView = textView
  2819. }
  2820. private func aiCompanionMeetMeetingCode(from meetURL: URL) -> String? {
  2821. // Typical: https://meet.google.com/abc-defg-hij
  2822. guard let host = meetURL.host?.lowercased(),
  2823. host == "meet.google.com" || host.hasSuffix(".meet.google.com") else { return nil }
  2824. let codeCandidate = meetURL.pathComponents.filter { !$0.isEmpty }.last
  2825. guard let codeCandidate else { return nil }
  2826. // Allow flexible token shapes; Meet codes are usually 3 hyphen-separated chunks.
  2827. let cleaned = codeCandidate.trimmingCharacters(in: .whitespacesAndNewlines)
  2828. let parts = cleaned.split(separator: "-")
  2829. guard parts.count >= 3 else { return nil }
  2830. return cleaned
  2831. }
  2832. private func aiCompanionSelectConferenceRecord(for meeting: ScheduledMeeting, from records: [ConferenceRecord]) -> ConferenceRecord? {
  2833. // Prefer a record whose time window overlaps the calendar meeting.
  2834. let overlapping = records.filter { r in
  2835. guard let start = r.startTime, let end = r.endTime else { return false }
  2836. return start <= meeting.endDate && end >= meeting.startDate
  2837. }
  2838. if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
  2839. return best
  2840. }
  2841. // Fallback: choose the most recent one we can.
  2842. return records.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
  2843. }
  2844. private func aiCompanionSelectTranscript(for meeting: ScheduledMeeting, from transcripts: [Transcript]) -> Transcript? {
  2845. let overlapping = transcripts.filter { t in
  2846. guard let start = t.startTime, let end = t.endTime else { return false }
  2847. return start <= meeting.endDate && end >= meeting.startDate
  2848. }
  2849. if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
  2850. return best
  2851. }
  2852. return transcripts.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
  2853. }
  2854. private func aiCompanionFormatTranscriptText(entries: [TranscriptEntry]) -> String {
  2855. let lines = entries.compactMap { entry -> String? in
  2856. guard let raw = entry.text else { return nil }
  2857. let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)
  2858. guard t.isEmpty == false else { return nil }
  2859. let speaker = entry.participant?.trimmingCharacters(in: .whitespacesAndNewlines)
  2860. guard let speaker, speaker.isEmpty == false else { return t }
  2861. return "\(speaker): \(t)"
  2862. }
  2863. if lines.isEmpty { return "(No transcript entries found.)" }
  2864. return lines.joined(separator: "\n")
  2865. }
  2866. private func aiCompanionFetchTranscriptText(for meeting: ScheduledMeeting, accessToken: String) async throws -> String {
  2867. guard let meetingCode = aiCompanionMeetMeetingCode(from: meeting.meetURL) else {
  2868. throw NSError(
  2869. domain: "AiCompanionTranscript",
  2870. code: 1,
  2871. userInfo: [NSLocalizedDescriptionKey: "Couldn't determine Meet meeting code from URL."]
  2872. )
  2873. }
  2874. // Resolve `spaces/{meetingCode}` into a stable space resource name (`spaces/{spaceId}`).
  2875. let space = try await googleMeetClient.getSpace(accessToken: accessToken, spaceNameOrMeetingCode: "spaces/\(meetingCode)")
  2876. let spaceName = space.name ?? "spaces/\(meetingCode)"
  2877. let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceName)
  2878. guard let conferenceRecord = aiCompanionSelectConferenceRecord(for: meeting, from: records),
  2879. let conferenceRecordName = conferenceRecord.name else {
  2880. throw NSError(
  2881. domain: "AiCompanionTranscript",
  2882. code: 2,
  2883. userInfo: [NSLocalizedDescriptionKey: "No conference record found for this meeting."]
  2884. )
  2885. }
  2886. let transcripts = try await googleMeetClient.listTranscripts(accessToken: accessToken, conferenceRecordName: conferenceRecordName)
  2887. guard let transcript = aiCompanionSelectTranscript(for: meeting, from: transcripts),
  2888. let transcriptName = transcript.name else {
  2889. throw NSError(
  2890. domain: "AiCompanionTranscript",
  2891. code: 3,
  2892. userInfo: [NSLocalizedDescriptionKey: "No transcript found for this meeting."]
  2893. )
  2894. }
  2895. let entries = try await googleMeetClient.listTranscriptEntries(accessToken: accessToken, transcriptName: transcriptName)
  2896. return aiCompanionFormatTranscriptText(entries: entries)
  2897. }
  2898. private func makePlaceholderPage(title: String, subtitle: String) -> NSView {
  2899. let panel = NSView()
  2900. panel.translatesAutoresizingMaskIntoConstraints = false
  2901. let titleLabel = textLabel(title, font: typography.pageTitle, color: palette.textPrimary)
  2902. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  2903. let sub = textLabel(subtitle, font: typography.fieldLabel, color: palette.textSecondary)
  2904. sub.translatesAutoresizingMaskIntoConstraints = false
  2905. panel.addSubview(titleLabel)
  2906. panel.addSubview(sub)
  2907. NSLayoutConstraint.activate([
  2908. titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  2909. titleLabel.topAnchor.constraint(equalTo: panel.topAnchor),
  2910. sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  2911. sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8)
  2912. ])
  2913. return panel
  2914. }
  2915. private func makeSettingsPageContent() -> NSView {
  2916. let panel = NSView()
  2917. panel.translatesAutoresizingMaskIntoConstraints = false
  2918. let scroll = NSScrollView()
  2919. scroll.translatesAutoresizingMaskIntoConstraints = false
  2920. scroll.drawsBackground = false
  2921. scroll.hasHorizontalScroller = false
  2922. scroll.hasVerticalScroller = true
  2923. scroll.autohidesScrollers = true
  2924. scroll.borderType = .noBorder
  2925. scroll.scrollerStyle = .overlay
  2926. scroll.automaticallyAdjustsContentInsets = false
  2927. let clip = TopAlignedClipView()
  2928. clip.drawsBackground = false
  2929. scroll.contentView = clip
  2930. panel.addSubview(scroll)
  2931. let content = NSView()
  2932. content.translatesAutoresizingMaskIntoConstraints = false
  2933. scroll.documentView = content
  2934. let card = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
  2935. card.translatesAutoresizingMaskIntoConstraints = false
  2936. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
  2937. content.addSubview(card)
  2938. let stack = NSStackView()
  2939. stack.translatesAutoresizingMaskIntoConstraints = false
  2940. stack.orientation = .vertical
  2941. stack.spacing = 18
  2942. stack.alignment = .leading
  2943. card.addSubview(stack)
  2944. let pageTitle = textLabel("Settings", font: typography.pageTitle, color: palette.textPrimary)
  2945. let pageSubtitle = textLabel("Manage appearance, account, and app options.", font: typography.fieldLabel, color: palette.textSecondary)
  2946. stack.addArrangedSubview(pageTitle)
  2947. stack.addArrangedSubview(pageSubtitle)
  2948. stack.setCustomSpacing(24, after: pageSubtitle)
  2949. let appearanceTitle = textLabel("Appearance", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2950. stack.addArrangedSubview(appearanceTitle)
  2951. let darkModeRow = makeSettingsDarkModeRow()
  2952. stack.addArrangedSubview(darkModeRow)
  2953. darkModeRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2954. stack.setCustomSpacing(24, after: darkModeRow)
  2955. let accountTitle = textLabel("Account", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2956. stack.addArrangedSubview(accountTitle)
  2957. let googleAccountRow = makeSettingsGoogleAccountRow()
  2958. stack.addArrangedSubview(googleAccountRow)
  2959. googleAccountRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2960. stack.setCustomSpacing(24, after: googleAccountRow)
  2961. let appTitle = textLabel("App", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2962. stack.addArrangedSubview(appTitle)
  2963. if shouldShowRateUsInSettings {
  2964. let rateButton = makeSettingsActionButton(icon: "★", title: "Rate Us", action: .rateUs)
  2965. stack.addArrangedSubview(rateButton)
  2966. rateButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2967. }
  2968. let shareButton = makeSettingsActionButton(icon: "⤴︎", title: "Share App", action: .shareApp)
  2969. stack.addArrangedSubview(shareButton)
  2970. shareButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2971. if storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess {
  2972. let upgradeButton = makeSettingsActionButton(icon: "⬆︎", title: "Upgrade", action: .upgrade)
  2973. stack.addArrangedSubview(upgradeButton)
  2974. upgradeButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2975. stack.setCustomSpacing(24, after: upgradeButton)
  2976. } else {
  2977. stack.setCustomSpacing(24, after: shareButton)
  2978. }
  2979. if storeKitCoordinator.hasPremiumAccess {
  2980. let notificationsTitle = textLabel("Notifications", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2981. stack.addArrangedSubview(notificationsTitle)
  2982. let remindersSection = makeSettingsRemindersSection()
  2983. stack.addArrangedSubview(remindersSection)
  2984. remindersSection.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2985. stack.setCustomSpacing(24, after: remindersSection)
  2986. }
  2987. let legalTitle = textLabel("Help & Legal", font: typography.joinWithURLTitle, color: palette.textPrimary)
  2988. stack.addArrangedSubview(legalTitle)
  2989. let privacyButton = makeSettingsActionButton(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy)
  2990. stack.addArrangedSubview(privacyButton)
  2991. privacyButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2992. let supportButton = makeSettingsActionButton(icon: "💬", title: "Support", action: .support)
  2993. stack.addArrangedSubview(supportButton)
  2994. supportButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2995. let termsButton = makeSettingsActionButton(icon: "📄", title: "Terms of Services", action: .termsOfServices)
  2996. stack.addArrangedSubview(termsButton)
  2997. termsButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  2998. NSLayoutConstraint.activate([
  2999. scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
  3000. scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
  3001. scroll.topAnchor.constraint(equalTo: panel.topAnchor),
  3002. scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),
  3003. content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  3004. content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  3005. content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  3006. content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
  3007. content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
  3008. card.centerXAnchor.constraint(equalTo: content.centerXAnchor),
  3009. card.topAnchor.constraint(equalTo: content.topAnchor, constant: 36),
  3010. content.bottomAnchor.constraint(greaterThanOrEqualTo: card.bottomAnchor, constant: 36),
  3011. card.widthAnchor.constraint(lessThanOrEqualToConstant: 620),
  3012. card.widthAnchor.constraint(greaterThanOrEqualToConstant: 460),
  3013. card.leadingAnchor.constraint(greaterThanOrEqualTo: content.leadingAnchor, constant: 30),
  3014. card.trailingAnchor.constraint(lessThanOrEqualTo: content.trailingAnchor, constant: -30),
  3015. stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 28),
  3016. stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -28),
  3017. stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 24),
  3018. stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -24)
  3019. ])
  3020. return panel
  3021. }
  3022. private func makeSettingsDarkModeRow() -> NSView {
  3023. let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  3024. row.translatesAutoresizingMaskIntoConstraints = false
  3025. row.heightAnchor.constraint(equalToConstant: 52).isActive = true
  3026. styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3027. let icon = textLabel("◐", font: NSFont.systemFont(ofSize: 18, weight: .medium), color: palette.textPrimary)
  3028. let title = textLabel("Dark Mode", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
  3029. let toggle = NSSwitch()
  3030. toggle.translatesAutoresizingMaskIntoConstraints = false
  3031. toggle.state = darkModeEnabled ? .on : .off
  3032. toggle.target = self
  3033. toggle.action = #selector(settingsPageDarkModeToggled(_:))
  3034. row.addSubview(icon)
  3035. row.addSubview(title)
  3036. row.addSubview(toggle)
  3037. NSLayoutConstraint.activate([
  3038. icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
  3039. icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3040. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
  3041. title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3042. toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
  3043. toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  3044. ])
  3045. return row
  3046. }
  3047. private func makeSettingsRemindersSection() -> NSView {
  3048. let container = NSStackView()
  3049. container.translatesAutoresizingMaskIntoConstraints = false
  3050. container.orientation = .vertical
  3051. container.spacing = 1
  3052. container.alignment = .leading
  3053. let masterRow = makeReminderToggleRow(
  3054. icon: "🔔",
  3055. title: "Reminders",
  3056. state: ReminderPreferences.remindersEnabled,
  3057. action: #selector(settingsReminderMasterToggled(_:)),
  3058. isSubRow: false
  3059. )
  3060. container.addArrangedSubview(masterRow)
  3061. masterRow.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
  3062. let subAlpha: CGFloat = ReminderPreferences.remindersEnabled ? 1.0 : 0.4
  3063. let day1Row = makeReminderToggleRow(
  3064. icon: "📅",
  3065. title: "1 Day Before",
  3066. state: ReminderPreferences.remind1Day,
  3067. action: #selector(settingsReminder1DayToggled(_:)),
  3068. isSubRow: true
  3069. )
  3070. day1Row.alphaValue = subAlpha
  3071. container.addArrangedSubview(day1Row)
  3072. day1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
  3073. let hours12Row = makeReminderToggleRow(
  3074. icon: "🕛",
  3075. title: "12 Hours Before",
  3076. state: ReminderPreferences.remind12Hours,
  3077. action: #selector(settingsReminder12HoursToggled(_:)),
  3078. isSubRow: true
  3079. )
  3080. hours12Row.alphaValue = subAlpha
  3081. container.addArrangedSubview(hours12Row)
  3082. hours12Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
  3083. let hour1Row = makeReminderToggleRow(
  3084. icon: "⏰",
  3085. title: "1 Hour Before",
  3086. state: ReminderPreferences.remind1Hour,
  3087. action: #selector(settingsReminder1HourToggled(_:)),
  3088. isSubRow: true
  3089. )
  3090. hour1Row.alphaValue = subAlpha
  3091. container.addArrangedSubview(hour1Row)
  3092. hour1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
  3093. settingsReminderMasterSwitch = masterRow.subviews.compactMap { $0 as? NSSwitch }.first
  3094. settingsReminder1DaySwitch = day1Row.subviews.compactMap { $0 as? NSSwitch }.first
  3095. settingsReminder12HoursSwitch = hours12Row.subviews.compactMap { $0 as? NSSwitch }.first
  3096. settingsReminder1HourSwitch = hour1Row.subviews.compactMap { $0 as? NSSwitch }.first
  3097. return container
  3098. }
  3099. private func makeReminderToggleRow(icon: String, title: String, state: Bool, action: Selector, isSubRow: Bool) -> NSView {
  3100. let row = roundedContainer(cornerRadius: 10, color: isSubRow ? palette.inputBackground.withAlphaComponent(0.6) : palette.inputBackground)
  3101. row.translatesAutoresizingMaskIntoConstraints = false
  3102. row.heightAnchor.constraint(equalToConstant: 48).isActive = true
  3103. styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3104. let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: isSubRow ? 15 : 17, weight: .medium), color: palette.textPrimary)
  3105. let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: isSubRow ? 14 : 15, weight: isSubRow ? .regular : .semibold), color: palette.textPrimary)
  3106. if isSubRow {
  3107. titleLabel.textColor = palette.textSecondary
  3108. }
  3109. let toggle = NSSwitch()
  3110. toggle.translatesAutoresizingMaskIntoConstraints = false
  3111. toggle.state = state ? .on : .off
  3112. toggle.target = self
  3113. toggle.action = action
  3114. row.addSubview(iconLabel)
  3115. row.addSubview(titleLabel)
  3116. row.addSubview(toggle)
  3117. NSLayoutConstraint.activate([
  3118. iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: isSubRow ? 30 : 14),
  3119. iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3120. titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
  3121. titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  3122. toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
  3123. toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  3124. ])
  3125. return row
  3126. }
  3127. @objc private func settingsReminderMasterToggled(_ sender: NSSwitch) {
  3128. let enabled = sender.state == .on
  3129. ReminderPreferences.remindersEnabled = enabled
  3130. let subAlpha: CGFloat = enabled ? 1.0 : 0.4
  3131. settingsReminder1DaySwitch?.superview?.alphaValue = subAlpha
  3132. settingsReminder12HoursSwitch?.superview?.alphaValue = subAlpha
  3133. settingsReminder1HourSwitch?.superview?.alphaValue = subAlpha
  3134. if enabled {
  3135. MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
  3136. guard let self else { return }
  3137. MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
  3138. }
  3139. } else {
  3140. MeetingReminderManager.shared.cancelAllReminders()
  3141. }
  3142. }
  3143. @objc private func settingsReminder1DayToggled(_ sender: NSSwitch) {
  3144. ReminderPreferences.remind1Day = sender.state == .on
  3145. MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
  3146. }
  3147. @objc private func settingsReminder12HoursToggled(_ sender: NSSwitch) {
  3148. ReminderPreferences.remind12Hours = sender.state == .on
  3149. MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
  3150. }
  3151. @objc private func settingsReminder1HourToggled(_ sender: NSSwitch) {
  3152. ReminderPreferences.remind1Hour = sender.state == .on
  3153. MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
  3154. }
  3155. private func makeSettingsGoogleAccountRow() -> NSView {
  3156. let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  3157. row.translatesAutoresizingMaskIntoConstraints = false
  3158. styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3159. let signedIn = hasGoogleSessionAvailable()
  3160. let titleText = signedIn ? (scheduleCurrentProfile?.name ?? "Google account connected") : "Google account not connected"
  3161. let subtitleText = signedIn ? (scheduleCurrentProfile?.email ?? "Signed in") : "Sign in to sync your meetings and calendar."
  3162. let title = textLabel(titleText, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
  3163. let subtitle = textLabel(subtitleText, font: NSFont.systemFont(ofSize: 13, weight: .regular), color: palette.textSecondary)
  3164. subtitle.maximumNumberOfLines = 2
  3165. subtitle.lineBreakMode = .byTruncatingTail
  3166. let actionButton = NSButton(title: signedIn ? "Sign Out" : "Sign in with Google", target: self, action: #selector(settingsGoogleActionButtonClicked(_:)))
  3167. actionButton.translatesAutoresizingMaskIntoConstraints = false
  3168. actionButton.bezelStyle = .rounded
  3169. actionButton.controlSize = .regular
  3170. row.addSubview(title)
  3171. row.addSubview(subtitle)
  3172. row.addSubview(actionButton)
  3173. NSLayoutConstraint.activate([
  3174. row.heightAnchor.constraint(equalToConstant: 78),
  3175. title.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
  3176. title.topAnchor.constraint(equalTo: row.topAnchor, constant: 12),
  3177. subtitle.leadingAnchor.constraint(equalTo: title.leadingAnchor),
  3178. subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 4),
  3179. subtitle.trailingAnchor.constraint(lessThanOrEqualTo: actionButton.leadingAnchor, constant: -14),
  3180. actionButton.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
  3181. actionButton.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  3182. ])
  3183. return row
  3184. }
  3185. private func makeSettingsActionButton(icon: String, title: String, action: SettingsAction) -> NSButton {
  3186. let button = HoverButton(title: "", target: self, action: #selector(settingsPageActionButtonClicked(_:)))
  3187. button.translatesAutoresizingMaskIntoConstraints = false
  3188. button.isBordered = false
  3189. button.wantsLayer = true
  3190. button.layer?.cornerRadius = 10
  3191. button.layer?.backgroundColor = palette.inputBackground.cgColor
  3192. styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3193. button.heightAnchor.constraint(equalToConstant: 46).isActive = true
  3194. button.tag = action.rawValue
  3195. let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 17, weight: .medium), color: palette.textPrimary)
  3196. let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
  3197. button.addSubview(iconLabel)
  3198. button.addSubview(titleLabel)
  3199. NSLayoutConstraint.activate([
  3200. iconLabel.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 14),
  3201. iconLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  3202. titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
  3203. titleLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor)
  3204. ])
  3205. return button
  3206. }
  3207. @objc private func settingsPageDarkModeToggled(_ sender: NSSwitch) {
  3208. setDarkMode(sender.state == .on)
  3209. }
  3210. @objc private func settingsPageActionButtonClicked(_ sender: NSButton) {
  3211. guard let action = SettingsAction(rawValue: sender.tag) else { return }
  3212. let clickPoint: NSPoint?
  3213. if let event = NSApp.currentEvent {
  3214. let pointInWindow = event.locationInWindow
  3215. clickPoint = sender.convert(pointInWindow, from: nil)
  3216. } else {
  3217. clickPoint = nil
  3218. }
  3219. handleSettingsAction(action, sourceView: sender, clickLocationInSourceView: clickPoint)
  3220. }
  3221. @objc private func settingsGoogleActionButtonClicked(_ sender: NSButton) {
  3222. if hasGoogleSessionAvailable() == false {
  3223. scheduleConnectClicked()
  3224. } else {
  3225. performGoogleSignOut()
  3226. }
  3227. }
  3228. func makeBrowseWebContent() -> NSView {
  3229. let panel = NSView()
  3230. panel.translatesAutoresizingMaskIntoConstraints = false
  3231. let titleLabel = textLabel("Browse the web", font: typography.pageTitle, color: palette.textPrimary)
  3232. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  3233. let sub = textLabel(
  3234. "Open sites in the in-app browser (back, forward, reload, address bar). OAuth and “Continue in browser” flows stay inside the app.",
  3235. font: typography.fieldLabel,
  3236. color: palette.textSecondary
  3237. )
  3238. sub.translatesAutoresizingMaskIntoConstraints = false
  3239. sub.maximumNumberOfLines = 0
  3240. sub.lineBreakMode = .byWordWrapping
  3241. let fieldShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  3242. fieldShell.translatesAutoresizingMaskIntoConstraints = false
  3243. fieldShell.heightAnchor.constraint(equalToConstant: 44).isActive = true
  3244. styleSurface(fieldShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3245. let field = NSTextField(string: "")
  3246. field.translatesAutoresizingMaskIntoConstraints = false
  3247. field.isEditable = true
  3248. field.isBordered = false
  3249. field.drawsBackground = false
  3250. field.focusRingType = .none
  3251. field.font = NSFont.systemFont(ofSize: 14, weight: .regular)
  3252. field.textColor = palette.textPrimary
  3253. field.placeholderString = "https://example.com or example.com"
  3254. field.delegate = self
  3255. browseAddressField = field
  3256. fieldShell.addSubview(field)
  3257. let openBtn = meetActionButton(
  3258. title: "Open in app browser",
  3259. color: palette.primaryBlue,
  3260. textColor: .white,
  3261. width: 220,
  3262. action: #selector(browseOpenAddressClicked(_:))
  3263. )
  3264. let quickTitle = textLabel("Quick links", font: typography.joinWithURLTitle, color: palette.textPrimary)
  3265. quickTitle.translatesAutoresizingMaskIntoConstraints = false
  3266. let quickRow = NSStackView()
  3267. quickRow.translatesAutoresizingMaskIntoConstraints = false
  3268. quickRow.orientation = .horizontal
  3269. quickRow.spacing = 10
  3270. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Google Meet", action: #selector(browseQuickLinkMeetClicked(_:))))
  3271. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Meet help", action: #selector(browseQuickLinkMeetHelpClicked(_:))))
  3272. quickRow.addArrangedSubview(browseQuickLinkButton(title: "Zoom help", action: #selector(browseQuickLinkZoomHelpClicked(_:))))
  3273. panel.addSubview(titleLabel)
  3274. panel.addSubview(sub)
  3275. panel.addSubview(fieldShell)
  3276. panel.addSubview(openBtn)
  3277. panel.addSubview(quickTitle)
  3278. panel.addSubview(quickRow)
  3279. NSLayoutConstraint.activate([
  3280. titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  3281. titleLabel.topAnchor.constraint(equalTo: panel.topAnchor, constant: 26),
  3282. titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
  3283. sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  3284. sub.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
  3285. sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
  3286. fieldShell.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  3287. fieldShell.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  3288. fieldShell.topAnchor.constraint(equalTo: sub.bottomAnchor, constant: 18),
  3289. field.leadingAnchor.constraint(equalTo: fieldShell.leadingAnchor, constant: 12),
  3290. field.trailingAnchor.constraint(equalTo: fieldShell.trailingAnchor, constant: -12),
  3291. field.centerYAnchor.constraint(equalTo: fieldShell.centerYAnchor),
  3292. openBtn.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  3293. openBtn.topAnchor.constraint(equalTo: fieldShell.bottomAnchor, constant: 12),
  3294. openBtn.heightAnchor.constraint(equalToConstant: 36),
  3295. quickTitle.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  3296. quickTitle.topAnchor.constraint(equalTo: openBtn.bottomAnchor, constant: 28),
  3297. quickRow.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  3298. quickRow.topAnchor.constraint(equalTo: quickTitle.bottomAnchor, constant: 10)
  3299. ])
  3300. return panel
  3301. }
  3302. private func browseQuickLinkButton(title: String, action: Selector) -> NSButton {
  3303. let b = NSButton(title: title, target: self, action: action)
  3304. b.translatesAutoresizingMaskIntoConstraints = false
  3305. b.bezelStyle = .rounded
  3306. b.font = NSFont.systemFont(ofSize: 13, weight: .medium)
  3307. return b
  3308. }
  3309. private func applyWindowTitle(for page: SidebarPage) {
  3310. let title: String
  3311. switch page {
  3312. case .joinMeetings:
  3313. title = "App for Google Meet"
  3314. case .photo:
  3315. title = "Schedule"
  3316. case .video:
  3317. title = "Calendar"
  3318. case .widgets:
  3319. title = "Widgets"
  3320. case .settings:
  3321. title = "Settings"
  3322. case .aiCompanion:
  3323. title = "Ai companion"
  3324. }
  3325. view.window?.title = title
  3326. }
  3327. private func configureMainWindowChrome(_ window: NSWindow) {
  3328. window.styleMask.insert(.fullSizeContentView)
  3329. window.titleVisibility = .hidden
  3330. window.titlebarAppearsTransparent = true
  3331. window.isMovableByWindowBackground = true
  3332. }
  3333. private func updateSidebarAppearance() {
  3334. for (page, row) in sidebarRowViews {
  3335. applySidebarRowStyle(row, page: page, logoTemplate: logoTemplateForSidebarPage(page))
  3336. }
  3337. }
  3338. private func logoTemplateForSidebarPage(_ page: SidebarPage) -> Bool {
  3339. switch page {
  3340. case .photo: return false
  3341. case .joinMeetings, .video, .widgets, .settings, .aiCompanion: return true
  3342. }
  3343. }
  3344. func makeSidebar() -> NSView {
  3345. let sidebar = NSView()
  3346. sidebar.translatesAutoresizingMaskIntoConstraints = false
  3347. sidebar.wantsLayer = true
  3348. sidebar.layer?.backgroundColor = palette.sidebarBackground.cgColor
  3349. sidebar.layer?.borderColor = palette.separator.cgColor
  3350. sidebar.layer?.borderWidth = 1
  3351. sidebar.layer?.shadowColor = NSColor.black.cgColor
  3352. sidebar.layer?.shadowOpacity = 0.18
  3353. sidebar.layer?.shadowOffset = CGSize(width: 2, height: 0)
  3354. sidebar.layer?.shadowRadius = 10
  3355. sidebar.widthAnchor.constraint(equalToConstant: 210).isActive = true
  3356. let sidebarTopInset: CGFloat = 44
  3357. let appIconView = NSImageView()
  3358. if let headerLogo = NSImage(named: "HeaderLogo") {
  3359. headerLogo.isTemplate = false
  3360. appIconView.image = headerLogo
  3361. } else if let appIconImage = NSApplication.shared.applicationIconImage {
  3362. appIconImage.isTemplate = false
  3363. appIconView.image = appIconImage
  3364. }
  3365. appIconView.translatesAutoresizingMaskIntoConstraints = false
  3366. appIconView.imageScaling = NSImageScaling.scaleProportionallyDown
  3367. appIconView.imageAlignment = NSImageAlignment.alignCenter
  3368. appIconView.contentTintColor = nil
  3369. appIconView.widthAnchor.constraint(equalToConstant: 44).isActive = true
  3370. appIconView.heightAnchor.constraint(equalToConstant: 44).isActive = true
  3371. let titleRow = NSStackView(views: [
  3372. appIconView,
  3373. textLabel("Meetings", font: typography.sidebarBrand, color: palette.textPrimary)
  3374. ])
  3375. titleRow.translatesAutoresizingMaskIntoConstraints = false
  3376. titleRow.orientation = NSUserInterfaceLayoutOrientation.horizontal
  3377. titleRow.alignment = NSLayoutConstraint.Attribute.centerY
  3378. titleRow.spacing = 16
  3379. let menuStack = NSStackView()
  3380. menuStack.translatesAutoresizingMaskIntoConstraints = false
  3381. menuStack.orientation = .vertical
  3382. menuStack.alignment = .leading
  3383. menuStack.spacing = 10
  3384. menuStack.addArrangedSubview(sidebarSectionTitle("Meetings"))
  3385. let joinRow = sidebarItem("Join Meetings", icon: "􀉣", page: .joinMeetings, logoImageName: "JoinMeetingsLogo", logoIconWidth: 24, logoHeightMultiplier: 56.0 / 52.0)
  3386. menuStack.addArrangedSubview(joinRow)
  3387. sidebarRowViews[.joinMeetings] = joinRow
  3388. menuStack.addArrangedSubview(sidebarSectionTitle("Planning"))
  3389. let photoRow = sidebarItem("Schedule", icon: "􀏂", page: .photo, systemSymbolName: "clock.badge.checkmark")
  3390. menuStack.addArrangedSubview(photoRow)
  3391. sidebarRowViews[.photo] = photoRow
  3392. let videoRow = sidebarItem("Calendar", icon: "􀎚", page: .video, systemSymbolName: "calendar")
  3393. menuStack.addArrangedSubview(videoRow)
  3394. sidebarRowViews[.video] = videoRow
  3395. let widgetsRow = sidebarItem("Widgets", icon: "􀏅", page: .widgets, systemSymbolName: "square.grid.2x2.fill")
  3396. menuStack.addArrangedSubview(widgetsRow)
  3397. sidebarRowViews[.widgets] = widgetsRow
  3398. let aiCompanionRow = sidebarItem("Ai companion", icon: "􀁚", page: .aiCompanion, systemSymbolName: "waveform")
  3399. menuStack.addArrangedSubview(aiCompanionRow)
  3400. sidebarRowViews[.aiCompanion] = aiCompanionRow
  3401. menuStack.addArrangedSubview(sidebarSectionTitle("Additional"))
  3402. let settingsRow = sidebarItem("Settings", icon: "􀍟", page: .settings, systemSymbolName: "gearshape.fill", logoHeightMultiplier: 1, showsDisclosure: true)
  3403. menuStack.addArrangedSubview(settingsRow)
  3404. sidebarRowViews[.settings] = settingsRow
  3405. let premiumButton = sidebarPremiumButton()
  3406. sidebar.addSubview(titleRow)
  3407. sidebar.addSubview(menuStack)
  3408. sidebar.addSubview(premiumButton)
  3409. NSLayoutConstraint.activate([
  3410. titleRow.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 16),
  3411. titleRow.topAnchor.constraint(equalTo: sidebar.topAnchor, constant: sidebarTopInset),
  3412. titleRow.trailingAnchor.constraint(lessThanOrEqualTo: sidebar.trailingAnchor, constant: -16),
  3413. menuStack.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
  3414. menuStack.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
  3415. menuStack.topAnchor.constraint(equalTo: titleRow.bottomAnchor, constant: 20),
  3416. menuStack.bottomAnchor.constraint(lessThanOrEqualTo: premiumButton.topAnchor, constant: -16),
  3417. premiumButton.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
  3418. premiumButton.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
  3419. premiumButton.bottomAnchor.constraint(equalTo: sidebar.bottomAnchor, constant: -14)
  3420. ])
  3421. for subview in menuStack.arrangedSubviews {
  3422. subview.widthAnchor.constraint(equalTo: menuStack.widthAnchor).isActive = true
  3423. }
  3424. return sidebar
  3425. }
  3426. func sidebarPremiumButton() -> NSView {
  3427. let button = HoverTrackingView()
  3428. button.translatesAutoresizingMaskIntoConstraints = false
  3429. button.wantsLayer = true
  3430. button.layer?.cornerRadius = 17
  3431. button.layer?.backgroundColor = palette.primaryBlue.cgColor
  3432. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  3433. styleSurface(button, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: false)
  3434. let icon = NSImageView()
  3435. icon.translatesAutoresizingMaskIntoConstraints = false
  3436. icon.imageScaling = .scaleProportionallyUpOrDown
  3437. icon.contentTintColor = .white
  3438. icon.image = premiumButtonSymbolImage(named: "star.fill")
  3439. let title = textLabel("Get Premium", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: .white)
  3440. button.addSubview(icon)
  3441. button.addSubview(title)
  3442. NSLayoutConstraint.activate([
  3443. icon.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 12),
  3444. icon.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  3445. icon.widthAnchor.constraint(equalToConstant: 14),
  3446. icon.heightAnchor.constraint(equalToConstant: 14),
  3447. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 8),
  3448. title.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  3449. title.trailingAnchor.constraint(lessThanOrEqualTo: button.trailingAnchor, constant: -12)
  3450. ])
  3451. button.onHoverChanged = { [weak self, weak button] hovering in
  3452. guard let self, let button else { return }
  3453. let isPremium = self.storeKitCoordinator.hasPremiumAccess
  3454. let baseColor = isPremium
  3455. ? NSColor(calibratedRed: 0.93, green: 0.73, blue: 0.16, alpha: 1.0)
  3456. : self.palette.primaryBlue
  3457. let borderColor = isPremium
  3458. ? NSColor(calibratedRed: 0.78, green: 0.56, blue: 0.10, alpha: 1.0)
  3459. : self.palette.primaryBlueBorder
  3460. let hoverColor: NSColor
  3461. let hoverBorderColor: NSColor
  3462. if isPremium {
  3463. // Darker rich-gold hover for stronger premium feedback.
  3464. hoverColor = NSColor(calibratedRed: 0.84, green: 0.62, blue: 0.11, alpha: 1.0)
  3465. hoverBorderColor = NSColor(calibratedRed: 0.67, green: 0.46, blue: 0.07, alpha: 1.0)
  3466. } else {
  3467. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  3468. hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  3469. hoverBorderColor = borderColor
  3470. }
  3471. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  3472. button.layer?.shadowColor = NSColor.black.cgColor
  3473. button.layer?.shadowOpacity = hovering ? (isPremium ? 0.30 : 0.20) : 0.14
  3474. button.layer?.shadowOffset = CGSize(width: 0, height: -1)
  3475. button.layer?.shadowRadius = hovering ? (isPremium ? 8 : 6) : 4
  3476. self.styleSurface(button, borderColor: (hovering ? hoverBorderColor : borderColor), borderWidth: hovering ? 1.5 : 1, shadow: false)
  3477. }
  3478. button.onHoverChanged?(false)
  3479. sidebarPremiumTitleLabel = title
  3480. sidebarPremiumIconView = icon
  3481. sidebarPremiumButtonView = button
  3482. refreshSidebarPremiumButton()
  3483. let click = NSClickGestureRecognizer(target: self, action: #selector(premiumButtonClicked(_:)))
  3484. button.addGestureRecognizer(click)
  3485. return button
  3486. }
  3487. func makeMainPanel() -> NSView {
  3488. let panel = NSView()
  3489. panel.translatesAutoresizingMaskIntoConstraints = false
  3490. panel.wantsLayer = true
  3491. panel.layer?.backgroundColor = palette.pageBackground.cgColor
  3492. let authBar = scheduleTopAuthRow()
  3493. authBar.translatesAutoresizingMaskIntoConstraints = false
  3494. panel.addSubview(authBar)
  3495. let host = NSView()
  3496. host.translatesAutoresizingMaskIntoConstraints = false
  3497. panel.addSubview(host)
  3498. let hostTopToAuth = host.topAnchor.constraint(equalTo: authBar.bottomAnchor, constant: 20)
  3499. let hostTopToPanel = host.topAnchor.constraint(equalTo: panel.topAnchor)
  3500. hostTopToPanel.isActive = false
  3501. NSLayoutConstraint.activate([
  3502. authBar.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  3503. authBar.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  3504. authBar.topAnchor.constraint(equalTo: panel.safeAreaLayoutGuide.topAnchor, constant: 26),
  3505. host.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
  3506. host.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
  3507. hostTopToAuth,
  3508. host.bottomAnchor.constraint(equalTo: panel.bottomAnchor)
  3509. ])
  3510. mainContentHost = host
  3511. mainPanelAuthBar = authBar
  3512. mainContentHostTopToAuthConstraint = hostTopToAuth
  3513. mainContentHostTopToPanelConstraint = hostTopToPanel
  3514. if hasGoogleSessionAvailable(), let profile = scheduleCurrentProfile {
  3515. applyGoogleProfile(profile)
  3516. }
  3517. // Preserve the currently selected page during rebuilds (e.g. dark mode toggle).
  3518. showSidebarPage(selectedSidebarPage)
  3519. return panel
  3520. }
  3521. func makeJoinMeetingsContent() -> NSView {
  3522. let panel = NSView()
  3523. panel.translatesAutoresizingMaskIntoConstraints = false
  3524. let contentStack = NSStackView()
  3525. contentStack.translatesAutoresizingMaskIntoConstraints = false
  3526. contentStack.orientation = .vertical
  3527. contentStack.spacing = 14
  3528. contentStack.alignment = .leading
  3529. let joinActions = meetJoinActionsRow()
  3530. contentStack.addArrangedSubview(textLabel("Join Meetings", font: typography.pageTitle, color: palette.textPrimary))
  3531. contentStack.addArrangedSubview(meetJoinSectionRow())
  3532. contentStack.addArrangedSubview(joinActions)
  3533. contentStack.setCustomSpacing(26, after: joinActions)
  3534. let scheduleHeaderView = scheduleHeader()
  3535. contentStack.addArrangedSubview(scheduleHeaderView)
  3536. contentStack.setCustomSpacing(joinPageScheduleHeaderToDateSpacing, after: scheduleHeaderView)
  3537. let dateHeading = textLabel(scheduleInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
  3538. scheduleDateHeadingLabel = dateHeading
  3539. contentStack.addArrangedSubview(dateHeading)
  3540. contentStack.setCustomSpacing(joinPageDateToMeetingCardsSpacing, after: dateHeading)
  3541. let cardsRow = scheduleCardsRow(meetings: [])
  3542. contentStack.addArrangedSubview(cardsRow)
  3543. panel.addSubview(contentStack)
  3544. NSLayoutConstraint.activate([
  3545. contentStack.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
  3546. contentStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
  3547. contentStack.topAnchor.constraint(equalTo: panel.topAnchor)
  3548. ])
  3549. Task { [weak self] in
  3550. await self?.loadSchedule()
  3551. }
  3552. return panel
  3553. }
  3554. func makeSchedulePageContent() -> NSView {
  3555. let panel = NSView()
  3556. panel.translatesAutoresizingMaskIntoConstraints = false
  3557. panel.userInterfaceLayoutDirection = .leftToRight
  3558. let contentStack = NSStackView()
  3559. contentStack.translatesAutoresizingMaskIntoConstraints = false
  3560. contentStack.userInterfaceLayoutDirection = .leftToRight
  3561. contentStack.orientation = .vertical
  3562. contentStack.spacing = schedulePageStackSpacing
  3563. contentStack.alignment = .width
  3564. contentStack.distribution = .fill
  3565. let header = schedulePageHeader()
  3566. header.setContentHuggingPriority(.required, for: .vertical)
  3567. header.setContentCompressionResistancePriority(.required, for: .vertical)
  3568. contentStack.addArrangedSubview(header)
  3569. contentStack.setCustomSpacing(schedulePageHeaderToDateSpacing, after: header)
  3570. let heading = textLabel(schedulePageInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
  3571. heading.alignment = .left
  3572. heading.setContentHuggingPriority(.required, for: .vertical)
  3573. heading.setContentCompressionResistancePriority(.required, for: .vertical)
  3574. schedulePageDateHeadingLabel = heading
  3575. contentStack.addArrangedSubview(heading)
  3576. let rangeError = textLabel("", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: .systemRed)
  3577. rangeError.alignment = .left
  3578. rangeError.isHidden = true
  3579. rangeError.setContentHuggingPriority(.required, for: .vertical)
  3580. rangeError.setContentCompressionResistancePriority(.required, for: .vertical)
  3581. schedulePageRangeErrorLabel = rangeError
  3582. contentStack.addArrangedSubview(rangeError)
  3583. let cardsContainer = makeSchedulePageCardsContainer()
  3584. cardsContainer.setContentHuggingPriority(.defaultLow, for: .vertical)
  3585. contentStack.addArrangedSubview(cardsContainer)
  3586. panel.addSubview(contentStack)
  3587. NSLayoutConstraint.activate([
  3588. contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: schedulePageLeadingInset),
  3589. contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -schedulePageTrailingInset),
  3590. contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
  3591. contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -16),
  3592. header.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3593. heading.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3594. rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3595. cardsContainer.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
  3596. ])
  3597. Task { [weak self] in
  3598. await self?.loadSchedule()
  3599. }
  3600. return panel
  3601. }
  3602. func makeCalendarPageContent() -> NSView {
  3603. let panel = NSView()
  3604. panel.translatesAutoresizingMaskIntoConstraints = false
  3605. panel.userInterfaceLayoutDirection = .leftToRight
  3606. let contentStack = NSStackView()
  3607. contentStack.translatesAutoresizingMaskIntoConstraints = false
  3608. contentStack.userInterfaceLayoutDirection = .leftToRight
  3609. contentStack.orientation = .vertical
  3610. contentStack.spacing = 14
  3611. contentStack.alignment = .width
  3612. contentStack.distribution = .fill
  3613. let titleRow = NSStackView()
  3614. titleRow.translatesAutoresizingMaskIntoConstraints = false
  3615. titleRow.userInterfaceLayoutDirection = .leftToRight
  3616. titleRow.orientation = .horizontal
  3617. titleRow.alignment = .centerY
  3618. titleRow.distribution = .fill
  3619. titleRow.spacing = 10
  3620. let titleLabel = textLabel("Calendar", font: typography.pageTitle, color: palette.textPrimary)
  3621. titleLabel.alignment = .left
  3622. titleLabel.maximumNumberOfLines = 1
  3623. titleLabel.lineBreakMode = .byTruncatingTail
  3624. titleLabel.setContentHuggingPriority(.required, for: .horizontal)
  3625. titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  3626. let spacer = NSView()
  3627. spacer.translatesAutoresizingMaskIntoConstraints = false
  3628. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  3629. spacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  3630. let prevButton = makeCalendarHeaderPillButton(title: "‹", action: #selector(calendarPrevMonthPressed(_:)))
  3631. prevButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
  3632. let nextButton = makeCalendarHeaderPillButton(title: "›", action: #selector(calendarNextMonthPressed(_:)))
  3633. nextButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
  3634. let monthLabel = textLabel("", font: NSFont.systemFont(ofSize: 16, weight: .semibold), color: palette.textSecondary)
  3635. monthLabel.alignment = .right
  3636. monthLabel.maximumNumberOfLines = 1
  3637. monthLabel.lineBreakMode = .byTruncatingTail
  3638. monthLabel.setContentHuggingPriority(.required, for: .horizontal)
  3639. monthLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  3640. calendarPageMonthLabel = monthLabel
  3641. let refreshButton = HoverButton(title: "", target: self, action: #selector(calendarRefreshPressed(_:)))
  3642. refreshButton.translatesAutoresizingMaskIntoConstraints = false
  3643. refreshButton.isBordered = false
  3644. refreshButton.bezelStyle = .regularSquare
  3645. refreshButton.wantsLayer = true
  3646. refreshButton.layer?.cornerRadius = 15
  3647. refreshButton.layer?.masksToBounds = true
  3648. refreshButton.layer?.backgroundColor = palette.inputBackground.cgColor
  3649. refreshButton.layer?.borderColor = palette.inputBorder.cgColor
  3650. refreshButton.layer?.borderWidth = 1
  3651. refreshButton.setButtonType(.momentaryChange)
  3652. refreshButton.contentTintColor = palette.textSecondary
  3653. refreshButton.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Sync calendar")
  3654. refreshButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  3655. refreshButton.imagePosition = .imageOnly
  3656. refreshButton.imageScaling = .scaleProportionallyDown
  3657. refreshButton.focusRingType = .none
  3658. refreshButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
  3659. refreshButton.widthAnchor.constraint(equalToConstant: 32).isActive = true
  3660. titleRow.addArrangedSubview(titleLabel)
  3661. titleRow.addArrangedSubview(spacer)
  3662. titleRow.addArrangedSubview(prevButton)
  3663. titleRow.addArrangedSubview(nextButton)
  3664. titleRow.addArrangedSubview(monthLabel)
  3665. titleRow.addArrangedSubview(refreshButton)
  3666. let weekdayRow = NSStackView()
  3667. weekdayRow.translatesAutoresizingMaskIntoConstraints = false
  3668. weekdayRow.userInterfaceLayoutDirection = .leftToRight
  3669. weekdayRow.orientation = .horizontal
  3670. weekdayRow.alignment = .centerY
  3671. weekdayRow.distribution = .fillEqually
  3672. weekdayRow.spacing = 12
  3673. for symbol in calendarWeekdaySymbolsStartingAtFirstWeekday() {
  3674. let label = textLabel(symbol, font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textMuted)
  3675. label.alignment = .center
  3676. label.maximumNumberOfLines = 1
  3677. label.lineBreakMode = .byClipping
  3678. weekdayRow.addArrangedSubview(label)
  3679. }
  3680. let gridStack = NSStackView()
  3681. gridStack.translatesAutoresizingMaskIntoConstraints = false
  3682. gridStack.userInterfaceLayoutDirection = .leftToRight
  3683. gridStack.orientation = .vertical
  3684. gridStack.alignment = .width
  3685. gridStack.distribution = .fillEqually
  3686. gridStack.spacing = 10
  3687. calendarPageGridStack = gridStack
  3688. let gridCard = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
  3689. gridCard.translatesAutoresizingMaskIntoConstraints = false
  3690. styleSurface(gridCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3691. let gridHeightConstraint = gridCard.heightAnchor.constraint(equalToConstant: 360)
  3692. gridHeightConstraint.isActive = true
  3693. calendarPageGridHeightConstraint = gridHeightConstraint
  3694. gridCard.heightAnchor.constraint(greaterThanOrEqualToConstant: 360).isActive = true
  3695. gridCard.addSubview(gridStack)
  3696. NSLayoutConstraint.activate([
  3697. gridStack.leadingAnchor.constraint(equalTo: gridCard.leadingAnchor, constant: 16),
  3698. gridStack.trailingAnchor.constraint(equalTo: gridCard.trailingAnchor, constant: -16),
  3699. gridStack.topAnchor.constraint(equalTo: gridCard.topAnchor, constant: 16),
  3700. gridStack.bottomAnchor.constraint(equalTo: gridCard.bottomAnchor, constant: -16)
  3701. ])
  3702. let daySummary = textLabel("", font: typography.dateHeading, color: palette.textSecondary)
  3703. daySummary.alignment = .left
  3704. daySummary.maximumNumberOfLines = 2
  3705. daySummary.lineBreakMode = .byWordWrapping
  3706. calendarPageDaySummaryLabel = daySummary
  3707. contentStack.addArrangedSubview(titleRow)
  3708. contentStack.setCustomSpacing(16, after: titleRow)
  3709. contentStack.addArrangedSubview(weekdayRow)
  3710. contentStack.setCustomSpacing(10, after: weekdayRow)
  3711. contentStack.addArrangedSubview(gridCard)
  3712. contentStack.setCustomSpacing(16, after: gridCard)
  3713. contentStack.addArrangedSubview(daySummary)
  3714. panel.addSubview(contentStack)
  3715. NSLayoutConstraint.activate([
  3716. contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: 28),
  3717. contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -28),
  3718. contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
  3719. contentStack.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16),
  3720. titleRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3721. weekdayRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3722. gridCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
  3723. daySummary.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
  3724. ])
  3725. if !storeKitCoordinator.hasPremiumAccess {
  3726. let lockOverlay = NSVisualEffectView()
  3727. lockOverlay.translatesAutoresizingMaskIntoConstraints = false
  3728. lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
  3729. lockOverlay.blendingMode = .withinWindow
  3730. lockOverlay.state = .active
  3731. lockOverlay.wantsLayer = true
  3732. lockOverlay.layer?.cornerRadius = 14
  3733. lockOverlay.layer?.masksToBounds = true
  3734. lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.30 : 0.12).cgColor
  3735. panel.addSubview(lockOverlay)
  3736. let message = textLabel("Premium required. Get Premium now to unlock Calendar.", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: darkModeEnabled ? .white : .black)
  3737. message.alignment = .center
  3738. message.maximumNumberOfLines = 2
  3739. message.lineBreakMode = .byWordWrapping
  3740. lockOverlay.addSubview(message)
  3741. let hit = HoverTrackingView()
  3742. hit.translatesAutoresizingMaskIntoConstraints = false
  3743. hit.wantsLayer = true
  3744. hit.layer?.backgroundColor = NSColor.clear.cgColor
  3745. hit.onClick = { [weak self] in
  3746. self?.showPaywall()
  3747. }
  3748. hit.toolTip = "Premium required. Click to open paywall."
  3749. lockOverlay.addSubview(hit)
  3750. NSLayoutConstraint.activate([
  3751. lockOverlay.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor),
  3752. lockOverlay.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor),
  3753. lockOverlay.topAnchor.constraint(equalTo: contentStack.topAnchor),
  3754. lockOverlay.bottomAnchor.constraint(equalTo: contentStack.bottomAnchor),
  3755. message.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
  3756. message.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
  3757. message.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 22),
  3758. message.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -22),
  3759. hit.leadingAnchor.constraint(equalTo: lockOverlay.leadingAnchor),
  3760. hit.trailingAnchor.constraint(equalTo: lockOverlay.trailingAnchor),
  3761. hit.topAnchor.constraint(equalTo: lockOverlay.topAnchor),
  3762. hit.bottomAnchor.constraint(equalTo: lockOverlay.bottomAnchor)
  3763. ])
  3764. }
  3765. let calendar = Calendar.current
  3766. calendarPageMonthAnchor = calendarStartOfMonth(for: Date())
  3767. calendarPageSelectedDate = calendar.startOfDay(for: Date())
  3768. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  3769. renderCalendarMonthGrid()
  3770. renderCalendarSelectedDay()
  3771. Task { [weak self] in
  3772. await self?.loadSchedule()
  3773. }
  3774. return panel
  3775. }
  3776. func meetJoinSectionRow() -> NSView {
  3777. let row = NSStackView()
  3778. row.translatesAutoresizingMaskIntoConstraints = false
  3779. row.orientation = .horizontal
  3780. row.spacing = 12
  3781. row.alignment = .top
  3782. row.distribution = .fillEqually
  3783. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
  3784. row.heightAnchor.constraint(equalToConstant: 140).isActive = true
  3785. let instant = HoverSurfaceView()
  3786. instant.translatesAutoresizingMaskIntoConstraints = false
  3787. instant.wantsLayer = true
  3788. instant.layer?.cornerRadius = 14
  3789. instant.layer?.backgroundColor = palette.sectionCard.cgColor
  3790. styleSurface(instant, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3791. let iconWrap = roundedContainer(cornerRadius: 12, color: NSColor.clear)
  3792. iconWrap.translatesAutoresizingMaskIntoConstraints = false
  3793. iconWrap.widthAnchor.constraint(equalToConstant: 58).isActive = true
  3794. iconWrap.heightAnchor.constraint(equalToConstant: 58).isActive = true
  3795. iconWrap.layer?.borderWidth = 0
  3796. let meetLogoImage = NSImage(named: "MeetLogo") ?? NSImage()
  3797. meetLogoImage.isTemplate = false
  3798. let meetLogo = NSImageView(image: meetLogoImage)
  3799. meetLogo.translatesAutoresizingMaskIntoConstraints = false
  3800. meetLogo.imageScaling = .scaleProportionallyDown
  3801. meetLogo.contentTintColor = nil
  3802. iconWrap.addSubview(meetLogo)
  3803. let instantTitle = textLabel("New Instant Meet", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
  3804. let instantSub = textLabel("Start instant Meet in more section with\nGoogle Meet meet.", font: NSFont.systemFont(ofSize: 16 / 2, weight: .medium), color: palette.textSecondary)
  3805. instantSub.maximumNumberOfLines = 2
  3806. instant.addSubview(iconWrap)
  3807. instant.addSubview(instantTitle)
  3808. instant.addSubview(instantSub)
  3809. let codeCard = HoverSurfaceView()
  3810. codeCard.translatesAutoresizingMaskIntoConstraints = false
  3811. codeCard.wantsLayer = true
  3812. codeCard.layer?.cornerRadius = 14
  3813. codeCard.layer?.backgroundColor = palette.sectionCard.cgColor
  3814. styleSurface(codeCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3815. let codeTitle = textLabel("Join with Link", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
  3816. let codeInputShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  3817. codeInputShell.translatesAutoresizingMaskIntoConstraints = false
  3818. codeInputShell.heightAnchor.constraint(equalToConstant: 52).isActive = true
  3819. styleSurface(codeInputShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3820. let codeField = NSTextField(string: "")
  3821. codeField.translatesAutoresizingMaskIntoConstraints = false
  3822. codeField.isEditable = true
  3823. codeField.isBordered = false
  3824. codeField.drawsBackground = false
  3825. codeField.focusRingType = .none
  3826. codeField.font = NSFont.systemFont(ofSize: 36 / 2, weight: .regular)
  3827. codeField.textColor = palette.textPrimary
  3828. codeField.placeholderString = "Code or meet.google.com/…"
  3829. codeInputShell.addSubview(codeField)
  3830. meetLinkField = codeField
  3831. codeCard.addSubview(codeTitle)
  3832. codeCard.addSubview(codeInputShell)
  3833. NSLayoutConstraint.activate([
  3834. meetLogo.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
  3835. meetLogo.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor),
  3836. meetLogo.widthAnchor.constraint(equalToConstant: 46),
  3837. meetLogo.heightAnchor.constraint(equalToConstant: 46),
  3838. iconWrap.leadingAnchor.constraint(equalTo: instant.leadingAnchor, constant: 18),
  3839. iconWrap.topAnchor.constraint(equalTo: instant.topAnchor, constant: 22),
  3840. instantTitle.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 14),
  3841. instantTitle.topAnchor.constraint(equalTo: instant.topAnchor, constant: 24),
  3842. instantSub.leadingAnchor.constraint(equalTo: instantTitle.leadingAnchor),
  3843. instantSub.topAnchor.constraint(equalTo: instantTitle.bottomAnchor, constant: 6),
  3844. instantSub.trailingAnchor.constraint(lessThanOrEqualTo: instant.trailingAnchor, constant: -16),
  3845. codeTitle.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
  3846. codeTitle.topAnchor.constraint(equalTo: codeCard.topAnchor, constant: 22),
  3847. codeInputShell.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
  3848. codeInputShell.trailingAnchor.constraint(equalTo: codeCard.trailingAnchor, constant: -18),
  3849. codeInputShell.topAnchor.constraint(equalTo: codeTitle.bottomAnchor, constant: 12),
  3850. codeField.leadingAnchor.constraint(equalTo: codeInputShell.leadingAnchor, constant: 14),
  3851. codeField.trailingAnchor.constraint(equalTo: codeInputShell.trailingAnchor, constant: -14),
  3852. codeField.centerYAnchor.constraint(equalTo: codeInputShell.centerYAnchor)
  3853. ])
  3854. let baseColor = palette.sectionCard
  3855. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  3856. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  3857. instant.onHoverChanged = { [weak self] hovering in
  3858. guard let self else { return }
  3859. instant.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  3860. }
  3861. codeCard.onHoverChanged = { [weak self] hovering in
  3862. guard let self else { return }
  3863. codeCard.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  3864. }
  3865. instant.onHoverChanged?(false)
  3866. codeCard.onHoverChanged?(false)
  3867. let instantClick = NSClickGestureRecognizer(target: self, action: #selector(instantMeetClicked(_:)))
  3868. instant.addGestureRecognizer(instantClick)
  3869. let joinWithLinkClick = NSClickGestureRecognizer(target: self, action: #selector(joinWithLinkCardClicked(_:)))
  3870. codeCard.addGestureRecognizer(joinWithLinkClick)
  3871. instantMeetCardView = instant
  3872. instantMeetTitleLabel = instantTitle
  3873. instantMeetSubtitleLabel = instantSub
  3874. joinWithLinkCardView = codeCard
  3875. joinWithLinkTitleLabel = codeTitle
  3876. refreshInstantMeetPremiumState()
  3877. row.addArrangedSubview(instant)
  3878. row.addArrangedSubview(codeCard)
  3879. return row
  3880. }
  3881. func meetJoinActionsRow() -> NSView {
  3882. let row = NSStackView()
  3883. row.translatesAutoresizingMaskIntoConstraints = false
  3884. row.orientation = .horizontal
  3885. row.spacing = 12
  3886. row.alignment = .centerY
  3887. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
  3888. let spacer = NSView()
  3889. spacer.translatesAutoresizingMaskIntoConstraints = false
  3890. row.addArrangedSubview(spacer)
  3891. row.addArrangedSubview(meetActionButton(
  3892. title: "Cancel",
  3893. color: palette.cancelButton,
  3894. textColor: palette.textSecondary,
  3895. width: 110,
  3896. action: #selector(cancelMeetJoinClicked(_:))
  3897. ))
  3898. let joinButton = meetActionButton(
  3899. title: "Join",
  3900. color: palette.primaryBlue,
  3901. textColor: .white,
  3902. width: 116,
  3903. action: #selector(joinMeetClicked(_:))
  3904. )
  3905. joinMeetPrimaryButton = joinButton
  3906. row.addArrangedSubview(joinButton)
  3907. refreshInstantMeetPremiumState()
  3908. return row
  3909. }
  3910. func meetActionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat, action: Selector) -> NSButton {
  3911. let button = HoverButton(title: title, target: self, action: action)
  3912. button.translatesAutoresizingMaskIntoConstraints = false
  3913. button.isBordered = false
  3914. button.bezelStyle = .regularSquare
  3915. button.wantsLayer = true
  3916. button.layer?.cornerRadius = 9
  3917. let baseBackground = color
  3918. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  3919. let hoverBackground = baseBackground.blended(withFraction: 0.10, of: hoverBlend) ?? baseBackground
  3920. let baseBorder = (title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder)
  3921. let hoverBorder = baseBorder.blended(withFraction: 0.18, of: hoverBlend) ?? baseBorder
  3922. button.layer?.backgroundColor = baseBackground.cgColor
  3923. button.layer?.borderColor = baseBorder.cgColor
  3924. button.layer?.borderWidth = 1
  3925. button.font = typography.buttonText
  3926. button.contentTintColor = textColor
  3927. button.widthAnchor.constraint(equalToConstant: width).isActive = true
  3928. button.heightAnchor.constraint(equalToConstant: 36).isActive = true
  3929. button.onHoverChanged = { [weak self, weak button] hovering in
  3930. guard let self, let button else { return }
  3931. button.layer?.backgroundColor = (hovering ? hoverBackground : baseBackground).cgColor
  3932. button.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  3933. if title == "Cancel" {
  3934. button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : textColor
  3935. }
  3936. }
  3937. button.onHoverChanged?(false)
  3938. return button
  3939. }
  3940. func makePaywallContent() -> NSView {
  3941. paywallPlanViews.removeAll()
  3942. premiumPlanByView.removeAll()
  3943. let panel = NSView()
  3944. panel.translatesAutoresizingMaskIntoConstraints = false
  3945. panel.wantsLayer = true
  3946. panel.layer?.backgroundColor = palette.pageBackground.cgColor
  3947. let contentStack = NSStackView()
  3948. contentStack.translatesAutoresizingMaskIntoConstraints = false
  3949. contentStack.orientation = .vertical
  3950. contentStack.spacing = 12
  3951. contentStack.distribution = .fill
  3952. contentStack.alignment = .centerX
  3953. panel.addSubview(contentStack)
  3954. let paywallLayoutWidth: CGFloat = 980
  3955. let topRow = NSStackView()
  3956. topRow.translatesAutoresizingMaskIntoConstraints = false
  3957. topRow.orientation = .horizontal
  3958. topRow.alignment = .centerY
  3959. topRow.distribution = .fill
  3960. topRow.spacing = 10
  3961. topRow.addArrangedSubview(textLabel("Meetings Pro", font: NSFont.systemFont(ofSize: 27, weight: .bold), color: palette.textPrimary))
  3962. var closeButton: HoverButton?
  3963. if storeKitCoordinator.hasPremiumAccess {
  3964. let button = HoverButton(title: "✕", target: self, action: #selector(closePaywallClicked(_:)))
  3965. button.translatesAutoresizingMaskIntoConstraints = false
  3966. button.isBordered = false
  3967. button.bezelStyle = .regularSquare
  3968. button.wantsLayer = true
  3969. button.layer?.cornerRadius = 14
  3970. button.layer?.backgroundColor = palette.inputBackground.cgColor
  3971. button.layer?.borderColor = palette.inputBorder.cgColor
  3972. button.layer?.borderWidth = 1
  3973. button.font = typography.iconButton
  3974. button.contentTintColor = palette.textSecondary
  3975. button.widthAnchor.constraint(equalToConstant: 28).isActive = true
  3976. button.heightAnchor.constraint(equalToConstant: 28).isActive = true
  3977. button.onHoverChanged = { [weak button, weak self] hovering in
  3978. guard let button, let self else { return }
  3979. let base = self.palette.inputBackground
  3980. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  3981. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  3982. button.layer?.backgroundColor = (hovering ? hover : base).cgColor
  3983. button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
  3984. }
  3985. panel.addSubview(button)
  3986. closeButton = button
  3987. }
  3988. contentStack.addArrangedSubview(topRow)
  3989. topRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  3990. let hero = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
  3991. hero.translatesAutoresizingMaskIntoConstraints = false
  3992. styleSurface(hero, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  3993. contentStack.addArrangedSubview(hero)
  3994. hero.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  3995. let heroBadge = textLabel("PREMIUM EXPERIENCE", font: NSFont.systemFont(ofSize: 10, weight: .bold), color: NSColor(calibratedRed: 0.42, green: 0.93, blue: 0.70, alpha: 1))
  3996. hero.addSubview(heroBadge)
  3997. let heroTitle = textLabel("Elevate your meetings workflow", font: NSFont.systemFont(ofSize: 22, weight: .bold), color: palette.textPrimary)
  3998. let heroSubtitle = textLabel("Unlock automation, premium meeting tools, and priority support for every session.", font: NSFont.systemFont(ofSize: 13, weight: .medium), color: palette.textSecondary)
  3999. heroTitle.maximumNumberOfLines = 2
  4000. heroSubtitle.maximumNumberOfLines = 3
  4001. hero.addSubview(heroTitle)
  4002. hero.addSubview(heroSubtitle)
  4003. NSLayoutConstraint.activate([
  4004. heroBadge.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
  4005. heroBadge.topAnchor.constraint(equalTo: hero.topAnchor, constant: 14),
  4006. heroTitle.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
  4007. heroTitle.trailingAnchor.constraint(lessThanOrEqualTo: hero.trailingAnchor, constant: -16),
  4008. heroTitle.topAnchor.constraint(equalTo: heroBadge.bottomAnchor, constant: 10),
  4009. heroSubtitle.leadingAnchor.constraint(equalTo: heroTitle.leadingAnchor),
  4010. heroSubtitle.trailingAnchor.constraint(equalTo: hero.trailingAnchor, constant: -16),
  4011. heroSubtitle.topAnchor.constraint(equalTo: heroTitle.bottomAnchor, constant: 8),
  4012. heroSubtitle.bottomAnchor.constraint(equalTo: hero.bottomAnchor, constant: -16)
  4013. ])
  4014. let benefitsRow = NSStackView()
  4015. benefitsRow.translatesAutoresizingMaskIntoConstraints = false
  4016. benefitsRow.orientation = .horizontal
  4017. benefitsRow.spacing = 8
  4018. benefitsRow.distribution = .fillEqually
  4019. benefitsRow.alignment = .centerY
  4020. benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
  4021. benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🧠", text: "Smart scheduling"))
  4022. benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Faster workflow"))
  4023. benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🔔", text: "Reminder notifications"))
  4024. contentStack.addArrangedSubview(benefitsRow)
  4025. benefitsRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4026. let plansRow = NSStackView()
  4027. plansRow.translatesAutoresizingMaskIntoConstraints = false
  4028. plansRow.orientation = .horizontal
  4029. plansRow.spacing = 10
  4030. plansRow.distribution = .fillEqually
  4031. plansRow.alignment = .centerY
  4032. let weeklyCard = paywallPlanCard(
  4033. title: "Weekly",
  4034. price: "PKR 1,100.00",
  4035. badge: "Basic",
  4036. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  4037. subtitle: nil,
  4038. plan: .weekly,
  4039. strikePrice: nil
  4040. )
  4041. let monthlyCard = paywallPlanCard(
  4042. title: "Monthly",
  4043. price: "PKR 2,500.00",
  4044. badge: "Popular",
  4045. badgeColor: NSColor(calibratedRed: 0.19, green: 0.82, blue: 0.39, alpha: 1),
  4046. subtitle: "3 days free trial",
  4047. plan: .monthly,
  4048. strikePrice: nil
  4049. )
  4050. let yearlyCard = paywallPlanCard(
  4051. title: "Yearly",
  4052. price: "PKR 9,900.00",
  4053. badge: "Best Value",
  4054. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  4055. subtitle: "190.38/week",
  4056. plan: .yearly,
  4057. strikePrice: nil
  4058. )
  4059. let lifetimeCard = paywallPlanCard(
  4060. title: "Lifetime",
  4061. price: "PKR 14,900.00",
  4062. badge: "Save 50%",
  4063. badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
  4064. subtitle: nil,
  4065. plan: .lifetime,
  4066. strikePrice: "PKR 29,800.00"
  4067. )
  4068. plansRow.addArrangedSubview(weeklyCard)
  4069. plansRow.addArrangedSubview(monthlyCard)
  4070. plansRow.addArrangedSubview(yearlyCard)
  4071. plansRow.addArrangedSubview(lifetimeCard)
  4072. contentStack.addArrangedSubview(plansRow)
  4073. plansRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4074. updatePaywallPlanSelection()
  4075. let trustRow = NSStackView()
  4076. trustRow.translatesAutoresizingMaskIntoConstraints = false
  4077. trustRow.orientation = .horizontal
  4078. trustRow.spacing = 8
  4079. trustRow.distribution = .fillEqually
  4080. trustRow.alignment = .centerY
  4081. trustRow.addArrangedSubview(paywallMetaItem(title: "Cancel anytime", subtitle: "No lock-in"))
  4082. trustRow.addArrangedSubview(paywallMetaItem(title: "Instant access", subtitle: "Unlock all tools"))
  4083. trustRow.addArrangedSubview(paywallMetaItem(title: "Secure billing", subtitle: "Handled by Apple"))
  4084. contentStack.addArrangedSubview(trustRow)
  4085. trustRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4086. let offer = textLabel(paywallOfferText(for: selectedPremiumPlan), font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
  4087. offer.alignment = .center
  4088. paywallOfferLabel = offer
  4089. let offerWrap = NSView()
  4090. offerWrap.translatesAutoresizingMaskIntoConstraints = false
  4091. offerWrap.addSubview(offer)
  4092. contentStack.addArrangedSubview(offerWrap)
  4093. offerWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4094. NSLayoutConstraint.activate([
  4095. offer.centerXAnchor.constraint(equalTo: offerWrap.centerXAnchor),
  4096. offer.topAnchor.constraint(equalTo: offerWrap.topAnchor, constant: 4),
  4097. offer.bottomAnchor.constraint(equalTo: offerWrap.bottomAnchor, constant: -2)
  4098. ])
  4099. let continueButton = HoverButton(title: "", target: self, action: #selector(paywallContinueClicked(_:)))
  4100. continueButton.translatesAutoresizingMaskIntoConstraints = false
  4101. continueButton.isBordered = false
  4102. continueButton.bezelStyle = .regularSquare
  4103. continueButton.wantsLayer = true
  4104. continueButton.layer?.cornerRadius = 12
  4105. continueButton.layer?.backgroundColor = palette.primaryBlue.cgColor
  4106. continueButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
  4107. styleSurface(continueButton, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: true)
  4108. let continueLabel = textLabel("Continue", font: NSFont.systemFont(ofSize: 14, weight: .bold), color: .white)
  4109. continueButton.addSubview(continueLabel)
  4110. NSLayoutConstraint.activate([
  4111. continueLabel.centerXAnchor.constraint(equalTo: continueButton.centerXAnchor),
  4112. continueLabel.centerYAnchor.constraint(equalTo: continueButton.centerYAnchor)
  4113. ])
  4114. let baseBlue = palette.primaryBlue
  4115. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4116. let hoverBlue = baseBlue.blended(withFraction: 0.10, of: hoverBlend) ?? baseBlue
  4117. continueButton.onHoverChanged = { hovering in
  4118. continueButton.layer?.backgroundColor = (hovering ? hoverBlue : baseBlue).cgColor
  4119. }
  4120. continueButton.onHoverChanged?(false)
  4121. paywallContinueButton = continueButton
  4122. paywallContinueLabel = continueLabel
  4123. contentStack.addArrangedSubview(continueButton)
  4124. continueButton.widthAnchor.constraint(equalToConstant: 360).isActive = true
  4125. let secure = textLabel("Secured by Apple. Cancel anytime.", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textSecondary)
  4126. secure.alignment = .center
  4127. let secureWrap = NSView()
  4128. secureWrap.translatesAutoresizingMaskIntoConstraints = false
  4129. secureWrap.addSubview(secure)
  4130. contentStack.addArrangedSubview(secureWrap)
  4131. secureWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4132. NSLayoutConstraint.activate([
  4133. secure.centerXAnchor.constraint(equalTo: secureWrap.centerXAnchor),
  4134. secure.topAnchor.constraint(equalTo: secureWrap.topAnchor, constant: 2),
  4135. secure.bottomAnchor.constraint(equalTo: secureWrap.bottomAnchor, constant: -4)
  4136. ])
  4137. let footer = paywallFooterLinks()
  4138. contentStack.addArrangedSubview(footer)
  4139. footer.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
  4140. var panelConstraints: [NSLayoutConstraint] = [
  4141. contentStack.centerXAnchor.constraint(equalTo: panel.centerXAnchor),
  4142. contentStack.widthAnchor.constraint(equalToConstant: paywallLayoutWidth),
  4143. contentStack.topAnchor.constraint(equalTo: panel.topAnchor, constant: 80),
  4144. contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -12)
  4145. ]
  4146. if let closeButton {
  4147. panelConstraints.append(closeButton.topAnchor.constraint(equalTo: panel.topAnchor, constant: 30))
  4148. panelConstraints.append(closeButton.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -30))
  4149. }
  4150. NSLayoutConstraint.activate(panelConstraints)
  4151. refreshPaywallStoreUI()
  4152. return panel
  4153. }
  4154. func paywallPlanCard(
  4155. title: String,
  4156. price: String,
  4157. badge: String,
  4158. badgeColor: NSColor,
  4159. subtitle: String?,
  4160. plan: PremiumPlan,
  4161. strikePrice: String?
  4162. ) -> NSView {
  4163. let wrapper = HoverButton(title: "", target: self, action: #selector(paywallPlanButtonClicked(_:)))
  4164. wrapper.translatesAutoresizingMaskIntoConstraints = false
  4165. wrapper.isBordered = false
  4166. wrapper.bezelStyle = .regularSquare
  4167. wrapper.wantsLayer = true
  4168. wrapper.layer?.backgroundColor = NSColor.clear.cgColor
  4169. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 160).isActive = true
  4170. wrapper.heightAnchor.constraint(equalToConstant: 162).isActive = true
  4171. wrapper.tag = plan.rawValue
  4172. let card = HoverTrackingView()
  4173. card.translatesAutoresizingMaskIntoConstraints = false
  4174. card.wantsLayer = true
  4175. card.layer?.cornerRadius = 16
  4176. card.layer?.backgroundColor = palette.sectionCard.cgColor
  4177. card.heightAnchor.constraint(equalToConstant: 150).isActive = true
  4178. wrapper.addSubview(card)
  4179. NSLayoutConstraint.activate([
  4180. card.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4181. card.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4182. card.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: 12),
  4183. card.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  4184. ])
  4185. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4186. let badgeLabel = textLabel(badge, font: NSFont.systemFont(ofSize: 10, weight: .bold), color: .white)
  4187. let badgeWrap = roundedContainer(cornerRadius: 10, color: badgeColor)
  4188. badgeWrap.translatesAutoresizingMaskIntoConstraints = false
  4189. badgeWrap.wantsLayer = true
  4190. badgeWrap.layer?.borderColor = NSColor(calibratedWhite: 1, alpha: 0.22).cgColor
  4191. badgeWrap.layer?.borderWidth = 1
  4192. badgeWrap.layer?.shadowColor = NSColor.black.cgColor
  4193. badgeWrap.layer?.shadowOpacity = 0.20
  4194. badgeWrap.layer?.shadowOffset = CGSize(width: 0, height: -1)
  4195. badgeWrap.layer?.shadowRadius = 3
  4196. badgeWrap.addSubview(badgeLabel)
  4197. NSLayoutConstraint.activate([
  4198. badgeLabel.leadingAnchor.constraint(equalTo: badgeWrap.leadingAnchor, constant: 8),
  4199. badgeLabel.trailingAnchor.constraint(equalTo: badgeWrap.trailingAnchor, constant: -8),
  4200. badgeLabel.topAnchor.constraint(equalTo: badgeWrap.topAnchor, constant: 2),
  4201. badgeLabel.bottomAnchor.constraint(equalTo: badgeWrap.bottomAnchor, constant: -2)
  4202. ])
  4203. wrapper.addSubview(badgeWrap)
  4204. let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .bold), color: palette.primaryBlue)
  4205. card.addSubview(titleLabel)
  4206. let priceLabel = textLabel(price, font: NSFont.systemFont(ofSize: 12, weight: .bold), color: palette.textPrimary)
  4207. card.addSubview(priceLabel)
  4208. paywallPriceLabels[plan] = priceLabel
  4209. NSLayoutConstraint.activate([
  4210. badgeWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
  4211. badgeWrap.centerYAnchor.constraint(equalTo: card.topAnchor),
  4212. titleLabel.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
  4213. titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 34),
  4214. priceLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
  4215. priceLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
  4216. priceLabel.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
  4217. ])
  4218. if let subtitle {
  4219. let sub = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .semibold), color: palette.textSecondary)
  4220. card.addSubview(sub)
  4221. paywallSubtitleLabels[plan] = sub
  4222. NSLayoutConstraint.activate([
  4223. sub.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
  4224. sub.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 2),
  4225. sub.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
  4226. ])
  4227. }
  4228. if let strikePrice {
  4229. let strike = textLabel(strikePrice, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: NSColor.systemRed)
  4230. card.addSubview(strike)
  4231. NSLayoutConstraint.activate([
  4232. strike.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
  4233. strike.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 4),
  4234. strike.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
  4235. ])
  4236. }
  4237. paywallPlanViews[plan] = card
  4238. wrapper.onHoverChanged = { [weak self, weak card] hovering in
  4239. guard let self, let card else { return }
  4240. self.applyPaywallPlanStyle(card, isSelected: plan == self.selectedPremiumPlan, hovering: hovering)
  4241. }
  4242. wrapper.onHoverChanged?(false)
  4243. return wrapper
  4244. }
  4245. func paywallFooterLinks() -> NSView {
  4246. let wrap = NSView()
  4247. wrap.translatesAutoresizingMaskIntoConstraints = false
  4248. wrap.heightAnchor.constraint(equalToConstant: 40).isActive = true
  4249. paywallFooterActionByView.removeAll()
  4250. let row = NSStackView()
  4251. row.translatesAutoresizingMaskIntoConstraints = false
  4252. row.orientation = .horizontal
  4253. row.distribution = .fillEqually
  4254. row.alignment = .centerY
  4255. row.spacing = 0
  4256. wrap.addSubview(row)
  4257. if storeKitCoordinator.hasPremiumAccess {
  4258. row.addArrangedSubview(footerLink("Manage Subscription", action: .manageSubscription))
  4259. row.addArrangedSubview(footerLink("Restore Purchase", action: .restorePurchase))
  4260. } else {
  4261. row.addArrangedSubview(footerLink("Continue with free plan", action: .continueWithFreePlan))
  4262. }
  4263. row.addArrangedSubview(footerLink("Privacy Policy", action: .privacyPolicy))
  4264. row.addArrangedSubview(footerLink("Support", action: .support))
  4265. row.addArrangedSubview(footerLink("Terms of Services", action: .termsOfServices))
  4266. NSLayoutConstraint.activate([
  4267. row.leadingAnchor.constraint(equalTo: wrap.leadingAnchor),
  4268. row.trailingAnchor.constraint(equalTo: wrap.trailingAnchor),
  4269. row.topAnchor.constraint(equalTo: wrap.topAnchor),
  4270. row.bottomAnchor.constraint(equalTo: wrap.bottomAnchor)
  4271. ])
  4272. return wrap
  4273. }
  4274. private func footerLink(_ title: String, action: PaywallFooterAction) -> NSView {
  4275. let button = HoverButton(title: title, target: self, action: #selector(paywallFooterButtonPressed(_:)))
  4276. button.translatesAutoresizingMaskIntoConstraints = false
  4277. button.isBordered = false
  4278. button.bezelStyle = .regularSquare
  4279. button.focusRingType = .none
  4280. button.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
  4281. button.alignment = .center
  4282. button.setButtonType(.momentaryChange)
  4283. button.contentTintColor = palette.textSecondary
  4284. paywallFooterActionByView[ObjectIdentifier(button)] = action
  4285. button.onHoverChanged = { [weak self, weak button] hovering in
  4286. guard let self, let button else { return }
  4287. button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
  4288. }
  4289. button.onHoverChanged?(false)
  4290. return button
  4291. }
  4292. func paywallMetaItem(title: String, subtitle: String) -> NSView {
  4293. let card = HoverTrackingView()
  4294. card.translatesAutoresizingMaskIntoConstraints = false
  4295. card.wantsLayer = true
  4296. card.layer?.cornerRadius = 10
  4297. card.layer?.backgroundColor = palette.inputBackground.cgColor
  4298. card.heightAnchor.constraint(equalToConstant: 44).isActive = true
  4299. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4300. let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textPrimary)
  4301. let subtitleLabel = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .medium), color: palette.textSecondary)
  4302. card.addSubview(titleLabel)
  4303. card.addSubview(subtitleLabel)
  4304. NSLayoutConstraint.activate([
  4305. titleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
  4306. titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 7),
  4307. subtitleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
  4308. subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 1),
  4309. subtitleLabel.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -6)
  4310. ])
  4311. let base = palette.inputBackground
  4312. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4313. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  4314. card.onHoverChanged = { [weak card] hovering in
  4315. card?.layer?.backgroundColor = (hovering ? hover : base).cgColor
  4316. }
  4317. card.onHoverChanged?(false)
  4318. return card
  4319. }
  4320. func paywallBenefitsSection() -> NSView {
  4321. let stack = NSStackView()
  4322. stack.translatesAutoresizingMaskIntoConstraints = false
  4323. stack.orientation = .vertical
  4324. stack.spacing = 8
  4325. stack.alignment = .leading
  4326. stack.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
  4327. let rowOne = NSStackView()
  4328. rowOne.translatesAutoresizingMaskIntoConstraints = false
  4329. rowOne.orientation = .horizontal
  4330. rowOne.spacing = 10
  4331. rowOne.distribution = .fillEqually
  4332. rowOne.alignment = .centerY
  4333. rowOne.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
  4334. rowOne.addArrangedSubview(paywallBenefitItem(icon: "🖼️", text: "Virtual backgrounds"))
  4335. let rowTwo = NSStackView()
  4336. rowTwo.translatesAutoresizingMaskIntoConstraints = false
  4337. rowTwo.orientation = .horizontal
  4338. rowTwo.spacing = 10
  4339. rowTwo.distribution = .fillEqually
  4340. rowTwo.alignment = .centerY
  4341. rowTwo.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Tools for productivity"))
  4342. rowTwo.addArrangedSubview(paywallBenefitItem(icon: "🛟", text: "24/7 support"))
  4343. stack.addArrangedSubview(rowOne)
  4344. stack.addArrangedSubview(rowTwo)
  4345. return stack
  4346. }
  4347. func paywallBenefitItem(icon: String, text: String) -> NSView {
  4348. let card = HoverTrackingView()
  4349. card.translatesAutoresizingMaskIntoConstraints = false
  4350. card.wantsLayer = true
  4351. card.layer?.cornerRadius = 10
  4352. card.layer?.backgroundColor = palette.inputBackground.cgColor
  4353. card.heightAnchor.constraint(equalToConstant: 36).isActive = true
  4354. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4355. let iconWrap = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
  4356. iconWrap.translatesAutoresizingMaskIntoConstraints = false
  4357. iconWrap.widthAnchor.constraint(equalToConstant: 24).isActive = true
  4358. iconWrap.heightAnchor.constraint(equalToConstant: 24).isActive = true
  4359. styleSurface(iconWrap, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4360. let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: palette.primaryBlue)
  4361. iconWrap.addSubview(iconLabel)
  4362. NSLayoutConstraint.activate([
  4363. iconLabel.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
  4364. iconLabel.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor)
  4365. ])
  4366. let title = textLabel(text, font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textPrimary)
  4367. card.addSubview(iconWrap)
  4368. card.addSubview(title)
  4369. NSLayoutConstraint.activate([
  4370. iconWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 8),
  4371. iconWrap.centerYAnchor.constraint(equalTo: card.centerYAnchor),
  4372. title.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 10),
  4373. title.centerYAnchor.constraint(equalTo: card.centerYAnchor),
  4374. title.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -8)
  4375. ])
  4376. let base = palette.inputBackground
  4377. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4378. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  4379. let hoverBorder = palette.primaryBlueBorder.withAlphaComponent(0.55)
  4380. card.onHoverChanged = { [weak card, weak iconWrap] hovering in
  4381. guard let card else { return }
  4382. card.layer?.backgroundColor = (hovering ? hover : base).cgColor
  4383. card.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
  4384. iconWrap?.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
  4385. }
  4386. card.onHoverChanged?(false)
  4387. return card
  4388. }
  4389. func zoomJoinModeTabs() -> NSView {
  4390. let row = NSStackView()
  4391. row.translatesAutoresizingMaskIntoConstraints = false
  4392. row.orientation = .horizontal
  4393. row.alignment = .centerY
  4394. row.spacing = 28
  4395. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  4396. let idTab = joinModeTab("Join with ID", mode: .id)
  4397. let urlTab = joinModeTab("Join with URL", mode: .url)
  4398. row.addArrangedSubview(idTab)
  4399. row.addArrangedSubview(urlTab)
  4400. let spacer = NSView()
  4401. spacer.translatesAutoresizingMaskIntoConstraints = false
  4402. row.addArrangedSubview(spacer)
  4403. zoomJoinModeViews[.id] = idTab
  4404. zoomJoinModeViews[.url] = urlTab
  4405. updateZoomJoinModeAppearance()
  4406. return row
  4407. }
  4408. func joinModeTab(_ title: String, mode: ZoomJoinMode) -> NSView {
  4409. let tab = HoverTrackingView()
  4410. tab.translatesAutoresizingMaskIntoConstraints = false
  4411. tab.wantsLayer = true
  4412. tab.layer?.cornerRadius = 6
  4413. tab.layer?.backgroundColor = NSColor.clear.cgColor
  4414. tab.heightAnchor.constraint(equalToConstant: 30).isActive = true
  4415. zoomJoinModeByView[ObjectIdentifier(tab)] = mode
  4416. let label = textLabel(title, font: NSFont.systemFont(ofSize: 33 / 2, weight: .medium), color: palette.textPrimary)
  4417. tab.addSubview(label)
  4418. NSLayoutConstraint.activate([
  4419. label.leadingAnchor.constraint(equalTo: tab.leadingAnchor, constant: 4),
  4420. label.trailingAnchor.constraint(equalTo: tab.trailingAnchor, constant: -4),
  4421. label.topAnchor.constraint(equalTo: tab.topAnchor, constant: 4),
  4422. label.bottomAnchor.constraint(equalTo: tab.bottomAnchor, constant: -6)
  4423. ])
  4424. let click = NSClickGestureRecognizer(target: self, action: #selector(zoomJoinModeClicked(_:)))
  4425. tab.addGestureRecognizer(click)
  4426. return tab
  4427. }
  4428. func updateZoomJoinModeAppearance() {
  4429. for (mode, tab) in zoomJoinModeViews {
  4430. let selected = (mode == selectedZoomJoinMode)
  4431. let textColor = selected ? palette.textPrimary : palette.textSecondary
  4432. let label = tab.subviews.first { $0 is NSTextField } as? NSTextField
  4433. label?.textColor = textColor
  4434. // Keep the active tab visually underlined like the reference.
  4435. if selected {
  4436. if tab.subviews.contains(where: { $0.identifier?.rawValue == "modeUnderline" }) == false {
  4437. let underline = NSView()
  4438. underline.identifier = NSUserInterfaceItemIdentifier("modeUnderline")
  4439. underline.translatesAutoresizingMaskIntoConstraints = false
  4440. underline.wantsLayer = true
  4441. underline.layer?.backgroundColor = palette.primaryBlue.cgColor
  4442. tab.addSubview(underline)
  4443. NSLayoutConstraint.activate([
  4444. underline.leadingAnchor.constraint(equalTo: tab.leadingAnchor),
  4445. underline.trailingAnchor.constraint(equalTo: tab.trailingAnchor),
  4446. underline.bottomAnchor.constraint(equalTo: tab.bottomAnchor),
  4447. underline.heightAnchor.constraint(equalToConstant: 2)
  4448. ])
  4449. }
  4450. } else {
  4451. tab.subviews
  4452. .filter { $0.identifier?.rawValue == "modeUnderline" }
  4453. .forEach { $0.removeFromSuperview() }
  4454. }
  4455. }
  4456. }
  4457. func joinWithIDHeading() -> NSView {
  4458. let container = NSView()
  4459. container.translatesAutoresizingMaskIntoConstraints = false
  4460. let title = textLabel("Join with ID", font: typography.joinWithURLTitle, color: palette.textPrimary)
  4461. title.alignment = .left
  4462. title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  4463. title.setContentCompressionResistancePriority(.required, for: .horizontal)
  4464. let bar = NSView()
  4465. bar.translatesAutoresizingMaskIntoConstraints = false
  4466. bar.wantsLayer = true
  4467. bar.layer?.backgroundColor = palette.primaryBlue.cgColor
  4468. bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
  4469. container.addSubview(title)
  4470. container.addSubview(bar)
  4471. NSLayoutConstraint.activate([
  4472. title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
  4473. title.topAnchor.constraint(equalTo: container.topAnchor),
  4474. bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
  4475. bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
  4476. bar.widthAnchor.constraint(equalTo: title.widthAnchor),
  4477. bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
  4478. container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
  4479. ])
  4480. return container
  4481. }
  4482. func zoomMeetingIDSection() -> NSView {
  4483. let wrapper = NSView()
  4484. wrapper.translatesAutoresizingMaskIntoConstraints = false
  4485. let fieldsRow = NSStackView()
  4486. fieldsRow.translatesAutoresizingMaskIntoConstraints = false
  4487. fieldsRow.orientation = .horizontal
  4488. fieldsRow.alignment = .top
  4489. fieldsRow.distribution = .fillEqually
  4490. fieldsRow.spacing = 12
  4491. fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting ID", placeholder: "Enter meeting ID..."))
  4492. fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting Passcode", placeholder: "Enter meeting passcode..."))
  4493. let actions = NSStackView()
  4494. actions.orientation = .horizontal
  4495. actions.spacing = 10
  4496. actions.translatesAutoresizingMaskIntoConstraints = false
  4497. actions.alignment = .centerY
  4498. actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
  4499. actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
  4500. wrapper.addSubview(fieldsRow)
  4501. wrapper.addSubview(actions)
  4502. NSLayoutConstraint.activate([
  4503. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
  4504. fieldsRow.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4505. fieldsRow.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4506. fieldsRow.topAnchor.constraint(equalTo: wrapper.topAnchor),
  4507. actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4508. actions.topAnchor.constraint(equalTo: fieldsRow.bottomAnchor, constant: 14),
  4509. actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  4510. ])
  4511. return wrapper
  4512. }
  4513. func zoomInputField(title: String, placeholder: String) -> NSView {
  4514. let wrapper = NSView()
  4515. wrapper.translatesAutoresizingMaskIntoConstraints = false
  4516. let heading = textLabel(title, font: typography.fieldLabel, color: palette.textPrimary)
  4517. let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  4518. textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
  4519. textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
  4520. styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4521. let field = NSTextField(string: "")
  4522. field.translatesAutoresizingMaskIntoConstraints = false
  4523. field.isEditable = true
  4524. field.isSelectable = true
  4525. field.isBordered = false
  4526. field.drawsBackground = false
  4527. field.placeholderString = placeholder
  4528. field.font = typography.inputPlaceholder
  4529. field.textColor = palette.textPrimary
  4530. field.focusRingType = .none
  4531. textFieldContainer.addSubview(field)
  4532. wrapper.addSubview(heading)
  4533. wrapper.addSubview(textFieldContainer)
  4534. NSLayoutConstraint.activate([
  4535. heading.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4536. heading.topAnchor.constraint(equalTo: wrapper.topAnchor),
  4537. textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4538. textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4539. textFieldContainer.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 10),
  4540. textFieldContainer.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
  4541. field.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
  4542. field.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
  4543. field.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor)
  4544. ])
  4545. return wrapper
  4546. }
  4547. func joinWithURLHeading() -> NSView {
  4548. let container = NSView()
  4549. container.translatesAutoresizingMaskIntoConstraints = false
  4550. let title = textLabel("Join with URL", font: typography.joinWithURLTitle, color: palette.textPrimary)
  4551. title.alignment = .left
  4552. title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  4553. title.setContentCompressionResistancePriority(.required, for: .horizontal)
  4554. let bar = NSView()
  4555. bar.translatesAutoresizingMaskIntoConstraints = false
  4556. bar.wantsLayer = true
  4557. bar.layer?.backgroundColor = palette.primaryBlue.cgColor
  4558. bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
  4559. container.addSubview(title)
  4560. container.addSubview(bar)
  4561. NSLayoutConstraint.activate([
  4562. title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
  4563. title.topAnchor.constraint(equalTo: container.topAnchor),
  4564. bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
  4565. bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
  4566. bar.widthAnchor.constraint(equalTo: title.widthAnchor),
  4567. bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
  4568. container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
  4569. ])
  4570. return container
  4571. }
  4572. func meetingUrlSection() -> NSView {
  4573. let wrapper = NSView()
  4574. wrapper.translatesAutoresizingMaskIntoConstraints = false
  4575. let title = textLabel("Meeting URL", font: typography.fieldLabel, color: palette.textSecondary)
  4576. let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
  4577. textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
  4578. textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
  4579. styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  4580. let urlField = NSTextField(string: "")
  4581. urlField.translatesAutoresizingMaskIntoConstraints = false
  4582. urlField.isEditable = true
  4583. urlField.isSelectable = true
  4584. urlField.isBordered = false
  4585. urlField.drawsBackground = false
  4586. urlField.placeholderString = "Enter meeting URL..."
  4587. urlField.font = typography.inputPlaceholder
  4588. urlField.textColor = palette.textPrimary
  4589. urlField.focusRingType = .none
  4590. textFieldContainer.addSubview(urlField)
  4591. let actions = NSStackView()
  4592. actions.orientation = .horizontal
  4593. actions.spacing = 10
  4594. actions.translatesAutoresizingMaskIntoConstraints = false
  4595. actions.alignment = .centerY
  4596. actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
  4597. actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
  4598. wrapper.addSubview(title)
  4599. wrapper.addSubview(textFieldContainer)
  4600. wrapper.addSubview(actions)
  4601. NSLayoutConstraint.activate([
  4602. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
  4603. title.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4604. title.topAnchor.constraint(equalTo: wrapper.topAnchor),
  4605. textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4606. textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4607. textFieldContainer.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 10),
  4608. urlField.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
  4609. urlField.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
  4610. urlField.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor),
  4611. actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4612. actions.topAnchor.constraint(equalTo: textFieldContainer.bottomAnchor, constant: 14),
  4613. actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
  4614. ])
  4615. return wrapper
  4616. }
  4617. func scheduleHeader() -> NSView {
  4618. let row = NSStackView()
  4619. row.translatesAutoresizingMaskIntoConstraints = false
  4620. row.orientation = .horizontal
  4621. row.alignment = .centerY
  4622. row.distribution = .fill
  4623. row.spacing = 12
  4624. row.addArrangedSubview(textLabel("Schedule", font: typography.sectionTitleBold, color: palette.textPrimary))
  4625. let spacer = NSView()
  4626. spacer.translatesAutoresizingMaskIntoConstraints = false
  4627. row.addArrangedSubview(spacer)
  4628. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4629. row.addArrangedSubview(makeScheduleRefreshButton())
  4630. row.addArrangedSubview(makeScheduleFilterDropdown())
  4631. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  4632. return row
  4633. }
  4634. private func schedulePageHeader() -> NSView {
  4635. let container = NSStackView()
  4636. container.translatesAutoresizingMaskIntoConstraints = false
  4637. container.userInterfaceLayoutDirection = .leftToRight
  4638. container.orientation = .vertical
  4639. container.spacing = 8
  4640. container.alignment = .width
  4641. let titleRow = NSStackView()
  4642. titleRow.translatesAutoresizingMaskIntoConstraints = false
  4643. titleRow.userInterfaceLayoutDirection = .leftToRight
  4644. titleRow.orientation = .horizontal
  4645. titleRow.alignment = .centerY
  4646. titleRow.distribution = .fill
  4647. titleRow.spacing = 0
  4648. let titleLabel = textLabel("Schedule", font: typography.pageTitle, color: palette.textPrimary)
  4649. titleLabel.alignment = .left
  4650. titleLabel.userInterfaceLayoutDirection = .leftToRight
  4651. titleLabel.maximumNumberOfLines = 1
  4652. titleLabel.lineBreakMode = .byTruncatingTail
  4653. titleLabel.setContentHuggingPriority(.required, for: .horizontal)
  4654. titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
  4655. let titleRowSpacer = NSView()
  4656. titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  4657. titleRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4658. titleRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  4659. titleRow.addArrangedSubview(titleLabel)
  4660. if hasGoogleSessionAvailable() && storeKitCoordinator.hasPremiumAccess {
  4661. titleRow.addArrangedSubview(makeSchedulePageAddButton())
  4662. titleRow.setCustomSpacing(12, after: titleLabel)
  4663. }
  4664. titleRow.addArrangedSubview(titleRowSpacer)
  4665. container.addArrangedSubview(titleRow)
  4666. let filterRow = NSStackView()
  4667. filterRow.translatesAutoresizingMaskIntoConstraints = false
  4668. filterRow.userInterfaceLayoutDirection = .leftToRight
  4669. filterRow.orientation = .horizontal
  4670. filterRow.alignment = .centerY
  4671. filterRow.spacing = 18
  4672. filterRow.distribution = .fill
  4673. let filterDropdown = makeSchedulePageFilterDropdown()
  4674. schedulePageFilterDropdown = filterDropdown
  4675. filterRow.addArrangedSubview(filterDropdown)
  4676. filterRow.setCustomSpacing(20, after: filterDropdown)
  4677. let (fromShell, fromPicker) = makeScheduleDatePicker(date: schedulePageFromDate)
  4678. schedulePageFromDatePicker = fromPicker
  4679. filterRow.addArrangedSubview(fromShell)
  4680. filterRow.setCustomSpacing(16, after: fromShell)
  4681. let (toShell, toPicker) = makeScheduleDatePicker(date: schedulePageToDate)
  4682. schedulePageToDatePicker = toPicker
  4683. filterRow.addArrangedSubview(toShell)
  4684. NSLayoutConstraint.activate([
  4685. fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
  4686. fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
  4687. ])
  4688. let filterRowSpacer = NSView()
  4689. filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
  4690. filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4691. filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  4692. filterRow.addArrangedSubview(filterRowSpacer)
  4693. let applyButton = makeSchedulePagePillButton(title: "Apply", action: #selector(schedulePageApplyDateRangePressed(_:)))
  4694. filterRow.addArrangedSubview(applyButton)
  4695. filterRow.setCustomSpacing(22, after: applyButton)
  4696. let resetButton = makeSchedulePagePillButton(title: "Reset", action: #selector(schedulePageResetFiltersPressed(_:)))
  4697. filterRow.addArrangedSubview(resetButton)
  4698. filterRow.setCustomSpacing(22, after: resetButton)
  4699. filterRow.addArrangedSubview(makeScheduleRefreshButton())
  4700. container.addArrangedSubview(filterRow)
  4701. NSLayoutConstraint.activate([
  4702. titleRow.widthAnchor.constraint(equalTo: container.widthAnchor),
  4703. filterRow.widthAnchor.constraint(equalTo: container.widthAnchor)
  4704. ])
  4705. refreshSchedulePageDateFilterUI()
  4706. return container
  4707. }
  4708. private func makeSchedulePageFilterDropdown() -> NSPopUpButton {
  4709. let button = HoverPopUpButton(frame: .zero, pullsDown: false)
  4710. button.translatesAutoresizingMaskIntoConstraints = false
  4711. button.autoenablesItems = false
  4712. button.isBordered = false
  4713. button.bezelStyle = .regularSquare
  4714. button.wantsLayer = true
  4715. button.layer?.cornerRadius = 8
  4716. button.layer?.masksToBounds = true
  4717. button.layer?.backgroundColor = palette.inputBackground.cgColor
  4718. button.layer?.borderColor = palette.inputBorder.cgColor
  4719. button.layer?.borderWidth = 1
  4720. button.font = typography.filterText
  4721. button.contentTintColor = palette.textSecondary
  4722. button.target = self
  4723. button.action = #selector(schedulePageFilterDropdownChanged(_:))
  4724. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  4725. button.widthAnchor.constraint(equalToConstant: 228).isActive = true
  4726. button.removeAllItems()
  4727. button.addItems(withTitles: ["All", "Today", "This week", "This month", "Custom range"])
  4728. button.selectItem(at: schedulePageFilter.rawValue)
  4729. if let menu = button.menu {
  4730. for (index, item) in menu.items.enumerated() {
  4731. item.tag = index
  4732. }
  4733. }
  4734. let baseColor = palette.inputBackground
  4735. let baseBorder = palette.inputBorder
  4736. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4737. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  4738. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  4739. button.onHoverChanged = { [weak button] hovering in
  4740. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  4741. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  4742. }
  4743. button.onHoverChanged?(false)
  4744. return button
  4745. }
  4746. /// Rounded shell matching `makeSchedulePageFilterDropdown` (34pt, 8pt corner, border + hover). Both pickers use the same field+stepper style inside the shell.
  4747. private func makeScheduleDatePicker(date: Date) -> (NSView, NSDatePicker) {
  4748. let shell = HoverSurfaceView()
  4749. shell.translatesAutoresizingMaskIntoConstraints = false
  4750. shell.wantsLayer = true
  4751. shell.layer?.cornerRadius = 8
  4752. shell.layer?.masksToBounds = true
  4753. shell.layer?.borderWidth = 1
  4754. let baseColor = palette.inputBackground
  4755. let baseBorder = palette.inputBorder
  4756. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4757. let hoverBackground = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  4758. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  4759. func applyShellIdleAppearance() {
  4760. shell.layer?.backgroundColor = baseColor.cgColor
  4761. shell.layer?.borderColor = baseBorder.cgColor
  4762. }
  4763. applyShellIdleAppearance()
  4764. shell.onHoverChanged = { [weak shell] hovering in
  4765. guard let shell else { return }
  4766. shell.layer?.backgroundColor = (hovering ? hoverBackground : baseColor).cgColor
  4767. shell.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  4768. }
  4769. let picker = NSDatePicker()
  4770. picker.translatesAutoresizingMaskIntoConstraints = false
  4771. picker.isBordered = false
  4772. picker.drawsBackground = false
  4773. picker.focusRingType = .none
  4774. picker.datePickerStyle = .textFieldAndStepper
  4775. picker.datePickerElements = [.yearMonthDay]
  4776. picker.dateValue = date
  4777. picker.font = typography.filterText
  4778. picker.textColor = palette.textSecondary
  4779. picker.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4780. picker.target = self
  4781. picker.action = #selector(schedulePageDatePickerChanged(_:))
  4782. shell.addSubview(picker)
  4783. NSLayoutConstraint.activate([
  4784. shell.heightAnchor.constraint(equalToConstant: 34),
  4785. picker.leadingAnchor.constraint(equalTo: shell.leadingAnchor, constant: 8),
  4786. picker.trailingAnchor.constraint(equalTo: shell.trailingAnchor, constant: -8),
  4787. picker.centerYAnchor.constraint(equalTo: shell.centerYAnchor)
  4788. ])
  4789. return (shell, picker)
  4790. }
  4791. private func makeSchedulePagePillButton(title: String, action: Selector) -> NSButton {
  4792. let button = makeSchedulePillButton(title: title)
  4793. button.target = self
  4794. button.action = action
  4795. button.widthAnchor.constraint(equalToConstant: 100).isActive = true
  4796. return button
  4797. }
  4798. private func makeSchedulePageCardsContainer() -> NSView {
  4799. if let observer = schedulePageScrollObservation {
  4800. NotificationCenter.default.removeObserver(observer)
  4801. }
  4802. schedulePageScrollObservation = nil
  4803. let wrapper = NSView()
  4804. wrapper.translatesAutoresizingMaskIntoConstraints = false
  4805. wrapper.userInterfaceLayoutDirection = .leftToRight
  4806. let scroll = NSScrollView()
  4807. scroll.translatesAutoresizingMaskIntoConstraints = false
  4808. scroll.userInterfaceLayoutDirection = .leftToRight
  4809. scroll.drawsBackground = false
  4810. scroll.hasHorizontalScroller = false
  4811. scroll.hasVerticalScroller = true
  4812. scroll.autohidesScrollers = true
  4813. scroll.borderType = .noBorder
  4814. scroll.scrollerStyle = .overlay
  4815. scroll.automaticallyAdjustsContentInsets = false
  4816. let clip = TopAlignedClipView()
  4817. clip.drawsBackground = false
  4818. clip.postsBoundsChangedNotifications = true
  4819. scroll.contentView = clip
  4820. schedulePageCardsScrollView = scroll
  4821. wrapper.addSubview(scroll)
  4822. let stack = NSStackView()
  4823. stack.translatesAutoresizingMaskIntoConstraints = false
  4824. stack.userInterfaceLayoutDirection = .leftToRight
  4825. stack.orientation = .vertical
  4826. stack.spacing = schedulePageCardSpacing
  4827. stack.alignment = .width
  4828. schedulePageCardsStack = stack
  4829. scroll.documentView = stack
  4830. NSLayoutConstraint.activate([
  4831. scroll.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
  4832. scroll.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
  4833. scroll.topAnchor.constraint(equalTo: wrapper.topAnchor),
  4834. scroll.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
  4835. scroll.heightAnchor.constraint(greaterThanOrEqualToConstant: 420),
  4836. stack.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  4837. stack.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
  4838. stack.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  4839. stack.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor)
  4840. ])
  4841. scroll.contentView.postsBoundsChangedNotifications = true
  4842. schedulePageScrollObservation = NotificationCenter.default.addObserver(
  4843. forName: NSView.boundsDidChangeNotification,
  4844. object: scroll.contentView,
  4845. queue: .main
  4846. ) { [weak self] _ in
  4847. self?.schedulePageScrolled()
  4848. }
  4849. renderSchedulePageCards()
  4850. return wrapper
  4851. }
  4852. private func scheduleTopAuthRow() -> NSView {
  4853. let row = NSStackView()
  4854. row.translatesAutoresizingMaskIntoConstraints = false
  4855. row.orientation = .horizontal
  4856. row.alignment = .centerY
  4857. row.spacing = 10
  4858. let spacer = NSView()
  4859. spacer.translatesAutoresizingMaskIntoConstraints = false
  4860. row.addArrangedSubview(spacer)
  4861. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  4862. let host = GoogleProfileAuthHostView()
  4863. host.translatesAutoresizingMaskIntoConstraints = false
  4864. let authButton = makeGoogleAuthButton()
  4865. host.authButton = authButton
  4866. scheduleGoogleAuthHostView = host
  4867. scheduleGoogleAuthButton = authButton
  4868. host.addSubview(authButton)
  4869. NSLayoutConstraint.activate([
  4870. authButton.centerXAnchor.constraint(equalTo: host.centerXAnchor),
  4871. authButton.centerYAnchor.constraint(equalTo: host.centerYAnchor)
  4872. ])
  4873. let hostPadW = host.widthAnchor.constraint(equalTo: authButton.widthAnchor, constant: 0)
  4874. let hostPadH = host.heightAnchor.constraint(equalTo: authButton.heightAnchor, constant: 0)
  4875. hostPadW.isActive = true
  4876. hostPadH.isActive = true
  4877. scheduleGoogleAuthHostPadWidthConstraint = hostPadW
  4878. scheduleGoogleAuthHostPadHeightConstraint = hostPadH
  4879. updateGoogleAuthButtonTitle()
  4880. row.addArrangedSubview(host)
  4881. row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  4882. return row
  4883. }
  4884. private func makeScheduleFilterDropdown() -> NSPopUpButton {
  4885. let button = HoverPopUpButton(frame: .zero, pullsDown: false)
  4886. button.translatesAutoresizingMaskIntoConstraints = false
  4887. button.autoenablesItems = false
  4888. button.isBordered = false
  4889. button.bezelStyle = .regularSquare
  4890. button.wantsLayer = true
  4891. button.layer?.cornerRadius = 8
  4892. button.layer?.masksToBounds = true
  4893. button.layer?.backgroundColor = palette.inputBackground.cgColor
  4894. button.layer?.borderColor = palette.inputBorder.cgColor
  4895. button.layer?.borderWidth = 1
  4896. button.font = typography.filterText
  4897. button.contentTintColor = palette.textSecondary
  4898. button.target = self
  4899. button.action = #selector(scheduleFilterDropdownChanged(_:))
  4900. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  4901. button.widthAnchor.constraint(equalToConstant: 156).isActive = true
  4902. button.removeAllItems()
  4903. button.addItems(withTitles: ["All", "Today", "This week"])
  4904. button.selectItem(at: scheduleFilter.rawValue)
  4905. if let menu = button.menu {
  4906. for (index, item) in menu.items.enumerated() {
  4907. item.tag = index
  4908. }
  4909. }
  4910. let baseColor = palette.inputBackground
  4911. let baseBorder = palette.inputBorder
  4912. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4913. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  4914. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  4915. button.onHoverChanged = { [weak button] hovering in
  4916. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  4917. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  4918. }
  4919. button.onHoverChanged?(false)
  4920. scheduleFilterDropdown = button
  4921. return button
  4922. }
  4923. private func makeSchedulePillButton(title: String) -> NSButton {
  4924. let button = NSButton(title: title, target: nil, action: nil)
  4925. button.translatesAutoresizingMaskIntoConstraints = false
  4926. button.isBordered = false
  4927. button.bezelStyle = .regularSquare
  4928. button.wantsLayer = true
  4929. button.layer?.cornerRadius = 8
  4930. button.layer?.backgroundColor = palette.inputBackground.cgColor
  4931. button.layer?.borderColor = palette.inputBorder.cgColor
  4932. button.layer?.borderWidth = 1
  4933. button.font = typography.filterText
  4934. button.contentTintColor = palette.textSecondary
  4935. button.setButtonType(.momentaryChange)
  4936. button.heightAnchor.constraint(equalToConstant: 34).isActive = true
  4937. button.widthAnchor.constraint(greaterThanOrEqualToConstant: 132).isActive = true
  4938. return button
  4939. }
  4940. private func makeGoogleAuthButton() -> NSButton {
  4941. let button = HoverButton(title: "", target: self, action: #selector(scheduleConnectButtonPressed(_:)))
  4942. button.translatesAutoresizingMaskIntoConstraints = false
  4943. button.isBordered = false
  4944. button.bezelStyle = .regularSquare
  4945. button.wantsLayer = true
  4946. button.layer?.cornerRadius = 16
  4947. button.layer?.borderWidth = 1
  4948. button.font = NSFont.systemFont(ofSize: 14, weight: .semibold)
  4949. button.imagePosition = .imageLeading
  4950. button.alignment = .center
  4951. button.imageHugsTitle = true
  4952. button.lineBreakMode = .byTruncatingTail
  4953. button.contentTintColor = palette.textPrimary
  4954. button.imageScaling = .scaleNone
  4955. button.layer?.masksToBounds = true
  4956. let heightConstraint = button.heightAnchor.constraint(equalToConstant: 42)
  4957. heightConstraint.isActive = true
  4958. scheduleGoogleAuthButtonHeightConstraint = heightConstraint
  4959. let widthConstraint = button.widthAnchor.constraint(equalToConstant: 248)
  4960. widthConstraint.isActive = true
  4961. scheduleGoogleAuthButtonWidthConstraint = widthConstraint
  4962. button.onHoverChanged = { [weak self] hovering in
  4963. self?.scheduleGoogleAuthHovering = hovering
  4964. self?.scheduleGoogleAuthHostView?.setProfileHoverActive(hovering)
  4965. self?.applyGoogleAuthButtonSurface()
  4966. }
  4967. button.onHoverChanged?(false)
  4968. return button
  4969. }
  4970. private func makeSchedulePageAddButton() -> NSButton {
  4971. let diameter: CGFloat = 30
  4972. let button = HoverButton(title: "", target: self, action: #selector(schedulePageAddMeetingPressed(_:)))
  4973. button.translatesAutoresizingMaskIntoConstraints = false
  4974. button.isBordered = false
  4975. button.bezelStyle = .regularSquare
  4976. button.wantsLayer = true
  4977. button.layer?.cornerRadius = diameter / 2
  4978. button.layer?.masksToBounds = true
  4979. button.layer?.backgroundColor = palette.inputBackground.cgColor
  4980. button.layer?.borderColor = palette.inputBorder.cgColor
  4981. button.layer?.borderWidth = 1
  4982. button.setButtonType(.momentaryChange)
  4983. button.contentTintColor = palette.textSecondary
  4984. button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: "Schedule meeting")
  4985. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  4986. button.imagePosition = .imageOnly
  4987. button.imageScaling = .scaleProportionallyDown
  4988. button.focusRingType = .none
  4989. button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
  4990. button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
  4991. let baseColor = palette.inputBackground
  4992. let baseBorder = palette.inputBorder
  4993. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  4994. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  4995. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  4996. button.onHoverChanged = { [weak button] hovering in
  4997. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  4998. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  4999. }
  5000. button.onHoverChanged?(false)
  5001. return button
  5002. }
  5003. private func makeScheduleRefreshButton() -> NSButton {
  5004. let diameter: CGFloat = 30
  5005. let button = HoverButton(title: "", target: self, action: #selector(scheduleReloadButtonPressed(_:)))
  5006. button.translatesAutoresizingMaskIntoConstraints = false
  5007. button.isBordered = false
  5008. button.bezelStyle = .regularSquare
  5009. button.wantsLayer = true
  5010. button.layer?.cornerRadius = diameter / 2
  5011. button.layer?.masksToBounds = true
  5012. button.layer?.backgroundColor = palette.inputBackground.cgColor
  5013. button.layer?.borderColor = palette.inputBorder.cgColor
  5014. button.layer?.borderWidth = 1
  5015. button.setButtonType(.momentaryChange)
  5016. button.contentTintColor = palette.textSecondary
  5017. button.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Refresh meetings")
  5018. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
  5019. button.imagePosition = .imageOnly
  5020. button.imageScaling = .scaleProportionallyDown
  5021. button.focusRingType = .none
  5022. button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
  5023. button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
  5024. let baseColor = palette.inputBackground
  5025. let baseBorder = palette.inputBorder
  5026. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  5027. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  5028. let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
  5029. button.onHoverChanged = { [weak button] hovering in
  5030. button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  5031. button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
  5032. }
  5033. button.onHoverChanged?(false)
  5034. return button
  5035. }
  5036. func scheduleCardsRow(meetings: [ScheduledMeeting]) -> NSView {
  5037. let cardWidth: CGFloat = 240
  5038. let cardsPerViewport: CGFloat = 3
  5039. let viewportWidth = (cardWidth * cardsPerViewport) + (12 * (cardsPerViewport - 1))
  5040. let wrapper = NSStackView()
  5041. wrapper.translatesAutoresizingMaskIntoConstraints = false
  5042. wrapper.orientation = .horizontal
  5043. wrapper.alignment = .centerY
  5044. wrapper.spacing = 10
  5045. let leftButton = makeScheduleScrollButton(systemSymbol: "chevron.left", action: #selector(scheduleScrollLeftPressed(_:)))
  5046. scheduleScrollLeftButton = leftButton
  5047. wrapper.addArrangedSubview(leftButton)
  5048. let scroll = NSScrollView()
  5049. scheduleCardsScrollView = scroll
  5050. scroll.translatesAutoresizingMaskIntoConstraints = false
  5051. scroll.drawsBackground = false
  5052. scroll.hasHorizontalScroller = false
  5053. scroll.hasVerticalScroller = false
  5054. scroll.horizontalScrollElasticity = .allowed
  5055. scroll.verticalScrollElasticity = .none
  5056. scroll.autohidesScrollers = false
  5057. scroll.borderType = .noBorder
  5058. scroll.automaticallyAdjustsContentInsets = false
  5059. scroll.heightAnchor.constraint(equalToConstant: 150).isActive = true
  5060. scroll.widthAnchor.constraint(equalToConstant: viewportWidth).isActive = true
  5061. let row = NSStackView()
  5062. row.translatesAutoresizingMaskIntoConstraints = false
  5063. row.orientation = .horizontal
  5064. row.spacing = 12
  5065. row.alignment = .top
  5066. row.distribution = .gravityAreas
  5067. row.setContentHuggingPriority(.defaultHigh, for: .horizontal)
  5068. row.heightAnchor.constraint(equalToConstant: 150).isActive = true
  5069. scheduleCardsStack = row
  5070. scroll.documentView = row
  5071. scroll.contentView.postsBoundsChangedNotifications = true
  5072. // Pin top/leading/trailing only; avoid bottom == clip so the horizontal stack is not stretched vertically inside the clip (same as Schedule cards scroll).
  5073. NSLayoutConstraint.activate([
  5074. row.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
  5075. row.trailingAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.trailingAnchor),
  5076. row.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
  5077. row.heightAnchor.constraint(equalToConstant: 150)
  5078. ])
  5079. renderScheduleCards(into: row, meetings: meetings)
  5080. wrapper.addArrangedSubview(scroll)
  5081. let rightButton = makeScheduleScrollButton(systemSymbol: "chevron.right", action: #selector(scheduleScrollRightPressed(_:)))
  5082. scheduleScrollRightButton = rightButton
  5083. wrapper.addArrangedSubview(rightButton)
  5084. scroll.setContentHuggingPriority(.defaultLow, for: .horizontal)
  5085. scroll.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5086. wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
  5087. return wrapper
  5088. }
  5089. func scheduleCard(meeting: ScheduledMeeting, useFlexibleWidth: Bool = false, contentHeight: CGFloat = 150) -> NSView {
  5090. let cardWidth: CGFloat = 240
  5091. let card = roundedContainer(cornerRadius: 12, color: palette.sectionCard)
  5092. styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
  5093. card.translatesAutoresizingMaskIntoConstraints = false
  5094. card.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
  5095. if useFlexibleWidth {
  5096. card.setContentHuggingPriority(.defaultLow, for: .horizontal)
  5097. card.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5098. } else {
  5099. card.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
  5100. card.setContentHuggingPriority(.required, for: .horizontal)
  5101. card.setContentCompressionResistancePriority(.required, for: .horizontal)
  5102. }
  5103. let icon = roundedContainer(cornerRadius: 8, color: palette.meetingBadge)
  5104. icon.translatesAutoresizingMaskIntoConstraints = false
  5105. icon.widthAnchor.constraint(equalToConstant: 28).isActive = true
  5106. icon.heightAnchor.constraint(equalToConstant: 28).isActive = true
  5107. let iconView = NSImageView()
  5108. iconView.translatesAutoresizingMaskIntoConstraints = false
  5109. iconView.image = NSImage(systemSymbolName: "video.circle.fill", accessibilityDescription: "Meeting")
  5110. iconView.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
  5111. iconView.contentTintColor = .white
  5112. icon.addSubview(iconView)
  5113. NSLayoutConstraint.activate([
  5114. iconView.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
  5115. iconView.centerYAnchor.constraint(equalTo: icon.centerYAnchor)
  5116. ])
  5117. let title = textLabel(meeting.title, font: typography.cardTitle, color: palette.textPrimary)
  5118. title.lineBreakMode = .byTruncatingTail
  5119. title.maximumNumberOfLines = 1
  5120. title.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5121. let subtitle = textLabel(meeting.subtitle ?? "Google Calendar", font: typography.cardSubtitle, color: palette.textPrimary)
  5122. let time = textLabel(scheduleTimeText(for: meeting), font: typography.cardTime, color: palette.textSecondary)
  5123. let duration = textLabel(scheduleDurationText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textMuted)
  5124. let dayChip = roundedContainer(cornerRadius: 7, color: palette.inputBackground)
  5125. dayChip.translatesAutoresizingMaskIntoConstraints = false
  5126. dayChip.layer?.borderWidth = 1
  5127. dayChip.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.8).cgColor
  5128. let dayText = textLabel(scheduleDayText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textSecondary)
  5129. dayText.translatesAutoresizingMaskIntoConstraints = false
  5130. dayChip.addSubview(dayText)
  5131. NSLayoutConstraint.activate([
  5132. dayText.leadingAnchor.constraint(equalTo: dayChip.leadingAnchor, constant: 8),
  5133. dayText.trailingAnchor.constraint(equalTo: dayChip.trailingAnchor, constant: -8),
  5134. dayText.topAnchor.constraint(equalTo: dayChip.topAnchor, constant: 4),
  5135. dayText.bottomAnchor.constraint(equalTo: dayChip.bottomAnchor, constant: -4)
  5136. ])
  5137. card.addSubview(icon)
  5138. card.addSubview(dayChip)
  5139. card.addSubview(title)
  5140. card.addSubview(subtitle)
  5141. card.addSubview(time)
  5142. card.addSubview(duration)
  5143. var titleConstraints: [NSLayoutConstraint] = [
  5144. icon.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  5145. icon.topAnchor.constraint(equalTo: card.topAnchor, constant: 10),
  5146. dayChip.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -10),
  5147. dayChip.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
  5148. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6),
  5149. title.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
  5150. title.trailingAnchor.constraint(lessThanOrEqualTo: dayChip.leadingAnchor, constant: -8)
  5151. ]
  5152. if !useFlexibleWidth {
  5153. titleConstraints.append(title.widthAnchor.constraint(lessThanOrEqualToConstant: 130))
  5154. }
  5155. NSLayoutConstraint.activate(titleConstraints + [
  5156. subtitle.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  5157. subtitle.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 10),
  5158. subtitle.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
  5159. time.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  5160. time.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 5),
  5161. time.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
  5162. duration.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
  5163. duration.topAnchor.constraint(equalTo: time.bottomAnchor, constant: 4),
  5164. duration.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10)
  5165. ])
  5166. let hit = HoverButton(title: "", target: self, action: #selector(scheduleCardButtonPressed(_:)))
  5167. hit.translatesAutoresizingMaskIntoConstraints = false
  5168. hit.isBordered = false
  5169. hit.bezelStyle = .regularSquare
  5170. hit.identifier = NSUserInterfaceItemIdentifier(meeting.meetURL.absoluteString)
  5171. hit.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
  5172. if useFlexibleWidth {
  5173. hit.setContentHuggingPriority(.defaultLow, for: .horizontal)
  5174. hit.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5175. } else {
  5176. hit.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
  5177. hit.setContentHuggingPriority(.required, for: .horizontal)
  5178. hit.setContentCompressionResistancePriority(.required, for: .horizontal)
  5179. }
  5180. hit.addSubview(card)
  5181. NSLayoutConstraint.activate([
  5182. card.leadingAnchor.constraint(equalTo: hit.leadingAnchor),
  5183. card.trailingAnchor.constraint(equalTo: hit.trailingAnchor),
  5184. card.topAnchor.constraint(equalTo: hit.topAnchor),
  5185. card.bottomAnchor.constraint(equalTo: hit.bottomAnchor)
  5186. ])
  5187. hit.onHoverChanged = { [weak self] hovering in
  5188. guard let self else { return }
  5189. let base = self.palette.sectionCard
  5190. let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
  5191. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  5192. if self.storeKitCoordinator.hasPremiumAccess {
  5193. card.layer?.backgroundColor = (hovering ? hover : base).cgColor
  5194. } else {
  5195. card.layer?.backgroundColor = base.cgColor
  5196. }
  5197. }
  5198. hit.onHoverChanged?(false)
  5199. if !storeKitCoordinator.hasPremiumAccess {
  5200. let lockOverlay = NSVisualEffectView()
  5201. lockOverlay.translatesAutoresizingMaskIntoConstraints = false
  5202. lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
  5203. lockOverlay.blendingMode = .withinWindow
  5204. lockOverlay.state = .active
  5205. lockOverlay.wantsLayer = true
  5206. lockOverlay.layer?.cornerRadius = 12
  5207. lockOverlay.layer?.masksToBounds = true
  5208. lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.28 : 0.12).cgColor
  5209. let lockLabel = textLabel("Get Premium to see events", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: darkModeEnabled ? .white : .black)
  5210. lockLabel.alignment = .center
  5211. card.addSubview(lockOverlay)
  5212. lockOverlay.addSubview(lockLabel)
  5213. NSLayoutConstraint.activate([
  5214. lockOverlay.leadingAnchor.constraint(equalTo: card.leadingAnchor),
  5215. lockOverlay.trailingAnchor.constraint(equalTo: card.trailingAnchor),
  5216. lockOverlay.topAnchor.constraint(equalTo: card.topAnchor),
  5217. lockOverlay.bottomAnchor.constraint(equalTo: card.bottomAnchor),
  5218. lockLabel.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
  5219. lockLabel.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
  5220. lockLabel.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 10),
  5221. lockLabel.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -10)
  5222. ])
  5223. hit.toolTip = "Premium required. Click to open paywall."
  5224. }
  5225. return hit
  5226. }
  5227. private func makeScheduleScrollButton(systemSymbol: String, action: Selector) -> NSButton {
  5228. let button = NSButton(title: "", target: self, action: action)
  5229. button.translatesAutoresizingMaskIntoConstraints = false
  5230. button.isBordered = false
  5231. button.bezelStyle = .regularSquare
  5232. button.wantsLayer = true
  5233. button.layer?.cornerRadius = 16
  5234. button.layer?.backgroundColor = palette.inputBackground.cgColor
  5235. button.layer?.borderColor = palette.inputBorder.cgColor
  5236. button.layer?.borderWidth = 1
  5237. button.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Scroll meetings")
  5238. button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
  5239. button.imagePosition = .imageOnly
  5240. button.imageScaling = .scaleProportionallyDown
  5241. button.contentTintColor = palette.textSecondary
  5242. button.focusRingType = .none
  5243. button.heightAnchor.constraint(equalToConstant: 32).isActive = true
  5244. button.widthAnchor.constraint(equalToConstant: 32).isActive = true
  5245. return button
  5246. }
  5247. }
  5248. private extension PremiumPlan {
  5249. var displayName: String {
  5250. switch self {
  5251. case .weekly: return "Weekly"
  5252. case .monthly: return "Monthly"
  5253. case .yearly: return "Yearly"
  5254. case .lifetime: return "Lifetime"
  5255. }
  5256. }
  5257. }
  5258. extension ViewController: NSTextFieldDelegate {
  5259. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  5260. if control === browseAddressField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
  5261. browseOpenAddressClicked(nil)
  5262. return true
  5263. }
  5264. return false
  5265. }
  5266. }
  5267. extension ViewController: AVSpeechSynthesizerDelegate {
  5268. func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
  5269. DispatchQueue.main.async { [weak self] in
  5270. guard let self else { return }
  5271. guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
  5272. guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }
  5273. self.aiCompanionIsUsingSpeech = false
  5274. self.aiCompanionCurrentlySpeakingButtonId = nil
  5275. if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
  5276. button.title = "Play Audio"
  5277. }
  5278. self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"
  5279. }
  5280. }
  5281. func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
  5282. DispatchQueue.main.async { [weak self] in
  5283. guard let self else { return }
  5284. guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
  5285. guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }
  5286. self.aiCompanionIsUsingSpeech = false
  5287. self.aiCompanionCurrentlySpeakingButtonId = nil
  5288. if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
  5289. button.title = "Play Audio"
  5290. }
  5291. self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Stopped"
  5292. }
  5293. }
  5294. }
  5295. extension ViewController: AVAudioPlayerDelegate {
  5296. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  5297. DispatchQueue.main.async { [weak self] in
  5298. guard let self else { return }
  5299. guard self.aiCompanionLocalAudioPlayer === player else { return }
  5300. self.aiCompanionAudioDidFinish()
  5301. }
  5302. }
  5303. func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
  5304. DispatchQueue.main.async { [weak self] in
  5305. guard let self else { return }
  5306. guard self.aiCompanionLocalAudioPlayer === player else { return }
  5307. if let button = self.aiCompanionCurrentlyPlayingButton {
  5308. let buttonId = ObjectIdentifier(button)
  5309. button.title = "Play Audio"
  5310. self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Failed: \(error?.localizedDescription ?? "decode error")"
  5311. }
  5312. self.aiCompanionAudioPlayer?.pause()
  5313. self.aiCompanionAudioPlayer = nil
  5314. self.aiCompanionLocalAudioPlayer?.stop()
  5315. self.aiCompanionLocalAudioPlayer = nil
  5316. self.aiCompanionCurrentlyPlayingURL = nil
  5317. self.aiCompanionCurrentlyPlayingButton = nil
  5318. self.aiCompanionTimeControlObserver = nil
  5319. }
  5320. }
  5321. }
  5322. extension ViewController: NSWindowDelegate {
  5323. func windowWillClose(_ notification: Notification) {
  5324. guard let closingWindow = notification.object as? NSWindow else { return }
  5325. if closingWindow === paywallWindow {
  5326. paywallWindow = nil
  5327. paywallUpgradeFlowEnabled = false
  5328. }
  5329. }
  5330. }
  5331. @available(macOS 13.0, *)
  5332. private final class MeetingSystemAudioRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
  5333. private let outputURL: URL
  5334. private var stream: SCStream?
  5335. private var writer: AVAssetWriter?
  5336. private var writerInput: AVAssetWriterInput?
  5337. private let outputQueue = DispatchQueue(label: "meeting.system.audio.capture")
  5338. private var didStartSession = false
  5339. init(outputURL: URL) {
  5340. self.outputURL = outputURL
  5341. }
  5342. func start() async throws {
  5343. try? FileManager.default.removeItem(at: outputURL)
  5344. let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
  5345. guard let display = content.displays.first else {
  5346. throw NSError(domain: "MeetingSystemAudioRecorder", code: 1, userInfo: [NSLocalizedDescriptionKey: "No display available for system audio capture."])
  5347. }
  5348. let writer = try AVAssetWriter(outputURL: outputURL, fileType: .m4a)
  5349. let inputSettings: [String: Any] = [
  5350. AVFormatIDKey: kAudioFormatMPEG4AAC,
  5351. AVSampleRateKey: 48_000,
  5352. AVNumberOfChannelsKey: 2,
  5353. AVEncoderBitRateKey: 128_000
  5354. ]
  5355. let input = AVAssetWriterInput(mediaType: .audio, outputSettings: inputSettings)
  5356. input.expectsMediaDataInRealTime = true
  5357. guard writer.canAdd(input) else {
  5358. throw NSError(domain: "MeetingSystemAudioRecorder", code: 2, userInfo: [NSLocalizedDescriptionKey: "Cannot add audio writer input."])
  5359. }
  5360. writer.add(input)
  5361. self.writer = writer
  5362. self.writerInput = input
  5363. didStartSession = false
  5364. let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: [])
  5365. let config = SCStreamConfiguration()
  5366. config.width = 2
  5367. config.height = 2
  5368. config.minimumFrameInterval = CMTime(value: 1, timescale: 2)
  5369. config.queueDepth = 1
  5370. config.capturesAudio = true
  5371. config.sampleRate = 48_000
  5372. config.channelCount = 2
  5373. if #available(macOS 13.0, *) {
  5374. config.excludesCurrentProcessAudio = true
  5375. }
  5376. let stream = SCStream(filter: filter, configuration: config, delegate: self)
  5377. self.stream = stream
  5378. try stream.addStreamOutput(self, type: .audio, sampleHandlerQueue: outputQueue)
  5379. try await stream.startCapture()
  5380. }
  5381. func stop() async throws {
  5382. if let stream {
  5383. try? await stream.stopCapture()
  5384. self.stream = nil
  5385. }
  5386. writerInput?.markAsFinished()
  5387. guard let writer else { return }
  5388. await withCheckedContinuation { continuation in
  5389. writer.finishWriting {
  5390. continuation.resume()
  5391. }
  5392. }
  5393. self.writer = nil
  5394. self.writerInput = nil
  5395. }
  5396. func stream(_ stream: SCStream, didStopWithError error: Error) {
  5397. // Capture may stop on permission changes or display changes; caller handles lifecycle.
  5398. }
  5399. func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of outputType: SCStreamOutputType) {
  5400. guard outputType == .audio else { return }
  5401. guard CMSampleBufferDataIsReady(sampleBuffer) else { return }
  5402. guard let writer = writer, let input = writerInput else { return }
  5403. if writer.status == .unknown {
  5404. writer.startWriting()
  5405. }
  5406. if writer.status == .writing {
  5407. let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
  5408. if !didStartSession {
  5409. writer.startSession(atSourceTime: pts)
  5410. didStartSession = true
  5411. }
  5412. if input.isReadyForMoreMediaData {
  5413. input.append(sampleBuffer)
  5414. }
  5415. }
  5416. }
  5417. }
  5418. /// Default `NSClipView` uses a non-flipped coordinate system, so a document shorter than the visible area is anchored to the **bottom** of the clip, leaving a large gap above (e.g. Schedule empty state). Flipped coordinates match Auto Layout’s top-leading anchors and keep content top-aligned.
  5419. private final class TopAlignedClipView: NSClipView {
  5420. override var isFlipped: Bool { true }
  5421. }
  5422. /// Wraps the Google auth control and draws a circular accent ring with a light pulse while the signed-in avatar is hovered.
  5423. private final class GoogleProfileAuthHostView: NSView {
  5424. weak var authButton: NSButton? {
  5425. didSet { needsLayout = true }
  5426. }
  5427. private let ringLayer = CAShapeLayer()
  5428. private var avatarRingMode = false
  5429. private static let ringLineWidth: CGFloat = 2.25
  5430. override init(frame frameRect: NSRect) {
  5431. super.init(frame: frameRect)
  5432. wantsLayer = true
  5433. layer?.masksToBounds = false
  5434. ringLayer.fillColor = nil
  5435. ringLayer.strokeColor = NSColor.clear.cgColor
  5436. ringLayer.lineWidth = Self.ringLineWidth
  5437. ringLayer.lineCap = .round
  5438. ringLayer.opacity = 0
  5439. ringLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
  5440. layer?.insertSublayer(ringLayer, at: 0)
  5441. }
  5442. @available(*, unavailable)
  5443. required init?(coder: NSCoder) {
  5444. nil
  5445. }
  5446. func setAvatarRingMode(_ enabled: Bool) {
  5447. avatarRingMode = enabled
  5448. if enabled == false {
  5449. ringLayer.removeAllAnimations()
  5450. ringLayer.opacity = 0
  5451. ringLayer.lineWidth = Self.ringLineWidth
  5452. }
  5453. needsLayout = true
  5454. }
  5455. func updateRingAppearance(isDark: Bool, accent: NSColor) {
  5456. let stroke = isDark
  5457. ? accent.blended(withFraction: 0.22, of: NSColor.white) ?? accent
  5458. : accent
  5459. CATransaction.begin()
  5460. CATransaction.setDisableActions(true)
  5461. ringLayer.strokeColor = stroke.withAlphaComponent(0.95).cgColor
  5462. CATransaction.commit()
  5463. }
  5464. func setProfileHoverActive(_ active: Bool) {
  5465. guard avatarRingMode else { return }
  5466. ringLayer.removeAnimation(forKey: "pulse")
  5467. if active {
  5468. layoutRingPathIfNeeded()
  5469. CATransaction.begin()
  5470. CATransaction.setAnimationDuration(0.22)
  5471. ringLayer.opacity = 1
  5472. CATransaction.commit()
  5473. let pulse = CABasicAnimation(keyPath: "lineWidth")
  5474. pulse.fromValue = Self.ringLineWidth * 0.88
  5475. pulse.toValue = Self.ringLineWidth * 1.45
  5476. pulse.duration = 0.72
  5477. pulse.autoreverses = true
  5478. pulse.repeatCount = .infinity
  5479. pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  5480. ringLayer.add(pulse, forKey: "pulse")
  5481. } else {
  5482. CATransaction.begin()
  5483. CATransaction.setAnimationDuration(0.18)
  5484. ringLayer.opacity = 0
  5485. CATransaction.commit()
  5486. ringLayer.lineWidth = Self.ringLineWidth
  5487. }
  5488. }
  5489. private func layoutRingPathIfNeeded() {
  5490. guard avatarRingMode, let btn = authButton else { return }
  5491. let f = btn.frame
  5492. guard f.width > 1, f.height > 1 else { return }
  5493. let center = CGPoint(x: f.midX, y: f.midY)
  5494. let avatarR = min(f.width, f.height) / 2
  5495. let gap: CGFloat = 3.5
  5496. let ringRadius = avatarR + gap
  5497. let d = ringRadius * 2
  5498. CATransaction.begin()
  5499. CATransaction.setDisableActions(true)
  5500. ringLayer.bounds = CGRect(x: 0, y: 0, width: d, height: d)
  5501. ringLayer.position = center
  5502. ringLayer.path = CGPath(ellipseIn: CGRect(origin: .zero, size: CGSize(width: d, height: d)), transform: nil)
  5503. CATransaction.commit()
  5504. }
  5505. override func layout() {
  5506. super.layout()
  5507. layoutRingPathIfNeeded()
  5508. }
  5509. }
  5510. /// Ensures `NSClickGestureRecognizer` on the row receives clicks instead of child label/image views swallowing them.
  5511. private class RowHitTestView: NSView {
  5512. override func hitTest(_ point: NSPoint) -> NSView? {
  5513. return bounds.contains(point) ? self : nil
  5514. }
  5515. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  5516. true
  5517. }
  5518. }
  5519. private final class HoverTrackingView: RowHitTestView {
  5520. var onHoverChanged: ((Bool) -> Void)?
  5521. var onClick: (() -> Void)?
  5522. var showsHandCursor = true
  5523. private var trackingAreaRef: NSTrackingArea?
  5524. private var isHovering = false {
  5525. didSet {
  5526. guard isHovering != oldValue else { return }
  5527. onHoverChanged?(isHovering)
  5528. }
  5529. }
  5530. override func updateTrackingAreas() {
  5531. super.updateTrackingAreas()
  5532. if let trackingAreaRef {
  5533. removeTrackingArea(trackingAreaRef)
  5534. }
  5535. let options: NSTrackingArea.Options = [
  5536. .activeInKeyWindow,
  5537. .inVisibleRect,
  5538. .mouseEnteredAndExited
  5539. ]
  5540. let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  5541. addTrackingArea(area)
  5542. trackingAreaRef = area
  5543. }
  5544. override func mouseEntered(with event: NSEvent) {
  5545. super.mouseEntered(with: event)
  5546. isHovering = true
  5547. }
  5548. override func mouseExited(with event: NSEvent) {
  5549. super.mouseExited(with: event)
  5550. isHovering = false
  5551. }
  5552. override func resetCursorRects() {
  5553. super.resetCursorRects()
  5554. guard showsHandCursor else { return }
  5555. addCursorRect(bounds, cursor: .pointingHand)
  5556. }
  5557. override func mouseUp(with event: NSEvent) {
  5558. super.mouseUp(with: event)
  5559. guard event.type == .leftMouseUp else { return }
  5560. onClick?()
  5561. }
  5562. }
  5563. /// Hover tracking without overriding hit-testing; keeps controls like text fields interactive.
  5564. private final class HoverSurfaceView: NSView {
  5565. var onHoverChanged: ((Bool) -> Void)?
  5566. private var trackingAreaRef: NSTrackingArea?
  5567. private var isHovering = false {
  5568. didSet {
  5569. guard isHovering != oldValue else { return }
  5570. onHoverChanged?(isHovering)
  5571. }
  5572. }
  5573. override func updateTrackingAreas() {
  5574. super.updateTrackingAreas()
  5575. if let trackingAreaRef {
  5576. removeTrackingArea(trackingAreaRef)
  5577. }
  5578. let options: NSTrackingArea.Options = [
  5579. .activeInKeyWindow,
  5580. .inVisibleRect,
  5581. .mouseEnteredAndExited
  5582. ]
  5583. let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  5584. addTrackingArea(area)
  5585. trackingAreaRef = area
  5586. }
  5587. override func mouseEntered(with event: NSEvent) {
  5588. super.mouseEntered(with: event)
  5589. isHovering = true
  5590. }
  5591. override func mouseExited(with event: NSEvent) {
  5592. super.mouseExited(with: event)
  5593. isHovering = false
  5594. }
  5595. }
  5596. private final class HoverButton: NSButton {
  5597. var onHoverChanged: ((Bool) -> Void)?
  5598. var showsHandCursor = true
  5599. private var trackingAreaRef: NSTrackingArea?
  5600. private var isHovering = false {
  5601. didSet {
  5602. guard isHovering != oldValue else { return }
  5603. onHoverChanged?(isHovering)
  5604. }
  5605. }
  5606. override func updateTrackingAreas() {
  5607. super.updateTrackingAreas()
  5608. if let trackingAreaRef {
  5609. removeTrackingArea(trackingAreaRef)
  5610. }
  5611. let options: NSTrackingArea.Options = [
  5612. .activeInKeyWindow,
  5613. .inVisibleRect,
  5614. .mouseEnteredAndExited
  5615. ]
  5616. let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  5617. addTrackingArea(tracking)
  5618. trackingAreaRef = tracking
  5619. }
  5620. override func mouseEntered(with event: NSEvent) {
  5621. super.mouseEntered(with: event)
  5622. if showsHandCursor {
  5623. NSCursor.pointingHand.set()
  5624. }
  5625. isHovering = true
  5626. }
  5627. override func mouseExited(with event: NSEvent) {
  5628. super.mouseExited(with: event)
  5629. isHovering = false
  5630. }
  5631. }
  5632. private final class HoverPopUpButton: NSPopUpButton {
  5633. var onHoverChanged: ((Bool) -> Void)?
  5634. private var trackingAreaRef: NSTrackingArea?
  5635. private var isHovering = false {
  5636. didSet {
  5637. guard isHovering != oldValue else { return }
  5638. onHoverChanged?(isHovering)
  5639. }
  5640. }
  5641. override func updateTrackingAreas() {
  5642. super.updateTrackingAreas()
  5643. if let trackingAreaRef {
  5644. removeTrackingArea(trackingAreaRef)
  5645. }
  5646. let options: NSTrackingArea.Options = [
  5647. .activeInKeyWindow,
  5648. .inVisibleRect,
  5649. .mouseEnteredAndExited
  5650. ]
  5651. let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
  5652. addTrackingArea(tracking)
  5653. trackingAreaRef = tracking
  5654. }
  5655. override func mouseEntered(with event: NSEvent) {
  5656. super.mouseEntered(with: event)
  5657. isHovering = true
  5658. }
  5659. override func mouseExited(with event: NSEvent) {
  5660. super.mouseExited(with: event)
  5661. isHovering = false
  5662. }
  5663. }
  5664. private func circularNSImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
  5665. let size = NSSize(width: diameter, height: diameter)
  5666. let result = NSImage(size: size)
  5667. result.lockFocus()
  5668. if let ctx = NSGraphicsContext.current {
  5669. ctx.imageInterpolation = .high
  5670. }
  5671. let rect = NSRect(origin: .zero, size: size)
  5672. let path = NSBezierPath(ovalIn: rect)
  5673. path.addClip()
  5674. let src = image.size.width > 0 && image.size.height > 0
  5675. ? NSRect(origin: .zero, size: image.size)
  5676. : NSRect(origin: .zero, size: size)
  5677. image.draw(in: rect, from: src, operation: .copy, fraction: 1.0)
  5678. result.unlockFocus()
  5679. result.isTemplate = false
  5680. return result
  5681. }
  5682. private final class GoogleAccountMenuViewController: NSViewController {
  5683. private let palette: Palette
  5684. private let darkModeEnabled: Bool
  5685. private let displayName: String
  5686. private let email: String
  5687. private let avatar: NSImage?
  5688. private let onSignOut: () -> Void
  5689. init(
  5690. palette: Palette,
  5691. darkModeEnabled: Bool,
  5692. displayName: String,
  5693. email: String,
  5694. avatar: NSImage?,
  5695. onSignOut: @escaping () -> Void
  5696. ) {
  5697. self.palette = palette
  5698. self.darkModeEnabled = darkModeEnabled
  5699. self.displayName = displayName
  5700. self.email = email
  5701. self.avatar = avatar
  5702. self.onSignOut = onSignOut
  5703. super.init(nibName: nil, bundle: nil)
  5704. view = makeContentView()
  5705. view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  5706. preferredContentSize = NSSize(width: 300, height: 158)
  5707. }
  5708. @available(*, unavailable)
  5709. required init?(coder: NSCoder) {
  5710. nil
  5711. }
  5712. private func makeContentView() -> NSView {
  5713. let root = NSView()
  5714. root.translatesAutoresizingMaskIntoConstraints = false
  5715. let card = NSView()
  5716. card.translatesAutoresizingMaskIntoConstraints = false
  5717. card.wantsLayer = true
  5718. card.layer?.cornerRadius = 14
  5719. card.layer?.backgroundColor = palette.sectionCard.cgColor
  5720. card.layer?.borderColor = palette.inputBorder.cgColor
  5721. card.layer?.borderWidth = 1
  5722. card.layer?.shadowColor = NSColor.black.cgColor
  5723. card.layer?.shadowOpacity = darkModeEnabled ? 0.5 : 0.2
  5724. card.layer?.shadowOffset = CGSize(width: 0, height: 6)
  5725. card.layer?.shadowRadius = 18
  5726. card.layer?.masksToBounds = false
  5727. root.addSubview(card)
  5728. NSLayoutConstraint.activate([
  5729. card.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 8),
  5730. card.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -8),
  5731. card.topAnchor.constraint(equalTo: root.topAnchor, constant: 8),
  5732. card.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -8),
  5733. root.widthAnchor.constraint(equalToConstant: 300)
  5734. ])
  5735. let inner = NSStackView()
  5736. inner.translatesAutoresizingMaskIntoConstraints = false
  5737. inner.orientation = .vertical
  5738. inner.spacing = 0
  5739. inner.alignment = .leading
  5740. card.addSubview(inner)
  5741. NSLayoutConstraint.activate([
  5742. inner.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
  5743. inner.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
  5744. inner.topAnchor.constraint(equalTo: card.topAnchor, constant: 18),
  5745. inner.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -10)
  5746. ])
  5747. let headerRow = NSView()
  5748. headerRow.translatesAutoresizingMaskIntoConstraints = false
  5749. let avatarBox = NSView()
  5750. avatarBox.translatesAutoresizingMaskIntoConstraints = false
  5751. avatarBox.wantsLayer = true
  5752. avatarBox.layer?.cornerRadius = 24
  5753. avatarBox.layer?.masksToBounds = true
  5754. avatarBox.layer?.borderColor = palette.inputBorder.cgColor
  5755. avatarBox.layer?.borderWidth = 1
  5756. let avatarView = NSImageView()
  5757. avatarView.translatesAutoresizingMaskIntoConstraints = false
  5758. avatarView.imageScaling = .scaleAxesIndependently
  5759. avatarView.image = resolvedAvatarImage()
  5760. avatarBox.addSubview(avatarView)
  5761. NSLayoutConstraint.activate([
  5762. avatarBox.widthAnchor.constraint(equalToConstant: 48),
  5763. avatarBox.heightAnchor.constraint(equalToConstant: 48),
  5764. avatarView.leadingAnchor.constraint(equalTo: avatarBox.leadingAnchor),
  5765. avatarView.trailingAnchor.constraint(equalTo: avatarBox.trailingAnchor),
  5766. avatarView.topAnchor.constraint(equalTo: avatarBox.topAnchor),
  5767. avatarView.bottomAnchor.constraint(equalTo: avatarBox.bottomAnchor)
  5768. ])
  5769. let textColumn = NSStackView()
  5770. textColumn.translatesAutoresizingMaskIntoConstraints = false
  5771. textColumn.orientation = .vertical
  5772. textColumn.spacing = 3
  5773. textColumn.alignment = .leading
  5774. let nameField = NSTextField(labelWithString: displayName)
  5775. nameField.translatesAutoresizingMaskIntoConstraints = false
  5776. nameField.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
  5777. nameField.textColor = palette.textPrimary
  5778. nameField.lineBreakMode = .byTruncatingTail
  5779. nameField.maximumNumberOfLines = 1
  5780. nameField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5781. let emailField = NSTextField(labelWithString: email)
  5782. emailField.translatesAutoresizingMaskIntoConstraints = false
  5783. emailField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
  5784. emailField.textColor = palette.textTertiary
  5785. emailField.lineBreakMode = .byTruncatingTail
  5786. emailField.maximumNumberOfLines = 1
  5787. emailField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
  5788. textColumn.addArrangedSubview(nameField)
  5789. textColumn.addArrangedSubview(emailField)
  5790. headerRow.addSubview(avatarBox)
  5791. headerRow.addSubview(textColumn)
  5792. NSLayoutConstraint.activate([
  5793. avatarBox.leadingAnchor.constraint(equalTo: headerRow.leadingAnchor),
  5794. avatarBox.topAnchor.constraint(equalTo: headerRow.topAnchor),
  5795. avatarBox.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor),
  5796. textColumn.leadingAnchor.constraint(equalTo: avatarBox.trailingAnchor, constant: 14),
  5797. textColumn.trailingAnchor.constraint(equalTo: headerRow.trailingAnchor),
  5798. textColumn.centerYAnchor.constraint(equalTo: avatarBox.centerYAnchor),
  5799. textColumn.topAnchor.constraint(greaterThanOrEqualTo: headerRow.topAnchor),
  5800. textColumn.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor)
  5801. ])
  5802. inner.addArrangedSubview(headerRow)
  5803. headerRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  5804. inner.setCustomSpacing(14, after: headerRow)
  5805. let separator = NSView()
  5806. separator.translatesAutoresizingMaskIntoConstraints = false
  5807. separator.wantsLayer = true
  5808. separator.layer?.backgroundColor = palette.separator.cgColor
  5809. separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
  5810. inner.addArrangedSubview(separator)
  5811. separator.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  5812. inner.setCustomSpacing(6, after: separator)
  5813. let signOutRow = HoverTrackingView()
  5814. signOutRow.translatesAutoresizingMaskIntoConstraints = false
  5815. signOutRow.heightAnchor.constraint(equalToConstant: 44).isActive = true
  5816. signOutRow.wantsLayer = true
  5817. signOutRow.layer?.cornerRadius = 10
  5818. let signOutIcon = NSImageView()
  5819. signOutIcon.translatesAutoresizingMaskIntoConstraints = false
  5820. signOutIcon.imageScaling = .scaleProportionallyDown
  5821. if let sym = NSImage(systemSymbolName: "rectangle.portrait.and.arrow.right", accessibilityDescription: nil) {
  5822. signOutIcon.image = sym
  5823. signOutIcon.contentTintColor = palette.textSecondary
  5824. signOutIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .medium)
  5825. }
  5826. let signOutLabel = NSTextField(labelWithString: "Log out")
  5827. signOutLabel.translatesAutoresizingMaskIntoConstraints = false
  5828. signOutLabel.font = NSFont.systemFont(ofSize: 14, weight: .medium)
  5829. signOutLabel.textColor = palette.textPrimary
  5830. signOutRow.addSubview(signOutIcon)
  5831. signOutRow.addSubview(signOutLabel)
  5832. NSLayoutConstraint.activate([
  5833. signOutIcon.leadingAnchor.constraint(equalTo: signOutRow.leadingAnchor, constant: 10),
  5834. signOutIcon.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
  5835. signOutIcon.widthAnchor.constraint(equalToConstant: 20),
  5836. signOutIcon.heightAnchor.constraint(equalToConstant: 20),
  5837. signOutLabel.leadingAnchor.constraint(equalTo: signOutIcon.trailingAnchor, constant: 10),
  5838. signOutLabel.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
  5839. signOutLabel.trailingAnchor.constraint(lessThanOrEqualTo: signOutRow.trailingAnchor, constant: -10)
  5840. ])
  5841. let signOutClick = NSClickGestureRecognizer(target: self, action: #selector(signOutClicked))
  5842. signOutRow.addGestureRecognizer(signOutClick)
  5843. signOutRow.onHoverChanged = { [weak self] hovering in
  5844. guard let self else { return }
  5845. signOutRow.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
  5846. }
  5847. signOutRow.onHoverChanged?(false)
  5848. inner.addArrangedSubview(signOutRow)
  5849. signOutRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
  5850. return root
  5851. }
  5852. private func resolvedAvatarImage() -> NSImage {
  5853. if let a = avatar {
  5854. return circularNSImage(a, diameter: 48)
  5855. }
  5856. return initialLetterAvatar()
  5857. }
  5858. private func initialLetterAvatar() -> NSImage {
  5859. let d: CGFloat = 48
  5860. let letter = displayName.trimmingCharacters(in: .whitespacesAndNewlines).first.map { String($0).uppercased() } ?? "?"
  5861. let img = NSImage(size: NSSize(width: d, height: d))
  5862. img.lockFocus()
  5863. palette.primaryBlue.setFill()
  5864. NSBezierPath(ovalIn: NSRect(x: 0, y: 0, width: d, height: d)).fill()
  5865. let attrs: [NSAttributedString.Key: Any] = [
  5866. .font: NSFont.systemFont(ofSize: 20, weight: .semibold),
  5867. .foregroundColor: NSColor.white
  5868. ]
  5869. let sz = (letter as NSString).size(withAttributes: attrs)
  5870. let origin = NSPoint(x: (d - sz.width) / 2, y: (d - sz.height) / 2)
  5871. (letter as NSString).draw(at: origin, withAttributes: attrs)
  5872. img.unlockFocus()
  5873. img.isTemplate = false
  5874. return img
  5875. }
  5876. @objc private func signOutClicked() {
  5877. onSignOut()
  5878. }
  5879. }
  5880. private final class SettingsMenuViewController: NSViewController {
  5881. private let palette: Palette
  5882. private let typography: Typography
  5883. private let onToggleDarkMode: (Bool) -> Void
  5884. private let onAction: (SettingsAction, NSView?, NSPoint?) -> Void
  5885. private var darkToggle: NSSwitch?
  5886. init(
  5887. palette: Palette,
  5888. typography: Typography,
  5889. darkModeEnabled: Bool,
  5890. showRateUsInSettings: Bool,
  5891. showUpgradeInSettings: Bool,
  5892. onToggleDarkMode: @escaping (Bool) -> Void,
  5893. onAction: @escaping (SettingsAction, NSView?, NSPoint?) -> Void
  5894. ) {
  5895. self.palette = palette
  5896. self.typography = typography
  5897. self.onToggleDarkMode = onToggleDarkMode
  5898. self.onAction = onAction
  5899. super.init(nibName: nil, bundle: nil)
  5900. self.view = makeView(
  5901. darkModeEnabled: darkModeEnabled,
  5902. showRateUsInSettings: showRateUsInSettings,
  5903. showUpgradeInSettings: showUpgradeInSettings
  5904. )
  5905. }
  5906. @available(*, unavailable)
  5907. required init?(coder: NSCoder) {
  5908. nil
  5909. }
  5910. func setDarkModeEnabled(_ enabled: Bool) {
  5911. darkToggle?.state = enabled ? .on : .off
  5912. }
  5913. private func makeView(
  5914. darkModeEnabled: Bool,
  5915. showRateUsInSettings: Bool,
  5916. showUpgradeInSettings: Bool
  5917. ) -> NSView {
  5918. let root = NSView()
  5919. root.translatesAutoresizingMaskIntoConstraints = false
  5920. let card = roundedCard()
  5921. root.addSubview(card)
  5922. NSLayoutConstraint.activate([
  5923. card.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  5924. card.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  5925. card.topAnchor.constraint(equalTo: root.topAnchor),
  5926. card.bottomAnchor.constraint(equalTo: root.bottomAnchor),
  5927. root.widthAnchor.constraint(equalToConstant: 260)
  5928. ])
  5929. let stack = NSStackView()
  5930. stack.translatesAutoresizingMaskIntoConstraints = false
  5931. stack.orientation = .vertical
  5932. stack.spacing = 6
  5933. stack.alignment = .leading
  5934. card.addSubview(stack)
  5935. NSLayoutConstraint.activate([
  5936. stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
  5937. stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
  5938. stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
  5939. stack.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -14)
  5940. ])
  5941. stack.addArrangedSubview(settingsDarkModeRow(enabled: darkModeEnabled))
  5942. if showRateUsInSettings {
  5943. stack.addArrangedSubview(settingsActionRow(icon: "★", title: "Rate Us", action: .rateUs))
  5944. }
  5945. stack.addArrangedSubview(settingsActionRow(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy))
  5946. stack.addArrangedSubview(settingsActionRow(icon: "💬", title: "Support", action: .support))
  5947. stack.addArrangedSubview(settingsActionRow(icon: "📄", title: "Terms of Services", action: .termsOfServices))
  5948. stack.addArrangedSubview(settingsActionRow(icon: "⤴︎", title: "Share App", action: .shareApp))
  5949. if showUpgradeInSettings {
  5950. stack.addArrangedSubview(settingsActionRow(icon: "⬆︎", title: "Upgrade", action: .upgrade))
  5951. }
  5952. for v in stack.arrangedSubviews {
  5953. v.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  5954. }
  5955. return root
  5956. }
  5957. private func roundedCard() -> NSView {
  5958. let view = NSView()
  5959. view.translatesAutoresizingMaskIntoConstraints = false
  5960. view.wantsLayer = true
  5961. view.layer?.cornerRadius = 12
  5962. view.layer?.backgroundColor = palette.sectionCard.cgColor
  5963. view.layer?.borderColor = palette.inputBorder.cgColor
  5964. view.layer?.borderWidth = 1
  5965. view.layer?.shadowColor = NSColor.black.cgColor
  5966. view.layer?.shadowOpacity = 0.28
  5967. view.layer?.shadowOffset = CGSize(width: 0, height: -1)
  5968. view.layer?.shadowRadius = 10
  5969. return view
  5970. }
  5971. private func settingsDarkModeRow(enabled: Bool) -> NSView {
  5972. let row = NSView()
  5973. row.translatesAutoresizingMaskIntoConstraints = false
  5974. row.heightAnchor.constraint(equalToConstant: 44).isActive = true
  5975. row.wantsLayer = true
  5976. row.layer?.cornerRadius = 10
  5977. let icon = NSTextField(labelWithString: "◐")
  5978. icon.translatesAutoresizingMaskIntoConstraints = false
  5979. icon.font = NSFont.systemFont(ofSize: 18, weight: .medium)
  5980. icon.textColor = palette.textPrimary
  5981. let title = NSTextField(labelWithString: "Dark Mode")
  5982. title.translatesAutoresizingMaskIntoConstraints = false
  5983. title.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  5984. title.textColor = palette.textPrimary
  5985. let toggle = NSSwitch()
  5986. toggle.translatesAutoresizingMaskIntoConstraints = false
  5987. toggle.state = enabled ? .on : .off
  5988. toggle.target = self
  5989. toggle.action = #selector(darkModeToggled(_:))
  5990. darkToggle = toggle
  5991. row.addSubview(icon)
  5992. row.addSubview(title)
  5993. row.addSubview(toggle)
  5994. row.layer?.backgroundColor = NSColor.clear.cgColor
  5995. NSLayoutConstraint.activate([
  5996. icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
  5997. icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  5998. title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
  5999. title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  6000. toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
  6001. toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  6002. ])
  6003. return row
  6004. }
  6005. private func settingsActionRow(icon: String, title: String, action: SettingsAction) -> NSView {
  6006. let row = HoverButton(title: "", target: self, action: #selector(settingsActionButtonPressed(_:)))
  6007. row.tag = action.rawValue
  6008. row.isBordered = false
  6009. row.translatesAutoresizingMaskIntoConstraints = false
  6010. row.heightAnchor.constraint(equalToConstant: 42).isActive = true
  6011. row.wantsLayer = true
  6012. row.layer?.cornerRadius = 10
  6013. row.layer?.backgroundColor = NSColor.clear.cgColor
  6014. let iconLabel = NSTextField(labelWithString: icon)
  6015. iconLabel.translatesAutoresizingMaskIntoConstraints = false
  6016. iconLabel.font = NSFont.systemFont(ofSize: 18, weight: .medium)
  6017. iconLabel.textColor = palette.textPrimary
  6018. let titleLabel = NSTextField(labelWithString: title)
  6019. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  6020. titleLabel.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  6021. titleLabel.textColor = palette.textPrimary
  6022. row.addSubview(iconLabel)
  6023. row.addSubview(titleLabel)
  6024. NSLayoutConstraint.activate([
  6025. iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
  6026. iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
  6027. titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
  6028. titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor)
  6029. ])
  6030. row.onHoverChanged = { hovering in
  6031. row.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
  6032. }
  6033. row.onHoverChanged?(false)
  6034. return row
  6035. }
  6036. @objc private func darkModeToggled(_ sender: NSSwitch) {
  6037. onToggleDarkMode(sender.state == .on)
  6038. }
  6039. @objc private func settingsActionButtonPressed(_ sender: NSButton) {
  6040. guard let action = SettingsAction(rawValue: sender.tag) else { return }
  6041. let clickPoint: NSPoint?
  6042. if let event = NSApp.currentEvent {
  6043. let pointInWindow = event.locationInWindow
  6044. clickPoint = sender.convert(pointInWindow, from: nil)
  6045. } else {
  6046. clickPoint = nil
  6047. }
  6048. onAction(action, sender, clickPoint)
  6049. }
  6050. }
  6051. private extension ViewController {
  6052. private func hasGoogleSessionAvailable() -> Bool {
  6053. guard let tokens = googleOAuth.loadTokens() else { return false }
  6054. if tokens.expiresAt.timeIntervalSinceNow > 60 {
  6055. return true
  6056. }
  6057. return (tokens.refreshToken?.isEmpty == false)
  6058. }
  6059. private func requireGoogleLoginForCalendarScheduling() -> Bool {
  6060. guard hasGoogleSessionAvailable() else {
  6061. showSimpleAlert(
  6062. title: "Connect Google",
  6063. message: "Sign in with Google first to schedule a meeting from Calendar."
  6064. )
  6065. return false
  6066. }
  6067. return true
  6068. }
  6069. func roundedContainer(cornerRadius: CGFloat, color: NSColor) -> NSView {
  6070. let view = NSView()
  6071. view.wantsLayer = true
  6072. view.layer?.backgroundColor = color.cgColor
  6073. view.layer?.cornerRadius = cornerRadius
  6074. return view
  6075. }
  6076. func styleSurface(_ view: NSView, borderColor: NSColor, borderWidth: CGFloat, shadow: Bool) {
  6077. view.layer?.borderColor = borderColor.cgColor
  6078. view.layer?.borderWidth = borderWidth
  6079. if shadow {
  6080. view.layer?.shadowColor = NSColor.black.cgColor
  6081. view.layer?.shadowOpacity = 0.18
  6082. view.layer?.shadowOffset = CGSize(width: 0, height: -1)
  6083. view.layer?.shadowRadius = 5
  6084. }
  6085. }
  6086. func textLabel(_ text: String, font: NSFont, color: NSColor) -> NSTextField {
  6087. let label = NSTextField(labelWithString: text)
  6088. label.translatesAutoresizingMaskIntoConstraints = false
  6089. label.textColor = color
  6090. label.font = font
  6091. return label
  6092. }
  6093. func iconLabel(_ text: String, size: CGFloat) -> NSTextField {
  6094. let label = NSTextField(labelWithString: text)
  6095. label.translatesAutoresizingMaskIntoConstraints = false
  6096. label.font = NSFont.systemFont(ofSize: size)
  6097. return label
  6098. }
  6099. func sidebarSectionTitle(_ text: String) -> NSTextField {
  6100. let sectionColor = darkModeEnabled ? palette.textMuted : NSColor(calibratedWhite: 0.14, alpha: 1.0)
  6101. let field = textLabel(text, font: typography.sidebarSection, color: sectionColor)
  6102. field.alignment = .left
  6103. return field
  6104. }
  6105. func sidebarItem(_ text: String, icon: String, page: SidebarPage, logoImageName: String? = nil, systemSymbolName: String? = nil, logoIconWidth: CGFloat = 18, logoHeightMultiplier: CGFloat = 1, logoTemplate: Bool = true, showsDisclosure: Bool = false) -> NSView {
  6106. let item = HoverButton(title: "", target: self, action: #selector(sidebarButtonClicked(_:)))
  6107. item.tag = page.rawValue
  6108. item.isBordered = false
  6109. item.wantsLayer = true
  6110. item.layer?.cornerRadius = 10
  6111. item.layer?.backgroundColor = NSColor.clear.cgColor
  6112. item.translatesAutoresizingMaskIntoConstraints = false
  6113. item.heightAnchor.constraint(equalToConstant: 36).isActive = true
  6114. item.layer?.borderWidth = 0
  6115. sidebarPageByView[ObjectIdentifier(item)] = page
  6116. let leadingView: NSView
  6117. if let name = logoImageName, let logo = NSImage(named: name) {
  6118. logo.isTemplate = true
  6119. let imageView = NSImageView(image: logo)
  6120. imageView.translatesAutoresizingMaskIntoConstraints = false
  6121. imageView.imageScaling = .scaleProportionallyDown
  6122. imageView.imageAlignment = .alignCenter
  6123. imageView.isEditable = false
  6124. leadingView = imageView
  6125. } else if let symbolName = systemSymbolName, let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) {
  6126. symbol.isTemplate = true
  6127. let imageView = NSImageView(image: symbol)
  6128. imageView.translatesAutoresizingMaskIntoConstraints = false
  6129. imageView.imageScaling = .scaleProportionallyDown
  6130. imageView.imageAlignment = .alignCenter
  6131. imageView.isEditable = false
  6132. leadingView = imageView
  6133. } else {
  6134. leadingView = textLabel(icon, font: typography.sidebarIcon, color: palette.textSecondary)
  6135. }
  6136. let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
  6137. let titleLabel = textLabel(text, font: typography.sidebarItem, color: baseSidebarTextColor)
  6138. titleLabel.alignment = .left
  6139. item.addSubview(leadingView)
  6140. item.addSubview(titleLabel)
  6141. var constraints: [NSLayoutConstraint] = [
  6142. leadingView.leadingAnchor.constraint(equalTo: item.leadingAnchor, constant: 12),
  6143. leadingView.centerYAnchor.constraint(equalTo: item.centerYAnchor),
  6144. titleLabel.leadingAnchor.constraint(equalTo: leadingView.trailingAnchor, constant: 8),
  6145. titleLabel.centerYAnchor.constraint(equalTo: item.centerYAnchor)
  6146. ]
  6147. if showsDisclosure {
  6148. let chevron = textLabel("›", font: NSFont.systemFont(ofSize: 22, weight: .semibold), color: baseSidebarTextColor)
  6149. chevron.translatesAutoresizingMaskIntoConstraints = false
  6150. chevron.alignment = .right
  6151. item.addSubview(chevron)
  6152. constraints.append(contentsOf: [
  6153. chevron.trailingAnchor.constraint(equalTo: item.trailingAnchor, constant: -10),
  6154. chevron.centerYAnchor.constraint(equalTo: item.centerYAnchor),
  6155. titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: chevron.leadingAnchor, constant: -8)
  6156. ])
  6157. } else {
  6158. constraints.append(titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: item.trailingAnchor, constant: -10))
  6159. }
  6160. if logoImageName != nil || systemSymbolName != nil {
  6161. let h = logoIconWidth * logoHeightMultiplier
  6162. constraints.append(contentsOf: [
  6163. leadingView.widthAnchor.constraint(equalToConstant: logoIconWidth),
  6164. leadingView.heightAnchor.constraint(equalToConstant: h)
  6165. ])
  6166. }
  6167. NSLayoutConstraint.activate(constraints)
  6168. applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate)
  6169. item.onHoverChanged = { [weak self, weak item] hovering in
  6170. guard let self, let item else { return }
  6171. self.applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate, hovering: hovering)
  6172. }
  6173. return item
  6174. }
  6175. func applySidebarRowStyle(_ item: NSView, page: SidebarPage, logoTemplate: Bool, hovering: Bool = false) {
  6176. let selected = (page == selectedSidebarPage)
  6177. let hoverColor = darkModeEnabled ? NSColor(calibratedWhite: 1, alpha: 0.07) : NSColor(calibratedWhite: 0, alpha: 0.08)
  6178. item.layer?.backgroundColor = (selected ? palette.primaryBlue : (hovering ? hoverColor : NSColor.clear)).cgColor
  6179. let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
  6180. let tint = selected ? NSColor.white : baseSidebarTextColor
  6181. let sidebarIconTint = darkModeEnabled ? tint : baseSidebarTextColor
  6182. guard item.subviews.count >= 2 else { return }
  6183. let leading = item.subviews[0]
  6184. let title = item.subviews.first { $0 is NSTextField } as? NSTextField
  6185. title?.textColor = tint
  6186. // Optional disclosure chevron (if present) is the last text field.
  6187. if let chevron = item.subviews.last as? NSTextField, chevron !== title {
  6188. chevron.textColor = sidebarIconTint
  6189. }
  6190. if let imageView = leading as? NSImageView {
  6191. if logoTemplate {
  6192. imageView.contentTintColor = sidebarIconTint
  6193. }
  6194. } else if let iconField = leading as? NSTextField {
  6195. iconField.textColor = sidebarIconTint
  6196. }
  6197. }
  6198. func actionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat) -> NSView {
  6199. let button = HoverTrackingView()
  6200. button.wantsLayer = true
  6201. button.layer?.cornerRadius = 9
  6202. button.layer?.backgroundColor = color.cgColor
  6203. button.translatesAutoresizingMaskIntoConstraints = false
  6204. button.widthAnchor.constraint(equalToConstant: width).isActive = true
  6205. button.heightAnchor.constraint(equalToConstant: 36).isActive = true
  6206. styleSurface(button, borderColor: title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder, borderWidth: 1, shadow: false)
  6207. if title == "Cancel" {
  6208. button.layer?.backgroundColor = palette.cancelButton.cgColor
  6209. }
  6210. let label = textLabel(title, font: typography.buttonText, color: textColor)
  6211. button.addSubview(label)
  6212. NSLayoutConstraint.activate([
  6213. label.centerXAnchor.constraint(equalTo: button.centerXAnchor),
  6214. label.centerYAnchor.constraint(equalTo: button.centerYAnchor)
  6215. ])
  6216. let baseColor = (title == "Cancel") ? palette.cancelButton : color
  6217. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  6218. let hoverColor = baseColor.blended(withFraction: 0.12, of: hoverBlend) ?? baseColor
  6219. button.onHoverChanged = { hovering in
  6220. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  6221. }
  6222. button.onHoverChanged?(false)
  6223. return button
  6224. }
  6225. func iconRoundButton(systemSymbol: String, size: CGFloat, iconPointSize: CGFloat = 16, onClick: (() -> Void)? = nil) -> NSView {
  6226. let button = HoverTrackingView()
  6227. button.wantsLayer = true
  6228. button.layer?.cornerRadius = size / 2
  6229. button.layer?.backgroundColor = palette.inputBackground.cgColor
  6230. button.translatesAutoresizingMaskIntoConstraints = false
  6231. button.widthAnchor.constraint(equalToConstant: size).isActive = true
  6232. button.heightAnchor.constraint(equalToConstant: size).isActive = true
  6233. styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  6234. let symbolConfig = NSImage.SymbolConfiguration(pointSize: iconPointSize, weight: .semibold)
  6235. let iconView = NSImageView()
  6236. iconView.translatesAutoresizingMaskIntoConstraints = false
  6237. iconView.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Refresh")
  6238. iconView.symbolConfiguration = symbolConfig
  6239. iconView.contentTintColor = palette.textSecondary
  6240. button.addSubview(iconView)
  6241. NSLayoutConstraint.activate([
  6242. iconView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
  6243. iconView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
  6244. ])
  6245. let baseColor = palette.inputBackground
  6246. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  6247. let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
  6248. button.onHoverChanged = { hovering in
  6249. button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
  6250. }
  6251. button.onHoverChanged?(false)
  6252. button.onClick = onClick
  6253. return button
  6254. }
  6255. }
  6256. private let calendarDayKeyFormatter: DateFormatter = {
  6257. let f = DateFormatter()
  6258. f.calendar = Calendar(identifier: .gregorian)
  6259. f.locale = Locale(identifier: "en_US_POSIX")
  6260. f.timeZone = TimeZone.current
  6261. f.dateFormat = "yyyy-MM-dd"
  6262. return f
  6263. }()
  6264. // MARK: - Calendar page actions + rendering
  6265. private extension ViewController {
  6266. private func makeCalendarHeaderPillButton(title: String, action: Selector) -> NSButton {
  6267. let button = makeSchedulePillButton(title: title)
  6268. button.target = self
  6269. button.action = action
  6270. button.heightAnchor.constraint(equalToConstant: 30).isActive = true
  6271. return button
  6272. }
  6273. private func calendarStartOfMonth(for date: Date) -> Date {
  6274. let calendar = Calendar.current
  6275. let comps = calendar.dateComponents([.year, .month], from: date)
  6276. return calendar.date(from: comps) ?? calendar.startOfDay(for: date)
  6277. }
  6278. private func calendarMonthTitleText(for monthAnchor: Date) -> String {
  6279. let f = DateFormatter()
  6280. f.locale = Locale.current
  6281. f.timeZone = TimeZone.current
  6282. f.dateFormat = "MMMM yyyy"
  6283. return f.string(from: monthAnchor)
  6284. }
  6285. private func calendarWeekdaySymbolsStartingAtFirstWeekday() -> [String] {
  6286. // Align weekday header to Calendar.current.firstWeekday
  6287. let calendar = Calendar.current
  6288. var symbols = DateFormatter().veryShortWeekdaySymbols ?? ["S", "M", "T", "W", "T", "F", "S"]
  6289. // veryShortWeekdaySymbols starts with Sunday in most locales; rotate to firstWeekday.
  6290. let first = max(1, min(7, calendar.firstWeekday)) // 1..7
  6291. let shift = (first - 1) % 7
  6292. if shift == 0 { return symbols }
  6293. let head = Array(symbols[shift...])
  6294. let tail = Array(symbols[..<shift])
  6295. symbols = head + tail
  6296. return symbols
  6297. }
  6298. @objc func calendarPrevMonthPressed(_ sender: NSButton) {
  6299. let calendar = Calendar.current
  6300. calendarPageMonthAnchor = calendar.date(byAdding: .month, value: -1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
  6301. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  6302. renderCalendarMonthGrid()
  6303. }
  6304. @objc func calendarNextMonthPressed(_ sender: NSButton) {
  6305. let calendar = Calendar.current
  6306. calendarPageMonthAnchor = calendar.date(byAdding: .month, value: 1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
  6307. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  6308. renderCalendarMonthGrid()
  6309. }
  6310. @objc func calendarRefreshPressed(_ sender: NSButton) {
  6311. Task { [weak self] in
  6312. await self?.loadSchedule()
  6313. }
  6314. }
  6315. @objc func calendarDayCellPressed(_ sender: NSButton) {
  6316. guard requireGoogleLoginForCalendarScheduling() else { return }
  6317. guard let raw = sender.identifier?.rawValue,
  6318. let date = calendarDayKeyFormatter.date(from: raw) else { return }
  6319. calendarPageSelectedDate = Calendar.current.startOfDay(for: date)
  6320. renderCalendarMonthGrid()
  6321. renderCalendarSelectedDay()
  6322. if let refreshedButton = calendarButton(forDateKey: raw) {
  6323. showCalendarDayActionPopover(relativeTo: refreshedButton)
  6324. }
  6325. }
  6326. private func showCalendarDayActionPopover(relativeTo anchor: NSView) {
  6327. guard anchor.window != nil else { return }
  6328. calendarPageActionPopover?.performClose(nil)
  6329. let popover = NSPopover()
  6330. popover.behavior = .transient
  6331. popover.animates = true
  6332. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  6333. popover.contentViewController = CalendarDayActionMenuViewController(
  6334. palette: palette,
  6335. onSchedule: { [weak self] in
  6336. self?.calendarPageActionPopover?.performClose(nil)
  6337. self?.calendarPageActionPopover = nil
  6338. self?.presentCreateMeetingPopover(relativeTo: anchor)
  6339. }
  6340. )
  6341. calendarPageActionPopover = popover
  6342. popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
  6343. }
  6344. private func presentCreateMeetingPopover(relativeTo anchor: NSView) {
  6345. guard anchor.window != nil else { return }
  6346. calendarPageCreatePopover?.performClose(nil)
  6347. let popover = NSPopover()
  6348. popover.behavior = .transient
  6349. popover.animates = true
  6350. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  6351. let selectedDate = Calendar.current.startOfDay(for: calendarPageSelectedDate)
  6352. let vc = CreateMeetingPopoverViewController(
  6353. palette: palette,
  6354. typography: typography,
  6355. selectedDate: selectedDate,
  6356. onCancel: { [weak self] in
  6357. self?.calendarPageCreatePopover?.performClose(nil)
  6358. self?.calendarPageCreatePopover = nil
  6359. },
  6360. onSave: { [weak self] draft in
  6361. guard let self else { return }
  6362. self.calendarPageCreatePopover?.performClose(nil)
  6363. self.calendarPageCreatePopover = nil
  6364. self.calendarCreateMeeting(title: draft.title, notes: draft.notes, start: draft.startDate, end: draft.endDate)
  6365. }
  6366. )
  6367. popover.contentViewController = vc
  6368. calendarPageCreatePopover = popover
  6369. popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
  6370. }
  6371. private func calendarCreateMeeting(title: String, notes: String?, start: Date, end: Date) {
  6372. Task { [weak self] in
  6373. guard let self else { return }
  6374. do {
  6375. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  6376. let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  6377. _ = try await self.calendarClient.createEvent(
  6378. accessToken: token,
  6379. title: title,
  6380. description: notes,
  6381. start: start,
  6382. end: end,
  6383. timeZone: .current
  6384. )
  6385. await self.loadSchedule()
  6386. await MainActor.run {
  6387. let calendar = Calendar.current
  6388. self.calendarPageSelectedDate = calendar.startOfDay(for: start)
  6389. self.calendarPageMonthAnchor = self.calendarStartOfMonth(for: start)
  6390. self.calendarPageMonthLabel?.stringValue = self.calendarMonthTitleText(for: self.calendarPageMonthAnchor)
  6391. self.renderCalendarMonthGrid()
  6392. self.renderCalendarSelectedDay()
  6393. self.showTopToast(message: "Meeting added successfully.", isError: false)
  6394. }
  6395. } catch {
  6396. await MainActor.run {
  6397. self.showTopToast(message: "An issue occurred. Please try again.", isError: true)
  6398. }
  6399. }
  6400. }
  6401. }
  6402. private func renderCalendarMonthGrid() {
  6403. guard let gridStack = calendarPageGridStack else { return }
  6404. gridStack.arrangedSubviews.forEach { v in
  6405. gridStack.removeArrangedSubview(v)
  6406. v.removeFromSuperview()
  6407. }
  6408. let calendar = Calendar.current
  6409. let monthStart = calendarStartOfMonth(for: calendarPageMonthAnchor)
  6410. guard let dayRange = calendar.range(of: .day, in: .month, for: monthStart),
  6411. let monthEnd = calendar.date(byAdding: DateComponents(month: 1, day: 0), to: monthStart) else { return }
  6412. let firstWeekday = calendar.component(.weekday, from: monthStart) // 1..7
  6413. let leadingEmpty = (firstWeekday - calendar.firstWeekday + 7) % 7
  6414. let totalDays = dayRange.count
  6415. let totalCells = leadingEmpty + totalDays
  6416. let rowCount = Int(ceil(Double(totalCells) / 7.0))
  6417. let rowHeight: CGFloat = 56
  6418. let rowSpacing: CGFloat = 12
  6419. let verticalPadding: CGFloat = 32
  6420. calendarPageGridHeightConstraint?.constant = verticalPadding + (CGFloat(rowCount) * rowHeight) + (CGFloat(max(0, rowCount - 1)) * rowSpacing)
  6421. let meetingCounts = calendarMeetingCountsByDay(from: scheduleCachedMeetings, monthStart: monthStart, monthEnd: monthEnd)
  6422. var day = 1
  6423. for _ in 0..<rowCount {
  6424. let row = NSStackView()
  6425. row.translatesAutoresizingMaskIntoConstraints = false
  6426. row.userInterfaceLayoutDirection = .leftToRight
  6427. row.orientation = .horizontal
  6428. row.alignment = .top
  6429. row.distribution = .fillEqually
  6430. row.spacing = rowSpacing
  6431. row.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true
  6432. for col in 0..<7 {
  6433. let cellIndex = (gridStack.arrangedSubviews.count * 7) + col
  6434. if cellIndex < leadingEmpty || day > totalDays {
  6435. row.addArrangedSubview(calendarEmptyDayCell())
  6436. continue
  6437. }
  6438. guard let date = calendar.date(byAdding: .day, value: day - 1, to: monthStart) else {
  6439. row.addArrangedSubview(calendarEmptyDayCell())
  6440. continue
  6441. }
  6442. let isSelected = calendar.isDate(date, inSameDayAs: calendarPageSelectedDate)
  6443. let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: date))
  6444. let count = meetingCounts[key] ?? 0
  6445. row.addArrangedSubview(calendarDayCell(dayNumber: day, dateKey: key, meetingCount: count, isSelected: isSelected))
  6446. day += 1
  6447. }
  6448. gridStack.addArrangedSubview(row)
  6449. row.widthAnchor.constraint(equalTo: gridStack.widthAnchor).isActive = true
  6450. }
  6451. }
  6452. private func calendarButton(forDateKey key: String) -> NSButton? {
  6453. guard let gridStack = calendarPageGridStack else { return nil }
  6454. for rowView in gridStack.arrangedSubviews {
  6455. guard let row = rowView as? NSStackView else { continue }
  6456. for cell in row.arrangedSubviews {
  6457. if let button = cell as? NSButton, button.identifier?.rawValue == key {
  6458. return button
  6459. }
  6460. }
  6461. }
  6462. return nil
  6463. }
  6464. private func renderCalendarSelectedDay() {
  6465. let calendar = Calendar.current
  6466. let selectedDay = calendar.startOfDay(for: calendarPageSelectedDate)
  6467. let nextDay = calendar.date(byAdding: .day, value: 1, to: selectedDay) ?? selectedDay.addingTimeInterval(86400)
  6468. let meetings = scheduleCachedMeetings
  6469. .filter { $0.startDate >= selectedDay && $0.startDate < nextDay }
  6470. .sorted(by: { $0.startDate < $1.startDate })
  6471. let f = DateFormatter()
  6472. f.locale = Locale.current
  6473. f.timeZone = TimeZone.current
  6474. f.dateFormat = "EEE, d MMM"
  6475. if meetings.isEmpty {
  6476. calendarPageDaySummaryLabel?.stringValue = hasGoogleSessionAvailable() == false
  6477. ? "Connect Google to see meetings"
  6478. : "No meetings on \(f.string(from: selectedDay))"
  6479. } else if meetings.count == 1 {
  6480. calendarPageDaySummaryLabel?.stringValue = "1 meeting on \(f.string(from: selectedDay))"
  6481. } else {
  6482. calendarPageDaySummaryLabel?.stringValue = "\(meetings.count) meetings on \(f.string(from: selectedDay))"
  6483. }
  6484. }
  6485. private func calendarMeetingCountsByDay(from meetings: [ScheduledMeeting], monthStart: Date, monthEnd: Date) -> [String: Int] {
  6486. let calendar = Calendar.current
  6487. var counts: [String: Int] = [:]
  6488. for meeting in meetings {
  6489. guard meeting.startDate >= monthStart && meeting.startDate < monthEnd else { continue }
  6490. let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: meeting.startDate))
  6491. counts[key, default: 0] += 1
  6492. }
  6493. return counts
  6494. }
  6495. private func calendarEmptyDayCell() -> NSView {
  6496. let v = NSView()
  6497. v.translatesAutoresizingMaskIntoConstraints = false
  6498. v.heightAnchor.constraint(equalToConstant: 56).isActive = true
  6499. return v
  6500. }
  6501. private func calendarDayCell(dayNumber: Int, dateKey: String, meetingCount: Int, isSelected: Bool) -> NSButton {
  6502. let button = HoverButton(title: "", target: self, action: #selector(calendarDayCellPressed(_:)))
  6503. button.translatesAutoresizingMaskIntoConstraints = false
  6504. button.isBordered = false
  6505. button.bezelStyle = .regularSquare
  6506. button.wantsLayer = true
  6507. button.layer?.cornerRadius = 12
  6508. button.layer?.masksToBounds = true
  6509. button.identifier = NSUserInterfaceItemIdentifier(dateKey)
  6510. button.heightAnchor.constraint(equalToConstant: 56).isActive = true
  6511. button.setContentHuggingPriority(.required, for: .vertical)
  6512. button.setContentCompressionResistancePriority(.required, for: .vertical)
  6513. button.alignment = .left
  6514. button.imagePosition = .noImage
  6515. let base = palette.inputBackground
  6516. let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
  6517. let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
  6518. let selectedBackground = darkModeEnabled
  6519. ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
  6520. : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
  6521. let borderIdle = palette.inputBorder
  6522. let borderSelected = palette.primaryBlueBorder
  6523. func applyAppearance(hovering: Bool) {
  6524. button.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hover : base)).cgColor
  6525. button.layer?.borderWidth = isSelected ? 1.5 : 1
  6526. button.layer?.borderColor = (isSelected ? borderSelected : borderIdle).cgColor
  6527. }
  6528. applyAppearance(hovering: false)
  6529. button.onHoverChanged = { hovering in
  6530. applyAppearance(hovering: hovering)
  6531. }
  6532. button.attributedTitle = NSAttributedString(
  6533. string: " \(dayNumber)",
  6534. attributes: [
  6535. .font: NSFont.systemFont(ofSize: 14, weight: .bold),
  6536. .foregroundColor: palette.textPrimary
  6537. ]
  6538. )
  6539. if meetingCount > 0 {
  6540. let dot = roundedContainer(cornerRadius: 4, color: palette.meetingBadge)
  6541. dot.translatesAutoresizingMaskIntoConstraints = false
  6542. dot.layer?.borderWidth = 0
  6543. button.addSubview(dot)
  6544. NSLayoutConstraint.activate([
  6545. dot.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -10),
  6546. dot.centerYAnchor.constraint(equalTo: button.centerYAnchor),
  6547. dot.widthAnchor.constraint(equalToConstant: 8),
  6548. dot.heightAnchor.constraint(equalToConstant: 8)
  6549. ])
  6550. }
  6551. return button
  6552. }
  6553. }
  6554. private final class CalendarDayActionMenuViewController: NSViewController {
  6555. private let palette: Palette
  6556. private let onSchedule: () -> Void
  6557. init(palette: Palette, onSchedule: @escaping () -> Void) {
  6558. self.palette = palette
  6559. self.onSchedule = onSchedule
  6560. super.init(nibName: nil, bundle: nil)
  6561. }
  6562. required init?(coder: NSCoder) { nil }
  6563. override func loadView() {
  6564. let root = NSView()
  6565. root.translatesAutoresizingMaskIntoConstraints = false
  6566. let stack = NSStackView()
  6567. stack.translatesAutoresizingMaskIntoConstraints = false
  6568. stack.orientation = .vertical
  6569. stack.alignment = .leading
  6570. stack.spacing = 10
  6571. let title = NSTextField(labelWithString: "Actions")
  6572. title.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
  6573. title.textColor = palette.textMuted
  6574. let schedule = NSButton(title: "Schedule meeting", target: self, action: #selector(schedulePressed(_:)))
  6575. schedule.bezelStyle = .rounded
  6576. schedule.font = NSFont.systemFont(ofSize: 13, weight: .medium)
  6577. stack.addArrangedSubview(title)
  6578. stack.addArrangedSubview(schedule)
  6579. root.addSubview(stack)
  6580. NSLayoutConstraint.activate([
  6581. root.widthAnchor.constraint(equalToConstant: 220),
  6582. root.heightAnchor.constraint(greaterThanOrEqualToConstant: 86),
  6583. stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14),
  6584. stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -14),
  6585. stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
  6586. stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -12)
  6587. ])
  6588. view = root
  6589. }
  6590. @objc private func schedulePressed(_ sender: NSButton) {
  6591. onSchedule()
  6592. }
  6593. }
  6594. private final class CreateMeetingPopoverViewController: NSViewController, NSTextViewDelegate {
  6595. struct Draft {
  6596. let title: String
  6597. let notes: String?
  6598. let startDate: Date
  6599. let endDate: Date
  6600. }
  6601. private let palette: Palette
  6602. private let typography: Typography
  6603. private let selectedDate: Date
  6604. private let onCancel: () -> Void
  6605. private let onSave: (Draft) -> Void
  6606. private var titleField: NSTextField?
  6607. private var timePicker: NSDatePicker?
  6608. private var durationField: NSTextField?
  6609. private var notesView: NSTextView?
  6610. private var notesScrollView: NSScrollView?
  6611. private var errorLabel: NSTextField?
  6612. private var notesBorderIdle = NSColor.clear
  6613. private var notesBorderHover = NSColor.clear
  6614. private var notesBorderFocused = NSColor.clear
  6615. private var notesIsHovered = false
  6616. private var notesIsFocused = false
  6617. init(palette: Palette,
  6618. typography: Typography,
  6619. selectedDate: Date,
  6620. onCancel: @escaping () -> Void,
  6621. onSave: @escaping (Draft) -> Void) {
  6622. self.palette = palette
  6623. self.typography = typography
  6624. self.selectedDate = selectedDate
  6625. self.onCancel = onCancel
  6626. self.onSave = onSave
  6627. super.init(nibName: nil, bundle: nil)
  6628. }
  6629. required init?(coder: NSCoder) { nil }
  6630. override func loadView() {
  6631. let root = NSView()
  6632. root.translatesAutoresizingMaskIntoConstraints = false
  6633. root.userInterfaceLayoutDirection = .leftToRight
  6634. root.wantsLayer = true
  6635. root.layer?.cornerRadius = 14
  6636. root.layer?.masksToBounds = true
  6637. root.layer?.backgroundColor = palette.sectionCard.cgColor
  6638. root.layer?.borderWidth = 1
  6639. root.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.9).cgColor
  6640. let stack = NSStackView()
  6641. stack.translatesAutoresizingMaskIntoConstraints = false
  6642. stack.orientation = .vertical
  6643. stack.alignment = .leading
  6644. stack.spacing = 14
  6645. stack.userInterfaceLayoutDirection = .leftToRight
  6646. let inputSurface = palette.inputBackground.blended(withFraction: 0.18, of: palette.sectionCard) ?? palette.inputBackground
  6647. let fieldBorder = palette.textSecondary.withAlphaComponent(0.4)
  6648. notesBorderIdle = fieldBorder
  6649. notesBorderHover = palette.textSecondary.withAlphaComponent(0.72)
  6650. notesBorderFocused = palette.primaryBlueBorder
  6651. let header = NSTextField(labelWithString: "Schedule meeting")
  6652. header.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
  6653. header.textColor = palette.textPrimary
  6654. header.alignment = .left
  6655. header.userInterfaceLayoutDirection = .leftToRight
  6656. header.baseWritingDirection = .leftToRight
  6657. let titleLabel = NSTextField(labelWithString: "Title")
  6658. titleLabel.font = typography.fieldLabel
  6659. titleLabel.textColor = palette.textSecondary
  6660. titleLabel.alignment = .left
  6661. titleLabel.userInterfaceLayoutDirection = .leftToRight
  6662. titleLabel.baseWritingDirection = .leftToRight
  6663. let titleShell = NSView()
  6664. titleShell.translatesAutoresizingMaskIntoConstraints = false
  6665. titleShell.wantsLayer = true
  6666. titleShell.layer?.cornerRadius = 8
  6667. titleShell.layer?.backgroundColor = inputSurface.cgColor
  6668. titleShell.layer?.borderColor = fieldBorder.cgColor
  6669. titleShell.layer?.borderWidth = 1.2
  6670. titleShell.heightAnchor.constraint(equalToConstant: 40).isActive = true
  6671. let titleField = NSTextField(string: "")
  6672. titleField.translatesAutoresizingMaskIntoConstraints = false
  6673. titleField.isBordered = false
  6674. titleField.drawsBackground = false
  6675. titleField.focusRingType = .none
  6676. titleField.font = NSFont.systemFont(ofSize: 14, weight: .regular)
  6677. titleField.textColor = palette.textPrimary
  6678. titleField.placeholderString = "Team sync"
  6679. titleShell.addSubview(titleField)
  6680. NSLayoutConstraint.activate([
  6681. titleField.leadingAnchor.constraint(equalTo: titleShell.leadingAnchor, constant: 10),
  6682. titleField.trailingAnchor.constraint(equalTo: titleShell.trailingAnchor, constant: -10),
  6683. titleField.centerYAnchor.constraint(equalTo: titleShell.centerYAnchor)
  6684. ])
  6685. self.titleField = titleField
  6686. let timeRow = NSStackView()
  6687. timeRow.translatesAutoresizingMaskIntoConstraints = false
  6688. timeRow.orientation = .horizontal
  6689. timeRow.alignment = .centerY
  6690. timeRow.spacing = 10
  6691. timeRow.distribution = .fill
  6692. let startLabel = NSTextField(labelWithString: "Start")
  6693. startLabel.font = typography.fieldLabel
  6694. startLabel.textColor = palette.textSecondary
  6695. startLabel.alignment = .left
  6696. startLabel.userInterfaceLayoutDirection = .leftToRight
  6697. startLabel.baseWritingDirection = .leftToRight
  6698. let pickerShell = NSView()
  6699. pickerShell.translatesAutoresizingMaskIntoConstraints = false
  6700. pickerShell.wantsLayer = true
  6701. pickerShell.layer?.cornerRadius = 8
  6702. pickerShell.layer?.backgroundColor = inputSurface.cgColor
  6703. pickerShell.layer?.borderColor = fieldBorder.cgColor
  6704. pickerShell.layer?.borderWidth = 1.2
  6705. pickerShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
  6706. let timePicker = NSDatePicker()
  6707. timePicker.translatesAutoresizingMaskIntoConstraints = false
  6708. timePicker.isBordered = false
  6709. timePicker.drawsBackground = false
  6710. timePicker.focusRingType = .none
  6711. timePicker.datePickerStyle = .textFieldAndStepper
  6712. timePicker.datePickerElements = [.hourMinute]
  6713. timePicker.font = typography.filterText
  6714. timePicker.textColor = palette.textSecondary
  6715. timePicker.dateValue = Date()
  6716. pickerShell.addSubview(timePicker)
  6717. NSLayoutConstraint.activate([
  6718. timePicker.leadingAnchor.constraint(equalTo: pickerShell.leadingAnchor, constant: 8),
  6719. timePicker.trailingAnchor.constraint(equalTo: pickerShell.trailingAnchor, constant: -8),
  6720. timePicker.centerYAnchor.constraint(equalTo: pickerShell.centerYAnchor)
  6721. ])
  6722. self.timePicker = timePicker
  6723. let durationLabel = NSTextField(labelWithString: "Duration (min)")
  6724. durationLabel.font = typography.fieldLabel
  6725. durationLabel.textColor = palette.textSecondary
  6726. durationLabel.alignment = .left
  6727. durationLabel.userInterfaceLayoutDirection = .leftToRight
  6728. durationLabel.baseWritingDirection = .leftToRight
  6729. let durationShell = NSView()
  6730. durationShell.translatesAutoresizingMaskIntoConstraints = false
  6731. durationShell.wantsLayer = true
  6732. durationShell.layer?.cornerRadius = 8
  6733. durationShell.layer?.backgroundColor = inputSurface.cgColor
  6734. durationShell.layer?.borderColor = fieldBorder.cgColor
  6735. durationShell.layer?.borderWidth = 1.2
  6736. durationShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
  6737. let durationField = NSTextField(string: "30")
  6738. durationField.translatesAutoresizingMaskIntoConstraints = false
  6739. durationField.isBordered = false
  6740. durationField.drawsBackground = false
  6741. durationField.focusRingType = .none
  6742. durationField.font = typography.filterText
  6743. durationField.textColor = palette.textSecondary
  6744. durationField.formatter = NumberFormatter()
  6745. durationShell.addSubview(durationField)
  6746. NSLayoutConstraint.activate([
  6747. durationField.leadingAnchor.constraint(equalTo: durationShell.leadingAnchor, constant: 8),
  6748. durationField.trailingAnchor.constraint(equalTo: durationShell.trailingAnchor, constant: -8),
  6749. durationField.centerYAnchor.constraint(equalTo: durationShell.centerYAnchor)
  6750. ])
  6751. self.durationField = durationField
  6752. let startGroup = NSStackView(views: [startLabel, pickerShell])
  6753. startGroup.translatesAutoresizingMaskIntoConstraints = false
  6754. startGroup.orientation = .vertical
  6755. startGroup.alignment = .leading
  6756. startGroup.spacing = 6
  6757. let durationGroup = NSStackView(views: [durationLabel, durationShell])
  6758. durationGroup.translatesAutoresizingMaskIntoConstraints = false
  6759. durationGroup.orientation = .vertical
  6760. durationGroup.alignment = .leading
  6761. durationGroup.spacing = 6
  6762. timeRow.addArrangedSubview(startGroup)
  6763. timeRow.addArrangedSubview(durationGroup)
  6764. startGroup.widthAnchor.constraint(equalTo: durationGroup.widthAnchor).isActive = true
  6765. let notesLabel = NSTextField(labelWithString: "Notes")
  6766. notesLabel.font = typography.fieldLabel
  6767. notesLabel.textColor = palette.textSecondary
  6768. notesLabel.alignment = .left
  6769. notesLabel.userInterfaceLayoutDirection = .leftToRight
  6770. notesLabel.baseWritingDirection = .leftToRight
  6771. let notesScroll = HoverFocusScrollView()
  6772. notesScroll.translatesAutoresizingMaskIntoConstraints = false
  6773. notesScroll.drawsBackground = true
  6774. notesScroll.backgroundColor = inputSurface
  6775. notesScroll.hasVerticalScroller = true
  6776. notesScroll.hasHorizontalScroller = false
  6777. notesScroll.borderType = .noBorder
  6778. notesScroll.wantsLayer = true
  6779. notesScroll.layer?.cornerRadius = 8
  6780. notesScroll.layer?.masksToBounds = true
  6781. notesScroll.layer?.borderWidth = 1.2
  6782. notesScroll.layer?.borderColor = notesBorderIdle.cgColor
  6783. notesScroll.heightAnchor.constraint(equalToConstant: 100).isActive = true
  6784. notesScroll.onHoverChanged = { [weak self] hovering in
  6785. guard let self else { return }
  6786. self.notesIsHovered = hovering
  6787. self.updateNotesBorderAppearance()
  6788. }
  6789. notesScroll.onMouseDown = { [weak self] in
  6790. guard let self, let notesView = self.notesView as? ImmediateFocusTextView else { return }
  6791. self.view.window?.makeFirstResponder(notesView)
  6792. notesView.ensureCaretVisibleImmediately()
  6793. self.notesIsFocused = true
  6794. self.updateNotesBorderAppearance()
  6795. }
  6796. let notesView = ImmediateFocusTextView(frame: .zero)
  6797. notesView.drawsBackground = false
  6798. notesView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
  6799. notesView.textColor = palette.textPrimary
  6800. notesView.insertionPointColor = palette.textPrimary
  6801. notesView.isEditable = true
  6802. notesView.isSelectable = true
  6803. notesView.isRichText = false
  6804. notesView.importsGraphics = false
  6805. notesView.isHorizontallyResizable = false
  6806. notesView.isVerticallyResizable = true
  6807. notesView.autoresizingMask = [.width]
  6808. notesView.textContainerInset = NSSize(width: 6, height: 6)
  6809. notesView.textContainer?.widthTracksTextView = true
  6810. notesView.textContainer?.containerSize = NSSize(
  6811. width: notesScroll.contentSize.width,
  6812. height: CGFloat.greatestFiniteMagnitude
  6813. )
  6814. notesView.delegate = self
  6815. notesScroll.documentView = notesView
  6816. self.notesView = notesView
  6817. self.notesScrollView = notesScroll
  6818. let error = NSTextField(labelWithString: "")
  6819. error.translatesAutoresizingMaskIntoConstraints = false
  6820. error.textColor = NSColor.systemRed
  6821. error.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
  6822. error.isHidden = true
  6823. self.errorLabel = error
  6824. let actions = NSStackView()
  6825. actions.translatesAutoresizingMaskIntoConstraints = false
  6826. actions.orientation = .horizontal
  6827. actions.alignment = .centerY
  6828. actions.spacing = 10
  6829. let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancelPressed(_:)))
  6830. cancel.bezelStyle = .rounded
  6831. let save = NSButton(title: "Save", target: self, action: #selector(savePressed(_:)))
  6832. save.bezelStyle = .rounded
  6833. save.keyEquivalent = "\r"
  6834. let actionsSpacer = NSView()
  6835. actionsSpacer.translatesAutoresizingMaskIntoConstraints = false
  6836. actionsSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  6837. actions.addArrangedSubview(cancel)
  6838. actions.addArrangedSubview(actionsSpacer)
  6839. actions.addArrangedSubview(save)
  6840. stack.addArrangedSubview(header)
  6841. stack.addArrangedSubview(titleLabel)
  6842. stack.addArrangedSubview(titleShell)
  6843. stack.addArrangedSubview(timeRow)
  6844. stack.addArrangedSubview(notesLabel)
  6845. stack.addArrangedSubview(notesScroll)
  6846. stack.addArrangedSubview(error)
  6847. stack.addArrangedSubview(actions)
  6848. root.addSubview(stack)
  6849. NSLayoutConstraint.activate([
  6850. root.widthAnchor.constraint(equalToConstant: 372),
  6851. stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
  6852. stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
  6853. stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 16),
  6854. stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16),
  6855. titleShell.widthAnchor.constraint(equalTo: stack.widthAnchor),
  6856. timeRow.widthAnchor.constraint(equalTo: stack.widthAnchor),
  6857. notesScroll.widthAnchor.constraint(equalTo: stack.widthAnchor),
  6858. error.widthAnchor.constraint(equalTo: stack.widthAnchor),
  6859. actions.widthAnchor.constraint(equalTo: stack.widthAnchor)
  6860. ])
  6861. view = root
  6862. }
  6863. @objc private func cancelPressed(_ sender: NSButton) {
  6864. onCancel()
  6865. }
  6866. @objc private func savePressed(_ sender: NSButton) {
  6867. setError(nil)
  6868. let title = (titleField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  6869. if title.isEmpty {
  6870. setError("Please enter a title.")
  6871. return
  6872. }
  6873. let durationText = (durationField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
  6874. let durationMinutes = Int(durationText) ?? 0
  6875. if durationMinutes <= 0 {
  6876. setError("Duration must be a positive number of minutes.")
  6877. return
  6878. }
  6879. let time = timePicker?.dateValue ?? Date()
  6880. let calendar = Calendar.current
  6881. let dateParts = calendar.dateComponents([.year, .month, .day], from: selectedDate)
  6882. let timeParts = calendar.dateComponents([.hour, .minute], from: time)
  6883. var merged = DateComponents()
  6884. merged.year = dateParts.year
  6885. merged.month = dateParts.month
  6886. merged.day = dateParts.day
  6887. merged.hour = timeParts.hour
  6888. merged.minute = timeParts.minute
  6889. guard let start = calendar.date(from: merged) else {
  6890. setError("Invalid start time.")
  6891. return
  6892. }
  6893. let end = start.addingTimeInterval(TimeInterval(durationMinutes * 60))
  6894. let notes = notesView?.string.trimmingCharacters(in: .whitespacesAndNewlines)
  6895. let cleanedNotes = (notes?.isEmpty == false) ? notes : nil
  6896. onSave(Draft(title: title, notes: cleanedNotes, startDate: start, endDate: end))
  6897. }
  6898. private func updateNotesBorderAppearance() {
  6899. let color: NSColor
  6900. let width: CGFloat
  6901. if notesIsFocused {
  6902. color = notesBorderFocused
  6903. width = 1.6
  6904. } else if notesIsHovered {
  6905. color = notesBorderHover
  6906. width = 1.4
  6907. } else {
  6908. color = notesBorderIdle
  6909. width = 1.2
  6910. }
  6911. notesScrollView?.layer?.borderColor = color.cgColor
  6912. notesScrollView?.layer?.borderWidth = width
  6913. }
  6914. private func setError(_ message: String?) {
  6915. guard let errorLabel else { return }
  6916. errorLabel.stringValue = message ?? ""
  6917. errorLabel.isHidden = message == nil
  6918. }
  6919. func textDidBeginEditing(_ notification: Notification) {
  6920. guard let current = notification.object as? NSTextView, current === notesView else { return }
  6921. notesIsFocused = true
  6922. updateNotesBorderAppearance()
  6923. }
  6924. func textDidEndEditing(_ notification: Notification) {
  6925. guard let current = notification.object as? NSTextView, current === notesView else { return }
  6926. notesIsFocused = false
  6927. updateNotesBorderAppearance()
  6928. }
  6929. }
  6930. private final class HoverFocusScrollView: NSScrollView {
  6931. var onHoverChanged: ((Bool) -> Void)?
  6932. var onMouseDown: (() -> Void)?
  6933. private var hoverTrackingArea: NSTrackingArea?
  6934. override func updateTrackingAreas() {
  6935. super.updateTrackingAreas()
  6936. if let hoverTrackingArea {
  6937. removeTrackingArea(hoverTrackingArea)
  6938. }
  6939. let area = NSTrackingArea(
  6940. rect: bounds,
  6941. options: [.activeInActiveApp, .inVisibleRect, .mouseEnteredAndExited],
  6942. owner: self,
  6943. userInfo: nil
  6944. )
  6945. addTrackingArea(area)
  6946. hoverTrackingArea = area
  6947. }
  6948. override func mouseEntered(with event: NSEvent) {
  6949. super.mouseEntered(with: event)
  6950. onHoverChanged?(true)
  6951. }
  6952. override func mouseExited(with event: NSEvent) {
  6953. super.mouseExited(with: event)
  6954. onHoverChanged?(false)
  6955. }
  6956. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  6957. true
  6958. }
  6959. override func mouseDown(with event: NSEvent) {
  6960. onMouseDown?()
  6961. if let window, !window.isKeyWindow {
  6962. window.makeKeyAndOrderFront(nil)
  6963. return
  6964. }
  6965. // Forward the click straight to the text view so caret placement/blink starts immediately.
  6966. if let textView = documentView as? NSTextView {
  6967. window?.makeFirstResponder(textView)
  6968. textView.mouseDown(with: event)
  6969. return
  6970. }
  6971. super.mouseDown(with: event)
  6972. }
  6973. }
  6974. private final class ImmediateFocusTextView: NSTextView {
  6975. override var acceptsFirstResponder: Bool { true }
  6976. override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
  6977. true
  6978. }
  6979. @discardableResult
  6980. override func becomeFirstResponder() -> Bool {
  6981. let accepted = super.becomeFirstResponder()
  6982. if accepted {
  6983. ensureCaretVisibleImmediately()
  6984. }
  6985. return accepted
  6986. }
  6987. override func mouseDown(with event: NSEvent) {
  6988. window?.makeFirstResponder(self)
  6989. super.mouseDown(with: event)
  6990. ensureCaretVisibleImmediately()
  6991. }
  6992. func ensureCaretVisibleImmediately() {
  6993. var range = selectedRange()
  6994. if range.location == NSNotFound {
  6995. range = NSRange(location: string.utf16.count, length: 0)
  6996. }
  6997. setSelectedRange(range)
  6998. scrollRangeToVisible(range)
  6999. needsDisplay = true
  7000. displayIfNeeded()
  7001. }
  7002. }
  7003. // MARK: - Schedule actions (OAuth entry)
  7004. private extension ViewController {
  7005. @objc func scheduleReloadButtonPressed(_ sender: NSButton) {
  7006. scheduleReloadClicked()
  7007. }
  7008. @objc func scheduleScrollLeftPressed(_ sender: NSButton) {
  7009. scrollScheduleCards(direction: -1)
  7010. }
  7011. @objc func scheduleScrollRightPressed(_ sender: NSButton) {
  7012. scrollScheduleCards(direction: 1)
  7013. }
  7014. @objc func scheduleCardButtonPressed(_ sender: NSButton) {
  7015. guard storeKitCoordinator.hasPremiumAccess else {
  7016. showPaywall()
  7017. return
  7018. }
  7019. guard let raw = sender.identifier?.rawValue,
  7020. let url = URL(string: raw) else { return }
  7021. let meeting = scheduleCachedMeetings.first(where: { $0.meetURL.absoluteString == raw })
  7022. openMeetingURL(url, meeting: meeting)
  7023. }
  7024. @objc func scheduleConnectButtonPressed(_ sender: NSButton) {
  7025. scheduleConnectClicked()
  7026. }
  7027. @objc func schedulePageLoadMorePressed(_ sender: NSButton) {
  7028. appendSchedulePageBatchIfNeeded()
  7029. }
  7030. private func scheduleInitialHeadingText() -> String {
  7031. hasGoogleSessionAvailable() ? "Loading…" : "Connect Google to see meetings"
  7032. }
  7033. private func schedulePageInitialHeadingText() -> String {
  7034. hasGoogleSessionAvailable() ? "Loading schedule…" : "Connect Google to see meetings"
  7035. }
  7036. @objc func scheduleFilterDropdownChanged(_ sender: NSPopUpButton) {
  7037. guard let selectedItem = sender.selectedItem,
  7038. let filter = ScheduleFilter(rawValue: selectedItem.tag) else { return }
  7039. applyScheduleFilter(filter)
  7040. }
  7041. private func applyScheduleFilter(_ filter: ScheduleFilter) {
  7042. scheduleFilter = filter
  7043. scheduleFilterDropdown?.selectItem(at: filter.rawValue)
  7044. Task { [weak self] in
  7045. await self?.loadSchedule()
  7046. }
  7047. }
  7048. @objc func schedulePageFilterDropdownChanged(_ sender: NSPopUpButton) {
  7049. guard let selectedItem = sender.selectedItem,
  7050. let filter = SchedulePageFilter(rawValue: selectedItem.tag) else { return }
  7051. schedulePageFilter = filter
  7052. refreshSchedulePageDateFilterUI()
  7053. applySchedulePageFiltersAndRender()
  7054. }
  7055. @objc func schedulePageDatePickerChanged(_ sender: NSDatePicker) {
  7056. schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
  7057. schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
  7058. }
  7059. @objc func schedulePageApplyDateRangePressed(_ sender: NSButton) {
  7060. if let selectedItem = schedulePageFilterDropdown?.selectedItem,
  7061. let selectedFilter = SchedulePageFilter(rawValue: selectedItem.tag) {
  7062. schedulePageFilter = selectedFilter
  7063. }
  7064. refreshSchedulePageDateFilterUI()
  7065. applySchedulePageFiltersAndRender()
  7066. }
  7067. @objc func schedulePageResetFiltersPressed(_ sender: NSButton) {
  7068. schedulePageFilter = .all
  7069. schedulePageFilterDropdown?.selectItem(at: SchedulePageFilter.all.rawValue)
  7070. let today = Calendar.current.startOfDay(for: Date())
  7071. schedulePageFromDate = today
  7072. schedulePageToDate = today
  7073. schedulePageFromDatePicker?.dateValue = today
  7074. schedulePageToDatePicker?.dateValue = today
  7075. refreshSchedulePageDateFilterUI()
  7076. applySchedulePageFiltersAndRender()
  7077. }
  7078. @objc func schedulePageAddMeetingPressed(_ sender: NSButton) {
  7079. guard requireGoogleLoginForCalendarScheduling() else { return }
  7080. let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 230, height: 28))
  7081. let datePicker = NSDatePicker(frame: accessory.bounds)
  7082. datePicker.autoresizingMask = [.width, .height]
  7083. datePicker.datePickerMode = .single
  7084. datePicker.datePickerStyle = .textFieldAndStepper
  7085. datePicker.datePickerElements = [.yearMonthDay]
  7086. datePicker.dateValue = Calendar.current.startOfDay(for: Date())
  7087. accessory.addSubview(datePicker)
  7088. let alert = NSAlert()
  7089. alert.messageText = "Select date"
  7090. alert.informativeText = "Choose a date to schedule your meeting."
  7091. alert.alertStyle = .informational
  7092. alert.accessoryView = accessory
  7093. alert.addButton(withTitle: "Continue")
  7094. alert.addButton(withTitle: "Cancel")
  7095. guard alert.runModal() == .alertFirstButtonReturn else { return }
  7096. calendarPageSelectedDate = Calendar.current.startOfDay(for: datePicker.dateValue)
  7097. presentCreateMeetingPopover(relativeTo: sender)
  7098. }
  7099. private func scheduleTimeText(for meeting: ScheduledMeeting) -> String {
  7100. if meeting.isAllDay { return "All day" }
  7101. let f = DateFormatter()
  7102. f.locale = Locale.current
  7103. f.timeZone = TimeZone.current
  7104. f.dateStyle = .none
  7105. f.timeStyle = .short
  7106. return "\(f.string(from: meeting.startDate)) - \(f.string(from: meeting.endDate))"
  7107. }
  7108. private func scheduleDayText(for meeting: ScheduledMeeting) -> String {
  7109. let f = DateFormatter()
  7110. f.locale = Locale.current
  7111. f.timeZone = TimeZone.current
  7112. f.dateFormat = "EEE, d MMM"
  7113. return f.string(from: meeting.startDate)
  7114. }
  7115. private func scheduleDurationText(for meeting: ScheduledMeeting) -> String {
  7116. if meeting.isAllDay { return "Duration: all day" }
  7117. let duration = max(0, meeting.endDate.timeIntervalSince(meeting.startDate))
  7118. let totalMinutes = Int(duration / 60)
  7119. let hours = totalMinutes / 60
  7120. let minutes = totalMinutes % 60
  7121. if hours > 0, minutes > 0 { return "Duration: \(hours)h \(minutes)m" }
  7122. if hours > 0 { return "Duration: \(hours)h" }
  7123. return "Duration: \(minutes)m"
  7124. }
  7125. private func scheduleHeadingText(for meetings: [ScheduledMeeting]) -> String {
  7126. guard let first = meetings.first else {
  7127. return hasGoogleSessionAvailable() ? "No upcoming meetings" : "Connect Google to see meetings"
  7128. }
  7129. let day = Calendar.current.startOfDay(for: first.startDate)
  7130. let f = DateFormatter()
  7131. f.locale = Locale.current
  7132. f.timeZone = TimeZone.current
  7133. f.dateFormat = "EEEE, d MMM"
  7134. return f.string(from: day)
  7135. }
  7136. private func openMeetingURL(_ url: URL, meeting: ScheduledMeeting? = nil) {
  7137. let title = meeting?.title ?? "Scheduled Meeting"
  7138. beginMeetingRecordingIfConsented(meetingTitle: title, meetingURL: url)
  7139. NSWorkspace.shared.open(url)
  7140. }
  7141. private func renderScheduleCards(into stack: NSStackView, meetings: [ScheduledMeeting]) {
  7142. displayedScheduleMeetings = meetings
  7143. let shouldShowScrollControls = meetings.count > 3
  7144. scheduleScrollLeftButton?.isHidden = !shouldShowScrollControls
  7145. scheduleScrollRightButton?.isHidden = !shouldShowScrollControls
  7146. scheduleCardsScrollView?.contentView.setBoundsOrigin(.zero)
  7147. if let scroll = scheduleCardsScrollView {
  7148. scroll.reflectScrolledClipView(scroll.contentView)
  7149. }
  7150. stack.arrangedSubviews.forEach { v in
  7151. stack.removeArrangedSubview(v)
  7152. v.removeFromSuperview()
  7153. }
  7154. if meetings.isEmpty {
  7155. let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
  7156. empty.translatesAutoresizingMaskIntoConstraints = false
  7157. empty.widthAnchor.constraint(equalToConstant: 240).isActive = true
  7158. empty.heightAnchor.constraint(equalToConstant: 150).isActive = true
  7159. styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  7160. let label = textLabel(hasGoogleSessionAvailable() ? "No meetings" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
  7161. label.translatesAutoresizingMaskIntoConstraints = false
  7162. empty.addSubview(label)
  7163. NSLayoutConstraint.activate([
  7164. label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
  7165. label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
  7166. ])
  7167. stack.addArrangedSubview(empty)
  7168. return
  7169. }
  7170. for meeting in meetings {
  7171. stack.addArrangedSubview(scheduleCard(meeting: meeting))
  7172. }
  7173. }
  7174. private func filteredMeetings(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
  7175. let now = Date()
  7176. switch scheduleFilter {
  7177. case .all:
  7178. return meetings.filter { $0.endDate >= now }
  7179. case .today:
  7180. let start = Calendar.current.startOfDay(for: now)
  7181. let end = Calendar.current.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
  7182. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  7183. case .week:
  7184. let end = Calendar.current.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
  7185. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  7186. }
  7187. }
  7188. private func filteredMeetingsForSchedulePage(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
  7189. let calendar = Calendar.current
  7190. let now = Date()
  7191. switch schedulePageFilter {
  7192. case .all:
  7193. return meetings.filter { $0.endDate >= now }
  7194. case .today:
  7195. let start = calendar.startOfDay(for: now)
  7196. let end = calendar.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
  7197. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  7198. case .week:
  7199. let end = calendar.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
  7200. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  7201. case .month:
  7202. let end = calendar.date(byAdding: .month, value: 1, to: now) ?? now.addingTimeInterval(30 * 86400)
  7203. return meetings.filter { $0.startDate >= now && $0.startDate <= end }
  7204. case .customRange:
  7205. let start = calendar.startOfDay(for: schedulePageFromDate)
  7206. let inclusiveEndDay = calendar.startOfDay(for: schedulePageToDate)
  7207. guard let end = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else {
  7208. return meetings
  7209. }
  7210. return meetings.filter { $0.startDate >= start && $0.startDate < end }
  7211. }
  7212. }
  7213. private func refreshSchedulePageDateFilterUI() {
  7214. let isCustom = schedulePageFilter == .customRange
  7215. schedulePageFromDatePicker?.isEnabled = isCustom
  7216. schedulePageToDatePicker?.isEnabled = isCustom
  7217. let dim: CGFloat = isCustom ? 1.0 : 0.65
  7218. schedulePageFromDatePicker?.alphaValue = 1
  7219. schedulePageToDatePicker?.alphaValue = 1
  7220. schedulePageFromDatePicker?.superview?.alphaValue = dim
  7221. schedulePageToDatePicker?.superview?.alphaValue = dim
  7222. }
  7223. private func schedulePageHasValidCustomRange() -> Bool {
  7224. let start = Calendar.current.startOfDay(for: schedulePageFromDate)
  7225. let end = Calendar.current.startOfDay(for: schedulePageToDate)
  7226. return start <= end
  7227. }
  7228. private func setSchedulePageRangeError(_ message: String?) {
  7229. guard let label = schedulePageRangeErrorLabel else { return }
  7230. label.stringValue = message ?? ""
  7231. label.isHidden = message == nil
  7232. }
  7233. private func applySchedulePageFiltersAndRender() {
  7234. schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
  7235. schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
  7236. if schedulePageFilter == .customRange && !schedulePageHasValidCustomRange() {
  7237. setSchedulePageRangeError("Start date must be on or before end date.")
  7238. schedulePageFilteredMeetings = []
  7239. schedulePageVisibleCount = 0
  7240. renderSchedulePageCards()
  7241. schedulePageDateHeadingLabel?.stringValue = "Invalid custom date range"
  7242. return
  7243. }
  7244. setSchedulePageRangeError(nil)
  7245. schedulePageFilteredMeetings = filteredMeetingsForSchedulePage(scheduleCachedMeetings)
  7246. schedulePageVisibleCount = min(schedulePageBatchSize, schedulePageFilteredMeetings.count)
  7247. renderSchedulePageCards()
  7248. schedulePageDateHeadingLabel?.stringValue = scheduleHeadingText(for: schedulePageFilteredMeetings)
  7249. }
  7250. private func appendSchedulePageBatchIfNeeded() {
  7251. guard schedulePageVisibleCount < schedulePageFilteredMeetings.count else { return }
  7252. let nextCount = min(schedulePageVisibleCount + schedulePageBatchSize, schedulePageFilteredMeetings.count)
  7253. guard nextCount > schedulePageVisibleCount else { return }
  7254. schedulePageVisibleCount = nextCount
  7255. renderSchedulePageCards()
  7256. // If we're still near the bottom after adding a batch (large viewport),
  7257. // immediately evaluate again so pagination keeps advancing in chunks of 6.
  7258. DispatchQueue.main.async { [weak self] in
  7259. self?.schedulePageScrolled()
  7260. }
  7261. }
  7262. private func schedulePageScrolled() {
  7263. guard let scroll = schedulePageCardsScrollView else { return }
  7264. let contentBounds = scroll.contentView.bounds
  7265. let contentHeight = scroll.documentView?.bounds.height ?? 0
  7266. guard contentHeight > 0 else { return }
  7267. let remaining = contentHeight - (contentBounds.origin.y + contentBounds.height)
  7268. if remaining <= 200 {
  7269. appendSchedulePageBatchIfNeeded()
  7270. }
  7271. }
  7272. private func renderSchedulePageCards() {
  7273. guard let stack = schedulePageCardsStack else { return }
  7274. stack.arrangedSubviews.forEach { v in
  7275. stack.removeArrangedSubview(v)
  7276. v.removeFromSuperview()
  7277. }
  7278. let visibleMeetings = Array(schedulePageFilteredMeetings.prefix(schedulePageVisibleCount))
  7279. if visibleMeetings.isEmpty {
  7280. let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
  7281. empty.translatesAutoresizingMaskIntoConstraints = false
  7282. empty.heightAnchor.constraint(equalToConstant: 140).isActive = true
  7283. styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
  7284. let label = textLabel(hasGoogleSessionAvailable() ? "No meetings for selected filters" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
  7285. label.translatesAutoresizingMaskIntoConstraints = false
  7286. empty.addSubview(label)
  7287. NSLayoutConstraint.activate([
  7288. label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
  7289. label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
  7290. ])
  7291. stack.addArrangedSubview(empty)
  7292. empty.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  7293. return
  7294. }
  7295. var index = 0
  7296. while index < visibleMeetings.count {
  7297. let row = NSStackView()
  7298. row.translatesAutoresizingMaskIntoConstraints = false
  7299. row.userInterfaceLayoutDirection = .leftToRight
  7300. row.orientation = .horizontal
  7301. row.alignment = .top
  7302. row.spacing = schedulePageCardSpacing
  7303. row.distribution = .fillEqually
  7304. let rowEnd = min(index + schedulePageCardsPerRow, visibleMeetings.count)
  7305. for meeting in visibleMeetings[index..<rowEnd] {
  7306. row.addArrangedSubview(scheduleCard(meeting: meeting, useFlexibleWidth: true, contentHeight: schedulePageCardHeight))
  7307. }
  7308. stack.addArrangedSubview(row)
  7309. row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  7310. index = rowEnd
  7311. }
  7312. if schedulePageVisibleCount < schedulePageFilteredMeetings.count {
  7313. let pagination = NSStackView()
  7314. pagination.translatesAutoresizingMaskIntoConstraints = false
  7315. pagination.orientation = .horizontal
  7316. pagination.alignment = .centerY
  7317. pagination.spacing = 10
  7318. let moreLabel = textLabel(
  7319. "Showing \(schedulePageVisibleCount) of \(schedulePageFilteredMeetings.count)",
  7320. font: NSFont.systemFont(ofSize: 12, weight: .medium),
  7321. color: palette.textMuted
  7322. )
  7323. pagination.addArrangedSubview(moreLabel)
  7324. let spacer = NSView()
  7325. spacer.translatesAutoresizingMaskIntoConstraints = false
  7326. spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
  7327. pagination.addArrangedSubview(spacer)
  7328. stack.addArrangedSubview(pagination)
  7329. pagination.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
  7330. }
  7331. }
  7332. private func scrollScheduleCards(direction: Int) {
  7333. guard let scroll = scheduleCardsScrollView else { return }
  7334. let contentBounds = scroll.contentView.bounds
  7335. let step = max(220, contentBounds.width * 0.7)
  7336. let proposedX = contentBounds.origin.x + (CGFloat(direction) * step)
  7337. let maxX = max(0, scroll.documentView?.bounds.width ?? 0 - contentBounds.width)
  7338. let nextX = min(max(0, proposedX), maxX)
  7339. scroll.contentView.animator().setBoundsOrigin(NSPoint(x: nextX, y: 0))
  7340. scroll.reflectScrolledClipView(scroll.contentView)
  7341. }
  7342. private func loadSchedule() async {
  7343. do {
  7344. if hasGoogleSessionAvailable() == false {
  7345. await MainActor.run {
  7346. updateGoogleAuthButtonTitle()
  7347. applyGoogleProfile(nil)
  7348. scheduleDateHeadingLabel?.stringValue = "Connect Google to see meetings"
  7349. schedulePageDateHeadingLabel?.stringValue = "Connect Google to see meetings"
  7350. if let stack = scheduleCardsStack {
  7351. renderScheduleCards(into: stack, meetings: [])
  7352. }
  7353. scheduleCachedMeetings = []
  7354. pageCache[.aiCompanion] = nil
  7355. publishWidgetMeetingsSnapshot(from: [])
  7356. DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
  7357. MeetingReminderManager.shared.cancelAllReminders()
  7358. applySchedulePageFiltersAndRender()
  7359. if calendarPageGridStack != nil {
  7360. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  7361. renderCalendarMonthGrid()
  7362. renderCalendarSelectedDay()
  7363. }
  7364. }
  7365. return
  7366. }
  7367. let token = try await googleOAuth.validAccessToken(presentingWindow: view.window)
  7368. let profile = try? await googleOAuth.fetchUserProfile(accessToken: token)
  7369. let meetings = try await calendarClient.fetchUpcomingMeetings(accessToken: token)
  7370. let filtered = filteredMeetings(meetings)
  7371. await MainActor.run {
  7372. updateGoogleAuthButtonTitle()
  7373. applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
  7374. scheduleDateHeadingLabel?.stringValue = scheduleHeadingText(for: filtered)
  7375. if let stack = scheduleCardsStack {
  7376. renderScheduleCards(into: stack, meetings: filtered)
  7377. }
  7378. scheduleCachedMeetings = meetings
  7379. pageCache[.aiCompanion] = nil
  7380. publishWidgetMeetingsSnapshot(from: filtered)
  7381. DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
  7382. if storeKitCoordinator.hasPremiumAccess {
  7383. MeetingReminderManager.shared.scheduleReminders(for: meetings)
  7384. }
  7385. applySchedulePageFiltersAndRender()
  7386. if calendarPageGridStack != nil {
  7387. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  7388. renderCalendarMonthGrid()
  7389. renderCalendarSelectedDay()
  7390. }
  7391. }
  7392. } catch {
  7393. await MainActor.run {
  7394. updateGoogleAuthButtonTitle()
  7395. if hasGoogleSessionAvailable() == false {
  7396. applyGoogleProfile(nil)
  7397. }
  7398. scheduleDateHeadingLabel?.stringValue = "Couldn’t load schedule"
  7399. schedulePageDateHeadingLabel?.stringValue = "Couldn’t load schedule"
  7400. if let stack = scheduleCardsStack {
  7401. renderScheduleCards(into: stack, meetings: [])
  7402. }
  7403. scheduleCachedMeetings = []
  7404. pageCache[.aiCompanion] = nil
  7405. publishWidgetMeetingsSnapshot(from: [])
  7406. DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
  7407. MeetingReminderManager.shared.cancelAllReminders()
  7408. applySchedulePageFiltersAndRender()
  7409. if calendarPageGridStack != nil {
  7410. calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
  7411. renderCalendarMonthGrid()
  7412. renderCalendarSelectedDay()
  7413. }
  7414. showSimpleError("Couldn’t load schedule.", error: error)
  7415. }
  7416. }
  7417. }
  7418. private func publishWidgetMeetingsSnapshot(from meetings: [ScheduledMeeting]) {
  7419. let formatter = DateFormatter()
  7420. formatter.dateFormat = "EEE, h:mm a"
  7421. formatter.locale = Locale.current
  7422. let payload = meetings.prefix(widgetSnapshotLimit).map { meeting in
  7423. let endText = DateFormatter.localizedString(from: meeting.endDate, dateStyle: .none, timeStyle: .short)
  7424. return WidgetMeetingSnapshot(
  7425. id: meeting.id,
  7426. title: meeting.title,
  7427. timeText: "\(formatter.string(from: meeting.startDate)) - \(endText)",
  7428. joinLink: meeting.meetURL.absoluteString
  7429. )
  7430. }
  7431. if let data = try? JSONEncoder().encode(payload) {
  7432. UserDefaults.standard.set(data, forKey: WidgetMeetingStore.key)
  7433. } else {
  7434. UserDefaults.standard.removeObject(forKey: WidgetMeetingStore.key)
  7435. }
  7436. NotificationCenter.default.post(name: .meetingsSnapshotUpdated, object: nil)
  7437. }
  7438. func showScheduleHelp() {
  7439. let alert = NSAlert()
  7440. alert.messageText = "Google schedule"
  7441. alert.informativeText = "To show scheduled meetings, connect your Google account. You’ll need a Google OAuth client ID (Desktop) and a redirect URI matching the app’s callback scheme."
  7442. alert.addButton(withTitle: "OK")
  7443. alert.runModal()
  7444. }
  7445. func scheduleReloadClicked() {
  7446. Task { [weak self] in
  7447. guard let self else { return }
  7448. do {
  7449. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  7450. _ = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  7451. await MainActor.run {
  7452. self.scheduleDateHeadingLabel?.stringValue = "Refreshing…"
  7453. self.pageCache[.joinMeetings] = nil
  7454. self.pageCache[.photo] = nil
  7455. self.pageCache[.widgets] = nil
  7456. self.pageCache[.aiCompanion] = nil
  7457. self.showSidebarPage(self.selectedSidebarPage)
  7458. }
  7459. await self.loadSchedule()
  7460. } catch {
  7461. await MainActor.run {
  7462. self.showSimpleError("Couldn’t refresh schedule.", error: error)
  7463. }
  7464. }
  7465. }
  7466. }
  7467. func scheduleConnectClicked() {
  7468. Task { [weak self] in
  7469. guard let self else { return }
  7470. do {
  7471. if self.hasGoogleSessionAvailable() {
  7472. await MainActor.run { self.showGoogleAccountMenu() }
  7473. return
  7474. }
  7475. try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
  7476. let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
  7477. let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token)
  7478. await MainActor.run {
  7479. self.updateGoogleAuthButtonTitle()
  7480. self.applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
  7481. self.pageCache[.joinMeetings] = nil
  7482. self.pageCache[.photo] = nil
  7483. self.pageCache[.video] = nil
  7484. self.pageCache[.widgets] = nil
  7485. self.pageCache[.settings] = nil
  7486. self.pageCache[.aiCompanion] = nil
  7487. self.showSidebarPage(self.selectedSidebarPage)
  7488. }
  7489. // Ensure desktop widgets refresh immediately with the newly available meetings.
  7490. await self.loadSchedule()
  7491. } catch {
  7492. self.showSimpleError("Couldn’t connect Google account.", error: error)
  7493. }
  7494. }
  7495. }
  7496. private func showGoogleAccountMenu() {
  7497. guard let button = scheduleGoogleAuthButton else { return }
  7498. if googleAccountPopover?.isShown == true {
  7499. googleAccountPopover?.performClose(nil)
  7500. googleAccountPopover = nil
  7501. return
  7502. }
  7503. let popover = NSPopover()
  7504. popover.behavior = .transient
  7505. popover.animates = true
  7506. popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
  7507. let name = scheduleCurrentProfile?.name ?? "Google account"
  7508. let email = scheduleCurrentProfile?.email ?? "Signed in"
  7509. let avatar = scheduleProfileMenuAvatar
  7510. popover.contentViewController = GoogleAccountMenuViewController(
  7511. palette: palette,
  7512. darkModeEnabled: darkModeEnabled,
  7513. displayName: name,
  7514. email: email,
  7515. avatar: avatar,
  7516. onSignOut: { [weak self] in
  7517. self?.googleAccountPopover?.performClose(nil)
  7518. self?.googleAccountPopover = nil
  7519. self?.performGoogleSignOut()
  7520. }
  7521. )
  7522. googleAccountPopover = popover
  7523. popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
  7524. }
  7525. private func performGoogleSignOut() {
  7526. do {
  7527. MeetingReminderManager.shared.cancelAllReminders()
  7528. try googleOAuth.signOut()
  7529. applyGoogleProfile(nil)
  7530. publishWidgetMeetingsSnapshot(from: [])
  7531. DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
  7532. updateGoogleAuthButtonTitle()
  7533. pageCache[.joinMeetings] = nil
  7534. pageCache[.photo] = nil
  7535. pageCache[.video] = nil
  7536. pageCache[.widgets] = nil
  7537. pageCache[.settings] = nil
  7538. pageCache[.aiCompanion] = nil
  7539. showSidebarPage(selectedSidebarPage)
  7540. Task { [weak self] in
  7541. await self?.loadSchedule()
  7542. }
  7543. } catch {
  7544. showSimpleError("Couldn’t logout Google account.", error: error)
  7545. }
  7546. }
  7547. private func updateGoogleAuthButtonTitle() {
  7548. let signedIn = hasGoogleSessionAvailable()
  7549. guard let button = scheduleGoogleAuthButton else { return }
  7550. let profileName = scheduleCurrentProfile?.name ?? "Google account"
  7551. let ringHostInset: CGFloat = signedIn ? 14 : 0
  7552. scheduleGoogleAuthHostPadWidthConstraint?.constant = ringHostInset
  7553. scheduleGoogleAuthHostPadHeightConstraint?.constant = ringHostInset
  7554. scheduleGoogleAuthHostView?.setAvatarRingMode(signedIn)
  7555. scheduleGoogleAuthHostView?.updateRingAppearance(isDark: darkModeEnabled, accent: palette.primaryBlue)
  7556. if signedIn == false {
  7557. scheduleGoogleAuthHostView?.setProfileHoverActive(false)
  7558. }
  7559. if signedIn {
  7560. button.setAccessibilityLabel("\(profileName), Google account")
  7561. button.attributedTitle = NSAttributedString(string: "")
  7562. button.imagePosition = .imageOnly
  7563. button.imageScaling = .scaleProportionallyDown
  7564. button.symbolConfiguration = nil
  7565. scheduleGoogleAuthButtonHeightConstraint?.constant = scheduleGoogleSignedInAvatarSize
  7566. scheduleGoogleAuthButtonWidthConstraint?.constant = scheduleGoogleSignedInAvatarSize
  7567. button.layer?.cornerRadius = scheduleGoogleSignedInAvatarSize / 2
  7568. let symbol = NSImage(systemSymbolName: "person.crop.circle.fill", accessibilityDescription: "Profile")
  7569. if let symbol {
  7570. let sized = resizedImage(symbol, to: NSSize(width: scheduleGoogleSignedInAvatarSize, height: scheduleGoogleSignedInAvatarSize))
  7571. button.image = sized
  7572. button.contentTintColor = palette.textSecondary
  7573. } else {
  7574. button.image = nil
  7575. button.contentTintColor = nil
  7576. }
  7577. scheduleProfileMenuAvatar = button.image
  7578. } else {
  7579. button.setAccessibilityLabel("Sign in with Google")
  7580. let title = "Sign in with Google"
  7581. let titleFont = NSFont.systemFont(ofSize: 14, weight: .medium)
  7582. let titleColor = darkModeEnabled ? NSColor(calibratedWhite: 0.96, alpha: 1) : NSColor(calibratedRed: 0.13, green: 0.14, blue: 0.16, alpha: 1)
  7583. button.attributedTitle = NSAttributedString(string: title, attributes: [
  7584. .font: titleFont,
  7585. .foregroundColor: titleColor
  7586. ])
  7587. let textWidth = (title as NSString).size(withAttributes: [.font: titleFont]).width
  7588. let idealWidth = ceil(textWidth + 80)
  7589. scheduleGoogleAuthButtonWidthConstraint?.constant = min(320, max(188, idealWidth))
  7590. scheduleGoogleAuthButtonHeightConstraint?.constant = 42
  7591. button.layer?.cornerRadius = 21
  7592. button.imagePosition = .imageLeading
  7593. button.imageScaling = .scaleNone
  7594. if let g = NSImage(named: "GoogleGLogo") {
  7595. button.image = paddedTrailingImage(g, iconSize: NSSize(width: 22, height: 22), trailingPadding: 8)
  7596. } else {
  7597. button.image = nil
  7598. }
  7599. button.contentTintColor = nil
  7600. }
  7601. applyGoogleAuthButtonSurface()
  7602. }
  7603. private func makeGoogleProfileDisplay(from profile: GoogleUserProfile) -> GoogleProfileDisplay {
  7604. let cleanedName = profile.name?.trimmingCharacters(in: .whitespacesAndNewlines)
  7605. let cleanedEmail = profile.email?.trimmingCharacters(in: .whitespacesAndNewlines)
  7606. return GoogleProfileDisplay(
  7607. name: (cleanedName?.isEmpty == false ? cleanedName : nil) ?? "Google User",
  7608. email: (cleanedEmail?.isEmpty == false ? cleanedEmail : nil) ?? "Signed in",
  7609. pictureURL: profile.picture.flatMap(URL.init(string:))
  7610. )
  7611. }
  7612. private func applyGoogleProfile(_ profile: GoogleProfileDisplay?) {
  7613. scheduleProfileImageTask?.cancel()
  7614. scheduleProfileImageTask = nil
  7615. if profile == nil {
  7616. scheduleProfileMenuAvatar = nil
  7617. }
  7618. scheduleCurrentProfile = profile
  7619. updateGoogleAuthButtonTitle()
  7620. guard let profile, let pictureURL = profile.pictureURL else { return }
  7621. let avatarDiameter = scheduleGoogleSignedInAvatarSize
  7622. scheduleProfileImageTask = Task { [weak self] in
  7623. do {
  7624. let (data, _) = try await URLSession.shared.data(from: pictureURL)
  7625. if Task.isCancelled { return }
  7626. guard let image = NSImage(data: data) else { return }
  7627. await MainActor.run { [weak self] in
  7628. guard let self else { return }
  7629. let rounded = self.circularProfileImage(image, diameter: avatarDiameter)
  7630. self.scheduleProfileMenuAvatar = circularNSImage(rounded, diameter: 48)
  7631. self.scheduleGoogleAuthButton?.image = rounded
  7632. self.scheduleGoogleAuthButton?.contentTintColor = nil
  7633. }
  7634. } catch {
  7635. // Keep placeholder avatar if image fetch fails.
  7636. }
  7637. }
  7638. }
  7639. private func resizedImage(_ image: NSImage, to size: NSSize) -> NSImage {
  7640. let result = NSImage(size: size)
  7641. result.lockFocus()
  7642. image.draw(in: NSRect(origin: .zero, size: size),
  7643. from: NSRect(origin: .zero, size: image.size),
  7644. operation: .copy,
  7645. fraction: 1.0)
  7646. result.unlockFocus()
  7647. result.isTemplate = false
  7648. return result
  7649. }
  7650. /// Clips a photo to a circle for the signed-in avatar (Google userinfo `picture` URLs are usually square).
  7651. private func circularProfileImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
  7652. circularNSImage(image, diameter: diameter)
  7653. }
  7654. private func paddedTrailingImage(_ image: NSImage, iconSize: NSSize, trailingPadding: CGFloat) -> NSImage {
  7655. let base = resizedImage(image, to: iconSize)
  7656. let canvas = NSSize(width: iconSize.width + trailingPadding, height: iconSize.height)
  7657. let result = NSImage(size: canvas)
  7658. result.lockFocus()
  7659. base.draw(in: NSRect(x: 0, y: 0, width: iconSize.width, height: iconSize.height),
  7660. from: NSRect(origin: .zero, size: base.size),
  7661. operation: .copy,
  7662. fraction: 1.0)
  7663. result.unlockFocus()
  7664. result.isTemplate = false
  7665. return result
  7666. }
  7667. private func applyGoogleAuthButtonSurface() {
  7668. guard let button = scheduleGoogleAuthButton else { return }
  7669. let signedIn = hasGoogleSessionAvailable()
  7670. let isDark = darkModeEnabled
  7671. if signedIn {
  7672. button.layer?.backgroundColor = NSColor.clear.cgColor
  7673. button.layer?.borderWidth = 0
  7674. scheduleGoogleAuthHostView?.updateRingAppearance(isDark: isDark, accent: palette.primaryBlue)
  7675. return
  7676. }
  7677. let baseBackground = isDark
  7678. ? NSColor(calibratedRed: 8.0 / 255.0, green: 14.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  7679. : NSColor.white
  7680. let hoverBlend = isDark ? NSColor.white : NSColor.black
  7681. let hoverBackground = baseBackground.blended(withFraction: 0.07, of: hoverBlend) ?? baseBackground
  7682. let baseBorder = isDark
  7683. ? NSColor(calibratedWhite: 0.50, alpha: 1)
  7684. : NSColor(calibratedWhite: 0.72, alpha: 1)
  7685. let hoverBorder = isDark
  7686. ? NSColor(calibratedWhite: 0.62, alpha: 1)
  7687. : NSColor(calibratedWhite: 0.56, alpha: 1)
  7688. button.layer?.borderWidth = 1
  7689. button.layer?.backgroundColor = (scheduleGoogleAuthHovering ? hoverBackground : baseBackground).cgColor
  7690. button.layer?.borderColor = (scheduleGoogleAuthHovering ? hoverBorder : baseBorder).cgColor
  7691. }
  7692. @MainActor
  7693. func ensureGoogleClientIdConfigured(presentingWindow: NSWindow?) async throws {
  7694. _ = presentingWindow
  7695. guard googleOAuth.configuredClientId() != nil else { throw GoogleOAuthError.missingClientId }
  7696. guard googleOAuth.configuredClientSecret() != nil else { throw GoogleOAuthError.missingClientSecret }
  7697. }
  7698. func showSimpleError(_ title: String, error: Error) {
  7699. DispatchQueue.main.async {
  7700. let alert = NSAlert()
  7701. alert.alertStyle = .warning
  7702. alert.messageText = title
  7703. alert.informativeText = error.localizedDescription
  7704. alert.addButton(withTitle: "OK")
  7705. alert.runModal()
  7706. }
  7707. }
  7708. }
  7709. private struct Palette {
  7710. let pageBackground: NSColor
  7711. let sidebarBackground: NSColor
  7712. let sectionCard: NSColor
  7713. let tabBarBackground: NSColor
  7714. let tabIdleBackground: NSColor
  7715. let inputBackground: NSColor
  7716. let inputBorder: NSColor
  7717. let primaryBlue: NSColor
  7718. let primaryBlueBorder: NSColor
  7719. let cancelButton: NSColor
  7720. let meetingBadge: NSColor
  7721. let separator: NSColor
  7722. let textPrimary: NSColor
  7723. let textSecondary: NSColor
  7724. let textTertiary: NSColor
  7725. let textMuted: NSColor
  7726. init(isDarkMode: Bool) {
  7727. if isDarkMode {
  7728. pageBackground = NSColor(calibratedRed: 10.0 / 255.0, green: 11.0 / 255.0, blue: 12.0 / 255.0, alpha: 1)
  7729. sidebarBackground = NSColor(calibratedRed: 16.0 / 255.0, green: 17.0 / 255.0, blue: 19.0 / 255.0, alpha: 1)
  7730. sectionCard = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  7731. tabBarBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  7732. tabIdleBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
  7733. inputBackground = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  7734. inputBorder = NSColor(calibratedRed: 38.0 / 255.0, green: 40.0 / 255.0, blue: 44.0 / 255.0, alpha: 1)
  7735. primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
  7736. primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
  7737. cancelButton = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
  7738. meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
  7739. separator = NSColor(calibratedRed: 26.0 / 255.0, green: 27.0 / 255.0, blue: 30.0 / 255.0, alpha: 1)
  7740. textPrimary = NSColor(calibratedWhite: 0.98, alpha: 1)
  7741. textSecondary = NSColor(calibratedWhite: 0.78, alpha: 1)
  7742. textTertiary = NSColor(calibratedWhite: 0.66, alpha: 1)
  7743. textMuted = NSColor(calibratedWhite: 0.44, alpha: 1)
  7744. } else {
  7745. pageBackground = NSColor(calibratedRed: 244.0 / 255.0, green: 246.0 / 255.0, blue: 249.0 / 255.0, alpha: 1)
  7746. sidebarBackground = NSColor(calibratedRed: 232.0 / 255.0, green: 236.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)
  7747. sectionCard = NSColor.white
  7748. tabBarBackground = NSColor.white
  7749. tabIdleBackground = NSColor.white
  7750. inputBackground = NSColor(calibratedRed: 247.0 / 255.0, green: 249.0 / 255.0, blue: 252.0 / 255.0, alpha: 1)
  7751. inputBorder = NSColor(calibratedRed: 211.0 / 255.0, green: 218.0 / 255.0, blue: 228.0 / 255.0, alpha: 1)
  7752. primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
  7753. primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
  7754. cancelButton = NSColor(calibratedRed: 240.0 / 255.0, green: 243.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
  7755. meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
  7756. separator = NSColor(calibratedRed: 212.0 / 255.0, green: 219.0 / 255.0, blue: 229.0 / 255.0, alpha: 1)
  7757. textPrimary = NSColor(calibratedRed: 32.0 / 255.0, green: 38.0 / 255.0, blue: 47.0 / 255.0, alpha: 1)
  7758. textSecondary = NSColor(calibratedRed: 82.0 / 255.0, green: 92.0 / 255.0, blue: 107.0 / 255.0, alpha: 1)
  7759. textTertiary = NSColor(calibratedRed: 110.0 / 255.0, green: 120.0 / 255.0, blue: 136.0 / 255.0, alpha: 1)
  7760. textMuted = NSColor(calibratedRed: 134.0 / 255.0, green: 145.0 / 255.0, blue: 162.0 / 255.0, alpha: 1)
  7761. }
  7762. }
  7763. }
  7764. private struct Typography {
  7765. let sidebarBrand = NSFont.systemFont(ofSize: 26, weight: .bold)
  7766. let sidebarSection = NSFont.systemFont(ofSize: 11, weight: .medium)
  7767. let sidebarIcon = NSFont.systemFont(ofSize: 12, weight: .medium)
  7768. let sidebarItem = NSFont.systemFont(ofSize: 16, weight: .medium)
  7769. let pageTitle = NSFont.systemFont(ofSize: 27, weight: .semibold)
  7770. let joinWithURLTitle = NSFont.systemFont(ofSize: 17, weight: .semibold)
  7771. let sectionTitleBold = NSFont.systemFont(ofSize: 25, weight: .bold)
  7772. let dateHeading = NSFont.systemFont(ofSize: 18, weight: .medium)
  7773. let tabIcon = NSFont.systemFont(ofSize: 13, weight: .regular)
  7774. let tabTitle = NSFont.systemFont(ofSize: 31 / 2, weight: .semibold)
  7775. let fieldLabel = NSFont.systemFont(ofSize: 15, weight: .medium)
  7776. let inputPlaceholder = NSFont.systemFont(ofSize: 14, weight: .regular)
  7777. let buttonText = NSFont.systemFont(ofSize: 16, weight: .medium)
  7778. let filterText = NSFont.systemFont(ofSize: 15, weight: .regular)
  7779. let filterArrow = NSFont.systemFont(ofSize: 12, weight: .regular)
  7780. let iconButton = NSFont.systemFont(ofSize: 14, weight: .medium)
  7781. let cardIcon = NSFont.systemFont(ofSize: 8, weight: .bold)
  7782. let cardTitle = NSFont.systemFont(ofSize: 15, weight: .semibold)
  7783. let cardSubtitle = NSFont.systemFont(ofSize: 13, weight: .bold)
  7784. let cardTime = NSFont.systemFont(ofSize: 12, weight: .regular)
  7785. }
  7786. // MARK: - In-app browser (macOS WKWebView + chrome)
  7787. // Note: This target is AppKit/macOS. iOS would use WKWebView or SFSafariViewController; Android would use WebView or Custom Tabs.
  7788. private enum InAppBrowserURLPolicy: Equatable {
  7789. case allowAll
  7790. case whitelist(hostSuffixes: [String])
  7791. }
  7792. private func inAppBrowserURLAllowed(_ url: URL, policy: InAppBrowserURLPolicy) -> Bool {
  7793. let scheme = (url.scheme ?? "").lowercased()
  7794. if scheme == "about" { return true }
  7795. guard scheme == "http" || scheme == "https" else { return false }
  7796. guard let host = url.host?.lowercased() else { return false }
  7797. switch policy {
  7798. case .allowAll:
  7799. return true
  7800. case .whitelist(let suffixes):
  7801. for suffix in suffixes {
  7802. let s = suffix.lowercased()
  7803. if host == s || host.hasSuffix("." + s) { return true }
  7804. }
  7805. return false
  7806. }
  7807. }
  7808. private enum InAppBrowserWebKitSupport {
  7809. static func makeWebViewConfiguration() -> WKWebViewConfiguration {
  7810. let config = WKWebViewConfiguration()
  7811. config.websiteDataStore = .default()
  7812. config.preferences.javaScriptCanOpenWindowsAutomatically = true
  7813. if #available(macOS 12.3, *) {
  7814. config.preferences.isElementFullscreenEnabled = true
  7815. }
  7816. config.mediaTypesRequiringUserActionForPlayback = []
  7817. if #available(macOS 11.0, *) {
  7818. config.defaultWebpagePreferences.allowsContentJavaScript = true
  7819. }
  7820. config.applicationNameForUserAgent = "MeetingsApp/1.0"
  7821. return config
  7822. }
  7823. }
  7824. private final class InAppBrowserWindowController: NSWindowController {
  7825. private static let defaultContentSize = NSSize(width: 1100, height: 760)
  7826. private static let minimumContentSize = NSSize(width: 800, height: 520)
  7827. private let browserViewController = InAppBrowserContainerViewController()
  7828. init() {
  7829. let browserWindow = NSWindow(
  7830. contentRect: NSRect(origin: .zero, size: Self.defaultContentSize),
  7831. styleMask: [.titled, .closable, .miniaturizable, .resizable],
  7832. backing: .buffered,
  7833. defer: false
  7834. )
  7835. browserWindow.title = "Browser"
  7836. browserWindow.isRestorable = false
  7837. browserWindow.setFrameAutosaveName("")
  7838. browserWindow.minSize = browserWindow.frameRect(forContentRect: NSRect(origin: .zero, size: Self.minimumContentSize)).size
  7839. browserWindow.center()
  7840. browserWindow.contentViewController = browserViewController
  7841. super.init(window: browserWindow)
  7842. }
  7843. @available(*, unavailable)
  7844. required init?(coder: NSCoder) {
  7845. nil
  7846. }
  7847. /// Resets size and position each time the browser is shown so a previously tiny window is never reused.
  7848. func applyDefaultFrameCenteredOnVisibleScreen() {
  7849. guard let w = window, let screen = w.screen ?? NSScreen.main else { return }
  7850. let windowFrame = w.frameRect(forContentRect: NSRect(origin: .zero, size: Self.defaultContentSize))
  7851. let vf = screen.visibleFrame
  7852. var frame = windowFrame
  7853. frame.origin.x = vf.midX - frame.width / 2
  7854. frame.origin.y = vf.midY - frame.height / 2
  7855. if frame.maxX > vf.maxX { frame.origin.x = vf.maxX - frame.width }
  7856. if frame.minX < vf.minX { frame.origin.x = vf.minX }
  7857. if frame.maxY > vf.maxY { frame.origin.y = vf.maxY - frame.height }
  7858. if frame.minY < vf.minY { frame.origin.y = vf.minY }
  7859. w.setFrame(frame, display: true)
  7860. }
  7861. func load(url: URL, policy: InAppBrowserURLPolicy) {
  7862. browserViewController.setNavigationPolicy(policy)
  7863. browserViewController.load(url: url)
  7864. }
  7865. }
  7866. private final class InAppBrowserContainerViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, NSTextFieldDelegate {
  7867. private var webView: WKWebView!
  7868. private var webContainerView: NSView!
  7869. private weak var urlField: NSTextField?
  7870. private var backButton: NSButton!
  7871. private var forwardButton: NSButton!
  7872. private var reloadStopButton: NSButton!
  7873. private var goButton: NSButton!
  7874. private var progressBar: NSProgressIndicator!
  7875. private var lastLoadedURL: URL?
  7876. private var navigationPolicy: InAppBrowserURLPolicy = .allowAll
  7877. private var processTerminateRetryCount = 0
  7878. /// Includes fresh WKWebView instances so each retry gets a new WebContent process after a crash.
  7879. private let maxProcessTerminateRetries = 3
  7880. private var kvoTokens: [NSKeyValueObservation] = []
  7881. deinit {
  7882. kvoTokens.removeAll()
  7883. }
  7884. func setNavigationPolicy(_ policy: InAppBrowserURLPolicy) {
  7885. navigationPolicy = policy
  7886. }
  7887. override func loadView() {
  7888. let root = NSView()
  7889. root.translatesAutoresizingMaskIntoConstraints = false
  7890. let wv = makeWebView()
  7891. webView = wv
  7892. let webHost = NSView()
  7893. webHost.translatesAutoresizingMaskIntoConstraints = false
  7894. webHost.wantsLayer = true
  7895. webHost.addSubview(wv)
  7896. NSLayoutConstraint.activate([
  7897. wv.leadingAnchor.constraint(equalTo: webHost.leadingAnchor),
  7898. wv.trailingAnchor.constraint(equalTo: webHost.trailingAnchor),
  7899. wv.topAnchor.constraint(equalTo: webHost.topAnchor),
  7900. wv.bottomAnchor.constraint(equalTo: webHost.bottomAnchor)
  7901. ])
  7902. webContainerView = webHost
  7903. let toolbar = NSStackView()
  7904. toolbar.translatesAutoresizingMaskIntoConstraints = false
  7905. toolbar.orientation = .horizontal
  7906. toolbar.spacing = 8
  7907. toolbar.alignment = .centerY
  7908. toolbar.edgeInsets = NSEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)
  7909. backButton = makeToolbarButton(title: "◀", symbolName: "chevron.backward", accessibilityDescription: "Back")
  7910. backButton.target = self
  7911. backButton.action = #selector(goBack)
  7912. forwardButton = makeToolbarButton(title: "▶", symbolName: "chevron.forward", accessibilityDescription: "Forward")
  7913. forwardButton.target = self
  7914. forwardButton.action = #selector(goForward)
  7915. reloadStopButton = makeToolbarButton(title: "Reload", symbolName: "arrow.clockwise", accessibilityDescription: "Reload")
  7916. reloadStopButton.target = self
  7917. reloadStopButton.action = #selector(reloadOrStop)
  7918. let field = NSTextField(string: "")
  7919. field.translatesAutoresizingMaskIntoConstraints = false
  7920. field.font = NSFont.systemFont(ofSize: 13, weight: .regular)
  7921. field.placeholderString = "Address"
  7922. field.cell?.sendsActionOnEndEditing = false
  7923. field.delegate = self
  7924. urlField = field
  7925. goButton = NSButton(title: "Go", target: self, action: #selector(addressFieldSubmitted))
  7926. goButton.translatesAutoresizingMaskIntoConstraints = false
  7927. goButton.bezelStyle = .rounded
  7928. toolbar.addArrangedSubview(backButton)
  7929. toolbar.addArrangedSubview(forwardButton)
  7930. toolbar.addArrangedSubview(reloadStopButton)
  7931. toolbar.addArrangedSubview(field)
  7932. toolbar.addArrangedSubview(goButton)
  7933. field.widthAnchor.constraint(greaterThanOrEqualToConstant: 240).isActive = true
  7934. let bar = NSProgressIndicator()
  7935. bar.translatesAutoresizingMaskIntoConstraints = false
  7936. bar.style = .bar
  7937. bar.isIndeterminate = false
  7938. bar.minValue = 0
  7939. bar.maxValue = 1
  7940. bar.doubleValue = 0
  7941. bar.isHidden = true
  7942. progressBar = bar
  7943. let separator = NSBox()
  7944. separator.translatesAutoresizingMaskIntoConstraints = false
  7945. separator.boxType = .separator
  7946. webView.navigationDelegate = self
  7947. webView.uiDelegate = self
  7948. root.addSubview(toolbar)
  7949. root.addSubview(bar)
  7950. root.addSubview(separator)
  7951. root.addSubview(webHost)
  7952. NSLayoutConstraint.activate([
  7953. toolbar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  7954. toolbar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  7955. toolbar.topAnchor.constraint(equalTo: root.topAnchor),
  7956. bar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  7957. bar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  7958. bar.topAnchor.constraint(equalTo: toolbar.bottomAnchor),
  7959. bar.heightAnchor.constraint(equalToConstant: 3),
  7960. separator.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  7961. separator.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  7962. separator.topAnchor.constraint(equalTo: bar.bottomAnchor),
  7963. webHost.leadingAnchor.constraint(equalTo: root.leadingAnchor),
  7964. webHost.trailingAnchor.constraint(equalTo: root.trailingAnchor),
  7965. webHost.topAnchor.constraint(equalTo: separator.bottomAnchor),
  7966. webHost.bottomAnchor.constraint(equalTo: root.bottomAnchor)
  7967. ])
  7968. view = root
  7969. installWebViewObservers()
  7970. syncToolbarFromWebView()
  7971. }
  7972. private func makeWebView() -> WKWebView {
  7973. let wv = WKWebView(frame: .zero, configuration: InAppBrowserWebKitSupport.makeWebViewConfiguration())
  7974. wv.translatesAutoresizingMaskIntoConstraints = false
  7975. return wv
  7976. }
  7977. private func teardownWebViewObservers() {
  7978. kvoTokens.removeAll()
  7979. }
  7980. /// New `WKWebView` = new WebContent process (helps after GPU/JS crashes on heavy sites like Meet).
  7981. private func replaceWebViewAndLoad(url: URL) {
  7982. teardownWebViewObservers()
  7983. webView.navigationDelegate = nil
  7984. webView.uiDelegate = nil
  7985. webView.removeFromSuperview()
  7986. let wv = makeWebView()
  7987. webView = wv
  7988. webContainerView.addSubview(wv)
  7989. NSLayoutConstraint.activate([
  7990. wv.leadingAnchor.constraint(equalTo: webContainerView.leadingAnchor),
  7991. wv.trailingAnchor.constraint(equalTo: webContainerView.trailingAnchor),
  7992. wv.topAnchor.constraint(equalTo: webContainerView.topAnchor),
  7993. wv.bottomAnchor.constraint(equalTo: webContainerView.bottomAnchor)
  7994. ])
  7995. webView.navigationDelegate = self
  7996. webView.uiDelegate = self
  7997. installWebViewObservers()
  7998. syncToolbarFromWebView()
  7999. webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData))
  8000. }
  8001. private func makeToolbarButton(title: String, symbolName: String, accessibilityDescription: String) -> NSButton {
  8002. let b = NSButton()
  8003. b.translatesAutoresizingMaskIntoConstraints = false
  8004. b.bezelStyle = .texturedRounded
  8005. b.setAccessibilityLabel(accessibilityDescription)
  8006. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: symbolName, accessibilityDescription: accessibilityDescription) {
  8007. b.image = img
  8008. b.imagePosition = .imageOnly
  8009. } else {
  8010. b.title = title
  8011. }
  8012. b.widthAnchor.constraint(greaterThanOrEqualToConstant: 32).isActive = true
  8013. return b
  8014. }
  8015. private func installWebViewObservers() {
  8016. kvoTokens.append(webView.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in
  8017. self?.syncToolbarFromWebView()
  8018. })
  8019. kvoTokens.append(webView.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in
  8020. self?.syncToolbarFromWebView()
  8021. })
  8022. kvoTokens.append(webView.observe(\.isLoading, options: [.new]) { [weak self] _, _ in
  8023. self?.syncToolbarFromWebView()
  8024. })
  8025. kvoTokens.append(webView.observe(\.estimatedProgress, options: [.new]) { [weak self] _, _ in
  8026. self?.syncProgressFromWebView()
  8027. })
  8028. kvoTokens.append(webView.observe(\.title, options: [.new]) { [weak self] _, _ in
  8029. self?.syncWindowTitle()
  8030. })
  8031. kvoTokens.append(webView.observe(\.url, options: [.new]) { [weak self] _, _ in
  8032. self?.syncAddressFieldFromWebView()
  8033. })
  8034. }
  8035. private func syncToolbarFromWebView() {
  8036. backButton?.isEnabled = webView.canGoBack
  8037. forwardButton?.isEnabled = webView.canGoForward
  8038. if webView.isLoading {
  8039. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Stop") {
  8040. reloadStopButton.image = img
  8041. reloadStopButton.imagePosition = .imageOnly
  8042. reloadStopButton.title = ""
  8043. } else {
  8044. reloadStopButton.title = "Stop"
  8045. }
  8046. } else {
  8047. if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Reload") {
  8048. reloadStopButton.image = img
  8049. reloadStopButton.imagePosition = .imageOnly
  8050. reloadStopButton.title = ""
  8051. } else {
  8052. reloadStopButton.title = "Reload"
  8053. }
  8054. }
  8055. syncProgressFromWebView()
  8056. }
  8057. private func syncProgressFromWebView() {
  8058. guard let progressBar else { return }
  8059. if webView.isLoading {
  8060. progressBar.isHidden = false
  8061. progressBar.doubleValue = webView.estimatedProgress
  8062. } else {
  8063. progressBar.isHidden = true
  8064. progressBar.doubleValue = 0
  8065. }
  8066. }
  8067. private func syncAddressFieldFromWebView() {
  8068. guard let urlField, urlField.currentEditor() == nil, let url = webView.url else { return }
  8069. urlField.stringValue = url.absoluteString
  8070. }
  8071. private func syncWindowTitle() {
  8072. let t = webView.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  8073. let host = webView.url?.host ?? ""
  8074. view.window?.title = t.isEmpty ? (host.isEmpty ? "Browser" : host) : t
  8075. }
  8076. func load(url: URL) {
  8077. lastLoadedURL = url
  8078. processTerminateRetryCount = 0
  8079. urlField?.stringValue = url.absoluteString
  8080. webView.load(URLRequest(url: url))
  8081. syncWindowTitle()
  8082. }
  8083. @objc private func goBack() {
  8084. webView.goBack()
  8085. }
  8086. @objc private func goForward() {
  8087. webView.goForward()
  8088. }
  8089. @objc private func reloadOrStop() {
  8090. if webView.isLoading {
  8091. webView.stopLoading()
  8092. } else {
  8093. webView.reload()
  8094. }
  8095. }
  8096. @objc private func addressFieldSubmitted() {
  8097. let raw = urlField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
  8098. guard raw.isEmpty == false else { return }
  8099. var normalized = raw
  8100. if normalized.lowercased().hasPrefix("http://") == false && normalized.lowercased().hasPrefix("https://") == false {
  8101. normalized = "https://\(normalized)"
  8102. }
  8103. guard let url = URL(string: normalized),
  8104. let scheme = url.scheme?.lowercased(),
  8105. scheme == "http" || scheme == "https",
  8106. url.host != nil
  8107. else {
  8108. let alert = NSAlert()
  8109. alert.messageText = "Invalid address"
  8110. alert.informativeText = "Enter a valid web address, for example https://example.com"
  8111. alert.addButton(withTitle: "OK")
  8112. alert.runModal()
  8113. return
  8114. }
  8115. guard inAppBrowserURLAllowed(url, policy: navigationPolicy) else {
  8116. presentBlockedHostAlert()
  8117. return
  8118. }
  8119. load(url: url)
  8120. }
  8121. private func presentBlockedHostAlert() {
  8122. let alert = NSAlert()
  8123. alert.messageText = "Address not allowed"
  8124. alert.informativeText = "This URL is not permitted with the current in-app browser policy (whitelist)."
  8125. alert.addButton(withTitle: "OK")
  8126. alert.runModal()
  8127. }
  8128. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  8129. processTerminateRetryCount = 0
  8130. syncAddressFieldFromWebView()
  8131. syncWindowTitle()
  8132. }
  8133. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
  8134. let nsError = error as NSError
  8135. if nsError.code == NSURLErrorCancelled {
  8136. return
  8137. }
  8138. let alert = NSAlert()
  8139. alert.messageText = "Unable to load page"
  8140. alert.informativeText = "Could not load this page in the in-app browser.\n\n\(error.localizedDescription)"
  8141. alert.addButton(withTitle: "Try Again")
  8142. alert.addButton(withTitle: "OK")
  8143. if alert.runModal() == .alertFirstButtonReturn, let url = lastLoadedURL {
  8144. processTerminateRetryCount = 0
  8145. webView.load(URLRequest(url: url))
  8146. }
  8147. }
  8148. func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
  8149. guard let url = lastLoadedURL else { return }
  8150. if processTerminateRetryCount < maxProcessTerminateRetries {
  8151. processTerminateRetryCount += 1
  8152. replaceWebViewAndLoad(url: url)
  8153. return
  8154. }
  8155. let alert = NSAlert()
  8156. alert.messageText = "Page stopped loading"
  8157. alert.informativeText =
  8158. "The in-app browser closed this page unexpectedly. You can try loading it again in this same window."
  8159. alert.addButton(withTitle: "Try Again")
  8160. alert.addButton(withTitle: "OK")
  8161. if alert.runModal() == .alertFirstButtonReturn {
  8162. processTerminateRetryCount = 0
  8163. replaceWebViewAndLoad(url: url)
  8164. }
  8165. }
  8166. func webView(
  8167. _ webView: WKWebView,
  8168. decidePolicyFor navigationAction: WKNavigationAction,
  8169. decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
  8170. ) {
  8171. guard let url = navigationAction.request.url else {
  8172. decisionHandler(.allow)
  8173. return
  8174. }
  8175. let scheme = (url.scheme ?? "").lowercased()
  8176. if scheme == "mailto" || scheme == "tel" {
  8177. decisionHandler(.cancel)
  8178. return
  8179. }
  8180. if inAppBrowserURLAllowed(url, policy: navigationPolicy) == false {
  8181. if navigationAction.targetFrame?.isMainFrame != false {
  8182. DispatchQueue.main.async { [weak self] in
  8183. self?.presentBlockedHostAlert()
  8184. }
  8185. }
  8186. decisionHandler(.cancel)
  8187. return
  8188. }
  8189. decisionHandler(.allow)
  8190. }
  8191. func webView(
  8192. _ webView: WKWebView,
  8193. createWebViewWith configuration: WKWebViewConfiguration,
  8194. for navigationAction: WKNavigationAction,
  8195. windowFeatures: WKWindowFeatures
  8196. ) -> WKWebView? {
  8197. if navigationAction.targetFrame == nil, let requestURL = navigationAction.request.url {
  8198. if inAppBrowserURLAllowed(requestURL, policy: navigationPolicy) {
  8199. webView.load(URLRequest(url: requestURL))
  8200. } else {
  8201. presentBlockedHostAlert()
  8202. }
  8203. }
  8204. return nil
  8205. }
  8206. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  8207. if control === urlField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
  8208. addressFieldSubmitted()
  8209. return true
  8210. }
  8211. return false
  8212. }
  8213. }