| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493 |
- //
- // ViewController.swift
- // Assistant for Google Meet
- //
- // Created by Dev Mac 1 on 06/04/2026.
- //
- import Cocoa
- import QuartzCore
- import AVFoundation
- import AVKit
- import Speech
- import WebKit
- import AuthenticationServices
- import StoreKit
- import ScreenCaptureKit
- private enum SidebarPage: Int {
- case joinMeetings = 0
- case photo = 1
- case video = 2
- case widgets = 3
- case settings = 4
- case aiCompanion = 5
- }
- private enum ZoomJoinMode: Int {
- case id = 0
- case url = 1
- }
- private enum SettingsAction: Int {
- case restore = 0
- case rateUs = 1
- case support = 2
- case moreApps = 3
- case shareApp = 4
- case upgrade = 5
- case privacyPolicy = 6
- case termsOfServices = 7
- }
- private struct SpeechLocaleOption {
- let identifier: String
- let displayName: String
- }
- private enum PremiumPlan: Int {
- case weekly = 0
- case monthly = 1
- case yearly = 2
- case lifetime = 3
- }
- private enum PremiumStoreProduct {
- static let weekly = "com.mqldev.meetingsapp.premium.weekly"
- static let monthly = "com.mqldev.meetingsapp.premium.monthly"
- static let yearly = "com.mqldev.meetingsapp.premium.yearly"
- static let lifetime = "com.mqldev.meetingsapp.premium.lifetime"
- static let allIDs = [weekly, monthly, yearly, lifetime]
- static func productID(for plan: PremiumPlan) -> String {
- switch plan {
- case .weekly: return weekly
- case .monthly: return monthly
- case .yearly: return yearly
- case .lifetime: return lifetime
- }
- }
- static func plan(for productID: String) -> PremiumPlan? {
- switch productID {
- case weekly: return .weekly
- case monthly: return .monthly
- case yearly: return .yearly
- case lifetime: return .lifetime
- default: return nil
- }
- }
- }
- @MainActor
- private final class StoreKitCoordinator {
- enum PurchaseOutcome {
- case success
- case cancelled
- case pending
- case unavailable
- case alreadyOwned
- case failed(String)
- }
- private(set) var productsByID: [String: Product] = [:]
- private(set) var activeEntitlementProductIDs: Set<String> = []
- private(set) var lastProductLoadError: String?
- var onEntitlementsChanged: ((Bool) -> Void)?
- var hasPremiumAccess: Bool { !activeEntitlementProductIDs.isEmpty }
- var hasLifetimeAccess: Bool { activeEntitlementProductIDs.contains(PremiumStoreProduct.lifetime) }
- var activeNonLifetimePlan: PremiumPlan? {
- activeEntitlementProductIDs
- .compactMap { PremiumStoreProduct.plan(for: $0) }
- .filter { $0 != .lifetime }
- .max(by: { $0.rawValue < $1.rawValue })
- }
- private var transactionUpdatesTask: Task<Void, Never>?
- deinit {
- transactionUpdatesTask?.cancel()
- }
- func start() async {
- if transactionUpdatesTask == nil {
- transactionUpdatesTask = Task { [weak self] in
- await self?.observeTransactionUpdates()
- }
- }
- await refreshProducts()
- await refreshEntitlements()
- }
- func refreshProducts() async {
- do {
- let products = try await Product.products(for: PremiumStoreProduct.allIDs)
- productsByID = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) })
- lastProductLoadError = nil
- } catch {
- productsByID = [:]
- lastProductLoadError = error.localizedDescription
- }
- }
- func refreshEntitlements() async {
- let previousHasPremiumAccess = hasPremiumAccess
- var active = Set<String>()
- for await entitlement in Transaction.currentEntitlements {
- guard case .verified(let transaction) = entitlement else { continue }
- guard PremiumStoreProduct.allIDs.contains(transaction.productID) else { continue }
- if Self.isTransactionActive(transaction) {
- active.insert(transaction.productID)
- }
- }
- // Some StoreKit test timelines can briefly report empty current entitlements
- // even though a latest verified transaction exists for a non-consumable.
- // Merge in latest transactions to keep launch access state accurate.
- for productID in PremiumStoreProduct.allIDs {
- guard let latest = await Transaction.latest(for: productID),
- case .verified(let transaction) = latest,
- Self.isTransactionActive(transaction) else { continue }
- active.insert(productID)
- }
- activeEntitlementProductIDs = active
- let newHasPremiumAccess = hasPremiumAccess
- if newHasPremiumAccess != previousHasPremiumAccess {
- onEntitlementsChanged?(newHasPremiumAccess)
- }
- }
- func purchase(plan: PremiumPlan) async -> PurchaseOutcome {
- let productID = PremiumStoreProduct.productID(for: plan)
- if activeEntitlementProductIDs.contains(productID) {
- return .alreadyOwned
- }
- guard let product = productsByID[productID] else {
- await refreshProducts()
- guard let refreshed = productsByID[productID] else {
- if let lastProductLoadError, !lastProductLoadError.isEmpty {
- return .failed("Unable to load products: \(lastProductLoadError)")
- }
- let loadedIDs = productsByID.keys.sorted().joined(separator: ", ")
- let debugIDs = loadedIDs.isEmpty ? "none" : loadedIDs
- return .failed("Product ID not found in StoreKit response. Requested: \(productID). Loaded IDs: \(debugIDs)")
- }
- return await purchase(product: refreshed)
- }
- return await purchase(product: product)
- }
- func restorePurchases() async -> String {
- do {
- try await AppStore.sync()
- await refreshEntitlements()
- if hasPremiumAccess {
- return "Purchases restored successfully."
- }
- return "No previous premium purchase was found for this Apple ID."
- } catch {
- return "Restore failed: \(error.localizedDescription)"
- }
- }
- private func purchase(product: Product) async -> PurchaseOutcome {
- do {
- let result = try await product.purchase()
- switch result {
- case .success(let verificationResult):
- guard case .verified(let transaction) = verificationResult else {
- return .failed("Purchase verification failed.")
- }
- await transaction.finish()
- await refreshEntitlements()
- return .success
- case .pending:
- return .pending
- case .userCancelled:
- return .cancelled
- @unknown default:
- return .failed("Unknown purchase state.")
- }
- } catch {
- return .failed(error.localizedDescription)
- }
- }
- private func observeTransactionUpdates() async {
- for await update in Transaction.updates {
- guard case .verified(let transaction) = update else { continue }
- if PremiumStoreProduct.allIDs.contains(transaction.productID) {
- await refreshEntitlements()
- }
- await transaction.finish()
- }
- }
- private static func isTransactionActive(_ transaction: Transaction) -> Bool {
- if transaction.revocationDate != nil { return false }
- if let expirationDate = transaction.expirationDate {
- return expirationDate > Date()
- }
- return true
- }
- }
- final class ViewController: NSViewController {
- private enum MeetingTranscriptStatus: String, Codable {
- case notRequested
- case processing
- case ready
- case failed
- }
- private enum MeetingNotesStatus: String, Codable {
- case notRequested
- case processing
- case ready
- case failed
- }
- private enum MeetingTranscriptSource: String, Codable {
- case meetApi
- case localAudioAppleSpeech
- case localMultiChannelAppleSpeech
- }
- private enum PaywallFooterAction {
- case manageSubscription
- case restorePurchase
- case continueWithFreePlan
- case privacyPolicy
- case support
- case termsOfServices
- }
- private struct GoogleProfileDisplay {
- let name: String
- let email: String
- let pictureURL: URL?
- }
- private struct MeetingRecordingSummary: Codable {
- let id: String
- let title: String
- let meetURLString: String
- let startedAt: Date
- let endedAt: Date
- let audioFilePath: String
- var microphoneAudioFilePath: String?
- var systemAudioFilePath: String?
- var transcriptStatusRaw: String?
- var transcriptSourceRaw: String?
- var transcriptText: String?
- var transcriptSegmentsJSON: String?
- var transcriptErrorMessage: String?
- var notesStatusRaw: String?
- var notesText: String?
- var notesErrorMessage: String?
- }
- private struct ActiveMeetingRecordingSession {
- let id: String
- let title: String
- let meetURL: URL
- let startedAt: Date
- let systemAudioFileURL: URL
- let microphoneAudioFileURL: URL
- }
- private var palette = Palette(isDarkMode: true)
- private let typography = Typography()
- private let launchContentSize = NSSize(width: 920, height: 690)
- private let launchMinContentSize = NSSize(width: 760, height: 600)
- private let launchSplashMinimumVisibleDuration: TimeInterval = 2
- private let launchSplashTimeout: TimeInterval = 12
- private var launchSplashView: LaunchSplashView?
- private var launchSplashTimeoutWorkItem: DispatchWorkItem?
- private var launchSplashMinimumDelayWorkItem: DispatchWorkItem?
- private var launchSplashShownAt: Date?
- private var hasDismissedLaunchSplash = false
- private var mainContentHost: NSView?
- /// Pin constraints for the current page inside `mainContentHost`; deactivated before each swap so relayout never stacks duplicates.
- private var mainContentHostPinConstraints: [NSLayoutConstraint] = []
- private var sidebarRowViews: [SidebarPage: NSView] = [:]
- private var selectedSidebarPage: SidebarPage = .joinMeetings
- private var selectedZoomJoinMode: ZoomJoinMode = .id
- private var pageCache: [SidebarPage: NSView] = [:]
- private var sidebarPageByView = [ObjectIdentifier: SidebarPage]()
- private var zoomJoinModeByView = [ObjectIdentifier: ZoomJoinMode]()
- private var zoomJoinModeViews: [ZoomJoinMode: NSView] = [:]
- private var settingsActionByView = [ObjectIdentifier: SettingsAction]()
- private var aiCompanionAudioURLByView = [ObjectIdentifier: URL]()
- private var aiCompanionAudioStatusLabelByView = [ObjectIdentifier: NSTextField]()
- private var aiCompanionTranscriptMeetingIdByView = [ObjectIdentifier: String]()
- private var aiCompanionTranscriptStatusLabelByView = [ObjectIdentifier: NSTextField]()
- private var aiCompanionTranscriptCurrentRequestId: UUID?
- private var aiCompanionTranscriptWindow: NSWindow?
- private weak var aiCompanionTranscriptTextView: NSTextView?
- private var aiCompanionTranscriptTaskByMeetingId = [String: Task<Void, Never>]()
- private var aiCompanionNotesMeetingIdByView = [ObjectIdentifier: String]()
- private var aiCompanionNotesStatusLabelByView = [ObjectIdentifier: NSTextField]()
- private var aiCompanionNotesCurrentRequestId: UUID?
- private var aiCompanionNotesPanel: NSPanel?
- private weak var aiCompanionNotesRootView: NSView?
- private weak var aiCompanionNotesHeaderView: NSView?
- private weak var aiCompanionNotesTitleLabel: NSTextField?
- private weak var aiCompanionNotesSubtitleLabel: NSTextField?
- private weak var aiCompanionNotesTextView: NSTextView?
- private weak var aiCompanionNotesCopyButton: NSButton?
- private weak var aiCompanionNotesCloseButton: NSButton?
- private var aiCompanionNotesOutsideClickMonitor: Any?
- private var aiCompanionNotesTaskByMeetingId = [String: Task<Void, Never>]()
- private var aiCompanionAudioPlayer: AVPlayer?
- private var aiCompanionLocalAudioPlayer: AVAudioPlayer?
- private var aiCompanionCurrentlyPlayingURL: URL?
- private weak var aiCompanionCurrentlyPlayingButton: NSButton?
- private var aiCompanionPlaybackEndObserver: NSObjectProtocol?
- private var aiCompanionPlaybackFailedObserver: NSObjectProtocol?
- private var aiCompanionTimeControlObserver: NSKeyValueObservation?
- private var aiCompanionAudioRequestID = UUID()
- private var aiCompanionNoProgressWorkItem: DispatchWorkItem?
- private let aiCompanionSpeechSynthesizer = AVSpeechSynthesizer()
- private var aiCompanionIsUsingSpeech = false
- private var aiCompanionSpeechTextByView = [ObjectIdentifier: String]()
- private var aiCompanionCurrentlySpeakingButtonId: ObjectIdentifier?
- private var paywallWindow: NSWindow?
- private weak var paywallOverlayView: NSView?
- private let paywallContentWidth: CGFloat = 520
- private let launchWindowLeftOffset: CGFloat = 80
- private var selectedPremiumPlan: PremiumPlan = .monthly
- private var paywallPlanViews: [PremiumPlan: NSView] = [:]
- private var premiumPlanByView = [ObjectIdentifier: PremiumPlan]()
- private var paywallFooterActionByView = [ObjectIdentifier: PaywallFooterAction]()
- private weak var paywallOfferLabel: NSTextField?
- private weak var paywallContinueLabel: NSTextField?
- private weak var paywallContinueButton: NSView?
- private weak var sidebarPremiumTitleLabel: NSTextField?
- private weak var sidebarPremiumIconView: NSImageView?
- private weak var sidebarPremiumButtonView: HoverTrackingView?
- private weak var instantMeetCardView: HoverSurfaceView?
- private weak var instantMeetTitleLabel: NSTextField?
- private weak var instantMeetSubtitleLabel: NSTextField?
- private weak var joinWithLinkCardView: HoverSurfaceView?
- private weak var joinWithLinkTitleLabel: NSTextField?
- private weak var joinMeetPrimaryButton: NSButton?
- private weak var meetLinkField: NSTextField?
- private weak var browseAddressField: NSTextField?
- private var inAppBrowserWindowController: InAppBrowserWindowController?
- private var embeddedBrowserViewController: InAppBrowserContainerViewController?
- private var embeddedBrowserURL: URL?
- private var embeddedBrowserPolicy: InAppBrowserURLPolicy = .allowAll
- private weak var mainPanelAuthBar: NSView?
- private var mainContentHostTopToAuthConstraint: NSLayoutConstraint?
- private var mainContentHostTopToPanelConstraint: NSLayoutConstraint?
- private let googleOAuth = GoogleOAuthService.shared
- private let calendarClient = GoogleCalendarClient()
- private let googleMeetClient = GoogleMeetClient()
- private let storeKitCoordinator = StoreKitCoordinator()
- private var storeKitStartupTask: Task<Void, Never>?
- private var paywallPurchaseTask: Task<Void, Never>?
- private var paywallPriceLabels: [PremiumPlan: NSTextField] = [:]
- private var paywallSubtitleLabels: [PremiumPlan: NSTextField] = [:]
- private var paywallContinueEnabled = true
- private var paywallUpgradeFlowEnabled = false
- private let launchPaywallDelay: TimeInterval = 3
- private var hasCompletedInitialStoreKitSync = false
- private var hasPresentedLaunchPaywall = false
- private var launchPaywallWorkItem: DispatchWorkItem?
- private var hasViewAppearedOnce = false
- private var lastKnownPremiumAccess = false
- private var displayedScheduleMeetings: [ScheduledMeeting] = []
- private var appUsageSessionStartDate: Date?
- private var hasObservedAppLifecycleForUsage = false
- private var premiumUpgradeRatingPromptWorkItem: DispatchWorkItem?
- private enum ScheduleFilter: Int {
- case all = 0
- case today = 1
- case week = 2
- }
- private enum SchedulePageFilter: Int {
- case all = 0
- case today = 1
- case week = 2
- case month = 3
- case customRange = 4
- }
- /// Saved meeting list filters on AI Companion (uses each recording’s `endedAt` day in the current calendar).
- private enum AiCompanionRecordingsFilter: Int {
- case all = 0
- case today = 1
- case week = 2
- case previousWeek = 3
- case previousMonth = 4
- case customRange = 5
- }
- private var scheduleFilter: ScheduleFilter = .all
- private weak var scheduleDateHeadingLabel: NSTextField?
- private weak var scheduleCardsStack: NSStackView?
- private weak var scheduleCardsScrollView: NSScrollView?
- private weak var scheduleScrollLeftButton: NSView?
- private weak var scheduleScrollRightButton: NSView?
- private weak var scheduleFilterDropdown: NSPopUpButton?
- private weak var scheduleGoogleAuthButton: NSButton?
- private weak var scheduleGoogleAuthHostView: GoogleProfileAuthHostView?
- private var scheduleGoogleAuthHostPadWidthConstraint: NSLayoutConstraint?
- private var scheduleGoogleAuthHostPadHeightConstraint: NSLayoutConstraint?
- private var scheduleGoogleAuthButtonWidthConstraint: NSLayoutConstraint?
- private var scheduleGoogleAuthButtonHeightConstraint: NSLayoutConstraint?
- private weak var settingsReminderMasterSwitch: NSSwitch?
- private weak var settingsReminder1DaySwitch: NSSwitch?
- private weak var settingsReminder12HoursSwitch: NSSwitch?
- private weak var settingsReminder1HourSwitch: NSSwitch?
- /// Circular avatar size when signed in (top-right, Google-style).
- private let scheduleGoogleSignedInAvatarSize: CGFloat = 36
- private var scheduleGoogleAuthHovering = false
- private var scheduleCurrentProfile: GoogleProfileDisplay?
- /// Larger copy of the header avatar for the account popover (optional).
- private var scheduleProfileMenuAvatar: NSImage?
- private var scheduleProfileImageTask: Task<Void, Never>?
- private var googleAccountPopover: NSPopover?
- private var scheduleCachedMeetings: [ScheduledMeeting] = []
- private var aiCompanionLocalRecordings: [MeetingRecordingSummary] = []
- private var aiCompanionRecordingsFilter: AiCompanionRecordingsFilter = .today
- private var aiCompanionFilterFromDate: Date = Calendar.current.startOfDay(for: Date())
- private var aiCompanionFilterToDate: Date = Calendar.current.startOfDay(for: Date())
- private var aiCompanionRecordingsRangeErrorMessage: String?
- private weak var aiCompanionRecordingsFilterDropdown: NSPopUpButton?
- private weak var aiCompanionFilterFromDatePicker: NSDatePicker?
- private weak var aiCompanionFilterToDatePicker: NSDatePicker?
- private weak var aiCompanionRecordingsRangeErrorLabel: NSTextField?
- private var activeMeetingRecordingSession: ActiveMeetingRecordingSession?
- private var activeMeetingAudioRecorder: AVAudioRecorder?
- private var activeMeetingSystemAudioStopper: (() async -> Void)?
- private var meetingRecordingMonitorTask: Task<Void, Never>?
- private weak var aiCompanionStopRecordingButton: NSButton?
- private let widgetSnapshotLimit: Int = 3
- private var schedulePageFilter: SchedulePageFilter = .all
- private var schedulePageFromDate: Date = Calendar.current.startOfDay(for: Date())
- private var schedulePageToDate: Date = Calendar.current.startOfDay(for: Date())
- private var schedulePageFilteredMeetings: [ScheduledMeeting] = []
- private var schedulePageVisibleCount: Int = 0
- private let schedulePageBatchSize: Int = 6
- private let schedulePageCardsPerRow: Int = 3
- private let schedulePageCardSpacing: CGFloat = 20
- private let schedulePageCardHeight: CGFloat = 182
- /// Match `makeJoinMeetingsContent` vertical rhythm between sections.
- private let schedulePageStackSpacing: CGFloat = 14
- /// Tighter gap from header block (title + filters) to the date line below.
- private let schedulePageHeaderToDateSpacing: CGFloat = 10
- /// Join Meetings: gap from “Schedule” row to date heading, and date heading to card strip (keeps cards aligned with the rest of the column).
- private let joinPageScheduleHeaderToDateSpacing: CGFloat = 8
- private let joinPageDateToMeetingCardsSpacing: CGFloat = 8
- /// Match Join Meetings main content insets so the top auth/profile bar lines up with page edges.
- private let schedulePageLeadingInset: CGFloat = 28
- private let schedulePageTrailingInset: CGFloat = 28
- private var schedulePageScrollObservation: NSObjectProtocol?
- private weak var schedulePageDateHeadingLabel: NSTextField?
- private weak var schedulePageFilterDropdown: NSPopUpButton?
- private weak var schedulePageFromDatePicker: NSDatePicker?
- private weak var schedulePageToDatePicker: NSDatePicker?
- private weak var schedulePageRangeErrorLabel: NSTextField?
- private weak var schedulePageCardsStack: NSStackView?
- private weak var schedulePageCardsScrollView: NSScrollView?
- private weak var settingsPagePrimaryLanguagePopup: NSPopUpButton?
- private weak var settingsPageSecondaryLanguagePopup: NSPopUpButton?
- // MARK: - Calendar page (custom month UI)
- private var calendarPageMonthAnchor: Date = Calendar.current.startOfDay(for: Date())
- private var calendarPageSelectedDate: Date = Calendar.current.startOfDay(for: Date())
- private weak var calendarPageMonthLabel: NSTextField?
- private weak var calendarPageGridStack: NSStackView?
- private var calendarPageGridHeightConstraint: NSLayoutConstraint?
- private weak var calendarPageDaySummaryLabel: NSTextField?
- private var calendarPageActionPopover: NSPopover?
- private var calendarPageCreatePopover: NSPopover?
- private weak var topToastView: NSVisualEffectView?
- private var topToastHideWorkItem: DispatchWorkItem?
- /// In-app browser navigation: `.allowAll` or `.whitelist(hostSuffixes:)` (e.g. `["google.com"]` matches `meet.google.com`).
- private let inAppBrowserDefaultPolicy: InAppBrowserURLPolicy = .allowAll
- private let darkModeDefaultsKey = "settings.darkModeEnabled"
- private let appUsageAccumulatedSecondsDefaultsKey = "rating.appUsageAccumulatedSeconds"
- private let userHasRatedDefaultsKey = "rating.userHasRated"
- private let ratingStateMigrationV2DoneDefaultsKey = "rating.stateMigrationV2Done"
- private let nonPremiumJoinTrialConsumedDefaultsKey = "join.nonPremiumTrialConsumed"
- private let aiCompanionLocalRecordingsDefaultsKey = "aiCompanion.localRecordings"
- private let aiCompanionPreferredLanguage1DefaultsKey = "aiCompanion.preferredLanguage1"
- private let aiCompanionPreferredLanguage2DefaultsKey = "aiCompanion.preferredLanguage2"
- private weak var activeMeetingConsentWindow: NSWindow?
- private weak var meetingConsentPrimaryLanguagePopup: NSPopUpButton?
- private weak var meetingConsentSecondaryLanguagePopup: NSPopUpButton?
- private var didTapInlineMeetingConsentClose = false
- private let ratingEligibleUsageSeconds: TimeInterval = 30 * 60
- private let meetingTranscriptionService = MeetingTranscriptionService()
- private let meetingNotesService = MeetingNotesService()
- private var aiCompanionTranscriptProgressByMeetingId: [String: String] = [:]
- private var aiCompanionNotesProgressByMeetingId: [String: String] = [:]
- private var darkModeEnabled: Bool {
- get {
- let hasValue = UserDefaults.standard.object(forKey: darkModeDefaultsKey) != nil
- return hasValue ? UserDefaults.standard.bool(forKey: darkModeDefaultsKey) : systemPrefersDarkMode()
- }
- set { UserDefaults.standard.set(newValue, forKey: darkModeDefaultsKey) }
- }
- private var nonPremiumJoinTrialConsumed: Bool {
- get { UserDefaults.standard.bool(forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
- set { UserDefaults.standard.set(newValue, forKey: nonPremiumJoinTrialConsumedDefaultsKey) }
- }
- private var shouldGateJoinActionsForNonPremium: Bool {
- !storeKitCoordinator.hasPremiumAccess && nonPremiumJoinTrialConsumed
- }
- private func makeSettingsPopover() -> NSPopover {
- let popover = NSPopover()
- popover.behavior = .transient
- popover.animates = true
- let showUpgradeInSettings = storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess
- let showRateUsInSettings = shouldShowRateUsInSettings
- let speechOptions = aiCompanionSupportedSpeechLocaleOptions()
- popover.contentViewController = SettingsMenuViewController(
- palette: palette,
- typography: typography,
- darkModeEnabled: darkModeEnabled,
- showRateUsInSettings: showRateUsInSettings,
- showUpgradeInSettings: showUpgradeInSettings,
- speechLocaleOptions: speechOptions,
- selectedPrimaryLanguageIdentifier: UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey),
- selectedSecondaryLanguageIdentifier: UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
- onToggleDarkMode: { [weak self] enabled in
- self?.setDarkMode(enabled)
- },
- onUpdatePreferredSpeechLanguages: { [weak self] primary, secondary in
- self?.updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
- },
- onAction: { [weak self] action, sourceView, clickPoint in
- self?.handleSettingsAction(action, sourceView: sourceView, clickLocationInSourceView: clickPoint)
- }
- )
- return popover
- }
- private var settingsPopover: NSPopover?
- override func viewDidLoad() {
- super.viewDidLoad()
- aiCompanionSpeechSynthesizer.delegate = self
- loadAiCompanionLocalRecordings()
- // Sync toggle + palette with current macOS appearance on launch.
- darkModeEnabled = systemPrefersDarkMode()
- palette = Palette(isDarkMode: darkModeEnabled)
- storeKitCoordinator.onEntitlementsChanged = { [weak self] hasPremiumAccess in
- guard let self else { return }
- self.handlePremiumAccessChanged(hasPremiumAccess)
- }
- NotificationCenter.default.post(
- name: .statusBarPremiumAccessChanged,
- object: nil,
- userInfo: ["hasPremiumAccess": storeKitCoordinator.hasPremiumAccess]
- )
- migrateLegacyRatingStateIfNeeded()
- beginUsageTrackingSessionIfNeeded()
- observeAppLifecycleForUsageTrackingIfNeeded()
- registerWidgetNotificationObservers()
- setupRootView()
- buildMainLayout()
- showLaunchSplashIfNeeded()
- startStoreKit()
- }
- override func viewDidAppear() {
- super.viewDidAppear()
- DesktopWidgetWindowManager.shared.restore()
- hasViewAppearedOnce = true
- presentLaunchPaywallIfNeeded()
- dismissLaunchSplashIfReady()
- applyWindowTitle(for: selectedSidebarPage)
- guard let window = view.window else { return }
- configureMainWindowChrome(window)
- // Ensure launch size is applied even when macOS tries to restore prior window state.
- window.isRestorable = false
- window.setFrameAutosaveName("")
- DispatchQueue.main.async { [weak self, weak window] in
- guard let self, let window else { return }
- let frameSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchContentSize)).size
- var newFrame = window.frame
- newFrame.size = frameSize
- window.setFrame(newFrame, display: true)
- window.center()
- if let screen = window.screen ?? NSScreen.main {
- var adjustedFrame = window.frame
- adjustedFrame.origin.x -= self.launchWindowLeftOffset
- let minX = screen.visibleFrame.minX
- adjustedFrame.origin.x = max(minX, adjustedFrame.origin.x)
- window.setFrame(adjustedFrame, display: true)
- }
- window.minSize = window.frameRect(forContentRect: NSRect(origin: .zero, size: self.launchMinContentSize)).size
- }
- }
- override var representedObject: Any? {
- didSet {}
- }
- deinit {
- premiumUpgradeRatingPromptWorkItem?.cancel()
- endUsageTrackingSession()
- launchSplashTimeoutWorkItem?.cancel()
- launchSplashMinimumDelayWorkItem?.cancel()
- NotificationCenter.default.removeObserver(self)
- if let observer = schedulePageScrollObservation {
- NotificationCenter.default.removeObserver(observer)
- }
- storeKitStartupTask?.cancel()
- paywallPurchaseTask?.cancel()
- launchPaywallWorkItem?.cancel()
- meetingRecordingMonitorTask?.cancel()
- }
- }
- private extension ViewController {
- func setupRootView() {
- view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
- view.wantsLayer = true
- view.layer?.backgroundColor = palette.pageBackground.cgColor
- }
- private func makeLaunchSplashTheme() -> LaunchSplashView.Theme {
- let borderAlpha: CGFloat = darkModeEnabled ? 0.9 : 0.45
- let cardBackground = darkModeEnabled ? palette.sectionCard : palette.tabBarBackground
- let cardBorder = darkModeEnabled ? palette.inputBorder : palette.separator
- return LaunchSplashView.Theme(
- background: palette.pageBackground,
- cardBackground: cardBackground,
- cardBorder: cardBorder.withAlphaComponent(borderAlpha),
- titleText: palette.textPrimary,
- subtitleText: palette.textSecondary,
- accent: palette.primaryBlue
- )
- }
- private func showLaunchSplashIfNeeded() {
- guard launchSplashView == nil else { return }
- let splash = LaunchSplashView(frame: .zero)
- splash.alphaValue = 1
- let displayName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String)?
- .trimmingCharacters(in: .whitespacesAndNewlines)
- let fallbackName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
- let resolvedName = (displayName?.isEmpty == false ? displayName : fallbackName) ?? "Assistant for Google Meet"
- splash.configure(appName: resolvedName, appIcon: NSApp.applicationIconImage, theme: makeLaunchSplashTheme())
- view.addSubview(splash)
- NSLayoutConstraint.activate([
- splash.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- splash.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- splash.topAnchor.constraint(equalTo: view.topAnchor),
- splash.bottomAnchor.constraint(equalTo: view.bottomAnchor)
- ])
- view.layoutSubtreeIfNeeded()
- launchSplashView = splash
- launchSplashShownAt = Date()
- launchSplashTimeoutWorkItem?.cancel()
- let timeoutWorkItem = DispatchWorkItem { [weak self] in
- self?.dismissLaunchSplash(force: true)
- }
- launchSplashTimeoutWorkItem = timeoutWorkItem
- DispatchQueue.main.asyncAfter(deadline: .now() + launchSplashTimeout, execute: timeoutWorkItem)
- }
- private func dismissLaunchSplashIfReady() {
- guard hasCompletedInitialStoreKitSync else { return }
- guard !hasDismissedLaunchSplash else { return }
- if let shownAt = launchSplashShownAt {
- let elapsed = Date().timeIntervalSince(shownAt)
- let remaining = launchSplashMinimumVisibleDuration - elapsed
- if remaining > 0 {
- launchSplashMinimumDelayWorkItem?.cancel()
- let minDelayWorkItem = DispatchWorkItem { [weak self] in
- self?.dismissLaunchSplash(force: false)
- }
- launchSplashMinimumDelayWorkItem = minDelayWorkItem
- DispatchQueue.main.asyncAfter(deadline: .now() + remaining, execute: minDelayWorkItem)
- return
- }
- }
- dismissLaunchSplash(force: false)
- }
- private func dismissLaunchSplash(force: Bool) {
- guard !hasDismissedLaunchSplash else { return }
- guard let splash = launchSplashView else { return }
- if !force && !hasCompletedInitialStoreKitSync { return }
- hasDismissedLaunchSplash = true
- launchSplashTimeoutWorkItem?.cancel()
- launchSplashTimeoutWorkItem = nil
- launchSplashMinimumDelayWorkItem?.cancel()
- launchSplashMinimumDelayWorkItem = nil
- let removeSplash: () -> Void = { [weak self] in
- splash.removeFromSuperview()
- self?.launchSplashView = nil
- self?.launchSplashShownAt = nil
- }
- let fadeOutAndRemove: () -> Void = {
- NSAnimationContext.runAnimationGroup({ context in
- context.duration = 0.24
- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- splash.animator().alphaValue = 0
- }, completionHandler: removeSplash)
- }
- if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
- splash.completeLoading(duration: 0) {
- removeSplash()
- }
- return
- }
- splash.completeLoading {
- fadeOutAndRemove()
- }
- }
- func systemPrefersDarkMode() -> Bool {
- // Use the system-wide appearance setting (not app/window effective appearance).
- // When the key is missing, macOS is in Light mode.
- let global = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)
- let style = global?["AppleInterfaceStyle"] as? String
- return style?.lowercased() == "dark"
- }
- func buildMainLayout() {
- let splitContainer = NSStackView()
- splitContainer.translatesAutoresizingMaskIntoConstraints = false
- splitContainer.orientation = .horizontal
- splitContainer.spacing = 14
- splitContainer.distribution = .fill
- splitContainer.alignment = .top
- view.addSubview(splitContainer)
- NSLayoutConstraint.activate([
- splitContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- splitContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- splitContainer.topAnchor.constraint(equalTo: view.topAnchor),
- splitContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor)
- ])
- let sidebar = makeSidebar()
- let mainPanel = makeMainPanel()
- sidebar.setContentHuggingPriority(.required, for: .horizontal)
- sidebar.setContentCompressionResistancePriority(.required, for: .horizontal)
- mainPanel.setContentHuggingPriority(.defaultLow, for: .horizontal)
- mainPanel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- splitContainer.addArrangedSubview(sidebar)
- splitContainer.addArrangedSubview(mainPanel)
- }
- @objc private func sidebarItemClicked(_ sender: NSClickGestureRecognizer) {
- guard let view = sender.view else { return }
- activateSidebarItem(view)
- }
- private func activateSidebarItem(_ view: NSView) {
- guard let page = sidebarPageByView[ObjectIdentifier(view)],
- page != selectedSidebarPage || page == .settings else { return }
- showSidebarPage(page)
- }
- @objc private func zoomJoinModeClicked(_ sender: NSClickGestureRecognizer) {
- guard let view = sender.view,
- let mode = zoomJoinModeByView[ObjectIdentifier(view)],
- mode != selectedZoomJoinMode else { return }
- selectedZoomJoinMode = mode
- updateZoomJoinModeAppearance()
- if selectedSidebarPage == .joinMeetings {
- pageCache[.joinMeetings] = nil
- showSidebarPage(.joinMeetings)
- }
- }
- @objc private func premiumButtonClicked(_ sender: NSClickGestureRecognizer) {
- if storeKitCoordinator.hasLifetimeAccess {
- openManageSubscriptions()
- } else if storeKitCoordinator.hasPremiumAccess {
- showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
- } else {
- showPaywall()
- }
- }
- @objc private func sidebarButtonClicked(_ sender: NSButton) {
- guard let page = SidebarPage(rawValue: sender.tag),
- page != selectedSidebarPage || page == .settings else { return }
- showSidebarPage(page)
- }
- private func registerWidgetNotificationObservers() {
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenJoinMeetingsPageRequested), name: .widgetOpenJoinMeetingsPage, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSchedulePageRequested), name: .widgetOpenSchedulePage, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenCalendarPageRequested), name: .widgetOpenCalendarPage, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenSettingsPageRequested), name: .widgetOpenSettingsPage, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetSignInRequested), name: .widgetSignInRequested, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetRefreshRequested), name: .widgetRefreshRequested, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetWebRequested), name: .widgetOpenMeetWebRequested, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(widgetOpenMeetingLinkRequested(_:)), name: .widgetOpenMeetingLinkRequested, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(statusBarOpenSidebarPageRequested(_:)), name: .statusBarOpenSidebarPage, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(statusBarSignOutRequested), name: .statusBarSignOutRequested, object: nil)
- }
- @objc private func widgetOpenJoinMeetingsPageRequested() { showSidebarPage(.joinMeetings) }
- @objc private func widgetOpenSchedulePageRequested() { showSidebarPage(.photo) }
- @objc private func widgetOpenCalendarPageRequested() { showSidebarPage(.video) }
- @objc private func widgetOpenSettingsPageRequested() { showSidebarPage(.settings) }
- @objc private func widgetSignInRequested() { scheduleConnectClicked() }
- @objc private func widgetRefreshRequested() { scheduleReloadClicked() }
- @objc private func widgetOpenMeetWebRequested() {
- guard let url = URL(string: "https://meet.google.com/") else { return }
- openInDefaultBrowser(url: url)
- }
- @objc private func widgetOpenMeetingLinkRequested(_ notification: Notification) {
- guard let link = notification.userInfo?["link"] as? String,
- let url = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)) else { return }
- openInDefaultBrowser(url: url)
- }
- @objc private func statusBarOpenSidebarPageRequested(_ notification: Notification) {
- guard let pageRaw = notification.userInfo?["page"] as? Int,
- let page = SidebarPage(rawValue: pageRaw) else { return }
- showSidebarPage(page)
- }
- @objc private func statusBarSignOutRequested() { performGoogleSignOut() }
- @objc private func joinMeetClicked(_ sender: Any?) {
- guard shouldGateJoinActionsForNonPremium == false else {
- showPaywall()
- return
- }
- let rawInput = meetLinkField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- guard let url = normalizedMeetJoinURL(from: rawInput) else {
- showSimpleAlert(
- title: "Invalid Meet link",
- 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)."
- )
- return
- }
- let shouldOpenMeeting = beginMeetingRecordingIfConsented(meetingTitle: "Quick Join Meeting", meetingURL: url)
- guard shouldOpenMeeting else { return }
- openInDefaultBrowser(url: url)
- consumeNonPremiumJoinTrialIfNeeded()
- }
- @objc private func joinWithLinkCardClicked(_ sender: NSClickGestureRecognizer) {
- meetLinkField?.window?.makeFirstResponder(meetLinkField)
- }
- @objc private func cancelMeetJoinClicked(_ sender: Any?) {
- meetLinkField?.stringValue = ""
- }
- @objc private func browseOpenAddressClicked(_ sender: Any?) {
- let raw = browseAddressField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- guard raw.isEmpty == false else {
- showSimpleAlert(title: "Browse", message: "Enter a web address (for example meet.google.com).")
- return
- }
- let normalized = normalizedURLString(from: raw)
- guard let url = URL(string: normalized), url.scheme == "http" || url.scheme == "https" else {
- showSimpleAlert(title: "Invalid address", message: "Enter a valid http or https URL.")
- return
- }
- openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
- }
- @objc private func browseQuickLinkMeetClicked(_ sender: Any?) {
- guard let url = URL(string: "https://meet.google.com/") else { return }
- openInDefaultBrowser(url: url)
- }
- @objc private func browseQuickLinkMeetHelpClicked(_ sender: Any?) {
- guard let url = URL(string: "https://support.google.com/meet") else { return }
- openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
- }
- @objc private func browseQuickLinkZoomHelpClicked(_ sender: Any?) {
- guard let url = URL(string: "https://support.zoom.us") else { return }
- openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
- }
- @objc private func instantMeetClicked(_ sender: NSClickGestureRecognizer) {
- guard shouldGateJoinActionsForNonPremium == false else {
- showPaywall()
- return
- }
- guard let url = URL(string: "https://meet.google.com/new") else { return }
- openInDefaultBrowser(url: url)
- consumeNonPremiumJoinTrialIfNeeded()
- }
- private func consumeNonPremiumJoinTrialIfNeeded() {
- guard !storeKitCoordinator.hasPremiumAccess,
- !nonPremiumJoinTrialConsumed else { return }
- nonPremiumJoinTrialConsumed = true
- refreshInstantMeetPremiumState()
- }
- private func normalizedURLString(from value: String) -> String {
- if value.lowercased().hasPrefix("http://") || value.lowercased().hasPrefix("https://") {
- return value
- }
- return "https://\(value)"
- }
- /// Typical Meet meeting code shape: three hyphen-separated groups (e.g. `nkd-grps-duv`).
- private func isValidMeetMeetingCode(_ code: String) -> Bool {
- let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)
- guard trimmed.isEmpty == false else { return false }
- let pattern = "^[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{3}$"
- return trimmed.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
- }
- /// Accepts `https://meet.google.com/...`, `meet.google.com/...`, or a bare code; returns canonical Meet URL or `nil`.
- private func normalizedMeetJoinURL(from rawInput: String) -> URL? {
- let trimmed = rawInput.trimmingCharacters(in: .whitespacesAndNewlines)
- guard trimmed.isEmpty == false else { return nil }
- let lower = trimmed.lowercased()
- if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
- guard let url = URL(string: trimmed),
- let host = url.host?.lowercased(),
- host == "meet.google.com" || host.hasSuffix(".meet.google.com") else {
- return nil
- }
- let path = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
- guard path.isEmpty == false else { return nil }
- let firstSegment = path.split(separator: "/").first.map(String.init) ?? path
- guard isValidMeetMeetingCode(firstSegment) else { return nil }
- return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
- }
- if lower.hasPrefix("meet.google.com/") {
- let afterHost = trimmed.dropFirst("meet.google.com/".count)
- let beforeQuery = String(afterHost).split(separator: "?").first.map(String.init) ?? String(afterHost)
- let firstSegment = beforeQuery.split(separator: "/").first.map(String.init) ?? beforeQuery
- guard isValidMeetMeetingCode(firstSegment) else { return nil }
- return URL(string: "https://meet.google.com/\(firstSegment.lowercased())")
- }
- if isValidMeetMeetingCode(trimmed) {
- return URL(string: "https://meet.google.com/\(trimmed.lowercased())")
- }
- return nil
- }
- private func openInAppBrowser(with url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
- let browserController: InAppBrowserWindowController
- if let existing = inAppBrowserWindowController {
- browserController = existing
- } else {
- browserController = InAppBrowserWindowController()
- inAppBrowserWindowController = browserController
- }
- browserController.load(url: url, policy: policy)
- browserController.applyDefaultFrameCenteredOnVisibleScreen()
- browserController.showWindow(nil)
- browserController.window?.makeKeyAndOrderFront(nil)
- browserController.window?.orderFrontRegardless()
- NSApp.activate(ignoringOtherApps: true)
- }
- private func openInDefaultBrowser(url: URL) {
- NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { [weak self] _, error in
- if let error {
- DispatchQueue.main.async {
- self?.showSimpleAlert(title: "Unable to open browser", message: error.localizedDescription)
- }
- }
- }
- }
- private func openURLWithRouting(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
- let scheme = (url.scheme ?? "").lowercased()
- if scheme == "http" || scheme == "https" {
- showEmbeddedWebPage(url, policy: policy)
- return
- }
- openInDefaultBrowser(url: url)
- }
- private func embeddedBrowserController() -> InAppBrowserContainerViewController {
- if let existing = embeddedBrowserViewController {
- return existing
- }
- let controller = InAppBrowserContainerViewController()
- embeddedBrowserViewController = controller
- return controller
- }
- private func detachEmbeddedBrowserIfNeeded() {
- guard let controller = embeddedBrowserViewController, controller.parent === self else { return }
- controller.view.removeFromSuperview()
- controller.removeFromParent()
- }
- private func mountMainContentView(_ child: NSView) {
- guard let host = mainContentHost else { return }
- NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
- mainContentHostPinConstraints.removeAll()
- host.subviews.forEach { $0.removeFromSuperview() }
- child.translatesAutoresizingMaskIntoConstraints = false
- host.addSubview(child)
- mainContentHostPinConstraints = [
- child.leadingAnchor.constraint(equalTo: host.leadingAnchor),
- child.trailingAnchor.constraint(equalTo: host.trailingAnchor),
- child.topAnchor.constraint(equalTo: host.topAnchor),
- child.bottomAnchor.constraint(equalTo: host.bottomAnchor)
- ]
- NSLayoutConstraint.activate(mainContentHostPinConstraints)
- }
- private func showEmbeddedWebPage(_ url: URL, policy: InAppBrowserURLPolicy = .allowAll) {
- embeddedBrowserURL = url
- embeddedBrowserPolicy = policy
- let controller = embeddedBrowserController()
- _ = controller.view
- if controller.parent !== self {
- addChild(controller)
- }
- controller.setNavigationPolicy(policy)
- controller.load(url: url)
- setEmbeddedBrowserLayoutMode(isEmbedded: true)
- applyEmbeddedBrowserWindowTitle(url: url)
- mountMainContentView(controller.view)
- }
- private func setEmbeddedBrowserLayoutMode(isEmbedded: Bool) {
- mainPanelAuthBar?.isHidden = isEmbedded
- mainContentHostTopToAuthConstraint?.isActive = !isEmbedded
- mainContentHostTopToPanelConstraint?.isActive = isEmbedded
- }
- private func applyEmbeddedBrowserWindowTitle(url: URL) {
- if let host = url.host, host.isEmpty == false {
- view.window?.title = host
- } else {
- view.window?.title = "Browser"
- }
- }
- private func openRateUsDestination() {
- let configured = (Bundle.main.object(forInfoDictionaryKey: "RateUsURL") as? String)?
- .trimmingCharacters(in: .whitespacesAndNewlines)
- let placeholder = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String)?
- .trimmingCharacters(in: .whitespacesAndNewlines)
- let hardcodedRateUsURL = "https://apps.apple.com/pk/app/meeting-app-for-google-meet/id6654920763?mt=12"
- var candidateStrings = [String]()
- if let configured, !configured.isEmpty {
- candidateStrings.append(configured)
- if let appID = extractAppleAppID(from: configured) {
- candidateStrings.append("macappstore://apps.apple.com/app/id\(appID)")
- candidateStrings.append("macappstore://itunes.apple.com/app/id\(appID)")
- }
- }
- candidateStrings.append(hardcodedRateUsURL)
- candidateStrings.append("macappstore://apps.apple.com/app/id6654920763")
- candidateStrings.append("macappstore://itunes.apple.com/app/id6654920763")
- if let placeholder, !placeholder.isEmpty {
- candidateStrings.append(placeholder)
- }
- for candidate in candidateStrings {
- guard let url = URL(string: candidate) else { continue }
- if NSWorkspace.shared.open(url) {
- return
- }
- }
- showSimpleAlert(
- title: "Unable to Open Rate Page",
- message: "Could not open the App Store rating page. Please try again."
- )
- requestAppRatingIfEligible(markAsRated: true)
- }
- private func extractAppleAppID(from urlString: String) -> String? {
- guard let match = urlString.range(of: "id[0-9]+", options: .regularExpression) else {
- return nil
- }
- let token = String(urlString[match])
- return String(token.dropFirst())
- }
- private func openInSafari(url: URL) {
- guard let safariAppURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Safari") else {
- NSWorkspace.shared.open(url)
- return
- }
- let configuration = NSWorkspace.OpenConfiguration()
- NSWorkspace.shared.open([url], withApplicationAt: safariAppURL, configuration: configuration) { _, error in
- if let error {
- self.showSimpleAlert(title: "Unable to Open Safari", message: error.localizedDescription)
- }
- }
- }
- private func openManageSubscriptions() {
- if let appStoreURL = URL(string: "macappstore://apps.apple.com/account/subscriptions"),
- NSWorkspace.shared.open(appStoreURL) {
- return
- }
- guard let url = URL(string: "https://apps.apple.com/account/subscriptions") else {
- showSimpleAlert(title: "Unable to Open Subscriptions", message: "The subscriptions URL is invalid.")
- return
- }
- openInDefaultBrowser(url: url)
- }
- private func openRestoreSubscriptionPage() {
- let fallbackURL = "https://support.apple.com/en-us/108096"
- let restoreURL = (Bundle.main.object(forInfoDictionaryKey: "RestoreSubscriptionURL") as? String) ?? fallbackURL
- guard let url = URL(string: restoreURL) else {
- if let fallback = URL(string: fallbackURL) {
- NSWorkspace.shared.open(fallback)
- }
- return
- }
- NSWorkspace.shared.open(url)
- }
- private func performRestorePurchases() {
- Task { [weak self] in
- guard let self else { return }
- let message = await self.storeKitCoordinator.restorePurchases()
- self.refreshPaywallStoreUI()
- self.showSimpleAlert(title: "Restore Purchases", message: message)
- }
- }
- private func shareAppURL() -> URL? {
- if let configured = Bundle.main.object(forInfoDictionaryKey: "AppShareURL") as? String {
- let trimmed = configured.trimmingCharacters(in: .whitespacesAndNewlines)
- if trimmed.isEmpty == false, let url = URL(string: trimmed) {
- return url
- }
- }
- return nil
- }
- private func shareAppFromSettingsMenu(sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
- let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
- ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
- ?? "Meetings App"
- let message = "Check out \(appName) for managing and joining meetings."
- let appURL = shareAppURL()
- let shareItems: [Any] = appURL.map { [message, $0] } ?? [message]
- let picker = NSSharingServicePicker(items: shareItems)
- let anchorView = sourceView ?? sidebarRowViews[.settings] ?? view
- let anchorPoint = clickLocationInSourceView
- ?? NSPoint(x: anchorView.bounds.midX, y: anchorView.bounds.midY)
- let anchorRect = NSRect(x: anchorPoint.x, y: anchorPoint.y, width: 1, height: 1)
- picker.show(relativeTo: anchorRect, of: anchorView, preferredEdge: .minY)
- let clipboardText = ([message, appURL?.absoluteString].compactMap { $0 }).joined(separator: "\n")
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(clipboardText, forType: .string)
- }
- private func showSidebarPage(_ page: SidebarPage) {
- selectedSidebarPage = page
- updateSidebarAppearance()
- applyWindowTitle(for: page)
- setEmbeddedBrowserLayoutMode(isEmbedded: false)
- detachEmbeddedBrowserIfNeeded()
- let child = viewForPage(page)
- mountMainContentView(child)
- }
- private func showSettingsPopover() {
- guard let anchor = sidebarRowViews[.settings] else { return }
- if settingsPopover?.isShown == true {
- settingsPopover?.performClose(nil)
- return
- }
- settingsPopover = makeSettingsPopover()
- if let menu = settingsPopover?.contentViewController as? SettingsMenuViewController {
- menu.setDarkModeEnabled(darkModeEnabled)
- }
- settingsPopover?.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxX)
- }
- private func setDarkMode(_ enabled: Bool) {
- darkModeEnabled = enabled
- NSApp.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
- view.appearance = NSAppearance(named: enabled ? .darkAqua : .aqua)
- palette = Palette(isDarkMode: enabled)
- launchSplashView?.apply(theme: makeLaunchSplashTheme())
- reloadTheme()
- }
- private func reloadTheme() {
- pageCache.removeAll()
- if let observer = schedulePageScrollObservation {
- NotificationCenter.default.removeObserver(observer)
- }
- schedulePageScrollObservation = nil
- sidebarRowViews.removeAll()
- sidebarPageByView.removeAll()
- zoomJoinModeByView.removeAll()
- zoomJoinModeViews.removeAll()
- settingsActionByView.removeAll()
- paywallPlanViews.removeAll()
- premiumPlanByView.removeAll()
- paywallFooterActionByView.removeAll()
- paywallPriceLabels.removeAll()
- paywallSubtitleLabels.removeAll()
- paywallContinueLabel = nil
- paywallContinueButton = nil
- paywallContinueEnabled = true
- detachEmbeddedBrowserIfNeeded()
- embeddedBrowserViewController = nil
- embeddedBrowserURL = nil
- embeddedBrowserPolicy = .allowAll
- mainPanelAuthBar = nil
- mainContentHostTopToAuthConstraint = nil
- mainContentHostTopToPanelConstraint = nil
- googleAccountPopover?.performClose(nil)
- googleAccountPopover = nil
- NSLayoutConstraint.deactivate(mainContentHostPinConstraints)
- mainContentHostPinConstraints.removeAll()
- mainContentHost = nil
- view.subviews.forEach { $0.removeFromSuperview() }
- setupRootView()
- buildMainLayout()
- showSidebarPage(selectedSidebarPage)
- }
- private func handleSettingsAction(_ action: SettingsAction, sourceView: NSView? = nil, clickLocationInSourceView: NSPoint? = nil) {
- switch action {
- case .restore:
- performRestorePurchases()
- case .rateUs:
- openRateUsDestination()
- case .support:
- openSettingsLink(infoKey: "SupportURL")
- case .privacyPolicy:
- openSettingsLink(infoKey: "PrivacyPolicyURL")
- case .termsOfServices:
- openSettingsLink(infoKey: "TermsOfServiceURL")
- case .moreApps:
- if let moreAppsURL = Bundle.main.object(forInfoDictionaryKey: "MoreAppsURL") as? String,
- let url = URL(string: moreAppsURL) {
- openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
- }
- case .shareApp:
- shareAppFromSettingsMenu(sourceView: sourceView, clickLocationInSourceView: clickLocationInSourceView)
- case .upgrade:
- showPaywall(upgradeFlow: true, preferredPlan: .lifetime)
- }
- }
- private func openSettingsLink(infoKey: String) {
- let defaultURL = (Bundle.main.object(forInfoDictionaryKey: "AppLaunchPlaceholderURL") as? String) ?? "https://example.com/app-link-coming-soon"
- let urlString = (Bundle.main.object(forInfoDictionaryKey: infoKey) as? String) ?? defaultURL
- guard let url = URL(string: urlString) else { return }
- openURLWithRouting(url, policy: inAppBrowserDefaultPolicy)
- }
- private func showSimpleAlert(title: String, message: String) {
- let alert = NSAlert()
- alert.messageText = title
- alert.informativeText = message
- alert.addButton(withTitle: "OK")
- alert.runModal()
- }
- private enum MeetingRecordingConsentChoice {
- case allowAndContinue
- case continueWithoutRecording
- case dismissed
- }
- private func requestMeetingRecordingConsent(title: String) -> MeetingRecordingConsentChoice {
- let alert = NSAlert()
- alert.messageText = "Record this meeting locally?"
- alert.informativeText = "With your consent, the app will record meeting audio on this Mac and show it in AI Companion after the meeting."
- alert.addButton(withTitle: "Allow and Continue")
- alert.addButton(withTitle: "Continue Without Recording")
- alert.window.title = title
- let speechOptions = aiCompanionSupportedSpeechLocaleOptions()
- let languageContainer = NSView(frame: NSRect(x: 0, y: 0, width: 320, height: 96))
- languageContainer.translatesAutoresizingMaskIntoConstraints = false
- languageContainer.widthAnchor.constraint(equalToConstant: 320).isActive = true
- languageContainer.heightAnchor.constraint(equalToConstant: 96).isActive = true
- let languageTitle = NSTextField(labelWithString: "Transcription Languages")
- languageTitle.translatesAutoresizingMaskIntoConstraints = false
- languageTitle.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
- languageTitle.textColor = NSColor.secondaryLabelColor
- let language1Popup = NSPopUpButton(frame: .zero, pullsDown: false)
- language1Popup.translatesAutoresizingMaskIntoConstraints = false
- language1Popup.controlSize = .small
- language1Popup.target = self
- language1Popup.action = #selector(meetingConsentSpeechLanguageChanged(_:))
- for option in speechOptions {
- language1Popup.addItem(withTitle: option.displayName)
- language1Popup.lastItem?.representedObject = option.identifier
- }
- let selectedPrimary = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey)
- ?? speechOptions.first?.identifier
- ?? Locale.current.identifier
- selectSettingsPageLanguage(identifier: selectedPrimary, in: language1Popup)
- let language2Popup = NSPopUpButton(frame: .zero, pullsDown: false)
- language2Popup.translatesAutoresizingMaskIntoConstraints = false
- language2Popup.controlSize = .small
- language2Popup.target = self
- language2Popup.action = #selector(meetingConsentSpeechLanguageChanged(_:))
- language2Popup.addItem(withTitle: "None")
- language2Popup.lastItem?.representedObject = ""
- for option in speechOptions {
- language2Popup.addItem(withTitle: option.displayName)
- language2Popup.lastItem?.representedObject = option.identifier
- }
- if let selectedSecondary = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
- selectedSecondary.isEmpty == false {
- selectSettingsPageLanguage(identifier: selectedSecondary, in: language2Popup)
- } else {
- language2Popup.selectItem(at: 0)
- }
- let language1Label = NSTextField(labelWithString: "Preferred Language 1")
- language1Label.translatesAutoresizingMaskIntoConstraints = false
- language1Label.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
- language1Label.textColor = NSColor.secondaryLabelColor
- language1Label.alignment = .center
- let language2Label = NSTextField(labelWithString: "Preferred Language 2")
- language2Label.translatesAutoresizingMaskIntoConstraints = false
- language2Label.font = NSFont.systemFont(ofSize: 11, weight: .semibold)
- language2Label.textColor = NSColor.secondaryLabelColor
- language2Label.alignment = .center
- languageContainer.addSubview(languageTitle)
- languageContainer.addSubview(language1Label)
- languageContainer.addSubview(language1Popup)
- languageContainer.addSubview(language2Label)
- languageContainer.addSubview(language2Popup)
- NSLayoutConstraint.activate([
- languageTitle.topAnchor.constraint(equalTo: languageContainer.topAnchor, constant: 0),
- languageTitle.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
- language1Label.topAnchor.constraint(equalTo: languageTitle.bottomAnchor, constant: 2),
- language1Label.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
- language1Popup.topAnchor.constraint(equalTo: language1Label.bottomAnchor, constant: 2),
- language1Popup.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
- language1Popup.widthAnchor.constraint(equalToConstant: 240),
- language2Label.topAnchor.constraint(equalTo: language1Popup.bottomAnchor, constant: 3),
- language2Label.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
- language2Popup.topAnchor.constraint(equalTo: language2Label.bottomAnchor, constant: 2),
- language2Popup.centerXAnchor.constraint(equalTo: languageContainer.centerXAnchor),
- language2Popup.widthAnchor.constraint(equalToConstant: 240),
- language2Popup.bottomAnchor.constraint(equalTo: languageContainer.bottomAnchor, constant: -1)
- ])
- alert.accessoryView = languageContainer
- didTapInlineMeetingConsentClose = false
- activeMeetingConsentWindow = alert.window
- meetingConsentPrimaryLanguagePopup = language1Popup
- meetingConsentSecondaryLanguagePopup = language2Popup
- if let contentView = alert.window.contentView {
- let topCloseButton = NSButton(title: "✕", target: self, action: #selector(meetingConsentInlineCloseTapped(_:)))
- topCloseButton.translatesAutoresizingMaskIntoConstraints = false
- topCloseButton.isBordered = false
- topCloseButton.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
- topCloseButton.contentTintColor = NSColor.tertiaryLabelColor
- topCloseButton.wantsLayer = true
- topCloseButton.layer?.cornerRadius = 20
- topCloseButton.layer?.backgroundColor = NSColor.windowBackgroundColor.withAlphaComponent(0.35).cgColor
- contentView.addSubview(topCloseButton)
- NSLayoutConstraint.activate([
- topCloseButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
- topCloseButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
- topCloseButton.widthAnchor.constraint(equalToConstant: 40),
- topCloseButton.heightAnchor.constraint(equalToConstant: 40)
- ])
- }
- let response = alert.runModal()
- activeMeetingConsentWindow = nil
- meetingConsentPrimaryLanguagePopup = nil
- meetingConsentSecondaryLanguagePopup = nil
- if didTapInlineMeetingConsentClose {
- return .dismissed
- }
- if let primary = language1Popup.selectedItem?.representedObject as? String,
- primary.isEmpty == false {
- var secondary = language2Popup.selectedItem?.representedObject as? String
- if secondary?.isEmpty == true {
- secondary = nil
- }
- updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
- }
- switch response {
- case .alertFirstButtonReturn:
- return .allowAndContinue
- case .alertSecondButtonReturn:
- return .continueWithoutRecording
- default:
- return .dismissed
- }
- }
- @objc private func meetingConsentInlineCloseTapped(_ sender: NSButton) {
- didTapInlineMeetingConsentClose = true
- guard let consentWindow = activeMeetingConsentWindow else { return }
- NSApp.stopModal(withCode: .abort)
- consentWindow.orderOut(nil)
- }
- @objc private func meetingConsentSpeechLanguageChanged(_ sender: NSPopUpButton) {
- guard let primary = meetingConsentPrimaryLanguagePopup?.selectedItem?.representedObject as? String,
- primary.isEmpty == false else { return }
- var secondary: String? = meetingConsentSecondaryLanguagePopup?.selectedItem?.representedObject as? String
- if secondary?.isEmpty == true {
- secondary = nil
- }
- if let secondaryValue = secondary,
- secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
- secondary = nil
- meetingConsentSecondaryLanguagePopup?.selectItem(at: 0)
- }
- updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
- }
- private func loadAiCompanionLocalRecordings() {
- guard let raw = UserDefaults.standard.data(forKey: aiCompanionLocalRecordingsDefaultsKey) else {
- aiCompanionLocalRecordings = []
- return
- }
- let decoder = JSONDecoder()
- if let decoded = try? decoder.decode([MeetingRecordingSummary].self, from: raw) {
- aiCompanionLocalRecordings = decoded.sorted(by: { $0.endedAt > $1.endedAt })
- } else {
- aiCompanionLocalRecordings = []
- }
- }
- private func persistAiCompanionLocalRecordings() {
- let encoder = JSONEncoder()
- guard let encoded = try? encoder.encode(aiCompanionLocalRecordings) else { return }
- UserDefaults.standard.set(encoded, forKey: aiCompanionLocalRecordingsDefaultsKey)
- }
- private func requestSpeechRecognitionAuthorizationIfNeeded() async throws {
- switch SFSpeechRecognizer.authorizationStatus() {
- case .authorized:
- return
- case .notDetermined:
- let status = await withCheckedContinuation { continuation in
- SFSpeechRecognizer.requestAuthorization { status in
- continuation.resume(returning: status)
- }
- }
- guard status == .authorized else {
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 15,
- userInfo: [NSLocalizedDescriptionKey: "Speech recognition permission denied. Enable it in System Settings and try again."]
- )
- }
- case .denied:
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 15,
- userInfo: [NSLocalizedDescriptionKey: "Speech recognition permission denied. Enable it in System Settings and try again."]
- )
- case .restricted:
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 16,
- userInfo: [NSLocalizedDescriptionKey: "Speech recognition is restricted on this Mac."]
- )
- @unknown default:
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 17,
- userInfo: [NSLocalizedDescriptionKey: "Speech recognition authorization is unavailable."]
- )
- }
- }
- private func transcribeLocalAudioWithAppleSpeech(audioURL: URL) async throws -> String {
- try await requestSpeechRecognitionAuthorizationIfNeeded()
- guard let recognizer = SFSpeechRecognizer(locale: Locale.current) ?? SFSpeechRecognizer(locale: Locale(identifier: "en-US")) else {
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 18,
- userInfo: [NSLocalizedDescriptionKey: "Speech recognizer is unavailable for the current locale."]
- )
- }
- let request = SFSpeechURLRecognitionRequest(url: audioURL)
- request.shouldReportPartialResults = false
- if #available(macOS 13.0, *) {
- request.addsPunctuation = true
- }
- return try await withCheckedThrowingContinuation { continuation in
- var hasResumed = false
- var task: SFSpeechRecognitionTask?
- task = recognizer.recognitionTask(with: request) { result, error in
- if hasResumed { return }
- if let error {
- hasResumed = true
- task?.cancel()
- continuation.resume(throwing: error)
- return
- }
- guard let result else { return }
- if result.isFinal {
- hasResumed = true
- task?.finish()
- continuation.resume(returning: result.bestTranscription.formattedString)
- }
- }
- }
- }
- private func aiCompanionTranscriptStatus(for recording: MeetingRecordingSummary) -> MeetingTranscriptStatus {
- guard let raw = recording.transcriptStatusRaw, let status = MeetingTranscriptStatus(rawValue: raw) else {
- return .notRequested
- }
- return status
- }
- private func aiCompanionTranscriptStatusText(for recording: MeetingRecordingSummary) -> String {
- switch aiCompanionTranscriptStatus(for: recording) {
- case .notRequested:
- return "Transcript not requested"
- case .processing:
- if let progress = aiCompanionTranscriptProgressByMeetingId[recording.id], progress.isEmpty == false {
- return progress
- }
- return "Transcript processing..."
- case .ready:
- return "Transcript ready"
- case .failed:
- let error = recording.transcriptErrorMessage?.trimmingCharacters(in: .whitespacesAndNewlines)
- if let error, error.isEmpty == false {
- return "Transcript unavailable (tap to retry)"
- }
- return "Transcript unavailable (tap to retry)"
- }
- }
- private func aiCompanionNotesStatus(for recording: MeetingRecordingSummary) -> MeetingNotesStatus {
- guard let raw = recording.notesStatusRaw, let status = MeetingNotesStatus(rawValue: raw) else {
- return .notRequested
- }
- return status
- }
- private func aiCompanionNotesStatusText(for recording: MeetingRecordingSummary) -> String {
- switch aiCompanionNotesStatus(for: recording) {
- case .notRequested:
- return "Notes not requested"
- case .processing:
- if let progress = aiCompanionNotesProgressByMeetingId[recording.id], progress.isEmpty == false {
- return progress
- }
- return "Notes processing..."
- case .ready:
- return "Notes ready"
- case .failed:
- return "Notes unavailable (tap to retry)"
- }
- }
- private func aiCompanionMeetingFromRecording(_ recording: MeetingRecordingSummary) -> ScheduledMeeting? {
- guard let meetURL = URL(string: recording.meetURLString) else { return nil }
- return ScheduledMeeting(
- id: recording.id,
- title: recording.title,
- subtitle: nil,
- startDate: recording.startedAt,
- endDate: recording.endedAt,
- meetURL: meetURL,
- isAllDay: false
- )
- }
- @discardableResult
- private func aiCompanionUpdateRecording(meetingId: String, mutate: (inout MeetingRecordingSummary) -> Void) -> MeetingRecordingSummary? {
- guard let idx = aiCompanionLocalRecordings.firstIndex(where: { $0.id == meetingId }) else { return nil }
- mutate(&aiCompanionLocalRecordings[idx])
- persistAiCompanionLocalRecordings()
- return aiCompanionLocalRecordings[idx]
- }
- private func aiCompanionRefreshTranscriptStatusLabels(forMeetingID meetingId: String) {
- guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else { return }
- let statusText = aiCompanionTranscriptStatusText(for: recording)
- for (buttonId, linkedMeetingId) in aiCompanionTranscriptMeetingIdByView where linkedMeetingId == meetingId {
- aiCompanionTranscriptStatusLabelByView[buttonId]?.stringValue = statusText
- }
- }
- private func aiCompanionRefreshNotesStatusLabels(forMeetingID meetingId: String) {
- guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else { return }
- let statusText = aiCompanionNotesStatusText(for: recording)
- for (buttonId, linkedMeetingId) in aiCompanionNotesMeetingIdByView where linkedMeetingId == meetingId {
- aiCompanionNotesStatusLabelByView[buttonId]?.stringValue = statusText
- }
- }
- private func localRecordingDirectoryURL() -> URL {
- let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
- ?? URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
- let bundleID = Bundle.main.bundleIdentifier ?? "meetings_app"
- let directory = base.appendingPathComponent(bundleID, isDirectory: true).appendingPathComponent("MeetingRecordings", isDirectory: true)
- try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
- return directory
- }
- private func beginMeetingRecordingIfConsented(meetingTitle: String, meetingURL: URL) -> Bool {
- let consentChoice = requestMeetingRecordingConsent(title: meetingTitle)
- if consentChoice == .dismissed {
- return false
- }
- meetingRecordingMonitorTask?.cancel()
- meetingRecordingMonitorTask = nil
- if activeMeetingRecordingSession != nil { finishActiveMeetingRecording(cancelMonitoring: false) }
- guard consentChoice == .allowAndContinue else { return true }
- let permission = AVCaptureDevice.authorizationStatus(for: .audio)
- switch permission {
- case .authorized:
- startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
- case .notDetermined:
- AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted in
- DispatchQueue.main.async {
- guard let self else { return }
- if granted {
- self.startAutomaticRecordingFlow(meetingTitle: meetingTitle, meetingURL: meetingURL)
- } else {
- self.showSimpleAlert(title: "Microphone permission denied", message: "Enable microphone access in System Settings to record meetings locally.")
- }
- }
- }
- case .denied, .restricted:
- showSimpleAlert(title: "Microphone permission required", message: "Enable microphone access in System Settings to record meetings locally.")
- @unknown default:
- break
- }
- return true
- }
- private func startAutomaticRecordingFlow(meetingTitle: String, meetingURL: URL) {
- guard let meetingCode = aiCompanionMeetMeetingCode(from: meetingURL), hasGoogleSessionAvailable() else {
- startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
- return
- }
- showTopToast(message: "Recording will start when the meeting starts", isError: false)
- meetingRecordingMonitorTask = Task { [weak self] in
- guard let self else { return }
- defer { self.meetingRecordingMonitorTask = nil }
- do {
- let space = try await self.googleMeetClient.getSpace(
- accessToken: try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window),
- spaceNameOrMeetingCode: "spaces/\(meetingCode)"
- )
- let spaceName = space.name ?? "spaces/\(meetingCode)"
- var hasStarted = false
- var inactivePollCount = 0
- let noStartDeadline = Date().addingTimeInterval(20 * 60)
- while !Task.isCancelled {
- let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
- let isActive = try await self.aiCompanionIsMeetingActive(spaceResourceName: spaceName, accessToken: token)
- if isActive {
- inactivePollCount = 0
- if !hasStarted {
- self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
- hasStarted = true
- }
- } else if hasStarted {
- inactivePollCount += 1
- if inactivePollCount >= 1 {
- self.finishActiveMeetingRecording(cancelMonitoring: false)
- break
- }
- } else if Date() > noStartDeadline {
- break
- }
- try await Task.sleep(nanoseconds: 2_000_000_000)
- }
- } catch {
- if self.activeMeetingRecordingSession == nil {
- self.startMeetingRecording(meetingTitle: meetingTitle, meetingURL: meetingURL)
- }
- }
- }
- }
- private func aiCompanionIsMeetingActive(spaceResourceName: String, accessToken: String) async throws -> Bool {
- let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceResourceName)
- return records.contains { $0.startTime != nil && $0.endTime == nil }
- }
- private func startMeetingRecording(meetingTitle: String, meetingURL: URL) {
- let recordingID = UUID().uuidString
- let outputURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-system.m4a")
- let microphoneURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID)-mic.m4a")
- activeMeetingRecordingSession = ActiveMeetingRecordingSession(
- id: recordingID,
- title: meetingTitle,
- meetURL: meetingURL,
- startedAt: Date(),
- systemAudioFileURL: outputURL,
- microphoneAudioFileURL: microphoneURL
- )
- pageCache[.aiCompanion] = nil
- if selectedSidebarPage == .aiCompanion { showSidebarPage(.aiCompanion) }
- startMicrophoneRecording(at: microphoneURL, showToast: false)
- if #available(macOS 13.0, *) {
- let systemRecorder = MeetingSystemAudioRecorder(outputURL: outputURL)
- activeMeetingSystemAudioStopper = { [systemRecorder] in
- try? await systemRecorder.stop()
- }
- Task { [weak self] in
- guard let self else { return }
- do {
- try await systemRecorder.start()
- await MainActor.run {
- self.showTopToast(message: "Meeting recording started (meeting + microphone)", isError: false)
- }
- } catch {
- await MainActor.run {
- self.activeMeetingSystemAudioStopper = nil
- self.showTopToast(message: "System audio unavailable. Recording microphone only.", isError: true)
- }
- }
- }
- return
- }
- showTopToast(message: "Meeting recording started (microphone only)", isError: false)
- }
- private func startMicrophoneRecording(at outputURL: URL, showToast: Bool) {
- let settings: [String: Any] = [
- AVFormatIDKey: kAudioFormatMPEG4AAC,
- AVSampleRateKey: 48_000,
- AVNumberOfChannelsKey: 1,
- AVEncoderBitRateKey: 128_000,
- AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
- ]
- do {
- let recorder = try AVAudioRecorder(url: outputURL, settings: settings)
- recorder.prepareToRecord()
- recorder.record()
- activeMeetingAudioRecorder = recorder
- if showToast {
- showTopToast(message: "Meeting recording started (microphone only)", isError: false)
- }
- } catch {
- activeMeetingRecordingSession = nil
- showSimpleAlert(title: "Could not start recording", message: error.localizedDescription)
- }
- }
- private func finishActiveMeetingRecording(cancelMonitoring: Bool = true) {
- if cancelMonitoring {
- meetingRecordingMonitorTask?.cancel()
- meetingRecordingMonitorTask = nil
- }
- guard let session = activeMeetingRecordingSession else { return }
- let stopSystemAudio = activeMeetingSystemAudioStopper
- activeMeetingSystemAudioStopper = nil
- activeMeetingAudioRecorder?.stop()
- activeMeetingAudioRecorder = nil
- activeMeetingRecordingSession = nil
- Task { [weak self] in
- guard let self else { return }
- if let stopSystemAudio { await stopSystemAudio() }
- let finalized = await self.finalizeMeetingAudioFile(
- systemURL: session.systemAudioFileURL,
- microphoneURL: session.microphoneAudioFileURL,
- recordingID: session.id
- )
- await MainActor.run {
- let summary = MeetingRecordingSummary(
- id: session.id,
- title: session.title,
- meetURLString: session.meetURL.absoluteString,
- startedAt: session.startedAt,
- endedAt: Date(),
- audioFilePath: finalized.mixedURL.path,
- microphoneAudioFilePath: finalized.microphoneURL?.path,
- systemAudioFilePath: finalized.systemURL?.path,
- transcriptStatusRaw: MeetingTranscriptStatus.notRequested.rawValue,
- transcriptSourceRaw: nil,
- transcriptText: nil,
- transcriptSegmentsJSON: nil,
- transcriptErrorMessage: nil,
- notesStatusRaw: MeetingNotesStatus.notRequested.rawValue,
- notesText: nil,
- notesErrorMessage: nil
- )
- self.aiCompanionLocalRecordings.insert(summary, at: 0)
- self.aiCompanionLocalRecordings.sort(by: { $0.endedAt > $1.endedAt })
- self.persistAiCompanionLocalRecordings()
- self.aiCompanionStartTranscriptProcessing(forMeetingID: summary.id, requestId: nil, interactiveAuth: false, forceRegenerate: false)
- self.pageCache[.aiCompanion] = nil
- self.showTopToast(message: "Meeting recording saved", isError: false)
- if self.selectedSidebarPage == .aiCompanion {
- self.showSidebarPage(.aiCompanion)
- }
- }
- }
- }
- private func fileSize(at url: URL) -> Int64 {
- let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)
- return attrs?[.size] as? Int64 ?? 0
- }
- private func hasAudioPayload(at url: URL, minBytes: Int64 = 10_000) -> Bool {
- guard FileManager.default.fileExists(atPath: url.path) else { return false }
- return fileSize(at: url) >= minBytes
- }
- private struct FinalizedMeetingAudio {
- let mixedURL: URL
- let microphoneURL: URL?
- let systemURL: URL?
- }
- private func finalizeMeetingAudioFile(systemURL: URL, microphoneURL: URL, recordingID: String) async -> FinalizedMeetingAudio {
- let destinationURL = localRecordingDirectoryURL().appendingPathComponent("\(recordingID).m4a")
- let hasSystem = hasAudioPayload(at: systemURL)
- let hasMic = hasAudioPayload(at: microphoneURL)
- if !hasSystem { try? FileManager.default.removeItem(at: systemURL) }
- if !hasMic { try? FileManager.default.removeItem(at: microphoneURL) }
- let savedMicURL: URL? = hasMic ? microphoneURL : nil
- let savedSystemURL: URL? = hasSystem ? systemURL : nil
- if hasSystem && hasMic {
- do {
- try await mixAudioFiles(systemURL: systemURL, microphoneURL: microphoneURL, destinationURL: destinationURL)
- return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
- } catch {
- // Fall back to best available single track for playback; per-channel files stay intact.
- }
- }
- let chosenURL: URL?
- if hasSystem {
- chosenURL = systemURL
- } else if hasMic {
- chosenURL = microphoneURL
- } else {
- chosenURL = nil
- }
- if let chosenURL {
- if chosenURL.path != destinationURL.path {
- try? FileManager.default.removeItem(at: destinationURL)
- do {
- try FileManager.default.copyItem(at: chosenURL, to: destinationURL)
- } catch {
- return FinalizedMeetingAudio(mixedURL: chosenURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
- }
- }
- return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: savedMicURL, systemURL: savedSystemURL)
- }
- return FinalizedMeetingAudio(mixedURL: destinationURL, microphoneURL: nil, systemURL: nil)
- }
- private func mixAudioFiles(systemURL: URL, microphoneURL: URL, destinationURL: URL) async throws {
- try? FileManager.default.removeItem(at: destinationURL)
- let composition = AVMutableComposition()
- guard let systemTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid),
- let micTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
- throw NSError(domain: "MeetingAudioMix", code: 1, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio composition tracks."])
- }
- let systemAsset = AVURLAsset(url: systemURL)
- let micAsset = AVURLAsset(url: microphoneURL)
- if let src = try await systemAsset.loadTracks(withMediaType: .audio).first {
- let duration = try await systemAsset.load(.duration)
- try systemTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
- }
- if let src = try await micAsset.loadTracks(withMediaType: .audio).first {
- let duration = try await micAsset.load(.duration)
- try micTrack.insertTimeRange(CMTimeRange(start: .zero, duration: duration), of: src, at: .zero)
- }
- guard let export = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
- throw NSError(domain: "MeetingAudioMix", code: 2, userInfo: [NSLocalizedDescriptionKey: "Unable to create audio export session."])
- }
- // Give the local microphone a small speech-focused boost while preserving meeting audio.
- let systemMix = AVMutableAudioMixInputParameters(track: systemTrack)
- systemMix.setVolume(1.0, at: .zero)
- let micMix = AVMutableAudioMixInputParameters(track: micTrack)
- micMix.setVolume(1.35, at: .zero)
- let audioMix = AVMutableAudioMix()
- audioMix.inputParameters = [systemMix, micMix]
- export.outputURL = destinationURL
- export.outputFileType = .m4a
- export.audioMix = audioMix
- await withCheckedContinuation { continuation in
- export.exportAsynchronously {
- continuation.resume()
- }
- }
- if export.status != .completed {
- throw export.error ?? NSError(domain: "MeetingAudioMix", code: 3, userInfo: [NSLocalizedDescriptionKey: "Audio mix export failed."])
- }
- }
- private func showTopToast(message: String, isError: Bool) {
- topToastHideWorkItem?.cancel()
- topToastHideWorkItem = nil
- topToastView?.removeFromSuperview()
- topToastView = nil
- let toast = NSVisualEffectView()
- toast.translatesAutoresizingMaskIntoConstraints = false
- toast.material = darkModeEnabled ? .hudWindow : .popover
- toast.blendingMode = .withinWindow
- toast.state = .active
- toast.wantsLayer = true
- toast.layer?.cornerRadius = 10
- toast.layer?.masksToBounds = true
- toast.layer?.borderWidth = 1
- toast.layer?.borderColor = NSColor.white.withAlphaComponent(darkModeEnabled ? 0.10 : 0.18).cgColor
- toast.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.68 : 0.78).cgColor
- toast.alphaValue = 0
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.alignment = .centerY
- row.spacing = 8
- row.distribution = .fill
- let icon = NSImageView()
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.imageScaling = .scaleProportionallyDown
- icon.image = NSImage(
- systemSymbolName: isError ? "xmark.circle.fill" : "checkmark.circle.fill",
- accessibilityDescription: isError ? "Error" : "Success"
- )
- icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 16, weight: .semibold)
- icon.contentTintColor = isError ? NSColor.systemRed : NSColor.systemGreen
- let label = textLabel(
- message,
- font: NSFont.systemFont(ofSize: 13, weight: .semibold),
- color: NSColor.white
- )
- label.alignment = .left
- label.maximumNumberOfLines = 2
- label.lineBreakMode = .byWordWrapping
- row.addArrangedSubview(icon)
- row.addArrangedSubview(label)
- toast.addSubview(row)
- view.addSubview(toast)
- NSLayoutConstraint.activate([
- toast.topAnchor.constraint(equalTo: view.topAnchor, constant: 14),
- toast.centerXAnchor.constraint(equalTo: view.centerXAnchor),
- toast.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -40),
- toast.heightAnchor.constraint(greaterThanOrEqualToConstant: 40),
- icon.widthAnchor.constraint(equalToConstant: 16),
- icon.heightAnchor.constraint(equalToConstant: 16),
- row.leadingAnchor.constraint(equalTo: toast.leadingAnchor, constant: 14),
- row.trailingAnchor.constraint(equalTo: toast.trailingAnchor, constant: -14),
- row.topAnchor.constraint(equalTo: toast.topAnchor, constant: 10),
- row.bottomAnchor.constraint(equalTo: toast.bottomAnchor, constant: -10)
- ])
- topToastView = toast
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.18
- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- toast.animator().alphaValue = 1
- }
- let hideWorkItem = DispatchWorkItem { [weak self, weak toast] in
- guard let self, let toast else { return }
- NSAnimationContext.runAnimationGroup({ context in
- context.duration = 0.2
- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- toast.animator().alphaValue = 0
- }, completionHandler: {
- toast.removeFromSuperview()
- if self.topToastView === toast {
- self.topToastView = nil
- }
- })
- }
- topToastHideWorkItem = hideWorkItem
- DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: hideWorkItem)
- }
- private func confirmPremiumUpgrade(for targetPlan: PremiumPlan) -> Bool {
- let alert = NSAlert()
- alert.messageText = "Already Premium"
- alert.informativeText = "You are already premium. Do you want to continue with this purchase?"
- alert.addButton(withTitle: "Continue")
- alert.addButton(withTitle: "Cancel")
- return alert.runModal() == .alertFirstButtonReturn
- }
- private func showPaywall(upgradeFlow: Bool = false, preferredPlan: PremiumPlan? = nil) {
- if !Thread.isMainThread {
- DispatchQueue.main.async { [weak self] in
- self?.showPaywall(upgradeFlow: upgradeFlow, preferredPlan: preferredPlan)
- }
- return
- }
- paywallUpgradeFlowEnabled = upgradeFlow
- if let preferredPlan {
- selectedPremiumPlan = preferredPlan
- }
- if let existingOverlay = paywallOverlayView {
- refreshPaywallStoreUI()
- existingOverlay.alphaValue = 1
- view.addSubview(existingOverlay, positioned: .above, relativeTo: nil)
- return
- }
- if let existing = paywallWindow {
- refreshPaywallStoreUI()
- animatePaywallPresentation(existing)
- existing.makeKeyAndOrderFront(nil)
- NSApp.activate(ignoringOtherApps: true)
- return
- }
- let content = makePaywallContent()
- let overlay = NSView()
- overlay.translatesAutoresizingMaskIntoConstraints = false
- overlay.wantsLayer = true
- overlay.layer?.backgroundColor = palette.pageBackground.withAlphaComponent(0.98).cgColor
- overlay.alphaValue = 0
- overlay.addSubview(content)
- view.addSubview(overlay, positioned: .above, relativeTo: nil)
- NSLayoutConstraint.activate([
- overlay.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- overlay.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- overlay.topAnchor.constraint(equalTo: view.topAnchor),
- overlay.bottomAnchor.constraint(equalTo: view.bottomAnchor),
- content.leadingAnchor.constraint(equalTo: overlay.leadingAnchor),
- content.trailingAnchor.constraint(equalTo: overlay.trailingAnchor),
- content.topAnchor.constraint(equalTo: overlay.topAnchor),
- content.bottomAnchor.constraint(equalTo: overlay.bottomAnchor)
- ])
- paywallOverlayView = overlay
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.20
- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- overlay.animator().alphaValue = 1
- }
- Task { [weak self] in
- guard let self else { return }
- await self.storeKitCoordinator.refreshProducts()
- self.refreshPaywallStoreUI()
- }
- }
- private func animatePaywallPresentation(_ window: NSWindow) {
- let finalFrame = window.frame
- let targetScreen = window.screen ?? NSScreen.main
- let startY: CGFloat
- if let screen = targetScreen {
- startY = screen.visibleFrame.maxY + 12
- } else {
- startY = finalFrame.origin.y + 120
- }
- let startFrame = NSRect(x: finalFrame.origin.x, y: startY, width: finalFrame.width, height: finalFrame.height)
- window.setFrame(startFrame, display: false)
- window.alphaValue = 0
- NSAnimationContext.runAnimationGroup { context in
- context.duration = 0.28
- context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- window.animator().alphaValue = 1
- window.animator().setFrame(finalFrame, display: true)
- }
- }
- @objc private func closePaywallClicked(_ sender: Any?) {
- if let overlay = paywallOverlayView {
- paywallOverlayView = nil
- paywallUpgradeFlowEnabled = false
- overlay.removeFromSuperview()
- return
- }
- if let win = paywallWindow {
- win.performClose(nil)
- return
- }
- if let gesture = sender as? NSGestureRecognizer, let win = gesture.view?.window {
- win.performClose(nil)
- return
- }
- if let view = sender as? NSView, let win = view.window {
- win.performClose(nil)
- return
- }
- }
- private func dismissPaywallIfPresented() {
- if !Thread.isMainThread {
- DispatchQueue.main.async { [weak self] in
- self?.dismissPaywallIfPresented()
- }
- return
- }
- closePaywallClicked(nil)
- }
- @objc private func paywallFooterLinkClicked(_ sender: NSClickGestureRecognizer) {
- guard let view = sender.view else { return }
- let action = paywallFooterActionByView[ObjectIdentifier(view)]
- let text = (view.subviews.first { $0 is NSTextField } as? NSTextField)?.stringValue ?? "Link"
- guard let action else {
- showSimpleAlert(title: text, message: "\(text) tapped.")
- return
- }
- handlePaywallFooterAction(action)
- }
- private func handlePaywallFooterAction(_ action: PaywallFooterAction) {
- switch action {
- case .manageSubscription:
- openManageSubscriptions()
- case .restorePurchase:
- openRestoreSubscriptionPage()
- case .continueWithFreePlan:
- closePaywallClicked(nil)
- case .privacyPolicy:
- openSettingsLink(infoKey: "PrivacyPolicyURL")
- case .support:
- openSettingsLink(infoKey: "SupportURL")
- case .termsOfServices:
- openSettingsLink(infoKey: "TermsOfServiceURL")
- }
- }
- @objc private func paywallFooterButtonPressed(_ sender: NSButton) {
- guard let action = paywallFooterActionByView[ObjectIdentifier(sender)] else { return }
- handlePaywallFooterAction(action)
- }
- @objc private func paywallPlanClicked(_ sender: NSClickGestureRecognizer) {
- guard let view = sender.view,
- let plan = premiumPlanByView[ObjectIdentifier(view)] else { return }
- selectedPremiumPlan = plan
- updatePaywallPlanSelection()
- }
- @objc private func paywallPlanButtonClicked(_ sender: NSButton) {
- guard let plan = PremiumPlan(rawValue: sender.tag) else { return }
- selectedPremiumPlan = plan
- updatePaywallPlanSelection()
- }
- private func updatePaywallPlanSelection() {
- for (plan, view) in paywallPlanViews {
- applyPaywallPlanStyle(view, isSelected: plan == selectedPremiumPlan)
- }
- paywallOfferLabel?.stringValue = paywallOfferText(for: selectedPremiumPlan)
- }
- private func paywallOfferText(for plan: PremiumPlan) -> String {
- if storeKitCoordinator.hasPremiumAccess {
- if storeKitCoordinator.hasLifetimeAccess {
- return "Lifetime premium is active on this Apple ID."
- }
- if paywallUpgradeFlowEnabled {
- let currentPlanName = storeKitCoordinator.activeNonLifetimePlan?.displayName ?? "Premium"
- if plan == .lifetime {
- return "Current plan: \(currentPlanName). Tap Continue to upgrade to Lifetime."
- }
- return "Current plan: \(currentPlanName). Select Lifetime to upgrade."
- }
- return "Premium is active on this Apple ID."
- }
- let productID = PremiumStoreProduct.productID(for: plan)
- if let product = storeKitCoordinator.productsByID[productID] {
- let pkrPrice = pkrDisplayPrice(product.displayPrice)
- if product.type == .nonConsumable {
- return "\(pkrPrice) one-time purchase"
- }
- if let subscription = product.subscription {
- let billingText = "\(pkrPrice)/\(subscriptionUnitText(subscription.subscriptionPeriod.unit))"
- if let introOffer = subscription.introductoryOffer,
- introOffer.paymentMode == .freeTrial {
- return "Free for \(subscriptionPeriodText(introOffer.period)), then \(billingText)"
- }
- return billingText
- }
- return pkrPrice
- }
- switch plan {
- case .weekly:
- return "PKR 1,100.00/week"
- case .monthly:
- return "PKR 2,500.00/month (3 days free trial)"
- case .yearly:
- return "PKR 9,900.00/year (about 190.38/week)"
- case .lifetime:
- return "PKR 14,900.00 one-time purchase"
- }
- }
- private func pkrDisplayPrice(_ value: String) -> String {
- if value.hasPrefix("PKR ") { return value }
- if value.hasPrefix("Rs ") {
- return "PKR " + value.dropFirst(3)
- }
- if value.contains("PKR") { return value }
- return "PKR \(value)"
- }
- private func subscriptionUnitText(_ unit: Product.SubscriptionPeriod.Unit) -> String {
- switch unit {
- case .day: return "day"
- case .week: return "week"
- case .month: return "month"
- case .year: return "year"
- @unknown default: return "period"
- }
- }
- private func subscriptionPeriodText(_ period: Product.SubscriptionPeriod) -> String {
- let unit = subscriptionUnitText(period.unit)
- if period.value == 1 {
- return "1 \(unit)"
- }
- return "\(period.value) \(unit)s"
- }
- private func freeTrialPackageText(for product: Product) -> String? {
- guard let introOffer = product.subscription?.introductoryOffer,
- introOffer.paymentMode == .freeTrial else {
- return nil
- }
- return "\(subscriptionPeriodText(introOffer.period)) free trial"
- }
- private func startStoreKit() {
- storeKitStartupTask?.cancel()
- storeKitStartupTask = Task { [weak self] in
- guard let self else { return }
- await self.storeKitCoordinator.start()
- self.hasCompletedInitialStoreKitSync = true
- self.refreshPaywallStoreUI()
- self.presentLaunchPaywallIfNeeded()
- self.dismissLaunchSplashIfReady()
- }
- }
- private func refreshPaywallStoreUI() {
- for (plan, label) in paywallPriceLabels {
- let productID = PremiumStoreProduct.productID(for: plan)
- if let product = storeKitCoordinator.productsByID[productID] {
- label.stringValue = pkrDisplayPrice(product.displayPrice)
- }
- }
- for (plan, label) in paywallSubtitleLabels {
- let productID = PremiumStoreProduct.productID(for: plan)
- guard let product = storeKitCoordinator.productsByID[productID],
- let period = product.subscription?.subscriptionPeriod else {
- // Show neutral fallback text when subscription metadata isn't available.
- label.stringValue = "Billed via App Store"
- continue
- }
- let recurringText = "\(pkrDisplayPrice(product.displayPrice))/\(subscriptionUnitText(period.unit))"
- if let trialText = freeTrialPackageText(for: product) {
- label.stringValue = "\(recurringText) • \(trialText)"
- } else {
- label.stringValue = recurringText
- }
- }
- refreshSidebarPremiumButton()
- refreshInstantMeetPremiumState()
- updatePaywallPlanSelection()
- updatePaywallContinueState(isLoading: false)
- }
- private func refreshInstantMeetPremiumState() {
- let isLocked = shouldGateJoinActionsForNonPremium
- let lockedAlpha: CGFloat = 0.6
- instantMeetCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
- instantMeetTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
- instantMeetSubtitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
- instantMeetCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
- instantMeetCardView?.onHoverChanged?(false)
- joinWithLinkCardView?.alphaValue = isLocked ? lockedAlpha : 1.0
- joinWithLinkTitleLabel?.alphaValue = isLocked ? lockedAlpha : 1.0
- meetLinkField?.isEditable = !isLocked
- meetLinkField?.isSelectable = !isLocked
- meetLinkField?.alphaValue = isLocked ? lockedAlpha : 1.0
- joinMeetPrimaryButton?.isEnabled = true
- joinMeetPrimaryButton?.alphaValue = isLocked ? lockedAlpha : 1.0
- joinMeetPrimaryButton?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
- joinWithLinkCardView?.toolTip = isLocked ? "Free trial used. Upgrade to continue." : nil
- }
- private func handlePremiumAccessChanged(_ hasPremiumAccess: Bool) {
- let hadPremiumAccess = lastKnownPremiumAccess
- lastKnownPremiumAccess = hasPremiumAccess
- NotificationCenter.default.post(
- name: .statusBarPremiumAccessChanged,
- object: nil,
- userInfo: ["hasPremiumAccess": hasPremiumAccess]
- )
- premiumUpgradeRatingPromptWorkItem?.cancel()
- refreshPaywallStoreUI()
- refreshScheduleCardsForPremiumStateChange()
- refreshPagesAfterPremiumStateUpdate()
- Task { [weak self] in
- await self?.loadSchedule()
- }
- if !hadPremiumAccess && hasPremiumAccess {
- dismissPaywallIfPresented()
- if selectedSidebarPage != .joinMeetings {
- Task { [weak self] in
- await self?.loadSchedule()
- }
- }
- // Skip delayed review prompt during initial launch entitlement sync.
- // We only want this after a real in-session upgrade.
- if hasCompletedInitialStoreKitSync {
- scheduleRatingPromptAfterPremiumUpgrade()
- }
- MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
- guard let self else { return }
- MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
- }
- }
- if hadPremiumAccess && !hasPremiumAccess {
- MeetingReminderManager.shared.cancelAllReminders()
- DesktopWidgetWindowManager.shared.removeAllInstances()
- showPaywall()
- }
- }
- private func refreshPagesAfterPremiumStateUpdate() {
- pageCache[.joinMeetings] = nil
- pageCache[.photo] = nil
- pageCache[.video] = nil
- pageCache[.widgets] = nil
- pageCache[.settings] = nil
- pageCache[.aiCompanion] = nil
- showSidebarPage(selectedSidebarPage)
- }
- private var userHasRated: Bool {
- UserDefaults.standard.bool(forKey: userHasRatedDefaultsKey)
- }
- private var accumulatedAppUsageSeconds: TimeInterval {
- get {
- UserDefaults.standard.double(forKey: appUsageAccumulatedSecondsDefaultsKey)
- }
- set {
- UserDefaults.standard.set(newValue, forKey: appUsageAccumulatedSecondsDefaultsKey)
- }
- }
- private var totalTrackedUsageSeconds: TimeInterval {
- let liveSessionSeconds: TimeInterval
- if let start = appUsageSessionStartDate {
- liveSessionSeconds = max(0, Date().timeIntervalSince(start))
- } else {
- liveSessionSeconds = 0
- }
- return accumulatedAppUsageSeconds + liveSessionSeconds
- }
- private var hasReachedRatingUsageThreshold: Bool {
- totalTrackedUsageSeconds >= ratingEligibleUsageSeconds
- }
- private var shouldShowRateUsInSettings: Bool {
- true
- }
- private func migrateLegacyRatingStateIfNeeded() {
- let defaults = UserDefaults.standard
- guard !defaults.bool(forKey: ratingStateMigrationV2DoneDefaultsKey) else { return }
- // Legacy behavior marked "rated" immediately after requesting review.
- // Clear once so testing and new logic can run correctly.
- defaults.set(false, forKey: userHasRatedDefaultsKey)
- defaults.set(true, forKey: ratingStateMigrationV2DoneDefaultsKey)
- }
- private func beginUsageTrackingSessionIfNeeded() {
- guard appUsageSessionStartDate == nil else { return }
- appUsageSessionStartDate = Date()
- }
- private func endUsageTrackingSession() {
- guard let start = appUsageSessionStartDate else { return }
- let sessionElapsedSeconds = max(0, Date().timeIntervalSince(start))
- accumulatedAppUsageSeconds += sessionElapsedSeconds
- appUsageSessionStartDate = nil
- }
- private func observeAppLifecycleForUsageTrackingIfNeeded() {
- guard !hasObservedAppLifecycleForUsage else { return }
- hasObservedAppLifecycleForUsage = true
- NotificationCenter.default.addObserver(
- self,
- selector: #selector(applicationDidBecomeActiveForUsageTracking),
- name: NSApplication.didBecomeActiveNotification,
- object: nil
- )
- NotificationCenter.default.addObserver(
- self,
- selector: #selector(applicationWillResignActiveForUsageTracking),
- name: NSApplication.willResignActiveNotification,
- object: nil
- )
- NotificationCenter.default.addObserver(
- self,
- selector: #selector(applicationWillTerminateForUsageTracking),
- name: NSApplication.willTerminateNotification,
- object: nil
- )
- }
- @objc private func applicationDidBecomeActiveForUsageTracking() {
- beginUsageTrackingSessionIfNeeded()
- }
- @objc private func applicationWillResignActiveForUsageTracking() {
- endUsageTrackingSession()
- }
- @objc private func applicationWillTerminateForUsageTracking() {
- endUsageTrackingSession()
- }
- private func scheduleRatingPromptAfterPremiumUpgrade() {
- guard !userHasRated else { return }
- let workItem = DispatchWorkItem { [weak self] in
- self?.requestAppRatingIfEligible(markAsRated: false)
- }
- premiumUpgradeRatingPromptWorkItem = workItem
- DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: workItem)
- }
- private func requestAppRatingIfEligible(markAsRated: Bool) {
- guard storeKitCoordinator.hasPremiumAccess, !userHasRated else { return }
- SKStoreReviewController.requestReview()
- if markAsRated {
- UserDefaults.standard.set(true, forKey: userHasRatedDefaultsKey)
- }
- }
- private func refreshScheduleCardsForPremiumStateChange() {
- if let stack = scheduleCardsStack {
- renderScheduleCards(into: stack, meetings: displayedScheduleMeetings)
- }
- applySchedulePageFiltersAndRender()
- }
- private func refreshSidebarPremiumButton() {
- let isPremium = storeKitCoordinator.hasPremiumAccess
- if isPremium {
- sidebarPremiumTitleLabel?.stringValue = "Manage Subscription"
- sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "crown.fill")
- } else {
- sidebarPremiumTitleLabel?.stringValue = "Get Premium"
- sidebarPremiumIconView?.image = premiumButtonSymbolImage(named: "star.fill")
- }
- sidebarPremiumIconView?.contentTintColor = .white
- sidebarPremiumButtonView?.onHoverChanged?(false)
- }
- private func premiumButtonSymbolImage(named symbolName: String) -> NSImage? {
- let configuration = NSImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
- return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
- .withSymbolConfiguration(configuration)
- }
- private func presentLaunchPaywallIfNeeded() {
- guard hasCompletedInitialStoreKitSync, hasViewAppearedOnce, !hasPresentedLaunchPaywall else { return }
- hasPresentedLaunchPaywall = true
- if !storeKitCoordinator.hasPremiumAccess {
- launchPaywallWorkItem?.cancel()
- let workItem = DispatchWorkItem { [weak self] in
- guard let self else { return }
- self.launchPaywallWorkItem = nil
- guard !self.storeKitCoordinator.hasPremiumAccess else { return }
- self.showPaywall()
- }
- launchPaywallWorkItem = workItem
- DispatchQueue.main.asyncAfter(deadline: .now() + launchPaywallDelay, execute: workItem)
- }
- }
- @objc private func paywallContinueClicked(_ sender: Any?) {
- startSelectedPlanPurchase()
- }
- private func startSelectedPlanPurchase() {
- guard paywallContinueEnabled else {
- if storeKitCoordinator.hasPremiumAccess {
- showSimpleAlert(title: "Premium Active", message: "This Apple ID already has premium access.")
- } else {
- showSimpleAlert(title: "Please Wait", message: "A purchase is already being processed.")
- }
- return
- }
- if paywallUpgradeFlowEnabled,
- storeKitCoordinator.hasPremiumAccess,
- selectedPremiumPlan != .lifetime,
- !confirmPremiumUpgrade(for: selectedPremiumPlan) {
- return
- }
- paywallPurchaseTask?.cancel()
- updatePaywallContinueState(isLoading: true)
- let selectedPlan = selectedPremiumPlan
- paywallPurchaseTask = Task { [weak self] in
- guard let self else { return }
- let result = await self.storeKitCoordinator.purchase(plan: selectedPlan)
- self.updatePaywallContinueState(isLoading: false)
- self.refreshPaywallStoreUI()
- switch result {
- case .success:
- self.refreshPagesAfterPremiumStateUpdate()
- Task { [weak self] in
- await self?.loadSchedule()
- }
- if selectedPlan == .lifetime, self.storeKitCoordinator.activeNonLifetimePlan != nil {
- self.showSimpleAlert(
- title: "Lifetime Premium Activated",
- message: "You are premium for lifetime now. Please cancel your previous subscription in App Store Subscriptions to avoid future renewal charges."
- )
- } else if selectedPlan == .lifetime {
- self.showSimpleAlert(title: "Purchase Complete", message: "Lifetime premium has been unlocked successfully.")
- } else {
- self.showSimpleAlert(title: "Purchase Complete", message: "Premium has been unlocked successfully.")
- }
- self.dismissPaywallIfPresented()
- self.scheduleRatingPromptAfterPremiumUpgrade()
- case .cancelled:
- break
- case .pending:
- self.showSimpleAlert(title: "Purchase Pending", message: "Your purchase is pending approval. You can continue once it completes.")
- case .unavailable:
- self.showSimpleAlert(title: "Product Not Available", message: "Unable to load this product. Check your StoreKit configuration and product IDs.")
- case .alreadyOwned:
- self.showSimpleAlert(title: "Already Purchased", message: "This plan is already active on your Apple ID.")
- case .failed(let message):
- self.showSimpleAlert(title: "Purchase Failed", message: message)
- }
- }
- }
- private func updatePaywallContinueState(isLoading: Bool) {
- if isLoading {
- paywallContinueEnabled = false
- paywallContinueLabel?.stringValue = "Processing..."
- paywallContinueButton?.alphaValue = 0.75
- return
- }
- if storeKitCoordinator.hasLifetimeAccess {
- paywallContinueEnabled = false
- paywallContinueLabel?.stringValue = "Premium Active"
- paywallContinueButton?.alphaValue = 0.75
- } else if paywallUpgradeFlowEnabled && storeKitCoordinator.hasPremiumAccess {
- paywallContinueEnabled = true
- paywallContinueLabel?.stringValue = "Continue"
- paywallContinueButton?.alphaValue = 1.0
- } else {
- paywallContinueEnabled = true
- paywallContinueLabel?.stringValue = "Continue"
- paywallContinueButton?.alphaValue = 1.0
- }
- }
- private func applyPaywallPlanStyle(_ card: NSView, isSelected: Bool, hovering: Bool = false) {
- let selectedBorder = NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1)
- let idleBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverIdleBackground =
- palette.sectionCard.blended(withFraction: 0.10, of: hoverBlend) ?? palette.sectionCard
- let selectedBackground = darkModeEnabled
- ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
- : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
- card.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hoverIdleBackground : palette.sectionCard)).cgColor
- card.layer?.borderColor = (isSelected ? selectedBorder : (hovering ? selectedBorder.withAlphaComponent(0.55) : idleBorder)).cgColor
- card.layer?.borderWidth = isSelected ? 2 : 1
- card.layer?.shadowColor = NSColor.black.cgColor
- card.layer?.shadowOpacity = isSelected ? (darkModeEnabled ? 0.26 : 0.10) : (hovering ? 0.18 : 0.12)
- card.layer?.shadowOffset = CGSize(width: 0, height: -1)
- card.layer?.shadowRadius = isSelected ? (darkModeEnabled ? 10 : 6) : (hovering ? 7 : 5)
- }
- private func viewForPage(_ page: SidebarPage) -> NSView {
- if let cached = pageCache[page] { return cached }
- let built: NSView
- switch page {
- case .joinMeetings:
- built = makeJoinMeetingsContent()
- case .photo:
- built = makeSchedulePageContent()
- case .video:
- built = makeCalendarPageContent()
- case .widgets:
- built = makeWidgetsPageContent()
- case .settings:
- built = makeSettingsPageContent()
- case .aiCompanion:
- built = makeAiCompanionPageContent()
- }
- pageCache[page] = built
- return built
- }
- private func makeWidgetsPageContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let host = makeWidgetsPageHost(canAddWidgets: storeKitCoordinator.hasPremiumAccess) { [weak self] in
- self?.showPaywall()
- }
- panel.addSubview(host)
- NSLayoutConstraint.activate([
- host.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- host.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- host.topAnchor.constraint(equalTo: panel.topAnchor),
- host.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16)
- ])
- // Keep widgets anchored to the top instead of drifting vertically in tall windows.
- host.setContentHuggingPriority(.required, for: .vertical)
- host.setContentCompressionResistancePriority(.required, for: .vertical)
- return panel
- }
- private func makeAiCompanionPageContent() -> NSView {
- // Reset per-card mappings so stale buttons/labels from previous page builds don't linger.
- aiCompanionAudioPlayer?.pause()
- aiCompanionAudioPlayer = nil
- aiCompanionLocalAudioPlayer?.stop()
- aiCompanionLocalAudioPlayer = nil
- aiCompanionCurrentlyPlayingURL = nil
- aiCompanionCurrentlyPlayingButton = nil
- aiCompanionTimeControlObserver = nil
- aiCompanionNoProgressWorkItem?.cancel()
- aiCompanionNoProgressWorkItem = nil
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionIsUsingSpeech = false
- aiCompanionCurrentlySpeakingButtonId = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- aiCompanionAudioURLByView.removeAll()
- aiCompanionAudioStatusLabelByView.removeAll()
- aiCompanionSpeechTextByView.removeAll()
- aiCompanionTranscriptMeetingIdByView.removeAll()
- aiCompanionTranscriptStatusLabelByView.removeAll()
- aiCompanionNotesMeetingIdByView.removeAll()
- aiCompanionNotesStatusLabelByView.removeAll()
- // Keep transcript requests and window state alive across AI Companion page rebuilds.
- // The page is rebuilt while processing starts/completes, and cancelling here interrupts
- // the active request before it can update the transcript view.
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- panel.userInterfaceLayoutDirection = .leftToRight
- let scroll = NSScrollView()
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.drawsBackground = false
- scroll.hasHorizontalScroller = false
- scroll.hasVerticalScroller = true
- scroll.autohidesScrollers = true
- scroll.borderType = .noBorder
- scroll.scrollerStyle = .overlay
- scroll.automaticallyAdjustsContentInsets = false
- let clip = TopAlignedClipView()
- clip.drawsBackground = false
- scroll.contentView = clip
- panel.addSubview(scroll)
- let content = NSView()
- content.translatesAutoresizingMaskIntoConstraints = false
- scroll.documentView = content
- let contentStack = NSStackView()
- contentStack.translatesAutoresizingMaskIntoConstraints = false
- contentStack.userInterfaceLayoutDirection = .leftToRight
- contentStack.orientation = .vertical
- contentStack.spacing = 12
- contentStack.alignment = .width
- contentStack.distribution = .fill
- let titleLabel = textLabel("AI Companion", font: typography.pageTitle, color: palette.textPrimary)
- titleLabel.alignment = .left
- contentStack.addArrangedSubview(titleLabel)
- let subtitle = textLabel("Get notes from your previous meetings", font: typography.fieldLabel, color: palette.textSecondary)
- subtitle.alignment = .left
- contentStack.addArrangedSubview(subtitle)
- contentStack.setCustomSpacing(14, after: subtitle)
- titleLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- subtitle.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- if let session = activeMeetingRecordingSession {
- let activeCard = aiCompanionActiveRecordingCard(session: session)
- contentStack.addArrangedSubview(activeCard)
- activeCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- }
- if aiCompanionLocalRecordings.isEmpty {
- let emptyLabel = textLabel(
- "No previous meetings yet. End a meeting to save it here and generate notes.",
- font: typography.fieldLabel,
- color: palette.textMuted
- )
- emptyLabel.alignment = .left
- emptyLabel.maximumNumberOfLines = 2
- emptyLabel.lineBreakMode = .byWordWrapping
- contentStack.addArrangedSubview(emptyLabel)
- emptyLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- } else {
- let filterRow = NSStackView()
- filterRow.translatesAutoresizingMaskIntoConstraints = false
- filterRow.userInterfaceLayoutDirection = .leftToRight
- filterRow.orientation = .horizontal
- filterRow.alignment = .centerY
- filterRow.spacing = 18
- filterRow.distribution = .fill
- let filterDropdown = makeAiCompanionRecordingsFilterDropdown()
- aiCompanionRecordingsFilterDropdown = filterDropdown
- filterRow.addArrangedSubview(filterDropdown)
- filterRow.setCustomSpacing(20, after: filterDropdown)
- let (fromShell, fromPicker) = makeFilterStyleDatePicker(
- date: aiCompanionFilterFromDate,
- changeAction: #selector(aiCompanionFilterDatePickerChanged(_:))
- )
- aiCompanionFilterFromDatePicker = fromPicker
- filterRow.addArrangedSubview(fromShell)
- filterRow.setCustomSpacing(16, after: fromShell)
- let (toShell, toPicker) = makeFilterStyleDatePicker(
- date: aiCompanionFilterToDate,
- changeAction: #selector(aiCompanionFilterDatePickerChanged(_:))
- )
- aiCompanionFilterToDatePicker = toPicker
- filterRow.addArrangedSubview(toShell)
- NSLayoutConstraint.activate([
- fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
- fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
- ])
- let filterRowSpacer = NSView()
- filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
- filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- filterRow.addArrangedSubview(filterRowSpacer)
- let applyFilterButton = makeSchedulePagePillButton(title: "Apply", action: #selector(aiCompanionRecordingsApplyPressed(_:)))
- filterRow.addArrangedSubview(applyFilterButton)
- filterRow.setCustomSpacing(22, after: applyFilterButton)
- let resetFilterButton = makeSchedulePagePillButton(title: "Reset", action: #selector(aiCompanionRecordingsResetPressed(_:)))
- filterRow.addArrangedSubview(resetFilterButton)
- filterRow.setCustomSpacing(22, after: resetFilterButton)
- filterRow.addArrangedSubview(
- makeScheduleRefreshButton(
- action: #selector(aiCompanionRecordingsRefreshPressed(_:)),
- accessibilityDescription: "Refresh saved meetings"
- )
- )
- contentStack.addArrangedSubview(filterRow)
- filterRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- let rangeError = textLabel(
- aiCompanionRecordingsRangeErrorMessage ?? "",
- font: NSFont.systemFont(ofSize: 12, weight: .semibold),
- color: .systemRed
- )
- rangeError.alignment = .left
- rangeError.isHidden = aiCompanionRecordingsRangeErrorMessage == nil
- rangeError.maximumNumberOfLines = 3
- rangeError.lineBreakMode = .byWordWrapping
- aiCompanionRecordingsRangeErrorLabel = rangeError
- contentStack.addArrangedSubview(rangeError)
- rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- let previousMeetingsLabel = textLabel("Previous meetings", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: palette.textPrimary)
- previousMeetingsLabel.alignment = .left
- contentStack.addArrangedSubview(previousMeetingsLabel)
- previousMeetingsLabel.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- contentStack.setCustomSpacing(10, after: previousMeetingsLabel)
- let displayedRecordings = filteredAiCompanionRecordings()
- if displayedRecordings.isEmpty {
- let emptyFiltered = textLabel(
- aiCompanionRecordingsRangeErrorMessage == nil
- ? "No meetings match the selected filters."
- : "Adjust the date range and tap Apply.",
- font: typography.fieldLabel,
- color: palette.textMuted
- )
- emptyFiltered.alignment = .left
- emptyFiltered.maximumNumberOfLines = 2
- emptyFiltered.lineBreakMode = .byWordWrapping
- contentStack.addArrangedSubview(emptyFiltered)
- emptyFiltered.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- } else {
- for recording in displayedRecordings {
- let card = aiCompanionMeetingCard(recording)
- contentStack.addArrangedSubview(card)
- card.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- }
- }
- refreshAiCompanionRecordingsFilterChrome()
- }
- content.addSubview(contentStack)
- NSLayoutConstraint.activate([
- scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
- scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
- scroll.topAnchor.constraint(equalTo: panel.topAnchor),
- scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),
- content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
- content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
- content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
- content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
- content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
- contentStack.leftAnchor.constraint(equalTo: content.leftAnchor, constant: 28),
- contentStack.rightAnchor.constraint(equalTo: content.rightAnchor, constant: -28),
- contentStack.topAnchor.constraint(equalTo: content.topAnchor, constant: 16),
- content.bottomAnchor.constraint(greaterThanOrEqualTo: contentStack.bottomAnchor, constant: 16)
- ])
- return panel
- }
- private func makeAiCompanionRecordingsFilterDropdown() -> NSPopUpButton {
- let button = HoverPopUpButton(frame: .zero, pullsDown: false)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.autoenablesItems = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 8
- button.layer?.masksToBounds = true
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.filterText
- button.contentTintColor = palette.textSecondary
- button.target = self
- button.action = #selector(aiCompanionRecordingsFilterChanged(_:))
- button.heightAnchor.constraint(equalToConstant: 34).isActive = true
- button.widthAnchor.constraint(equalToConstant: 268).isActive = true
- button.removeAllItems()
- button.addItems(withTitles: ["All", "Today", "This week", "Previous week", "Previous month", "Custom range"])
- button.selectItem(at: aiCompanionRecordingsFilter.rawValue)
- if let menu = button.menu {
- for (index, item) in menu.items.enumerated() {
- item.tag = index
- }
- }
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- button.onHoverChanged = { [weak button] hovering in
- button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- button.onHoverChanged?(false)
- return button
- }
- private func aiCompanionHasValidCustomFilterRange() -> Bool {
- let calendar = Calendar.current
- let start = calendar.startOfDay(for: aiCompanionFilterFromDate)
- let end = calendar.startOfDay(for: aiCompanionFilterToDate)
- return start <= end
- }
- private func filteredAiCompanionRecordings() -> [MeetingRecordingSummary] {
- let calendar = Calendar.current
- let now = Date()
- let recordings = aiCompanionLocalRecordings
- func previousCalendarWeekBounds(reference: Date) -> (start: Date, end: Date)? {
- guard let thisWeek = calendar.dateInterval(of: .weekOfYear, for: reference),
- let prevStart = calendar.date(byAdding: .weekOfYear, value: -1, to: thisWeek.start)
- else { return nil }
- return (prevStart, thisWeek.start)
- }
- func previousCalendarMonthBounds(reference: Date) -> (start: Date, end: Date)? {
- guard let thisMonth = calendar.dateInterval(of: .month, for: reference),
- let prevStart = calendar.date(byAdding: .month, value: -1, to: thisMonth.start)
- else { return nil }
- return (prevStart, thisMonth.start)
- }
- switch aiCompanionRecordingsFilter {
- case .all:
- return recordings
- case .today:
- let dayStart = calendar.startOfDay(for: now)
- guard let nextDay = calendar.date(byAdding: .day, value: 1, to: dayStart) else { return [] }
- return recordings.filter { $0.endedAt >= dayStart && $0.endedAt < nextDay }
- case .week:
- guard let thisWeek = calendar.dateInterval(of: .weekOfYear, for: now) else { return [] }
- return recordings.filter { $0.endedAt >= thisWeek.start && $0.endedAt < thisWeek.end }
- case .previousWeek:
- guard let bounds = previousCalendarWeekBounds(reference: now) else { return [] }
- return recordings.filter { $0.endedAt >= bounds.start && $0.endedAt < bounds.end }
- case .previousMonth:
- guard let bounds = previousCalendarMonthBounds(reference: now) else { return [] }
- return recordings.filter { $0.endedAt >= bounds.start && $0.endedAt < bounds.end }
- case .customRange:
- guard aiCompanionHasValidCustomFilterRange() else { return [] }
- let start = calendar.startOfDay(for: aiCompanionFilterFromDate)
- let inclusiveEndDay = calendar.startOfDay(for: aiCompanionFilterToDate)
- guard let endExclusive = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else { return [] }
- return recordings.filter { $0.endedAt >= start && $0.endedAt < endExclusive }
- }
- }
- private func refreshAiCompanionRecordingsFilterChrome() {
- let isCustom = aiCompanionRecordingsFilter == .customRange
- aiCompanionFilterFromDatePicker?.isEnabled = isCustom
- aiCompanionFilterToDatePicker?.isEnabled = isCustom
- let dim: CGFloat = isCustom ? 1.0 : 0.65
- aiCompanionFilterFromDatePicker?.superview?.alphaValue = dim
- aiCompanionFilterToDatePicker?.superview?.alphaValue = dim
- }
- private func setAiCompanionRecordingsRangeError(_ message: String?) {
- aiCompanionRecordingsRangeErrorMessage = message
- aiCompanionRecordingsRangeErrorLabel?.stringValue = message ?? ""
- aiCompanionRecordingsRangeErrorLabel?.isHidden = message == nil
- }
- private func redrawAiCompanionPageIfNeeded() {
- guard selectedSidebarPage == .aiCompanion else { return }
- pageCache[.aiCompanion] = nil
- showSidebarPage(.aiCompanion)
- }
- private func aiCompanionActiveRecordingCard(session: ActiveMeetingRecordingSession) -> NSView {
- let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
- card.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.userInterfaceLayoutDirection = .leftToRight
- stack.orientation = .vertical
- stack.alignment = .leading
- stack.spacing = 8
- let title = textLabel("Recording in progress: \(session.title)", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
- let started = DateFormatter.localizedString(from: session.startedAt, dateStyle: .medium, timeStyle: .short)
- let status = textLabel("Started: \(started)", font: typography.fieldLabel, color: palette.textSecondary)
- let stopButton = NSButton(title: "Stop Recording", target: self, action: #selector(aiCompanionStopRecordingTapped(_:)))
- stopButton.translatesAutoresizingMaskIntoConstraints = false
- stopButton.isBordered = false
- stopButton.bezelStyle = .inline
- stopButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
- stopButton.contentTintColor = NSColor.systemRed
- stopButton.alignment = .left
- stopButton.setButtonType(.momentaryPushIn)
- aiCompanionStopRecordingButton = stopButton
- stack.addArrangedSubview(title)
- stack.addArrangedSubview(status)
- stack.addArrangedSubview(stopButton)
- card.addSubview(stack)
- NSLayoutConstraint.activate([
- stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
- stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
- stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
- stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
- ])
- return card
- }
- private func aiCompanionMeetingCard(_ recording: MeetingRecordingSummary) -> NSView {
- let card = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
- card.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.userInterfaceLayoutDirection = .leftToRight
- stack.orientation = .vertical
- stack.alignment = .leading
- stack.spacing = 8
- let title = textLabel(recording.title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
- title.alignment = .left
- title.maximumNumberOfLines = 2
- title.lineBreakMode = .byTruncatingTail
- let dateText = DateFormatter.localizedString(from: recording.endedAt, dateStyle: .medium, timeStyle: .none)
- let dateLabel = textLabel("Date: \(dateText)", font: typography.fieldLabel, color: palette.textSecondary)
- dateLabel.alignment = .left
- let savedTimeText = DateFormatter.localizedString(from: recording.endedAt, dateStyle: .none, timeStyle: .short)
- let savedTimeLabel = textLabel("Saved time: \(savedTimeText)", font: typography.fieldLabel, color: palette.textMuted)
- savedTimeLabel.alignment = .left
- let notesButton = HoverButton(title: "Get Notes", target: self, action: #selector(aiCompanionNotesTapped(_:)))
- notesButton.translatesAutoresizingMaskIntoConstraints = false
- notesButton.isBordered = false
- notesButton.bezelStyle = .regularSquare
- notesButton.wantsLayer = true
- notesButton.layer?.cornerRadius = 16
- notesButton.layer?.masksToBounds = true
- notesButton.layer?.borderWidth = 1
- notesButton.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
- notesButton.contentTintColor = palette.primaryBlue
- notesButton.alignment = .center
- notesButton.setButtonType(.momentaryChange)
- notesButton.focusRingType = .none
- notesButton.image = NSImage(systemSymbolName: "note.text", accessibilityDescription: "Get Notes")
- notesButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
- notesButton.imagePosition = .imageLeading
- notesButton.imageHugsTitle = true
- notesButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
- notesButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 112).isActive = true
- let notesBaseFill = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.20 : 0.14)
- let notesHoverFill = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.30 : 0.22)
- let notesBaseBorder = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.65 : 0.52)
- let notesHoverBorder = palette.primaryBlue.withAlphaComponent(darkModeEnabled ? 0.90 : 0.72)
- notesButton.onHoverChanged = { [weak notesButton] hovering in
- notesButton?.layer?.backgroundColor = (hovering ? notesHoverFill : notesBaseFill).cgColor
- notesButton?.layer?.borderColor = (hovering ? notesHoverBorder : notesBaseBorder).cgColor
- }
- notesButton.onHoverChanged?(false)
- aiCompanionNotesMeetingIdByView[ObjectIdentifier(notesButton)] = recording.id
- let notesStatusLabel = textLabel(aiCompanionNotesStatusText(for: recording), font: typography.fieldLabel, color: palette.textMuted)
- notesStatusLabel.alignment = .left
- notesStatusLabel.maximumNumberOfLines = 2
- notesStatusLabel.lineBreakMode = .byTruncatingTail
- aiCompanionNotesStatusLabelByView[ObjectIdentifier(notesButton)] = notesStatusLabel
- stack.addArrangedSubview(title)
- stack.addArrangedSubview(dateLabel)
- stack.addArrangedSubview(savedTimeLabel)
- stack.addArrangedSubview(notesButton)
- stack.addArrangedSubview(notesStatusLabel)
- card.addSubview(stack)
- NSLayoutConstraint.activate([
- stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
- stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
- stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
- stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -14)
- ])
- return card
- }
- @objc private func aiCompanionAudioTapped(_ sender: NSButton) {
- let senderId = ObjectIdentifier(sender)
- guard let url = aiCompanionAudioURLByView[senderId] else { return }
- // Toggle play/pause if the same card is tapped.
- if aiCompanionCurrentlyPlayingURL == url {
- if aiCompanionIsUsingSpeech {
- if aiCompanionSpeechSynthesizer.isSpeaking {
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionIsUsingSpeech = false
- sender.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Stopped"
- } else {
- aiCompanionStartSpeech(forButtonId: senderId)
- sender.title = "Pause Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Speaking..."
- }
- return
- } else if let player = aiCompanionAudioPlayer {
- if player.rate != 0 {
- player.pause()
- sender.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
- } else {
- player.play()
- sender.title = "Pause Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
- }
- return
- } else if let player = aiCompanionLocalAudioPlayer {
- if player.isPlaying {
- player.pause()
- sender.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
- } else {
- player.play()
- sender.title = "Pause Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
- }
- return
- }
- }
- // Stop any previous playback and remove observers.
- aiCompanionAudioPlayer?.pause()
- aiCompanionLocalAudioPlayer?.stop()
- aiCompanionLocalAudioPlayer = nil
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionIsUsingSpeech = false
- aiCompanionNoProgressWorkItem?.cancel()
- aiCompanionNoProgressWorkItem = nil
- aiCompanionCurrentlySpeakingButtonId = nil
- aiCompanionTimeControlObserver = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- // Revert previous playing UI (if any).
- if let previousButton = aiCompanionCurrentlyPlayingButton {
- let previousId = ObjectIdentifier(previousButton)
- previousButton.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[previousId]?.stringValue = "Not playing"
- }
- aiCompanionCurrentlyPlayingURL = url
- aiCompanionCurrentlyPlayingButton = sender
- sender.title = "Pause Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Checking audio..."
- aiCompanionAudioRequestID = UUID()
- let requestID = aiCompanionAudioRequestID
- let urlToCheck = url
- let senderButton = sender
- if urlToCheck.isFileURL {
- guard FileManager.default.fileExists(atPath: urlToCheck.path) else {
- senderButton.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Audio file missing"
- return
- }
- do {
- let player = try AVAudioPlayer(contentsOf: urlToCheck)
- player.volume = 1.0
- player.delegate = self
- player.prepareToPlay()
- let didPlay = player.play()
- guard didPlay else {
- senderButton.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Could not play recording"
- return
- }
- aiCompanionLocalAudioPlayer = player
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
- } catch {
- senderButton.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Failed: \(error.localizedDescription)"
- }
- return
- }
- var request = URLRequest(url: urlToCheck)
- request.setValue("bytes=0-0", forHTTPHeaderField: "Range") // lightweight probe
- request.timeoutInterval = 10
- URLSession.shared.dataTask(with: request) { [weak self] _, response, error in
- guard let self else { return }
- DispatchQueue.main.async {
- guard self.aiCompanionAudioRequestID == requestID else { return } // stale tap
- if let error {
- senderButton.title = "Play Audio"
- self.aiCompanionAudioTimeControlObserverResetForFailure()
- self.aiCompanionStartSpeech(forButtonId: senderId)
- return
- }
- guard let http = response as? HTTPURLResponse else {
- senderButton.title = "Play Audio"
- self.aiCompanionAudioTimeControlObserverResetForFailure()
- self.aiCompanionStartSpeech(forButtonId: senderId)
- return
- }
- let mime = http.mimeType?.lowercased() ?? ""
- let okStatus = (200...299).contains(http.statusCode) || http.statusCode == 206
- guard okStatus else {
- senderButton.title = "Play Audio"
- self.aiCompanionAudioTimeControlObserverResetForFailure()
- self.aiCompanionStartSpeech(forButtonId: senderId)
- return
- }
- if !mime.isEmpty && mime.hasPrefix("audio/") == false {
- senderButton.title = "Play Audio"
- self.aiCompanionAudioTimeControlObserverResetForFailure()
- self.aiCompanionStartSpeech(forButtonId: senderId)
- return
- }
- self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Loading..."
- let player = AVPlayer(url: urlToCheck)
- player.volume = 1.0
- self.aiCompanionAudioPlayer = player
- if let item = player.currentItem {
- self.aiCompanionPlaybackEndObserver = NotificationCenter.default.addObserver(
- forName: .AVPlayerItemDidPlayToEndTime,
- object: item,
- queue: .main
- ) { [weak self] _ in
- self?.aiCompanionAudioDidFinish()
- }
- self.aiCompanionPlaybackFailedObserver = NotificationCenter.default.addObserver(
- forName: .AVPlayerItemFailedToPlayToEndTime,
- object: item,
- queue: .main
- ) { [weak self] notification in
- self?.aiCompanionAudioDidFail(notification: notification)
- }
- }
- // Update the UI only when playback actually starts (helps diagnose "playing but no audio").
- self.aiCompanionTimeControlObserver = player.observe(\.timeControlStatus, options: [.initial, .new]) { [weak self] p, _ in
- guard let self else { return }
- guard self.aiCompanionCurrentlyPlayingURL == urlToCheck else { return }
- switch p.timeControlStatus {
- case .playing:
- self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
- case .waitingToPlayAtSpecifiedRate:
- self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Buffering..."
- case .paused:
- self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Paused"
- @unknown default:
- self.aiCompanionAudioStatusLabelByView[senderId]?.stringValue = "Playing..."
- }
- }
- // If the remote file is silent/unplayable, AVPlayer can still report "playing".
- // After a short grace period, fall back to text-to-speech so you can always hear something.
- let startSeconds = player.currentTime().seconds
- player.play()
- let playerRef = player
- let urlRef = urlToCheck
- self.aiCompanionNoProgressWorkItem?.cancel()
- let workItem = DispatchWorkItem { [weak self] in
- guard let self else { return }
- guard self.aiCompanionAudioPlayer === playerRef else { return }
- guard self.aiCompanionCurrentlyPlayingURL == urlRef else { return }
- guard self.aiCompanionIsUsingSpeech == false else { return }
- let nowSeconds = playerRef.currentTime().seconds
- let progressed = startSeconds.isFinite && nowSeconds.isFinite && (nowSeconds - startSeconds) > 0.5
- let actuallyPlaying = playerRef.timeControlStatus == .playing
- if actuallyPlaying == false || progressed == false {
- self.aiCompanionStartSpeech(forButtonId: senderId)
- }
- }
- self.aiCompanionNoProgressWorkItem = workItem
- DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: workItem)
- }
- }.resume()
- }
- @objc private func aiCompanionTranscriptTapped(_ sender: NSButton) {
- let senderId = ObjectIdentifier(sender)
- guard let meetingId = aiCompanionTranscriptMeetingIdByView[senderId] else { return }
- guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
- aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript unavailable (tap to retry)"
- showSimpleAlert(title: "Transcript unavailable", message: "Could not find recording details for this meeting.")
- return
- }
- if aiCompanionTranscriptStatus(for: recording) == .ready,
- let cached = recording.transcriptText?.trimmingCharacters(in: .whitespacesAndNewlines),
- cached.isEmpty == false {
- aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: cached)
- aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = aiCompanionTranscriptStatusText(for: recording)
- return
- }
- aiCompanionTranscriptStatusLabelByView[senderId]?.stringValue = "Transcript processing..."
- let requestId = UUID()
- aiCompanionTranscriptCurrentRequestId = requestId
- aiCompanionPresentTranscriptWindow(meetingTitle: recording.title, initialText: "Transcript processing...")
- aiCompanionStartTranscriptProcessing(forMeetingID: meetingId, requestId: requestId, interactiveAuth: true, forceRegenerate: true)
- }
- private func aiCompanionStartTranscriptProcessing(
- forMeetingID meetingId: String,
- requestId: UUID?,
- interactiveAuth: Bool,
- forceRegenerate: Bool
- ) {
- if !forceRegenerate,
- let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }),
- aiCompanionTranscriptStatus(for: recording) == .ready {
- return
- }
- aiCompanionTranscriptTaskByMeetingId[meetingId]?.cancel()
- _ = aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.transcriptStatusRaw = MeetingTranscriptStatus.processing.rawValue
- recording.transcriptErrorMessage = nil
- if forceRegenerate {
- recording.transcriptText = nil
- recording.transcriptSourceRaw = nil
- recording.notesStatusRaw = MeetingNotesStatus.notRequested.rawValue
- recording.notesText = nil
- recording.notesErrorMessage = nil
- }
- }
- aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
- if selectedSidebarPage == .aiCompanion {
- pageCache[.aiCompanion] = nil
- showSidebarPage(.aiCompanion)
- }
- let presentingWindow = view.window
- let task = Task { [weak self] in
- guard let self else { return }
- defer { Task { @MainActor [weak self] in self?.aiCompanionTranscriptTaskByMeetingId[meetingId] = nil } }
- do {
- let result = try await self.aiCompanionFetchOrGenerateTranscript(
- meetingId: meetingId,
- interactiveAuth: interactiveAuth,
- presentingWindow: presentingWindow
- )
- await MainActor.run {
- guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
- self.aiCompanionTranscriptProgressByMeetingId[meetingId] = nil
- _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.transcriptStatusRaw = MeetingTranscriptStatus.ready.rawValue
- recording.transcriptSourceRaw = result.source.rawValue
- recording.transcriptText = result.text
- recording.transcriptSegmentsJSON = result.segmentsJSON
- recording.transcriptErrorMessage = nil
- }
- self.aiCompanionTranscriptTextView?.string = result.text
- self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
- if self.selectedSidebarPage == .aiCompanion {
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(.aiCompanion)
- }
- }
- } catch {
- await MainActor.run {
- guard requestId == nil || self.aiCompanionTranscriptCurrentRequestId == requestId else { return }
- self.aiCompanionTranscriptProgressByMeetingId[meetingId] = nil
- let msg = error.localizedDescription.isEmpty ? "Failed to load transcript." : error.localizedDescription
- _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.transcriptStatusRaw = MeetingTranscriptStatus.failed.rawValue
- recording.transcriptErrorMessage = msg
- }
- self.aiCompanionTranscriptTextView?.string = "Transcript unavailable.\n\n\(msg)"
- self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
- if self.selectedSidebarPage == .aiCompanion {
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(.aiCompanion)
- }
- }
- }
- }
- aiCompanionTranscriptTaskByMeetingId[meetingId] = task
- }
- private func aiCompanionFetchOrGenerateTranscript(
- meetingId: String,
- interactiveAuth: Bool,
- presentingWindow: NSWindow?
- ) async throws -> (text: String, segmentsJSON: String?, source: MeetingTranscriptSource) {
- guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
- throw NSError(domain: "AiCompanionTranscript", code: 10, userInfo: [NSLocalizedDescriptionKey: "Recording not found."])
- }
- _ = interactiveAuth
- _ = presentingWindow
- let micURL: URL? = recording.microphoneAudioFilePath
- .map { URL(fileURLWithPath: $0) }
- .flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }
- let systemURL: URL? = recording.systemAudioFilePath
- .map { URL(fileURLWithPath: $0) }
- .flatMap { FileManager.default.fileExists(atPath: $0.path) ? $0 : nil }
- let hasPerChannel = micURL != nil || systemURL != nil
- let mixedURL = URL(fileURLWithPath: recording.audioFilePath)
- if hasPerChannel == false {
- guard FileManager.default.fileExists(atPath: mixedURL.path) else {
- throw NSError(domain: "AiCompanionTranscript", code: 12, userInfo: [NSLocalizedDescriptionKey: "Local meeting audio is missing."])
- }
- }
- let preferredLocales = aiCompanionPreferredTranscriptionLocales()
- let progressHandler: @Sendable (MeetingTranscriptionProgress) -> Void = { [weak self] progress in
- Task { @MainActor [weak self] in
- guard let self else { return }
- let text: String
- if progress.totalChunks > 0 {
- text = "Transcribing \(progress.completedChunks)/\(progress.totalChunks) chunks..."
- } else {
- text = "Transcript processing..."
- }
- self.aiCompanionTranscriptProgressByMeetingId[meetingId] = text
- self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
- }
- }
- let segments: [TranscriptSegment]
- let source: MeetingTranscriptSource
- if hasPerChannel {
- segments = try await meetingTranscriptionService.transcribeMeeting(
- micURL: micURL,
- systemURL: systemURL,
- locales: preferredLocales,
- onProgress: progressHandler
- )
- source = .localMultiChannelAppleSpeech
- } else {
- // Backward compatibility: old recordings only have a mixed file.
- segments = try await meetingTranscriptionService.transcribeMeeting(
- micURL: nil,
- systemURL: mixedURL,
- locales: preferredLocales,
- onProgress: progressHandler
- )
- source = .localAudioAppleSpeech
- }
- let renderedText = segments.renderedTimelineText().trimmingCharacters(in: .whitespacesAndNewlines)
- guard renderedText.isEmpty == false else {
- throw NSError(domain: "AiCompanionTranscript", code: 14, userInfo: [NSLocalizedDescriptionKey: "Generated transcript was empty."])
- }
- let encoder = JSONEncoder()
- let segmentsJSON = (try? encoder.encode(segments)).flatMap { String(data: $0, encoding: .utf8) }
- return (renderedText, segmentsJSON, source)
- }
- private func aiCompanionPreferredTranscriptionLocales() -> [Locale] {
- let defaults = UserDefaults.standard
- let selectedIdentifiers = [
- defaults.string(forKey: aiCompanionPreferredLanguage1DefaultsKey),
- defaults.string(forKey: aiCompanionPreferredLanguage2DefaultsKey)
- ]
- .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { $0.isEmpty == false }
- var locales: [Locale] = []
- var seen = Set<String>()
- func appendIdentifier(_ identifier: String) {
- let locale = Locale(identifier: identifier)
- guard SFSpeechRecognizer(locale: locale)?.isAvailable == true else { return }
- let normalized = identifier.replacingOccurrences(of: "_", with: "-").lowercased()
- guard seen.contains(normalized) == false else { return }
- seen.insert(normalized)
- locales.append(locale)
- }
- for identifier in selectedIdentifiers {
- appendIdentifier(identifier)
- }
- // Safe defaults for mixed-language meetings if user has not configured preferences yet.
- appendIdentifier(Locale.current.identifier)
- appendIdentifier("en-US")
- if locales.isEmpty {
- return [Locale(identifier: "en-US")]
- }
- return locales
- }
- private func aiCompanionSupportedSpeechLocaleOptions() -> [SpeechLocaleOption] {
- let supported = SFSpeechRecognizer.supportedLocales()
- let currentIdentifier = Locale.current.identifier
- let englishUSIdentifier = "en-US"
- var candidates = Set<String>(supported.map { $0.identifier })
- for preferred in Locale.preferredLanguages {
- candidates.insert(preferred)
- }
- candidates.insert(currentIdentifier)
- candidates.insert(englishUSIdentifier)
- return candidates
- .map { identifier -> SpeechLocaleOption in
- let locale = Locale(identifier: identifier)
- let languageCode = locale.languageCode ?? Locale.components(fromIdentifier: identifier)[NSLocale.Key.languageCode.rawValue]
- let languageName = Locale.current.localizedString(forIdentifier: identifier)
- ?? languageCode.flatMap { Locale.current.localizedString(forLanguageCode: $0) }
- ?? identifier
- return SpeechLocaleOption(identifier: identifier, displayName: "\(languageName) (\(identifier))")
- }
- .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
- }
- private func updateAiCompanionPreferredSpeechLanguages(primary: String, secondary: String?) {
- let normalizedPrimary = primary.trimmingCharacters(in: .whitespacesAndNewlines)
- guard normalizedPrimary.isEmpty == false else { return }
- UserDefaults.standard.set(normalizedPrimary, forKey: aiCompanionPreferredLanguage1DefaultsKey)
- let cleanedSecondary = secondary?.trimmingCharacters(in: .whitespacesAndNewlines)
- if let cleanedSecondary, cleanedSecondary.isEmpty == false {
- let normalizedPrimaryKey = normalizedPrimary.replacingOccurrences(of: "_", with: "-").lowercased()
- let normalizedSecondaryKey = cleanedSecondary.replacingOccurrences(of: "_", with: "-").lowercased()
- if normalizedPrimaryKey == normalizedSecondaryKey {
- UserDefaults.standard.removeObject(forKey: aiCompanionPreferredLanguage2DefaultsKey)
- } else {
- UserDefaults.standard.set(cleanedSecondary, forKey: aiCompanionPreferredLanguage2DefaultsKey)
- }
- } else {
- UserDefaults.standard.removeObject(forKey: aiCompanionPreferredLanguage2DefaultsKey)
- }
- }
- @objc private func aiCompanionNotesTapped(_ sender: NSButton) {
- let senderId = ObjectIdentifier(sender)
- guard let meetingId = aiCompanionNotesMeetingIdByView[senderId] else { return }
- guard let recording = aiCompanionLocalRecordings.first(where: { $0.id == meetingId }) else {
- aiCompanionNotesStatusLabelByView[senderId]?.stringValue = "Notes unavailable (tap to retry)"
- showSimpleAlert(title: "Notes unavailable", message: "Could not find recording details for this meeting.")
- return
- }
- if aiCompanionNotesStatus(for: recording) == .ready,
- let cached = recording.notesText?.trimmingCharacters(in: .whitespacesAndNewlines),
- cached.isEmpty == false {
- aiCompanionPresentNotesWindow(meetingTitle: recording.title, initialText: cached)
- aiCompanionNotesStatusLabelByView[senderId]?.stringValue = aiCompanionNotesStatusText(for: recording)
- return
- }
- aiCompanionNotesStatusLabelByView[senderId]?.stringValue = "Notes processing..."
- let requestId = UUID()
- aiCompanionNotesCurrentRequestId = requestId
- aiCompanionPresentNotesWindow(meetingTitle: recording.title, initialText: "Generating notes...")
- aiCompanionStartNotesProcessing(forMeetingID: meetingId, requestId: requestId)
- }
- private func aiCompanionStartNotesProcessing(forMeetingID meetingId: String, requestId: UUID?) {
- aiCompanionNotesTaskByMeetingId[meetingId]?.cancel()
- _ = aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.notesStatusRaw = MeetingNotesStatus.processing.rawValue
- recording.notesErrorMessage = nil
- recording.notesText = nil
- }
- aiCompanionNotesProgressByMeetingId[meetingId] = "Preparing transcript..."
- aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
- if selectedSidebarPage == .aiCompanion {
- pageCache[.aiCompanion] = nil
- showSidebarPage(.aiCompanion)
- }
- let presentingWindow = view.window
- let task = Task { [weak self] in
- guard let self else { return }
- defer { Task { @MainActor [weak self] in self?.aiCompanionNotesTaskByMeetingId[meetingId] = nil } }
- do {
- let notes = try await self.aiCompanionGenerateNotesForMeeting(meetingId: meetingId, presentingWindow: presentingWindow)
- await MainActor.run {
- guard requestId == nil || self.aiCompanionNotesCurrentRequestId == requestId else { return }
- self.aiCompanionNotesProgressByMeetingId[meetingId] = nil
- _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.notesStatusRaw = MeetingNotesStatus.ready.rawValue
- recording.notesText = notes
- recording.notesErrorMessage = nil
- }
- self.aiCompanionNotesTextView?.string = notes
- self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
- if self.selectedSidebarPage == .aiCompanion {
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(.aiCompanion)
- }
- }
- } catch {
- await MainActor.run {
- guard requestId == nil || self.aiCompanionNotesCurrentRequestId == requestId else { return }
- self.aiCompanionNotesProgressByMeetingId[meetingId] = nil
- let msg = error.localizedDescription.isEmpty ? "Failed to generate notes." : error.localizedDescription
- _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.notesStatusRaw = MeetingNotesStatus.failed.rawValue
- recording.notesErrorMessage = msg
- }
- self.aiCompanionNotesTextView?.string = "Notes unavailable.\n\n\(msg)"
- self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
- if self.selectedSidebarPage == .aiCompanion {
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(.aiCompanion)
- }
- }
- }
- }
- aiCompanionNotesTaskByMeetingId[meetingId] = task
- }
- private func aiCompanionGenerateNotesForMeeting(meetingId: String, presentingWindow: NSWindow?) async throws -> String {
- let transcriptText: String
- if let existing = aiCompanionLocalRecordings.first(where: { $0.id == meetingId })?.transcriptText?.trimmingCharacters(in: .whitespacesAndNewlines),
- existing.isEmpty == false {
- transcriptText = existing
- } else {
- let transcript = try await aiCompanionFetchOrGenerateTranscript(
- meetingId: meetingId,
- interactiveAuth: true,
- presentingWindow: presentingWindow
- )
- await MainActor.run {
- _ = self.aiCompanionUpdateRecording(meetingId: meetingId) { recording in
- recording.transcriptStatusRaw = MeetingTranscriptStatus.ready.rawValue
- recording.transcriptSourceRaw = transcript.source.rawValue
- recording.transcriptText = transcript.text
- recording.transcriptSegmentsJSON = transcript.segmentsJSON
- recording.transcriptErrorMessage = nil
- }
- self.aiCompanionRefreshTranscriptStatusLabels(forMeetingID: meetingId)
- }
- transcriptText = transcript.text
- }
- await MainActor.run {
- self.aiCompanionNotesProgressByMeetingId[meetingId] = "Generating notes with GPT..."
- self.aiCompanionRefreshNotesStatusLabels(forMeetingID: meetingId)
- }
- return try await meetingNotesService.generateNotes(from: transcriptText)
- }
- @objc private func aiCompanionStopRecordingTapped(_ sender: NSButton) {
- finishActiveMeetingRecording()
- }
- private func aiCompanionAudioTimeControlObserverResetForFailure() {
- aiCompanionAudioPlayer?.pause()
- aiCompanionAudioPlayer = nil
- aiCompanionLocalAudioPlayer?.stop()
- aiCompanionLocalAudioPlayer = nil
- aiCompanionTimeControlObserver = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- }
- private func aiCompanionStartSpeech(forButtonId buttonId: ObjectIdentifier) {
- // Stop any remote audio playback first.
- aiCompanionAudioPlayer?.pause()
- aiCompanionAudioPlayer = nil
- aiCompanionTimeControlObserver = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- aiCompanionNoProgressWorkItem?.cancel()
- aiCompanionNoProgressWorkItem = nil
- aiCompanionIsUsingSpeech = true
- aiCompanionCurrentlySpeakingButtonId = buttonId
- if let button = aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
- button.title = "Pause Audio"
- }
- aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Speaking..."
- let text = aiCompanionSpeechTextByView[buttonId] ?? "Ended meeting."
- let utterance = AVSpeechUtterance(string: text)
- utterance.rate = 0.5
- utterance.volume = 1.0
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionSpeechSynthesizer.speak(utterance)
- }
- private func aiCompanionAudioDidFinish() {
- guard let button = aiCompanionCurrentlyPlayingButton else { return }
- let buttonId = ObjectIdentifier(button)
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionIsUsingSpeech = false
- aiCompanionCurrentlySpeakingButtonId = nil
- button.title = "Play Audio"
- aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"
- aiCompanionAudioPlayer?.pause()
- aiCompanionAudioPlayer = nil
- aiCompanionLocalAudioPlayer?.stop()
- aiCompanionLocalAudioPlayer = nil
- aiCompanionCurrentlyPlayingURL = nil
- aiCompanionCurrentlyPlayingButton = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- aiCompanionTimeControlObserver = nil
- }
- private func aiCompanionAudioDidFail(notification: Notification) {
- guard let button = aiCompanionCurrentlyPlayingButton else { return }
- let buttonId = ObjectIdentifier(button)
- aiCompanionSpeechSynthesizer.stopSpeaking(at: .immediate)
- aiCompanionIsUsingSpeech = false
- aiCompanionCurrentlySpeakingButtonId = nil
- button.title = "Play Audio"
- var message = "Failed to play audio"
- if let item = notification.object as? AVPlayerItem, let error = item.error {
- message = "Failed: \(error.localizedDescription)"
- }
- aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = message
- aiCompanionAudioPlayer?.pause()
- aiCompanionAudioPlayer = nil
- aiCompanionLocalAudioPlayer?.stop()
- aiCompanionLocalAudioPlayer = nil
- aiCompanionCurrentlyPlayingURL = nil
- aiCompanionCurrentlyPlayingButton = nil
- if let token = aiCompanionPlaybackEndObserver { NotificationCenter.default.removeObserver(token) }
- if let token = aiCompanionPlaybackFailedObserver { NotificationCenter.default.removeObserver(token) }
- aiCompanionPlaybackEndObserver = nil
- aiCompanionPlaybackFailedObserver = nil
- aiCompanionTimeControlObserver = nil
- }
- @MainActor
- private func aiCompanionPresentTranscriptWindow(meetingTitle: String, initialText: String) {
- if let window = aiCompanionTranscriptWindow, let textView = aiCompanionTranscriptTextView {
- window.title = "Transcript - \(meetingTitle)"
- textView.string = initialText
- window.makeKeyAndOrderFront(nil)
- NSApp.activate(ignoringOtherApps: true)
- return
- }
- let windowWidth: CGFloat = 640
- let windowHeight: CGFloat = 560
- let window = NSWindow(
- contentRect: NSRect(x: 0, y: 0, width: windowWidth, height: windowHeight),
- styleMask: [.titled, .closable, .resizable],
- backing: .buffered,
- defer: false
- )
- window.isReleasedWhenClosed = false
- window.title = "Transcript - \(meetingTitle)"
- window.center()
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- let scroll = NSScrollView()
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.drawsBackground = false
- scroll.hasVerticalScroller = true
- let textView = NSTextView()
- textView.isEditable = false
- textView.isSelectable = true
- textView.backgroundColor = .clear
- textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
- textView.string = initialText
- textView.textContainer?.widthTracksTextView = true
- scroll.documentView = textView
- root.addSubview(scroll)
- NSLayoutConstraint.activate([
- scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- scroll.topAnchor.constraint(equalTo: root.topAnchor),
- scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor)
- ])
- window.contentView = root
- window.makeKeyAndOrderFront(nil)
- NSApp.activate(ignoringOtherApps: true)
- aiCompanionTranscriptWindow = window
- aiCompanionTranscriptTextView = textView
- }
- @MainActor
- private func aiCompanionPresentNotesWindow(meetingTitle: String, initialText: String) {
- guard let hostWindow = view.window else { return }
- let hostIsDarkMode = darkModeEnabled
- let panelAppearanceName: NSAppearance.Name = hostIsDarkMode ? .darkAqua : .aqua
- let outerBackgroundColor: NSColor = hostIsDarkMode ? .windowBackgroundColor : NSColor(calibratedWhite: 0.98, alpha: 1.0)
- let headerBackgroundColor: NSColor = hostIsDarkMode ? .controlBackgroundColor : NSColor(calibratedWhite: 0.93, alpha: 1.0)
- if let panel = aiCompanionNotesPanel, let textView = aiCompanionNotesTextView {
- panel.title = "Notes - \(meetingTitle)"
- panel.appearance = NSAppearance(named: panelAppearanceName)
- panel.backgroundColor = outerBackgroundColor
- textView.string = initialText
- aiCompanionNotesRootView?.layer?.backgroundColor = outerBackgroundColor.cgColor
- aiCompanionNotesHeaderView?.layer?.backgroundColor = headerBackgroundColor.cgColor
- aiCompanionNotesTitleLabel?.textColor = hostIsDarkMode ? .labelColor : .black
- aiCompanionNotesSubtitleLabel?.stringValue = meetingTitle
- if hostWindow.attachedSheet !== panel {
- hostWindow.beginSheet(panel, completionHandler: nil)
- }
- aiCompanionStartNotesOutsideClickMonitor()
- panel.makeKeyAndOrderFront(nil)
- NSApp.activate(ignoringOtherApps: true)
- return
- }
- let panelWidth: CGFloat = 720
- let panelHeight: CGFloat = 540
- let panel = NSPanel(
- contentRect: NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight),
- styleMask: [.titled, .closable],
- backing: .buffered,
- defer: false
- )
- panel.isReleasedWhenClosed = false
- panel.title = "Notes - \(meetingTitle)"
- panel.isFloatingPanel = false
- panel.hidesOnDeactivate = false
- panel.delegate = self
- panel.appearance = NSAppearance(named: panelAppearanceName)
- panel.backgroundColor = outerBackgroundColor
- panel.standardWindowButton(.zoomButton)?.isHidden = true
- panel.standardWindowButton(.miniaturizeButton)?.isHidden = true
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- root.wantsLayer = true
- root.layer?.backgroundColor = outerBackgroundColor.cgColor
- let header = NSView()
- header.translatesAutoresizingMaskIntoConstraints = false
- header.wantsLayer = true
- header.layer?.backgroundColor = headerBackgroundColor.cgColor
- header.layer?.cornerRadius = 10
- let headingColor: NSColor = hostIsDarkMode ? .labelColor : .black
- let titleLabel = textLabel("Meeting Notes", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: headingColor)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- let subtitleLabel = textLabel(meetingTitle, font: NSFont.systemFont(ofSize: 12, weight: .regular), color: .secondaryLabelColor)
- subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
- subtitleLabel.lineBreakMode = .byTruncatingTail
- let scroll = NSScrollView()
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.drawsBackground = true
- scroll.backgroundColor = NSColor.textBackgroundColor
- scroll.hasVerticalScroller = true
- scroll.hasHorizontalScroller = false
- scroll.borderType = .bezelBorder
- let textView = NSTextView()
- textView.isEditable = false
- textView.isSelectable = true
- textView.backgroundColor = NSColor.textBackgroundColor
- textView.textColor = NSColor.labelColor
- textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
- textView.string = initialText
- textView.textContainer?.widthTracksTextView = true
- textView.textContainerInset = NSSize(width: 10, height: 10)
- let copyButton = NSButton(title: "Copy", target: self, action: #selector(aiCompanionCopyNotesTapped(_:)))
- copyButton.translatesAutoresizingMaskIntoConstraints = false
- copyButton.bezelStyle = .rounded
- let closeButton = NSButton(title: "Close", target: self, action: #selector(aiCompanionCloseNotesTapped(_:)))
- closeButton.translatesAutoresizingMaskIntoConstraints = false
- closeButton.bezelStyle = .rounded
- scroll.documentView = textView
- header.addSubview(titleLabel)
- header.addSubview(subtitleLabel)
- header.addSubview(copyButton)
- header.addSubview(closeButton)
- root.addSubview(header)
- root.addSubview(scroll)
- NSLayoutConstraint.activate([
- header.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
- header.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
- header.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
- titleLabel.topAnchor.constraint(equalTo: header.topAnchor, constant: 12),
- titleLabel.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 12),
- titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: copyButton.leadingAnchor, constant: -12),
- subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
- subtitleLabel.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 12),
- subtitleLabel.trailingAnchor.constraint(lessThanOrEqualTo: copyButton.leadingAnchor, constant: -12),
- subtitleLabel.bottomAnchor.constraint(equalTo: header.bottomAnchor, constant: -12),
- copyButton.centerYAnchor.constraint(equalTo: header.centerYAnchor),
- copyButton.trailingAnchor.constraint(equalTo: closeButton.leadingAnchor, constant: -8),
- closeButton.centerYAnchor.constraint(equalTo: header.centerYAnchor),
- closeButton.trailingAnchor.constraint(equalTo: header.trailingAnchor, constant: -12),
- scroll.topAnchor.constraint(equalTo: header.bottomAnchor, constant: 12),
- scroll.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
- scroll.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
- scroll.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16)
- ])
- panel.contentView = root
- hostWindow.beginSheet(panel, completionHandler: nil)
- aiCompanionStartNotesOutsideClickMonitor()
- panel.makeKeyAndOrderFront(nil)
- NSApp.activate(ignoringOtherApps: true)
- aiCompanionNotesPanel = panel
- aiCompanionNotesRootView = root
- aiCompanionNotesHeaderView = header
- aiCompanionNotesTitleLabel = titleLabel
- aiCompanionNotesSubtitleLabel = subtitleLabel
- aiCompanionNotesTextView = textView
- aiCompanionNotesCopyButton = copyButton
- aiCompanionNotesCloseButton = closeButton
- }
- @objc private func aiCompanionCopyNotesTapped(_ sender: NSButton) {
- guard let notes = aiCompanionNotesTextView?.string, notes.isEmpty == false else { return }
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(notes, forType: .string)
- sender.title = "Copied"
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in
- guard self?.aiCompanionNotesCopyButton === sender else { return }
- sender.title = "Copy"
- }
- }
- @objc private func aiCompanionCloseNotesTapped(_ sender: NSButton) {
- aiCompanionCloseNotesPanel()
- }
- private func aiCompanionStartNotesOutsideClickMonitor() {
- guard aiCompanionNotesOutsideClickMonitor == nil else { return }
- aiCompanionNotesOutsideClickMonitor = NSEvent.addLocalMonitorForEvents(
- matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
- ) { [weak self] event in
- guard let self, let panel = self.aiCompanionNotesPanel else { return event }
- if event.window === panel { return event }
- self.aiCompanionCloseNotesPanel()
- return event
- }
- }
- private func aiCompanionStopNotesOutsideClickMonitor() {
- guard let monitor = aiCompanionNotesOutsideClickMonitor else { return }
- NSEvent.removeMonitor(monitor)
- aiCompanionNotesOutsideClickMonitor = nil
- }
- private func aiCompanionCloseNotesPanel() {
- guard let panel = aiCompanionNotesPanel else { return }
- aiCompanionStopNotesOutsideClickMonitor()
- if let hostWindow = view.window, hostWindow.attachedSheet === panel {
- hostWindow.endSheet(panel)
- }
- panel.orderOut(nil)
- }
- private func aiCompanionMeetMeetingCode(from meetURL: URL) -> String? {
- // Typical: https://meet.google.com/abc-defg-hij
- guard let host = meetURL.host?.lowercased(),
- host == "meet.google.com" || host.hasSuffix(".meet.google.com") else { return nil }
- let codeCandidate = meetURL.pathComponents.filter { !$0.isEmpty }.last
- guard let codeCandidate else { return nil }
- // Allow flexible token shapes; Meet codes are usually 3 hyphen-separated chunks.
- let cleaned = codeCandidate.trimmingCharacters(in: .whitespacesAndNewlines)
- let parts = cleaned.split(separator: "-")
- guard parts.count >= 3 else { return nil }
- return cleaned
- }
- private func aiCompanionSelectConferenceRecord(for meeting: ScheduledMeeting, from records: [ConferenceRecord]) -> ConferenceRecord? {
- // Prefer a record whose time window overlaps the calendar meeting.
- let overlapping = records.filter { r in
- guard let start = r.startTime, let end = r.endTime else { return false }
- return start <= meeting.endDate && end >= meeting.startDate
- }
- if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
- return best
- }
- // Fallback: choose the most recent one we can.
- return records.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
- }
- private func aiCompanionSelectTranscript(for meeting: ScheduledMeeting, from transcripts: [Transcript]) -> Transcript? {
- let overlapping = transcripts.filter { t in
- guard let start = t.startTime, let end = t.endTime else { return false }
- return start <= meeting.endDate && end >= meeting.startDate
- }
- if let best = overlapping.sorted(by: { ($0.endTime ?? .distantPast) > ($1.endTime ?? .distantPast) }).first {
- return best
- }
- return transcripts.sorted(by: { ($0.startTime ?? .distantPast) > ($1.startTime ?? .distantPast) }).first
- }
- private func aiCompanionFormatTranscriptText(entries: [TranscriptEntry]) -> String {
- let lines = entries.compactMap { entry -> String? in
- guard let raw = entry.text else { return nil }
- let t = raw.trimmingCharacters(in: .whitespacesAndNewlines)
- guard t.isEmpty == false else { return nil }
- let speaker = entry.participant?.trimmingCharacters(in: .whitespacesAndNewlines)
- guard let speaker, speaker.isEmpty == false else { return t }
- return "\(speaker): \(t)"
- }
- if lines.isEmpty { return "(No transcript entries found.)" }
- return lines.joined(separator: "\n")
- }
- private func aiCompanionFetchTranscriptText(for meeting: ScheduledMeeting, accessToken: String) async throws -> String {
- guard let meetingCode = aiCompanionMeetMeetingCode(from: meeting.meetURL) else {
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 1,
- userInfo: [NSLocalizedDescriptionKey: "Couldn't determine Meet meeting code from URL."]
- )
- }
- // Resolve `spaces/{meetingCode}` into a stable space resource name (`spaces/{spaceId}`).
- let space = try await googleMeetClient.getSpace(accessToken: accessToken, spaceNameOrMeetingCode: "spaces/\(meetingCode)")
- let spaceName = space.name ?? "spaces/\(meetingCode)"
- let records = try await googleMeetClient.listConferenceRecords(accessToken: accessToken, spaceResourceName: spaceName)
- guard let conferenceRecord = aiCompanionSelectConferenceRecord(for: meeting, from: records),
- let conferenceRecordName = conferenceRecord.name else {
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 2,
- userInfo: [NSLocalizedDescriptionKey: "No conference record found for this meeting."]
- )
- }
- let transcripts = try await googleMeetClient.listTranscripts(accessToken: accessToken, conferenceRecordName: conferenceRecordName)
- guard let transcript = aiCompanionSelectTranscript(for: meeting, from: transcripts),
- let transcriptName = transcript.name else {
- throw NSError(
- domain: "AiCompanionTranscript",
- code: 3,
- userInfo: [NSLocalizedDescriptionKey: "No transcript found for this meeting."]
- )
- }
- let entries = try await googleMeetClient.listTranscriptEntries(accessToken: accessToken, transcriptName: transcriptName)
- return aiCompanionFormatTranscriptText(entries: entries)
- }
- private func makePlaceholderPage(title: String, subtitle: String) -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let titleLabel = textLabel(title, font: typography.pageTitle, color: palette.textPrimary)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- let sub = textLabel(subtitle, font: typography.fieldLabel, color: palette.textSecondary)
- sub.translatesAutoresizingMaskIntoConstraints = false
- panel.addSubview(titleLabel)
- panel.addSubview(sub)
- NSLayoutConstraint.activate([
- titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- titleLabel.topAnchor.constraint(equalTo: panel.topAnchor),
- sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8)
- ])
- return panel
- }
- private func makeSettingsPageContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let scroll = NSScrollView()
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.drawsBackground = false
- scroll.hasHorizontalScroller = false
- scroll.hasVerticalScroller = true
- scroll.autohidesScrollers = true
- scroll.borderType = .noBorder
- scroll.scrollerStyle = .overlay
- scroll.automaticallyAdjustsContentInsets = false
- let clip = TopAlignedClipView()
- clip.drawsBackground = false
- scroll.contentView = clip
- panel.addSubview(scroll)
- let content = NSView()
- content.translatesAutoresizingMaskIntoConstraints = false
- scroll.documentView = content
- let card = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
- card.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
- content.addSubview(card)
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.orientation = .vertical
- stack.spacing = 18
- stack.alignment = .leading
- card.addSubview(stack)
- let pageTitle = textLabel("Settings", font: typography.pageTitle, color: palette.textPrimary)
- let pageSubtitle = textLabel("Manage appearance, account, and app options.", font: typography.fieldLabel, color: palette.textSecondary)
- stack.addArrangedSubview(pageTitle)
- stack.addArrangedSubview(pageSubtitle)
- stack.setCustomSpacing(24, after: pageSubtitle)
- let appearanceTitle = textLabel("Appearance", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(appearanceTitle)
- let darkModeRow = makeSettingsDarkModeRow()
- stack.addArrangedSubview(darkModeRow)
- darkModeRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- stack.setCustomSpacing(24, after: darkModeRow)
- let aiCompanionTitle = textLabel("AI Companion", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(aiCompanionTitle)
- let language1Row = makeSettingsSpeechLanguageRow(title: "Preferred Language 1", isPrimary: true)
- stack.addArrangedSubview(language1Row)
- language1Row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- let language2Row = makeSettingsSpeechLanguageRow(title: "Preferred Language 2", isPrimary: false)
- stack.addArrangedSubview(language2Row)
- language2Row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- stack.setCustomSpacing(24, after: language2Row)
- let accountTitle = textLabel("Account", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(accountTitle)
- let googleAccountRow = makeSettingsGoogleAccountRow()
- stack.addArrangedSubview(googleAccountRow)
- googleAccountRow.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- stack.setCustomSpacing(24, after: googleAccountRow)
- let appTitle = textLabel("App", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(appTitle)
- if shouldShowRateUsInSettings {
- let rateButton = makeSettingsActionButton(icon: "★", title: "Rate Us", action: .rateUs)
- stack.addArrangedSubview(rateButton)
- rateButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- }
- let shareButton = makeSettingsActionButton(icon: "⤴︎", title: "Share App", action: .shareApp)
- stack.addArrangedSubview(shareButton)
- shareButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- if storeKitCoordinator.hasPremiumAccess && !storeKitCoordinator.hasLifetimeAccess {
- let upgradeButton = makeSettingsActionButton(icon: "⬆︎", title: "Upgrade", action: .upgrade)
- stack.addArrangedSubview(upgradeButton)
- upgradeButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- stack.setCustomSpacing(24, after: upgradeButton)
- } else {
- stack.setCustomSpacing(24, after: shareButton)
- }
- if storeKitCoordinator.hasPremiumAccess {
- let notificationsTitle = textLabel("Notifications", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(notificationsTitle)
- let remindersSection = makeSettingsRemindersSection()
- stack.addArrangedSubview(remindersSection)
- remindersSection.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- stack.setCustomSpacing(24, after: remindersSection)
- }
- let legalTitle = textLabel("Help & Legal", font: typography.joinWithURLTitle, color: palette.textPrimary)
- stack.addArrangedSubview(legalTitle)
- let privacyButton = makeSettingsActionButton(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy)
- stack.addArrangedSubview(privacyButton)
- privacyButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- let supportButton = makeSettingsActionButton(icon: "💬", title: "Support", action: .support)
- stack.addArrangedSubview(supportButton)
- supportButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- let termsButton = makeSettingsActionButton(icon: "📄", title: "Terms of Services", action: .termsOfServices)
- stack.addArrangedSubview(termsButton)
- termsButton.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- NSLayoutConstraint.activate([
- scroll.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
- scroll.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
- scroll.topAnchor.constraint(equalTo: panel.topAnchor),
- scroll.bottomAnchor.constraint(equalTo: panel.bottomAnchor),
- content.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
- content.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
- content.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
- content.bottomAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.bottomAnchor),
- content.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor),
- card.centerXAnchor.constraint(equalTo: content.centerXAnchor),
- card.topAnchor.constraint(equalTo: content.topAnchor, constant: 36),
- content.bottomAnchor.constraint(greaterThanOrEqualTo: card.bottomAnchor, constant: 36),
- card.widthAnchor.constraint(lessThanOrEqualToConstant: 620),
- card.widthAnchor.constraint(greaterThanOrEqualToConstant: 460),
- card.leadingAnchor.constraint(greaterThanOrEqualTo: content.leadingAnchor, constant: 30),
- card.trailingAnchor.constraint(lessThanOrEqualTo: content.trailingAnchor, constant: -30),
- stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 28),
- stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -28),
- stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 24),
- stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -24)
- ])
- return panel
- }
- private func makeSettingsDarkModeRow() -> NSView {
- let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 52).isActive = true
- styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let icon = textLabel("◐", font: NSFont.systemFont(ofSize: 18, weight: .medium), color: palette.textPrimary)
- let title = textLabel("Dark Mode", font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
- let toggle = NSSwitch()
- toggle.translatesAutoresizingMaskIntoConstraints = false
- toggle.state = darkModeEnabled ? .on : .off
- toggle.target = self
- toggle.action = #selector(settingsPageDarkModeToggled(_:))
- row.addSubview(icon)
- row.addSubview(title)
- row.addSubview(toggle)
- NSLayoutConstraint.activate([
- icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
- icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
- title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
- toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
- ])
- return row
- }
- private func makeSettingsSpeechLanguageRow(title: String, isPrimary: Bool) -> NSView {
- let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 72).isActive = true
- styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
- let popup = NSPopUpButton(frame: .zero, pullsDown: false)
- popup.translatesAutoresizingMaskIntoConstraints = false
- popup.target = self
- popup.action = #selector(settingsPageSpeechLanguageChanged(_:))
- let options = aiCompanionSupportedSpeechLocaleOptions()
- if isPrimary == false {
- popup.addItem(withTitle: "None")
- popup.lastItem?.representedObject = ""
- }
- for option in options {
- popup.addItem(withTitle: option.displayName)
- popup.lastItem?.representedObject = option.identifier
- }
- if isPrimary {
- let selected = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage1DefaultsKey)
- ?? options.first?.identifier
- ?? Locale.current.identifier
- selectSettingsPageLanguage(identifier: selected, in: popup)
- settingsPagePrimaryLanguagePopup = popup
- } else {
- if let selected = UserDefaults.standard.string(forKey: aiCompanionPreferredLanguage2DefaultsKey),
- selected.isEmpty == false {
- selectSettingsPageLanguage(identifier: selected, in: popup)
- } else {
- popup.selectItem(at: 0)
- }
- settingsPageSecondaryLanguagePopup = popup
- }
- row.addSubview(titleLabel)
- row.addSubview(popup)
- NSLayoutConstraint.activate([
- titleLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
- titleLabel.topAnchor.constraint(equalTo: row.topAnchor, constant: 10),
- titleLabel.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
- popup.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
- popup.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
- popup.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8),
- popup.heightAnchor.constraint(equalToConstant: 28)
- ])
- return row
- }
- private func selectSettingsPageLanguage(identifier: String, in popup: NSPopUpButton) {
- for item in popup.itemArray {
- if let value = item.representedObject as? String, value == identifier {
- popup.select(item)
- return
- }
- }
- }
- @objc private func settingsPageSpeechLanguageChanged(_ sender: NSPopUpButton) {
- guard let primary = settingsPagePrimaryLanguagePopup?.selectedItem?.representedObject as? String,
- primary.isEmpty == false else { return }
- var secondary: String? = settingsPageSecondaryLanguagePopup?.selectedItem?.representedObject as? String
- if secondary?.isEmpty == true {
- secondary = nil
- }
- if let secondaryValue = secondary,
- secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
- secondary = nil
- settingsPageSecondaryLanguagePopup?.selectItem(at: 0)
- }
- updateAiCompanionPreferredSpeechLanguages(primary: primary, secondary: secondary)
- }
- private func makeSettingsRemindersSection() -> NSView {
- let container = NSStackView()
- container.translatesAutoresizingMaskIntoConstraints = false
- container.orientation = .vertical
- container.spacing = 1
- container.alignment = .leading
- let masterRow = makeReminderToggleRow(
- icon: "🔔",
- title: "Reminders",
- state: ReminderPreferences.remindersEnabled,
- action: #selector(settingsReminderMasterToggled(_:)),
- isSubRow: false
- )
- container.addArrangedSubview(masterRow)
- masterRow.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
- let subAlpha: CGFloat = ReminderPreferences.remindersEnabled ? 1.0 : 0.4
- let day1Row = makeReminderToggleRow(
- icon: "📅",
- title: "1 Day Before",
- state: ReminderPreferences.remind1Day,
- action: #selector(settingsReminder1DayToggled(_:)),
- isSubRow: true
- )
- day1Row.alphaValue = subAlpha
- container.addArrangedSubview(day1Row)
- day1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
- let hours12Row = makeReminderToggleRow(
- icon: "🕛",
- title: "12 Hours Before",
- state: ReminderPreferences.remind12Hours,
- action: #selector(settingsReminder12HoursToggled(_:)),
- isSubRow: true
- )
- hours12Row.alphaValue = subAlpha
- container.addArrangedSubview(hours12Row)
- hours12Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
- let hour1Row = makeReminderToggleRow(
- icon: "⏰",
- title: "1 Hour Before",
- state: ReminderPreferences.remind1Hour,
- action: #selector(settingsReminder1HourToggled(_:)),
- isSubRow: true
- )
- hour1Row.alphaValue = subAlpha
- container.addArrangedSubview(hour1Row)
- hour1Row.widthAnchor.constraint(equalTo: container.widthAnchor).isActive = true
- settingsReminderMasterSwitch = masterRow.subviews.compactMap { $0 as? NSSwitch }.first
- settingsReminder1DaySwitch = day1Row.subviews.compactMap { $0 as? NSSwitch }.first
- settingsReminder12HoursSwitch = hours12Row.subviews.compactMap { $0 as? NSSwitch }.first
- settingsReminder1HourSwitch = hour1Row.subviews.compactMap { $0 as? NSSwitch }.first
- return container
- }
- private func makeReminderToggleRow(icon: String, title: String, state: Bool, action: Selector, isSubRow: Bool) -> NSView {
- let row = roundedContainer(cornerRadius: 10, color: isSubRow ? palette.inputBackground.withAlphaComponent(0.6) : palette.inputBackground)
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 48).isActive = true
- styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: isSubRow ? 15 : 17, weight: .medium), color: palette.textPrimary)
- let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: isSubRow ? 14 : 15, weight: isSubRow ? .regular : .semibold), color: palette.textPrimary)
- if isSubRow {
- titleLabel.textColor = palette.textSecondary
- }
- let toggle = NSSwitch()
- toggle.translatesAutoresizingMaskIntoConstraints = false
- toggle.state = state ? .on : .off
- toggle.target = self
- toggle.action = action
- row.addSubview(iconLabel)
- row.addSubview(titleLabel)
- row.addSubview(toggle)
- NSLayoutConstraint.activate([
- iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: isSubRow ? 30 : 14),
- iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
- titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
- toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
- ])
- return row
- }
- @objc private func settingsReminderMasterToggled(_ sender: NSSwitch) {
- let enabled = sender.state == .on
- ReminderPreferences.remindersEnabled = enabled
- let subAlpha: CGFloat = enabled ? 1.0 : 0.4
- settingsReminder1DaySwitch?.superview?.alphaValue = subAlpha
- settingsReminder12HoursSwitch?.superview?.alphaValue = subAlpha
- settingsReminder1HourSwitch?.superview?.alphaValue = subAlpha
- if enabled {
- MeetingReminderManager.shared.requestPermissionIfNeeded { [weak self] _ in
- guard let self else { return }
- MeetingReminderManager.shared.scheduleReminders(for: self.scheduleCachedMeetings)
- }
- } else {
- MeetingReminderManager.shared.cancelAllReminders()
- }
- }
- @objc private func settingsReminder1DayToggled(_ sender: NSSwitch) {
- ReminderPreferences.remind1Day = sender.state == .on
- MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
- }
- @objc private func settingsReminder12HoursToggled(_ sender: NSSwitch) {
- ReminderPreferences.remind12Hours = sender.state == .on
- MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
- }
- @objc private func settingsReminder1HourToggled(_ sender: NSSwitch) {
- ReminderPreferences.remind1Hour = sender.state == .on
- MeetingReminderManager.shared.scheduleReminders(for: scheduleCachedMeetings)
- }
- private func makeSettingsGoogleAccountRow() -> NSView {
- let row = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
- row.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(row, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let signedIn = hasGoogleSessionAvailable()
- let titleText = signedIn ? (scheduleCurrentProfile?.name ?? "Google account connected") : "Google account not connected"
- let subtitleText = signedIn ? (scheduleCurrentProfile?.email ?? "Signed in") : "Sign in to sync your meetings and calendar."
- let title = textLabel(titleText, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
- let subtitle = textLabel(subtitleText, font: NSFont.systemFont(ofSize: 13, weight: .regular), color: palette.textSecondary)
- subtitle.maximumNumberOfLines = 2
- subtitle.lineBreakMode = .byTruncatingTail
- let actionButton = NSButton(title: signedIn ? "Sign Out" : "Sign in with Google", target: self, action: #selector(settingsGoogleActionButtonClicked(_:)))
- actionButton.translatesAutoresizingMaskIntoConstraints = false
- actionButton.bezelStyle = .rounded
- actionButton.controlSize = .regular
- row.addSubview(title)
- row.addSubview(subtitle)
- row.addSubview(actionButton)
- NSLayoutConstraint.activate([
- row.heightAnchor.constraint(equalToConstant: 78),
- title.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 14),
- title.topAnchor.constraint(equalTo: row.topAnchor, constant: 12),
- subtitle.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 4),
- subtitle.trailingAnchor.constraint(lessThanOrEqualTo: actionButton.leadingAnchor, constant: -14),
- actionButton.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -14),
- actionButton.centerYAnchor.constraint(equalTo: row.centerYAnchor)
- ])
- return row
- }
- private func makeSettingsActionButton(icon: String, title: String, action: SettingsAction) -> NSButton {
- let button = HoverButton(title: "", target: self, action: #selector(settingsPageActionButtonClicked(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.wantsLayer = true
- button.layer?.cornerRadius = 10
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- button.heightAnchor.constraint(equalToConstant: 46).isActive = true
- button.tag = action.rawValue
- let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 17, weight: .medium), color: palette.textPrimary)
- let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .semibold), color: palette.textPrimary)
- button.addSubview(iconLabel)
- button.addSubview(titleLabel)
- NSLayoutConstraint.activate([
- iconLabel.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 14),
- iconLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor),
- titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
- titleLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor)
- ])
- return button
- }
- @objc private func settingsPageDarkModeToggled(_ sender: NSSwitch) {
- setDarkMode(sender.state == .on)
- }
- @objc private func settingsPageActionButtonClicked(_ sender: NSButton) {
- guard let action = SettingsAction(rawValue: sender.tag) else { return }
- let clickPoint: NSPoint?
- if let event = NSApp.currentEvent {
- let pointInWindow = event.locationInWindow
- clickPoint = sender.convert(pointInWindow, from: nil)
- } else {
- clickPoint = nil
- }
- handleSettingsAction(action, sourceView: sender, clickLocationInSourceView: clickPoint)
- }
- @objc private func settingsGoogleActionButtonClicked(_ sender: NSButton) {
- if hasGoogleSessionAvailable() == false {
- scheduleConnectClicked()
- } else {
- performGoogleSignOut()
- }
- }
- func makeBrowseWebContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let titleLabel = textLabel("Browse the web", font: typography.pageTitle, color: palette.textPrimary)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- let sub = textLabel(
- "Open sites in the in-app browser (back, forward, reload, address bar). OAuth and “Continue in browser” flows stay inside the app.",
- font: typography.fieldLabel,
- color: palette.textSecondary
- )
- sub.translatesAutoresizingMaskIntoConstraints = false
- sub.maximumNumberOfLines = 0
- sub.lineBreakMode = .byWordWrapping
- let fieldShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
- fieldShell.translatesAutoresizingMaskIntoConstraints = false
- fieldShell.heightAnchor.constraint(equalToConstant: 44).isActive = true
- styleSurface(fieldShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let field = NSTextField(string: "")
- field.translatesAutoresizingMaskIntoConstraints = false
- field.isEditable = true
- field.isBordered = false
- field.drawsBackground = false
- field.focusRingType = .none
- field.font = NSFont.systemFont(ofSize: 14, weight: .regular)
- field.textColor = palette.textPrimary
- field.placeholderString = "https://example.com or example.com"
- field.delegate = self
- browseAddressField = field
- fieldShell.addSubview(field)
- let openBtn = meetActionButton(
- title: "Open in app browser",
- color: palette.primaryBlue,
- textColor: .white,
- width: 220,
- action: #selector(browseOpenAddressClicked(_:))
- )
- let quickTitle = textLabel("Quick links", font: typography.joinWithURLTitle, color: palette.textPrimary)
- quickTitle.translatesAutoresizingMaskIntoConstraints = false
- let quickRow = NSStackView()
- quickRow.translatesAutoresizingMaskIntoConstraints = false
- quickRow.orientation = .horizontal
- quickRow.spacing = 10
- quickRow.addArrangedSubview(browseQuickLinkButton(title: "Google Meet", action: #selector(browseQuickLinkMeetClicked(_:))))
- quickRow.addArrangedSubview(browseQuickLinkButton(title: "Meet help", action: #selector(browseQuickLinkMeetHelpClicked(_:))))
- quickRow.addArrangedSubview(browseQuickLinkButton(title: "Zoom help", action: #selector(browseQuickLinkZoomHelpClicked(_:))))
- panel.addSubview(titleLabel)
- panel.addSubview(sub)
- panel.addSubview(fieldShell)
- panel.addSubview(openBtn)
- panel.addSubview(quickTitle)
- panel.addSubview(quickRow)
- NSLayoutConstraint.activate([
- titleLabel.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- titleLabel.topAnchor.constraint(equalTo: panel.topAnchor, constant: 26),
- titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
- sub.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- sub.trailingAnchor.constraint(lessThanOrEqualTo: panel.trailingAnchor, constant: -28),
- sub.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
- fieldShell.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- fieldShell.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- fieldShell.topAnchor.constraint(equalTo: sub.bottomAnchor, constant: 18),
- field.leadingAnchor.constraint(equalTo: fieldShell.leadingAnchor, constant: 12),
- field.trailingAnchor.constraint(equalTo: fieldShell.trailingAnchor, constant: -12),
- field.centerYAnchor.constraint(equalTo: fieldShell.centerYAnchor),
- openBtn.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- openBtn.topAnchor.constraint(equalTo: fieldShell.bottomAnchor, constant: 12),
- openBtn.heightAnchor.constraint(equalToConstant: 36),
- quickTitle.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- quickTitle.topAnchor.constraint(equalTo: openBtn.bottomAnchor, constant: 28),
- quickRow.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- quickRow.topAnchor.constraint(equalTo: quickTitle.bottomAnchor, constant: 10)
- ])
- return panel
- }
- private func browseQuickLinkButton(title: String, action: Selector) -> NSButton {
- let b = NSButton(title: title, target: self, action: action)
- b.translatesAutoresizingMaskIntoConstraints = false
- b.bezelStyle = .rounded
- b.font = NSFont.systemFont(ofSize: 13, weight: .medium)
- return b
- }
- private func applyWindowTitle(for page: SidebarPage) {
- let title: String
- switch page {
- case .joinMeetings:
- title = "App for Google Meet"
- case .photo:
- title = "Schedule"
- case .video:
- title = "Calendar"
- case .widgets:
- title = "Widgets"
- case .settings:
- title = "Settings"
- case .aiCompanion:
- title = "AI Companion"
- }
- view.window?.title = title
- }
- private func configureMainWindowChrome(_ window: NSWindow) {
- window.styleMask.insert(.fullSizeContentView)
- window.titleVisibility = .hidden
- window.titlebarAppearsTransparent = true
- window.isMovableByWindowBackground = true
- }
- private func updateSidebarAppearance() {
- for (page, row) in sidebarRowViews {
- applySidebarRowStyle(row, page: page, logoTemplate: logoTemplateForSidebarPage(page))
- }
- }
- private func logoTemplateForSidebarPage(_ page: SidebarPage) -> Bool {
- switch page {
- case .photo: return false
- case .joinMeetings, .video, .widgets, .settings, .aiCompanion: return true
- }
- }
- func makeSidebar() -> NSView {
- let sidebar = NSView()
- sidebar.translatesAutoresizingMaskIntoConstraints = false
- sidebar.wantsLayer = true
- sidebar.layer?.backgroundColor = palette.sidebarBackground.cgColor
- sidebar.layer?.borderColor = palette.separator.cgColor
- sidebar.layer?.borderWidth = 1
- sidebar.layer?.shadowColor = NSColor.black.cgColor
- sidebar.layer?.shadowOpacity = 0.18
- sidebar.layer?.shadowOffset = CGSize(width: 2, height: 0)
- sidebar.layer?.shadowRadius = 10
- sidebar.widthAnchor.constraint(equalToConstant: 210).isActive = true
- let sidebarTopInset: CGFloat = 44
- let appIconView = NSImageView()
- if let headerLogo = NSImage(named: "HeaderLogo") {
- headerLogo.isTemplate = false
- appIconView.image = headerLogo
- } else if let appIconImage = NSApplication.shared.applicationIconImage {
- appIconImage.isTemplate = false
- appIconView.image = appIconImage
- }
- appIconView.translatesAutoresizingMaskIntoConstraints = false
- appIconView.imageScaling = NSImageScaling.scaleProportionallyDown
- appIconView.imageAlignment = NSImageAlignment.alignCenter
- appIconView.contentTintColor = nil
- appIconView.widthAnchor.constraint(equalToConstant: 44).isActive = true
- appIconView.heightAnchor.constraint(equalToConstant: 44).isActive = true
- let titleRow = NSStackView(views: [
- appIconView,
- textLabel("Meetings", font: typography.sidebarBrand, color: palette.textPrimary)
- ])
- titleRow.translatesAutoresizingMaskIntoConstraints = false
- titleRow.orientation = NSUserInterfaceLayoutOrientation.horizontal
- titleRow.alignment = NSLayoutConstraint.Attribute.centerY
- titleRow.spacing = 16
- let menuStack = NSStackView()
- menuStack.translatesAutoresizingMaskIntoConstraints = false
- menuStack.orientation = .vertical
- menuStack.alignment = .leading
- menuStack.spacing = 10
- menuStack.addArrangedSubview(sidebarSectionTitle("Meetings"))
- let joinRow = sidebarItem("Join Meetings", icon: "", page: .joinMeetings, logoImageName: "JoinMeetingsLogo", logoIconWidth: 24, logoHeightMultiplier: 56.0 / 52.0)
- menuStack.addArrangedSubview(joinRow)
- sidebarRowViews[.joinMeetings] = joinRow
- menuStack.addArrangedSubview(sidebarSectionTitle("Planning"))
- let photoRow = sidebarItem("Schedule", icon: "", page: .photo, systemSymbolName: "clock.badge.checkmark")
- menuStack.addArrangedSubview(photoRow)
- sidebarRowViews[.photo] = photoRow
- let videoRow = sidebarItem("Calendar", icon: "", page: .video, systemSymbolName: "calendar")
- menuStack.addArrangedSubview(videoRow)
- sidebarRowViews[.video] = videoRow
- let widgetsRow = sidebarItem("Widgets", icon: "", page: .widgets, systemSymbolName: "square.grid.2x2.fill")
- menuStack.addArrangedSubview(widgetsRow)
- sidebarRowViews[.widgets] = widgetsRow
- let aiCompanionRow = sidebarItem("AI Companion", icon: "", page: .aiCompanion, systemSymbolName: "waveform")
- menuStack.addArrangedSubview(aiCompanionRow)
- sidebarRowViews[.aiCompanion] = aiCompanionRow
- menuStack.addArrangedSubview(sidebarSectionTitle("Additional"))
- let settingsRow = sidebarItem("Settings", icon: "", page: .settings, systemSymbolName: "gearshape.fill", logoHeightMultiplier: 1, showsDisclosure: true)
- menuStack.addArrangedSubview(settingsRow)
- sidebarRowViews[.settings] = settingsRow
- let premiumButton = sidebarPremiumButton()
- sidebar.addSubview(titleRow)
- sidebar.addSubview(menuStack)
- sidebar.addSubview(premiumButton)
- NSLayoutConstraint.activate([
- titleRow.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 16),
- titleRow.topAnchor.constraint(equalTo: sidebar.topAnchor, constant: sidebarTopInset),
- titleRow.trailingAnchor.constraint(lessThanOrEqualTo: sidebar.trailingAnchor, constant: -16),
- menuStack.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
- menuStack.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
- menuStack.topAnchor.constraint(equalTo: titleRow.bottomAnchor, constant: 20),
- menuStack.bottomAnchor.constraint(lessThanOrEqualTo: premiumButton.topAnchor, constant: -16),
- premiumButton.leadingAnchor.constraint(equalTo: sidebar.leadingAnchor, constant: 12),
- premiumButton.trailingAnchor.constraint(equalTo: sidebar.trailingAnchor, constant: -12),
- premiumButton.bottomAnchor.constraint(equalTo: sidebar.bottomAnchor, constant: -14)
- ])
- for subview in menuStack.arrangedSubviews {
- subview.widthAnchor.constraint(equalTo: menuStack.widthAnchor).isActive = true
- }
- return sidebar
- }
- func sidebarPremiumButton() -> NSView {
- let button = HoverTrackingView()
- button.translatesAutoresizingMaskIntoConstraints = false
- button.wantsLayer = true
- button.layer?.cornerRadius = 17
- button.layer?.backgroundColor = palette.primaryBlue.cgColor
- button.heightAnchor.constraint(equalToConstant: 34).isActive = true
- styleSurface(button, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: false)
- let icon = NSImageView()
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.imageScaling = .scaleProportionallyUpOrDown
- icon.contentTintColor = .white
- icon.image = premiumButtonSymbolImage(named: "star.fill")
- let title = textLabel("Get Premium", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: .white)
- button.addSubview(icon)
- button.addSubview(title)
- NSLayoutConstraint.activate([
- icon.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 12),
- icon.centerYAnchor.constraint(equalTo: button.centerYAnchor),
- icon.widthAnchor.constraint(equalToConstant: 14),
- icon.heightAnchor.constraint(equalToConstant: 14),
- title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 8),
- title.centerYAnchor.constraint(equalTo: button.centerYAnchor),
- title.trailingAnchor.constraint(lessThanOrEqualTo: button.trailingAnchor, constant: -12)
- ])
- button.onHoverChanged = { [weak self, weak button] hovering in
- guard let self, let button else { return }
- let isPremium = self.storeKitCoordinator.hasPremiumAccess
- let baseColor = isPremium
- ? NSColor(calibratedRed: 0.93, green: 0.73, blue: 0.16, alpha: 1.0)
- : self.palette.primaryBlue
- let borderColor = isPremium
- ? NSColor(calibratedRed: 0.78, green: 0.56, blue: 0.10, alpha: 1.0)
- : self.palette.primaryBlueBorder
- let hoverColor: NSColor
- let hoverBorderColor: NSColor
- if isPremium {
- // Darker rich-gold hover for stronger premium feedback.
- hoverColor = NSColor(calibratedRed: 0.84, green: 0.62, blue: 0.11, alpha: 1.0)
- hoverBorderColor = NSColor(calibratedRed: 0.67, green: 0.46, blue: 0.07, alpha: 1.0)
- } else {
- let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
- hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- hoverBorderColor = borderColor
- }
- button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button.layer?.shadowColor = NSColor.black.cgColor
- button.layer?.shadowOpacity = hovering ? (isPremium ? 0.30 : 0.20) : 0.14
- button.layer?.shadowOffset = CGSize(width: 0, height: -1)
- button.layer?.shadowRadius = hovering ? (isPremium ? 8 : 6) : 4
- self.styleSurface(button, borderColor: (hovering ? hoverBorderColor : borderColor), borderWidth: hovering ? 1.5 : 1, shadow: false)
- }
- button.onHoverChanged?(false)
- sidebarPremiumTitleLabel = title
- sidebarPremiumIconView = icon
- sidebarPremiumButtonView = button
- refreshSidebarPremiumButton()
- let click = NSClickGestureRecognizer(target: self, action: #selector(premiumButtonClicked(_:)))
- button.addGestureRecognizer(click)
- return button
- }
- func makeMainPanel() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- panel.wantsLayer = true
- panel.layer?.backgroundColor = palette.pageBackground.cgColor
- let authBar = scheduleTopAuthRow()
- authBar.translatesAutoresizingMaskIntoConstraints = false
- panel.addSubview(authBar)
- let host = NSView()
- host.translatesAutoresizingMaskIntoConstraints = false
- panel.addSubview(host)
- let hostTopToAuth = host.topAnchor.constraint(equalTo: authBar.bottomAnchor, constant: 20)
- let hostTopToPanel = host.topAnchor.constraint(equalTo: panel.topAnchor)
- hostTopToPanel.isActive = false
- NSLayoutConstraint.activate([
- authBar.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- authBar.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- authBar.topAnchor.constraint(equalTo: panel.safeAreaLayoutGuide.topAnchor, constant: 26),
- host.leadingAnchor.constraint(equalTo: panel.leadingAnchor),
- host.trailingAnchor.constraint(equalTo: panel.trailingAnchor),
- hostTopToAuth,
- host.bottomAnchor.constraint(equalTo: panel.bottomAnchor)
- ])
- mainContentHost = host
- mainPanelAuthBar = authBar
- mainContentHostTopToAuthConstraint = hostTopToAuth
- mainContentHostTopToPanelConstraint = hostTopToPanel
- if hasGoogleSessionAvailable(), let profile = scheduleCurrentProfile {
- applyGoogleProfile(profile)
- }
- // Preserve the currently selected page during rebuilds (e.g. dark mode toggle).
- showSidebarPage(selectedSidebarPage)
- return panel
- }
- func makeJoinMeetingsContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- let contentStack = NSStackView()
- contentStack.translatesAutoresizingMaskIntoConstraints = false
- contentStack.orientation = .vertical
- contentStack.spacing = 14
- contentStack.alignment = .leading
- let joinActions = meetJoinActionsRow()
- contentStack.addArrangedSubview(textLabel("Join Meetings", font: typography.pageTitle, color: palette.textPrimary))
- contentStack.addArrangedSubview(meetJoinSectionRow())
- contentStack.addArrangedSubview(joinActions)
- contentStack.setCustomSpacing(26, after: joinActions)
- let scheduleHeaderView = scheduleHeader()
- contentStack.addArrangedSubview(scheduleHeaderView)
- contentStack.setCustomSpacing(joinPageScheduleHeaderToDateSpacing, after: scheduleHeaderView)
- let dateHeading = textLabel(scheduleInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
- scheduleDateHeadingLabel = dateHeading
- contentStack.addArrangedSubview(dateHeading)
- contentStack.setCustomSpacing(joinPageDateToMeetingCardsSpacing, after: dateHeading)
- let cardsRow = scheduleCardsRow(meetings: [])
- contentStack.addArrangedSubview(cardsRow)
- panel.addSubview(contentStack)
- NSLayoutConstraint.activate([
- contentStack.leadingAnchor.constraint(equalTo: panel.leadingAnchor, constant: 28),
- contentStack.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -28),
- contentStack.topAnchor.constraint(equalTo: panel.topAnchor)
- ])
- Task { [weak self] in
- await self?.loadSchedule()
- }
- return panel
- }
- func makeSchedulePageContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- panel.userInterfaceLayoutDirection = .leftToRight
- let contentStack = NSStackView()
- contentStack.translatesAutoresizingMaskIntoConstraints = false
- contentStack.userInterfaceLayoutDirection = .leftToRight
- contentStack.orientation = .vertical
- contentStack.spacing = schedulePageStackSpacing
- contentStack.alignment = .width
- contentStack.distribution = .fill
- let header = schedulePageHeader()
- header.setContentHuggingPriority(.required, for: .vertical)
- header.setContentCompressionResistancePriority(.required, for: .vertical)
- contentStack.addArrangedSubview(header)
- contentStack.setCustomSpacing(schedulePageHeaderToDateSpacing, after: header)
- let heading = textLabel(schedulePageInitialHeadingText(), font: typography.dateHeading, color: palette.textSecondary)
- heading.alignment = .left
- heading.setContentHuggingPriority(.required, for: .vertical)
- heading.setContentCompressionResistancePriority(.required, for: .vertical)
- schedulePageDateHeadingLabel = heading
- contentStack.addArrangedSubview(heading)
- let rangeError = textLabel("", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: .systemRed)
- rangeError.alignment = .left
- rangeError.isHidden = true
- rangeError.setContentHuggingPriority(.required, for: .vertical)
- rangeError.setContentCompressionResistancePriority(.required, for: .vertical)
- schedulePageRangeErrorLabel = rangeError
- contentStack.addArrangedSubview(rangeError)
- let cardsContainer = makeSchedulePageCardsContainer()
- cardsContainer.setContentHuggingPriority(.defaultLow, for: .vertical)
- contentStack.addArrangedSubview(cardsContainer)
- panel.addSubview(contentStack)
- NSLayoutConstraint.activate([
- contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: schedulePageLeadingInset),
- contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -schedulePageTrailingInset),
- contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
- contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -16),
- header.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- heading.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- rangeError.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- cardsContainer.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
- ])
- Task { [weak self] in
- await self?.loadSchedule()
- }
- return panel
- }
- func makeCalendarPageContent() -> NSView {
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- panel.userInterfaceLayoutDirection = .leftToRight
- let contentStack = NSStackView()
- contentStack.translatesAutoresizingMaskIntoConstraints = false
- contentStack.userInterfaceLayoutDirection = .leftToRight
- contentStack.orientation = .vertical
- contentStack.spacing = 14
- contentStack.alignment = .width
- contentStack.distribution = .fill
- let titleRow = NSStackView()
- titleRow.translatesAutoresizingMaskIntoConstraints = false
- titleRow.userInterfaceLayoutDirection = .leftToRight
- titleRow.orientation = .horizontal
- titleRow.alignment = .centerY
- titleRow.distribution = .fill
- titleRow.spacing = 10
- let titleLabel = textLabel("Calendar", font: typography.pageTitle, color: palette.textPrimary)
- titleLabel.alignment = .left
- titleLabel.maximumNumberOfLines = 1
- titleLabel.lineBreakMode = .byTruncatingTail
- titleLabel.setContentHuggingPriority(.required, for: .horizontal)
- titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- spacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- let prevButton = makeCalendarHeaderPillButton(title: "‹", action: #selector(calendarPrevMonthPressed(_:)))
- prevButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
- let nextButton = makeCalendarHeaderPillButton(title: "›", action: #selector(calendarNextMonthPressed(_:)))
- nextButton.widthAnchor.constraint(equalToConstant: 46).isActive = true
- let monthLabel = textLabel("", font: NSFont.systemFont(ofSize: 16, weight: .semibold), color: palette.textSecondary)
- monthLabel.alignment = .right
- monthLabel.maximumNumberOfLines = 1
- monthLabel.lineBreakMode = .byTruncatingTail
- monthLabel.setContentHuggingPriority(.required, for: .horizontal)
- monthLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
- calendarPageMonthLabel = monthLabel
- let refreshButton = HoverButton(title: "", target: self, action: #selector(calendarRefreshPressed(_:)))
- refreshButton.translatesAutoresizingMaskIntoConstraints = false
- refreshButton.isBordered = false
- refreshButton.bezelStyle = .regularSquare
- refreshButton.wantsLayer = true
- refreshButton.layer?.cornerRadius = 15
- refreshButton.layer?.masksToBounds = true
- refreshButton.layer?.backgroundColor = palette.inputBackground.cgColor
- refreshButton.layer?.borderColor = palette.inputBorder.cgColor
- refreshButton.layer?.borderWidth = 1
- refreshButton.setButtonType(.momentaryChange)
- refreshButton.contentTintColor = palette.textSecondary
- refreshButton.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Sync calendar")
- refreshButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
- refreshButton.imagePosition = .imageOnly
- refreshButton.imageScaling = .scaleProportionallyDown
- refreshButton.focusRingType = .none
- refreshButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
- refreshButton.widthAnchor.constraint(equalToConstant: 32).isActive = true
- titleRow.addArrangedSubview(titleLabel)
- titleRow.addArrangedSubview(spacer)
- titleRow.addArrangedSubview(prevButton)
- titleRow.addArrangedSubview(nextButton)
- titleRow.addArrangedSubview(monthLabel)
- titleRow.addArrangedSubview(refreshButton)
- let weekdayRow = NSStackView()
- weekdayRow.translatesAutoresizingMaskIntoConstraints = false
- weekdayRow.userInterfaceLayoutDirection = .leftToRight
- weekdayRow.orientation = .horizontal
- weekdayRow.alignment = .centerY
- weekdayRow.distribution = .fillEqually
- weekdayRow.spacing = 12
- for symbol in calendarWeekdaySymbolsStartingAtFirstWeekday() {
- let label = textLabel(symbol, font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textMuted)
- label.alignment = .center
- label.maximumNumberOfLines = 1
- label.lineBreakMode = .byClipping
- weekdayRow.addArrangedSubview(label)
- }
- let gridStack = NSStackView()
- gridStack.translatesAutoresizingMaskIntoConstraints = false
- gridStack.userInterfaceLayoutDirection = .leftToRight
- gridStack.orientation = .vertical
- gridStack.alignment = .width
- gridStack.distribution = .fillEqually
- gridStack.spacing = 10
- calendarPageGridStack = gridStack
- let gridCard = roundedContainer(cornerRadius: 14, color: palette.sectionCard)
- gridCard.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(gridCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let gridHeightConstraint = gridCard.heightAnchor.constraint(equalToConstant: 360)
- gridHeightConstraint.isActive = true
- calendarPageGridHeightConstraint = gridHeightConstraint
- gridCard.heightAnchor.constraint(greaterThanOrEqualToConstant: 360).isActive = true
- gridCard.addSubview(gridStack)
- NSLayoutConstraint.activate([
- gridStack.leadingAnchor.constraint(equalTo: gridCard.leadingAnchor, constant: 16),
- gridStack.trailingAnchor.constraint(equalTo: gridCard.trailingAnchor, constant: -16),
- gridStack.topAnchor.constraint(equalTo: gridCard.topAnchor, constant: 16),
- gridStack.bottomAnchor.constraint(equalTo: gridCard.bottomAnchor, constant: -16)
- ])
- let daySummary = textLabel("", font: typography.dateHeading, color: palette.textSecondary)
- daySummary.alignment = .left
- daySummary.maximumNumberOfLines = 2
- daySummary.lineBreakMode = .byWordWrapping
- calendarPageDaySummaryLabel = daySummary
- contentStack.addArrangedSubview(titleRow)
- contentStack.setCustomSpacing(16, after: titleRow)
- contentStack.addArrangedSubview(weekdayRow)
- contentStack.setCustomSpacing(10, after: weekdayRow)
- contentStack.addArrangedSubview(gridCard)
- contentStack.setCustomSpacing(16, after: gridCard)
- contentStack.addArrangedSubview(daySummary)
- panel.addSubview(contentStack)
- NSLayoutConstraint.activate([
- contentStack.leftAnchor.constraint(equalTo: panel.leftAnchor, constant: 28),
- contentStack.rightAnchor.constraint(equalTo: panel.rightAnchor, constant: -28),
- contentStack.topAnchor.constraint(equalTo: panel.topAnchor),
- contentStack.bottomAnchor.constraint(lessThanOrEqualTo: panel.bottomAnchor, constant: -16),
- titleRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- weekdayRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- gridCard.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
- daySummary.widthAnchor.constraint(equalTo: contentStack.widthAnchor)
- ])
- if !storeKitCoordinator.hasPremiumAccess {
- let lockOverlay = NSVisualEffectView()
- lockOverlay.translatesAutoresizingMaskIntoConstraints = false
- lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
- lockOverlay.blendingMode = .withinWindow
- lockOverlay.state = .active
- lockOverlay.wantsLayer = true
- lockOverlay.layer?.cornerRadius = 14
- lockOverlay.layer?.masksToBounds = true
- lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.30 : 0.12).cgColor
- panel.addSubview(lockOverlay)
- let message = textLabel("Premium required. Get Premium now to unlock Calendar.", font: NSFont.systemFont(ofSize: 14, weight: .semibold), color: darkModeEnabled ? .white : .black)
- message.alignment = .center
- message.maximumNumberOfLines = 2
- message.lineBreakMode = .byWordWrapping
- lockOverlay.addSubview(message)
- let hit = HoverTrackingView()
- hit.translatesAutoresizingMaskIntoConstraints = false
- hit.wantsLayer = true
- hit.layer?.backgroundColor = NSColor.clear.cgColor
- hit.onClick = { [weak self] in
- self?.showPaywall()
- }
- hit.toolTip = "Premium required. Click to open paywall."
- lockOverlay.addSubview(hit)
- NSLayoutConstraint.activate([
- lockOverlay.leadingAnchor.constraint(equalTo: contentStack.leadingAnchor),
- lockOverlay.trailingAnchor.constraint(equalTo: contentStack.trailingAnchor),
- lockOverlay.topAnchor.constraint(equalTo: contentStack.topAnchor),
- lockOverlay.bottomAnchor.constraint(equalTo: contentStack.bottomAnchor),
- message.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
- message.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
- message.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 22),
- message.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -22),
- hit.leadingAnchor.constraint(equalTo: lockOverlay.leadingAnchor),
- hit.trailingAnchor.constraint(equalTo: lockOverlay.trailingAnchor),
- hit.topAnchor.constraint(equalTo: lockOverlay.topAnchor),
- hit.bottomAnchor.constraint(equalTo: lockOverlay.bottomAnchor)
- ])
- }
- let calendar = Calendar.current
- calendarPageMonthAnchor = calendarStartOfMonth(for: Date())
- calendarPageSelectedDate = calendar.startOfDay(for: Date())
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- renderCalendarSelectedDay()
- Task { [weak self] in
- await self?.loadSchedule()
- }
- return panel
- }
- func meetJoinSectionRow() -> NSView {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.spacing = 12
- row.alignment = .top
- row.distribution = .fillEqually
- row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
- row.heightAnchor.constraint(equalToConstant: 140).isActive = true
- let instant = HoverSurfaceView()
- instant.translatesAutoresizingMaskIntoConstraints = false
- instant.wantsLayer = true
- instant.layer?.cornerRadius = 14
- instant.layer?.backgroundColor = palette.sectionCard.cgColor
- styleSurface(instant, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let iconWrap = roundedContainer(cornerRadius: 12, color: NSColor.clear)
- iconWrap.translatesAutoresizingMaskIntoConstraints = false
- iconWrap.widthAnchor.constraint(equalToConstant: 58).isActive = true
- iconWrap.heightAnchor.constraint(equalToConstant: 58).isActive = true
- iconWrap.layer?.borderWidth = 0
- let meetLogoImage = NSImage(named: "MeetLogo") ?? NSImage()
- meetLogoImage.isTemplate = false
- let meetLogo = NSImageView(image: meetLogoImage)
- meetLogo.translatesAutoresizingMaskIntoConstraints = false
- meetLogo.imageScaling = .scaleProportionallyDown
- meetLogo.contentTintColor = nil
- iconWrap.addSubview(meetLogo)
- let instantTitle = textLabel("New Instant Meet", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
- let instantSub = textLabel("Start instant Meet in more section with\nGoogle Meet meet.", font: NSFont.systemFont(ofSize: 16 / 2, weight: .medium), color: palette.textSecondary)
- instantSub.maximumNumberOfLines = 2
- instant.addSubview(iconWrap)
- instant.addSubview(instantTitle)
- instant.addSubview(instantSub)
- let codeCard = HoverSurfaceView()
- codeCard.translatesAutoresizingMaskIntoConstraints = false
- codeCard.wantsLayer = true
- codeCard.layer?.cornerRadius = 14
- codeCard.layer?.backgroundColor = palette.sectionCard.cgColor
- styleSurface(codeCard, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let codeTitle = textLabel("Join with Link", font: NSFont.systemFont(ofSize: 40 / 2, weight: .semibold), color: palette.textPrimary)
- let codeInputShell = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
- codeInputShell.translatesAutoresizingMaskIntoConstraints = false
- codeInputShell.heightAnchor.constraint(equalToConstant: 52).isActive = true
- styleSurface(codeInputShell, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let codeField = NSTextField(string: "")
- codeField.translatesAutoresizingMaskIntoConstraints = false
- codeField.isEditable = true
- codeField.isBordered = false
- codeField.drawsBackground = false
- codeField.focusRingType = .none
- codeField.font = NSFont.systemFont(ofSize: 36 / 2, weight: .regular)
- codeField.textColor = palette.textPrimary
- codeField.placeholderString = "Code or meet.google.com/…"
- codeInputShell.addSubview(codeField)
- meetLinkField = codeField
- codeCard.addSubview(codeTitle)
- codeCard.addSubview(codeInputShell)
- NSLayoutConstraint.activate([
- meetLogo.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
- meetLogo.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor),
- meetLogo.widthAnchor.constraint(equalToConstant: 46),
- meetLogo.heightAnchor.constraint(equalToConstant: 46),
- iconWrap.leadingAnchor.constraint(equalTo: instant.leadingAnchor, constant: 18),
- iconWrap.topAnchor.constraint(equalTo: instant.topAnchor, constant: 22),
- instantTitle.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 14),
- instantTitle.topAnchor.constraint(equalTo: instant.topAnchor, constant: 24),
- instantSub.leadingAnchor.constraint(equalTo: instantTitle.leadingAnchor),
- instantSub.topAnchor.constraint(equalTo: instantTitle.bottomAnchor, constant: 6),
- instantSub.trailingAnchor.constraint(lessThanOrEqualTo: instant.trailingAnchor, constant: -16),
- codeTitle.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
- codeTitle.topAnchor.constraint(equalTo: codeCard.topAnchor, constant: 22),
- codeInputShell.leadingAnchor.constraint(equalTo: codeCard.leadingAnchor, constant: 18),
- codeInputShell.trailingAnchor.constraint(equalTo: codeCard.trailingAnchor, constant: -18),
- codeInputShell.topAnchor.constraint(equalTo: codeTitle.bottomAnchor, constant: 12),
- codeField.leadingAnchor.constraint(equalTo: codeInputShell.leadingAnchor, constant: 14),
- codeField.trailingAnchor.constraint(equalTo: codeInputShell.trailingAnchor, constant: -14),
- codeField.centerYAnchor.constraint(equalTo: codeInputShell.centerYAnchor)
- ])
- let baseColor = palette.sectionCard
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- instant.onHoverChanged = { [weak self] hovering in
- guard let self else { return }
- instant.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- }
- codeCard.onHoverChanged = { [weak self] hovering in
- guard let self else { return }
- codeCard.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- }
- instant.onHoverChanged?(false)
- codeCard.onHoverChanged?(false)
- let instantClick = NSClickGestureRecognizer(target: self, action: #selector(instantMeetClicked(_:)))
- instant.addGestureRecognizer(instantClick)
- let joinWithLinkClick = NSClickGestureRecognizer(target: self, action: #selector(joinWithLinkCardClicked(_:)))
- codeCard.addGestureRecognizer(joinWithLinkClick)
- instantMeetCardView = instant
- instantMeetTitleLabel = instantTitle
- instantMeetSubtitleLabel = instantSub
- joinWithLinkCardView = codeCard
- joinWithLinkTitleLabel = codeTitle
- refreshInstantMeetPremiumState()
- row.addArrangedSubview(instant)
- row.addArrangedSubview(codeCard)
- return row
- }
- func meetJoinActionsRow() -> NSView {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.spacing = 12
- row.alignment = .centerY
- row.widthAnchor.constraint(greaterThanOrEqualToConstant: 880).isActive = true
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- row.addArrangedSubview(spacer)
- row.addArrangedSubview(meetActionButton(
- title: "Cancel",
- color: palette.cancelButton,
- textColor: palette.textSecondary,
- width: 110,
- action: #selector(cancelMeetJoinClicked(_:))
- ))
- let joinButton = meetActionButton(
- title: "Join",
- color: palette.primaryBlue,
- textColor: .white,
- width: 116,
- action: #selector(joinMeetClicked(_:))
- )
- joinMeetPrimaryButton = joinButton
- row.addArrangedSubview(joinButton)
- refreshInstantMeetPremiumState()
- return row
- }
- func meetActionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat, action: Selector) -> NSButton {
- let button = HoverButton(title: title, target: self, action: action)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 9
- let baseBackground = color
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverBackground = baseBackground.blended(withFraction: 0.10, of: hoverBlend) ?? baseBackground
- let baseBorder = (title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder)
- let hoverBorder = baseBorder.blended(withFraction: 0.18, of: hoverBlend) ?? baseBorder
- button.layer?.backgroundColor = baseBackground.cgColor
- button.layer?.borderColor = baseBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.buttonText
- button.contentTintColor = textColor
- button.widthAnchor.constraint(equalToConstant: width).isActive = true
- button.heightAnchor.constraint(equalToConstant: 36).isActive = true
- button.onHoverChanged = { [weak self, weak button] hovering in
- guard let self, let button else { return }
- button.layer?.backgroundColor = (hovering ? hoverBackground : baseBackground).cgColor
- button.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- if title == "Cancel" {
- button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : textColor
- }
- }
- button.onHoverChanged?(false)
- return button
- }
- func makePaywallContent() -> NSView {
- paywallPlanViews.removeAll()
- premiumPlanByView.removeAll()
- let panel = NSView()
- panel.translatesAutoresizingMaskIntoConstraints = false
- panel.wantsLayer = true
- panel.layer?.backgroundColor = palette.pageBackground.cgColor
- let contentStack = NSStackView()
- contentStack.translatesAutoresizingMaskIntoConstraints = false
- contentStack.orientation = .vertical
- contentStack.spacing = 12
- contentStack.distribution = .fill
- contentStack.alignment = .centerX
- panel.addSubview(contentStack)
- let paywallLayoutWidth: CGFloat = 980
- let topRow = NSStackView()
- topRow.translatesAutoresizingMaskIntoConstraints = false
- topRow.orientation = .horizontal
- topRow.alignment = .centerY
- topRow.distribution = .fill
- topRow.spacing = 10
- topRow.addArrangedSubview(textLabel("Meetings Pro", font: NSFont.systemFont(ofSize: 27, weight: .bold), color: palette.textPrimary))
- var closeButton: HoverButton?
- if storeKitCoordinator.hasPremiumAccess {
- let button = HoverButton(title: "✕", target: self, action: #selector(closePaywallClicked(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 14
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.iconButton
- button.contentTintColor = palette.textSecondary
- button.widthAnchor.constraint(equalToConstant: 28).isActive = true
- button.heightAnchor.constraint(equalToConstant: 28).isActive = true
- button.onHoverChanged = { [weak button, weak self] hovering in
- guard let button, let self else { return }
- let base = self.palette.inputBackground
- let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
- let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
- button.layer?.backgroundColor = (hovering ? hover : base).cgColor
- button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
- }
- panel.addSubview(button)
- closeButton = button
- }
- contentStack.addArrangedSubview(topRow)
- topRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- let hero = roundedContainer(cornerRadius: 16, color: palette.sectionCard)
- hero.translatesAutoresizingMaskIntoConstraints = false
- styleSurface(hero, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- contentStack.addArrangedSubview(hero)
- hero.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- 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))
- hero.addSubview(heroBadge)
- let heroTitle = textLabel("Elevate your meetings workflow", font: NSFont.systemFont(ofSize: 22, weight: .bold), color: palette.textPrimary)
- let heroSubtitle = textLabel("Unlock automation, premium meeting tools, and priority support for every session.", font: NSFont.systemFont(ofSize: 13, weight: .medium), color: palette.textSecondary)
- heroTitle.maximumNumberOfLines = 2
- heroSubtitle.maximumNumberOfLines = 3
- hero.addSubview(heroTitle)
- hero.addSubview(heroSubtitle)
- NSLayoutConstraint.activate([
- heroBadge.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
- heroBadge.topAnchor.constraint(equalTo: hero.topAnchor, constant: 14),
- heroTitle.leadingAnchor.constraint(equalTo: hero.leadingAnchor, constant: 16),
- heroTitle.trailingAnchor.constraint(lessThanOrEqualTo: hero.trailingAnchor, constant: -16),
- heroTitle.topAnchor.constraint(equalTo: heroBadge.bottomAnchor, constant: 10),
- heroSubtitle.leadingAnchor.constraint(equalTo: heroTitle.leadingAnchor),
- heroSubtitle.trailingAnchor.constraint(equalTo: hero.trailingAnchor, constant: -16),
- heroSubtitle.topAnchor.constraint(equalTo: heroTitle.bottomAnchor, constant: 8),
- heroSubtitle.bottomAnchor.constraint(equalTo: hero.bottomAnchor, constant: -16)
- ])
- let benefitsRow = NSStackView()
- benefitsRow.translatesAutoresizingMaskIntoConstraints = false
- benefitsRow.orientation = .horizontal
- benefitsRow.spacing = 8
- benefitsRow.distribution = .fillEqually
- benefitsRow.alignment = .centerY
- benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
- benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🧠", text: "Smart scheduling"))
- benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Faster workflow"))
- benefitsRow.addArrangedSubview(paywallBenefitItem(icon: "🔔", text: "Reminder notifications"))
- contentStack.addArrangedSubview(benefitsRow)
- benefitsRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- let plansRow = NSStackView()
- plansRow.translatesAutoresizingMaskIntoConstraints = false
- plansRow.orientation = .horizontal
- plansRow.spacing = 10
- plansRow.distribution = .fillEqually
- plansRow.alignment = .centerY
- let weeklyCard = paywallPlanCard(
- title: "Weekly",
- price: "PKR 1,100.00",
- badge: "Basic",
- badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
- subtitle: nil,
- plan: .weekly,
- strikePrice: nil
- )
- let monthlyCard = paywallPlanCard(
- title: "Monthly",
- price: "PKR 2,500.00",
- badge: "Popular",
- badgeColor: NSColor(calibratedRed: 0.19, green: 0.82, blue: 0.39, alpha: 1),
- subtitle: "3 days free trial",
- plan: .monthly,
- strikePrice: nil
- )
- let yearlyCard = paywallPlanCard(
- title: "Yearly",
- price: "PKR 9,900.00",
- badge: "Best Value",
- badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
- subtitle: "190.38/week",
- plan: .yearly,
- strikePrice: nil
- )
- let lifetimeCard = paywallPlanCard(
- title: "Lifetime",
- price: "PKR 14,900.00",
- badge: "Save 50%",
- badgeColor: NSColor(calibratedRed: 1.0, green: 0.60, blue: 0.20, alpha: 1),
- subtitle: nil,
- plan: .lifetime,
- strikePrice: "PKR 29,800.00"
- )
- plansRow.addArrangedSubview(weeklyCard)
- plansRow.addArrangedSubview(monthlyCard)
- plansRow.addArrangedSubview(yearlyCard)
- plansRow.addArrangedSubview(lifetimeCard)
- contentStack.addArrangedSubview(plansRow)
- plansRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- updatePaywallPlanSelection()
- let trustRow = NSStackView()
- trustRow.translatesAutoresizingMaskIntoConstraints = false
- trustRow.orientation = .horizontal
- trustRow.spacing = 8
- trustRow.distribution = .fillEqually
- trustRow.alignment = .centerY
- trustRow.addArrangedSubview(paywallMetaItem(title: "Cancel anytime", subtitle: "No lock-in"))
- trustRow.addArrangedSubview(paywallMetaItem(title: "Instant access", subtitle: "Unlock all tools"))
- trustRow.addArrangedSubview(paywallMetaItem(title: "Secure billing", subtitle: "Handled by Apple"))
- contentStack.addArrangedSubview(trustRow)
- trustRow.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- let offer = textLabel(paywallOfferText(for: selectedPremiumPlan), font: NSFont.systemFont(ofSize: 13, weight: .semibold), color: palette.textPrimary)
- offer.alignment = .center
- paywallOfferLabel = offer
- let offerWrap = NSView()
- offerWrap.translatesAutoresizingMaskIntoConstraints = false
- offerWrap.addSubview(offer)
- contentStack.addArrangedSubview(offerWrap)
- offerWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- NSLayoutConstraint.activate([
- offer.centerXAnchor.constraint(equalTo: offerWrap.centerXAnchor),
- offer.topAnchor.constraint(equalTo: offerWrap.topAnchor, constant: 4),
- offer.bottomAnchor.constraint(equalTo: offerWrap.bottomAnchor, constant: -2)
- ])
- let continueButton = HoverButton(title: "", target: self, action: #selector(paywallContinueClicked(_:)))
- continueButton.translatesAutoresizingMaskIntoConstraints = false
- continueButton.isBordered = false
- continueButton.bezelStyle = .regularSquare
- continueButton.wantsLayer = true
- continueButton.layer?.cornerRadius = 12
- continueButton.layer?.backgroundColor = palette.primaryBlue.cgColor
- continueButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
- styleSurface(continueButton, borderColor: palette.primaryBlueBorder, borderWidth: 1, shadow: true)
- let continueLabel = textLabel("Continue", font: NSFont.systemFont(ofSize: 14, weight: .bold), color: .white)
- continueButton.addSubview(continueLabel)
- NSLayoutConstraint.activate([
- continueLabel.centerXAnchor.constraint(equalTo: continueButton.centerXAnchor),
- continueLabel.centerYAnchor.constraint(equalTo: continueButton.centerYAnchor)
- ])
- let baseBlue = palette.primaryBlue
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverBlue = baseBlue.blended(withFraction: 0.10, of: hoverBlend) ?? baseBlue
- continueButton.onHoverChanged = { hovering in
- continueButton.layer?.backgroundColor = (hovering ? hoverBlue : baseBlue).cgColor
- }
- continueButton.onHoverChanged?(false)
- paywallContinueButton = continueButton
- paywallContinueLabel = continueLabel
- contentStack.addArrangedSubview(continueButton)
- continueButton.widthAnchor.constraint(equalToConstant: 360).isActive = true
- let secure = textLabel("Secured by Apple. Cancel anytime.", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: palette.textSecondary)
- secure.alignment = .center
- let secureWrap = NSView()
- secureWrap.translatesAutoresizingMaskIntoConstraints = false
- secureWrap.addSubview(secure)
- contentStack.addArrangedSubview(secureWrap)
- secureWrap.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- NSLayoutConstraint.activate([
- secure.centerXAnchor.constraint(equalTo: secureWrap.centerXAnchor),
- secure.topAnchor.constraint(equalTo: secureWrap.topAnchor, constant: 2),
- secure.bottomAnchor.constraint(equalTo: secureWrap.bottomAnchor, constant: -4)
- ])
- let footer = paywallFooterLinks()
- contentStack.addArrangedSubview(footer)
- footer.widthAnchor.constraint(equalTo: contentStack.widthAnchor).isActive = true
- var panelConstraints: [NSLayoutConstraint] = [
- contentStack.centerXAnchor.constraint(equalTo: panel.centerXAnchor),
- contentStack.widthAnchor.constraint(equalToConstant: paywallLayoutWidth),
- contentStack.topAnchor.constraint(equalTo: panel.topAnchor, constant: 80),
- contentStack.bottomAnchor.constraint(equalTo: panel.bottomAnchor, constant: -12)
- ]
- if let closeButton {
- panelConstraints.append(closeButton.topAnchor.constraint(equalTo: panel.topAnchor, constant: 30))
- panelConstraints.append(closeButton.trailingAnchor.constraint(equalTo: panel.trailingAnchor, constant: -30))
- }
- NSLayoutConstraint.activate(panelConstraints)
- refreshPaywallStoreUI()
- return panel
- }
- func paywallPlanCard(
- title: String,
- price: String,
- badge: String,
- badgeColor: NSColor,
- subtitle: String?,
- plan: PremiumPlan,
- strikePrice: String?
- ) -> NSView {
- let wrapper = HoverButton(title: "", target: self, action: #selector(paywallPlanButtonClicked(_:)))
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- wrapper.isBordered = false
- wrapper.bezelStyle = .regularSquare
- wrapper.wantsLayer = true
- wrapper.layer?.backgroundColor = NSColor.clear.cgColor
- wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 160).isActive = true
- wrapper.heightAnchor.constraint(equalToConstant: 162).isActive = true
- wrapper.tag = plan.rawValue
- let card = HoverTrackingView()
- card.translatesAutoresizingMaskIntoConstraints = false
- card.wantsLayer = true
- card.layer?.cornerRadius = 16
- card.layer?.backgroundColor = palette.sectionCard.cgColor
- card.heightAnchor.constraint(equalToConstant: 150).isActive = true
- wrapper.addSubview(card)
- NSLayoutConstraint.activate([
- card.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- card.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- card.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: 12),
- card.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
- ])
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let badgeLabel = textLabel(badge, font: NSFont.systemFont(ofSize: 10, weight: .bold), color: .white)
- let badgeWrap = roundedContainer(cornerRadius: 10, color: badgeColor)
- badgeWrap.translatesAutoresizingMaskIntoConstraints = false
- badgeWrap.wantsLayer = true
- badgeWrap.layer?.borderColor = NSColor(calibratedWhite: 1, alpha: 0.22).cgColor
- badgeWrap.layer?.borderWidth = 1
- badgeWrap.layer?.shadowColor = NSColor.black.cgColor
- badgeWrap.layer?.shadowOpacity = 0.20
- badgeWrap.layer?.shadowOffset = CGSize(width: 0, height: -1)
- badgeWrap.layer?.shadowRadius = 3
- badgeWrap.addSubview(badgeLabel)
- NSLayoutConstraint.activate([
- badgeLabel.leadingAnchor.constraint(equalTo: badgeWrap.leadingAnchor, constant: 8),
- badgeLabel.trailingAnchor.constraint(equalTo: badgeWrap.trailingAnchor, constant: -8),
- badgeLabel.topAnchor.constraint(equalTo: badgeWrap.topAnchor, constant: 2),
- badgeLabel.bottomAnchor.constraint(equalTo: badgeWrap.bottomAnchor, constant: -2)
- ])
- wrapper.addSubview(badgeWrap)
- let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 15, weight: .bold), color: palette.primaryBlue)
- card.addSubview(titleLabel)
- let priceLabel = textLabel(price, font: NSFont.systemFont(ofSize: 12, weight: .bold), color: palette.textPrimary)
- card.addSubview(priceLabel)
- paywallPriceLabels[plan] = priceLabel
- NSLayoutConstraint.activate([
- badgeWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
- badgeWrap.centerYAnchor.constraint(equalTo: card.topAnchor),
- titleLabel.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 12),
- titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 34),
- priceLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor),
- priceLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
- priceLabel.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
- ])
- if let subtitle {
- let sub = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .semibold), color: palette.textSecondary)
- card.addSubview(sub)
- paywallSubtitleLabels[plan] = sub
- NSLayoutConstraint.activate([
- sub.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
- sub.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 2),
- sub.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
- ])
- }
- if let strikePrice {
- let strike = textLabel(strikePrice, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: NSColor.systemRed)
- card.addSubview(strike)
- NSLayoutConstraint.activate([
- strike.leadingAnchor.constraint(equalTo: priceLabel.leadingAnchor),
- strike.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 4),
- strike.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -12)
- ])
- }
- paywallPlanViews[plan] = card
- wrapper.onHoverChanged = { [weak self, weak card] hovering in
- guard let self, let card else { return }
- self.applyPaywallPlanStyle(card, isSelected: plan == self.selectedPremiumPlan, hovering: hovering)
- }
- wrapper.onHoverChanged?(false)
- return wrapper
- }
- func paywallFooterLinks() -> NSView {
- let wrap = NSView()
- wrap.translatesAutoresizingMaskIntoConstraints = false
- wrap.heightAnchor.constraint(equalToConstant: 40).isActive = true
- paywallFooterActionByView.removeAll()
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.distribution = .fillEqually
- row.alignment = .centerY
- row.spacing = 0
- wrap.addSubview(row)
- if storeKitCoordinator.hasPremiumAccess {
- row.addArrangedSubview(footerLink("Manage Subscription", action: .manageSubscription))
- row.addArrangedSubview(footerLink("Restore Purchase", action: .restorePurchase))
- } else {
- row.addArrangedSubview(footerLink("Continue with free plan", action: .continueWithFreePlan))
- }
- row.addArrangedSubview(footerLink("Privacy Policy", action: .privacyPolicy))
- row.addArrangedSubview(footerLink("Support", action: .support))
- row.addArrangedSubview(footerLink("Terms of Services", action: .termsOfServices))
- NSLayoutConstraint.activate([
- row.leadingAnchor.constraint(equalTo: wrap.leadingAnchor),
- row.trailingAnchor.constraint(equalTo: wrap.trailingAnchor),
- row.topAnchor.constraint(equalTo: wrap.topAnchor),
- row.bottomAnchor.constraint(equalTo: wrap.bottomAnchor)
- ])
- return wrap
- }
- private func footerLink(_ title: String, action: PaywallFooterAction) -> NSView {
- let button = HoverButton(title: title, target: self, action: #selector(paywallFooterButtonPressed(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.focusRingType = .none
- button.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
- button.alignment = .center
- button.setButtonType(.momentaryChange)
- button.contentTintColor = palette.textSecondary
- paywallFooterActionByView[ObjectIdentifier(button)] = action
- button.onHoverChanged = { [weak self, weak button] hovering in
- guard let self, let button else { return }
- button.contentTintColor = hovering ? (self.darkModeEnabled ? .white : self.palette.textPrimary) : self.palette.textSecondary
- }
- button.onHoverChanged?(false)
- return button
- }
- func paywallMetaItem(title: String, subtitle: String) -> NSView {
- let card = HoverTrackingView()
- card.translatesAutoresizingMaskIntoConstraints = false
- card.wantsLayer = true
- card.layer?.cornerRadius = 10
- card.layer?.backgroundColor = palette.inputBackground.cgColor
- card.heightAnchor.constraint(equalToConstant: 44).isActive = true
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let titleLabel = textLabel(title, font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textPrimary)
- let subtitleLabel = textLabel(subtitle, font: NSFont.systemFont(ofSize: 10, weight: .medium), color: palette.textSecondary)
- card.addSubview(titleLabel)
- card.addSubview(subtitleLabel)
- NSLayoutConstraint.activate([
- titleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
- titleLabel.topAnchor.constraint(equalTo: card.topAnchor, constant: 7),
- subtitleLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor),
- subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 1),
- subtitleLabel.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -6)
- ])
- let base = palette.inputBackground
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
- card.onHoverChanged = { [weak card] hovering in
- card?.layer?.backgroundColor = (hovering ? hover : base).cgColor
- }
- card.onHoverChanged?(false)
- return card
- }
- func paywallBenefitsSection() -> NSView {
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.orientation = .vertical
- stack.spacing = 8
- stack.alignment = .leading
- stack.widthAnchor.constraint(greaterThanOrEqualToConstant: paywallContentWidth).isActive = true
- let rowOne = NSStackView()
- rowOne.translatesAutoresizingMaskIntoConstraints = false
- rowOne.orientation = .horizontal
- rowOne.spacing = 10
- rowOne.distribution = .fillEqually
- rowOne.alignment = .centerY
- rowOne.addArrangedSubview(paywallBenefitItem(icon: "📅", text: "Manage meetings"))
- rowOne.addArrangedSubview(paywallBenefitItem(icon: "🖼️", text: "Virtual backgrounds"))
- let rowTwo = NSStackView()
- rowTwo.translatesAutoresizingMaskIntoConstraints = false
- rowTwo.orientation = .horizontal
- rowTwo.spacing = 10
- rowTwo.distribution = .fillEqually
- rowTwo.alignment = .centerY
- rowTwo.addArrangedSubview(paywallBenefitItem(icon: "⚡", text: "Tools for productivity"))
- rowTwo.addArrangedSubview(paywallBenefitItem(icon: "🛟", text: "24/7 support"))
- stack.addArrangedSubview(rowOne)
- stack.addArrangedSubview(rowTwo)
- return stack
- }
- func paywallBenefitItem(icon: String, text: String) -> NSView {
- let card = HoverTrackingView()
- card.translatesAutoresizingMaskIntoConstraints = false
- card.wantsLayer = true
- card.layer?.cornerRadius = 10
- card.layer?.backgroundColor = palette.inputBackground.cgColor
- card.heightAnchor.constraint(equalToConstant: 36).isActive = true
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let iconWrap = roundedContainer(cornerRadius: 8, color: palette.inputBackground)
- iconWrap.translatesAutoresizingMaskIntoConstraints = false
- iconWrap.widthAnchor.constraint(equalToConstant: 24).isActive = true
- iconWrap.heightAnchor.constraint(equalToConstant: 24).isActive = true
- styleSurface(iconWrap, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let iconLabel = textLabel(icon, font: NSFont.systemFont(ofSize: 12, weight: .medium), color: palette.primaryBlue)
- iconWrap.addSubview(iconLabel)
- NSLayoutConstraint.activate([
- iconLabel.centerXAnchor.constraint(equalTo: iconWrap.centerXAnchor),
- iconLabel.centerYAnchor.constraint(equalTo: iconWrap.centerYAnchor)
- ])
- let title = textLabel(text, font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textPrimary)
- card.addSubview(iconWrap)
- card.addSubview(title)
- NSLayoutConstraint.activate([
- iconWrap.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 8),
- iconWrap.centerYAnchor.constraint(equalTo: card.centerYAnchor),
- title.leadingAnchor.constraint(equalTo: iconWrap.trailingAnchor, constant: 10),
- title.centerYAnchor.constraint(equalTo: card.centerYAnchor),
- title.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -8)
- ])
- let base = palette.inputBackground
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
- let hoverBorder = palette.primaryBlueBorder.withAlphaComponent(0.55)
- card.onHoverChanged = { [weak card, weak iconWrap] hovering in
- guard let card else { return }
- card.layer?.backgroundColor = (hovering ? hover : base).cgColor
- card.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
- iconWrap?.layer?.borderColor = (hovering ? hoverBorder : self.palette.inputBorder).cgColor
- }
- card.onHoverChanged?(false)
- return card
- }
- func zoomJoinModeTabs() -> NSView {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.alignment = .centerY
- row.spacing = 28
- row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
- let idTab = joinModeTab("Join with ID", mode: .id)
- let urlTab = joinModeTab("Join with URL", mode: .url)
- row.addArrangedSubview(idTab)
- row.addArrangedSubview(urlTab)
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- row.addArrangedSubview(spacer)
- zoomJoinModeViews[.id] = idTab
- zoomJoinModeViews[.url] = urlTab
- updateZoomJoinModeAppearance()
- return row
- }
- func joinModeTab(_ title: String, mode: ZoomJoinMode) -> NSView {
- let tab = HoverTrackingView()
- tab.translatesAutoresizingMaskIntoConstraints = false
- tab.wantsLayer = true
- tab.layer?.cornerRadius = 6
- tab.layer?.backgroundColor = NSColor.clear.cgColor
- tab.heightAnchor.constraint(equalToConstant: 30).isActive = true
- zoomJoinModeByView[ObjectIdentifier(tab)] = mode
- let label = textLabel(title, font: NSFont.systemFont(ofSize: 33 / 2, weight: .medium), color: palette.textPrimary)
- tab.addSubview(label)
- NSLayoutConstraint.activate([
- label.leadingAnchor.constraint(equalTo: tab.leadingAnchor, constant: 4),
- label.trailingAnchor.constraint(equalTo: tab.trailingAnchor, constant: -4),
- label.topAnchor.constraint(equalTo: tab.topAnchor, constant: 4),
- label.bottomAnchor.constraint(equalTo: tab.bottomAnchor, constant: -6)
- ])
- let click = NSClickGestureRecognizer(target: self, action: #selector(zoomJoinModeClicked(_:)))
- tab.addGestureRecognizer(click)
- return tab
- }
- func updateZoomJoinModeAppearance() {
- for (mode, tab) in zoomJoinModeViews {
- let selected = (mode == selectedZoomJoinMode)
- let textColor = selected ? palette.textPrimary : palette.textSecondary
- let label = tab.subviews.first { $0 is NSTextField } as? NSTextField
- label?.textColor = textColor
- // Keep the active tab visually underlined like the reference.
- if selected {
- if tab.subviews.contains(where: { $0.identifier?.rawValue == "modeUnderline" }) == false {
- let underline = NSView()
- underline.identifier = NSUserInterfaceItemIdentifier("modeUnderline")
- underline.translatesAutoresizingMaskIntoConstraints = false
- underline.wantsLayer = true
- underline.layer?.backgroundColor = palette.primaryBlue.cgColor
- tab.addSubview(underline)
- NSLayoutConstraint.activate([
- underline.leadingAnchor.constraint(equalTo: tab.leadingAnchor),
- underline.trailingAnchor.constraint(equalTo: tab.trailingAnchor),
- underline.bottomAnchor.constraint(equalTo: tab.bottomAnchor),
- underline.heightAnchor.constraint(equalToConstant: 2)
- ])
- }
- } else {
- tab.subviews
- .filter { $0.identifier?.rawValue == "modeUnderline" }
- .forEach { $0.removeFromSuperview() }
- }
- }
- }
- func joinWithIDHeading() -> NSView {
- let container = NSView()
- container.translatesAutoresizingMaskIntoConstraints = false
- let title = textLabel("Join with ID", font: typography.joinWithURLTitle, color: palette.textPrimary)
- title.alignment = .left
- title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
- title.setContentCompressionResistancePriority(.required, for: .horizontal)
- let bar = NSView()
- bar.translatesAutoresizingMaskIntoConstraints = false
- bar.wantsLayer = true
- bar.layer?.backgroundColor = palette.primaryBlue.cgColor
- bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
- container.addSubview(title)
- container.addSubview(bar)
- NSLayoutConstraint.activate([
- title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
- title.topAnchor.constraint(equalTo: container.topAnchor),
- bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
- bar.widthAnchor.constraint(equalTo: title.widthAnchor),
- bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
- container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
- ])
- return container
- }
- func zoomMeetingIDSection() -> NSView {
- let wrapper = NSView()
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- let fieldsRow = NSStackView()
- fieldsRow.translatesAutoresizingMaskIntoConstraints = false
- fieldsRow.orientation = .horizontal
- fieldsRow.alignment = .top
- fieldsRow.distribution = .fillEqually
- fieldsRow.spacing = 12
- fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting ID", placeholder: "Enter meeting ID..."))
- fieldsRow.addArrangedSubview(zoomInputField(title: "Meeting Passcode", placeholder: "Enter meeting passcode..."))
- let actions = NSStackView()
- actions.orientation = .horizontal
- actions.spacing = 10
- actions.translatesAutoresizingMaskIntoConstraints = false
- actions.alignment = .centerY
- actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
- actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
- wrapper.addSubview(fieldsRow)
- wrapper.addSubview(actions)
- NSLayoutConstraint.activate([
- wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
- fieldsRow.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- fieldsRow.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- fieldsRow.topAnchor.constraint(equalTo: wrapper.topAnchor),
- actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- actions.topAnchor.constraint(equalTo: fieldsRow.bottomAnchor, constant: 14),
- actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
- ])
- return wrapper
- }
- func zoomInputField(title: String, placeholder: String) -> NSView {
- let wrapper = NSView()
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- let heading = textLabel(title, font: typography.fieldLabel, color: palette.textPrimary)
- let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
- textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
- textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
- styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let field = NSTextField(string: "")
- field.translatesAutoresizingMaskIntoConstraints = false
- field.isEditable = true
- field.isSelectable = true
- field.isBordered = false
- field.drawsBackground = false
- field.placeholderString = placeholder
- field.font = typography.inputPlaceholder
- field.textColor = palette.textPrimary
- field.focusRingType = .none
- textFieldContainer.addSubview(field)
- wrapper.addSubview(heading)
- wrapper.addSubview(textFieldContainer)
- NSLayoutConstraint.activate([
- heading.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- heading.topAnchor.constraint(equalTo: wrapper.topAnchor),
- textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- textFieldContainer.topAnchor.constraint(equalTo: heading.bottomAnchor, constant: 10),
- textFieldContainer.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
- field.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
- field.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
- field.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor)
- ])
- return wrapper
- }
- func joinWithURLHeading() -> NSView {
- let container = NSView()
- container.translatesAutoresizingMaskIntoConstraints = false
- let title = textLabel("Join with URL", font: typography.joinWithURLTitle, color: palette.textPrimary)
- title.alignment = .left
- title.setContentHuggingPriority(.defaultHigh, for: .horizontal)
- title.setContentCompressionResistancePriority(.required, for: .horizontal)
- let bar = NSView()
- bar.translatesAutoresizingMaskIntoConstraints = false
- bar.wantsLayer = true
- bar.layer?.backgroundColor = palette.primaryBlue.cgColor
- bar.heightAnchor.constraint(equalToConstant: 3).isActive = true
- container.addSubview(title)
- container.addSubview(bar)
- NSLayoutConstraint.activate([
- title.leadingAnchor.constraint(equalTo: container.leadingAnchor),
- title.topAnchor.constraint(equalTo: container.topAnchor),
- bar.leadingAnchor.constraint(equalTo: title.leadingAnchor),
- bar.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
- bar.widthAnchor.constraint(equalTo: title.widthAnchor),
- bar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
- container.trailingAnchor.constraint(equalTo: title.trailingAnchor)
- ])
- return container
- }
- func meetingUrlSection() -> NSView {
- let wrapper = NSView()
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- let title = textLabel("Meeting URL", font: typography.fieldLabel, color: palette.textSecondary)
- let textFieldContainer = roundedContainer(cornerRadius: 10, color: palette.inputBackground)
- textFieldContainer.translatesAutoresizingMaskIntoConstraints = false
- textFieldContainer.heightAnchor.constraint(equalToConstant: 40).isActive = true
- styleSurface(textFieldContainer, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let urlField = NSTextField(string: "")
- urlField.translatesAutoresizingMaskIntoConstraints = false
- urlField.isEditable = true
- urlField.isSelectable = true
- urlField.isBordered = false
- urlField.drawsBackground = false
- urlField.placeholderString = "Enter meeting URL..."
- urlField.font = typography.inputPlaceholder
- urlField.textColor = palette.textPrimary
- urlField.focusRingType = .none
- textFieldContainer.addSubview(urlField)
- let actions = NSStackView()
- actions.orientation = .horizontal
- actions.spacing = 10
- actions.translatesAutoresizingMaskIntoConstraints = false
- actions.alignment = .centerY
- actions.addArrangedSubview(actionButton(title: "Cancel", color: palette.cancelButton, textColor: palette.textSecondary, width: 110))
- actions.addArrangedSubview(actionButton(title: "Join", color: palette.primaryBlue, textColor: .white, width: 116))
- wrapper.addSubview(title)
- wrapper.addSubview(textFieldContainer)
- wrapper.addSubview(actions)
- NSLayoutConstraint.activate([
- wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780),
- title.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- title.topAnchor.constraint(equalTo: wrapper.topAnchor),
- textFieldContainer.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- textFieldContainer.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- textFieldContainer.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 10),
- urlField.leadingAnchor.constraint(equalTo: textFieldContainer.leadingAnchor, constant: 12),
- urlField.trailingAnchor.constraint(equalTo: textFieldContainer.trailingAnchor, constant: -12),
- urlField.centerYAnchor.constraint(equalTo: textFieldContainer.centerYAnchor),
- actions.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- actions.topAnchor.constraint(equalTo: textFieldContainer.bottomAnchor, constant: 14),
- actions.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor)
- ])
- return wrapper
- }
- func scheduleHeader() -> NSView {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.alignment = .centerY
- row.distribution = .fill
- row.spacing = 12
- row.addArrangedSubview(textLabel("Schedule", font: typography.sectionTitleBold, color: palette.textPrimary))
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- row.addArrangedSubview(spacer)
- spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- row.addArrangedSubview(makeScheduleRefreshButton())
- row.addArrangedSubview(makeScheduleFilterDropdown())
- row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
- return row
- }
- private func schedulePageHeader() -> NSView {
- let container = NSStackView()
- container.translatesAutoresizingMaskIntoConstraints = false
- container.userInterfaceLayoutDirection = .leftToRight
- container.orientation = .vertical
- container.spacing = 8
- container.alignment = .width
- let titleRow = NSStackView()
- titleRow.translatesAutoresizingMaskIntoConstraints = false
- titleRow.userInterfaceLayoutDirection = .leftToRight
- titleRow.orientation = .horizontal
- titleRow.alignment = .centerY
- titleRow.distribution = .fill
- titleRow.spacing = 0
- let titleLabel = textLabel("Schedule", font: typography.pageTitle, color: palette.textPrimary)
- titleLabel.alignment = .left
- titleLabel.userInterfaceLayoutDirection = .leftToRight
- titleLabel.maximumNumberOfLines = 1
- titleLabel.lineBreakMode = .byTruncatingTail
- titleLabel.setContentHuggingPriority(.required, for: .horizontal)
- titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
- let titleRowSpacer = NSView()
- titleRowSpacer.translatesAutoresizingMaskIntoConstraints = false
- titleRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- titleRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- titleRow.addArrangedSubview(titleLabel)
- if hasGoogleSessionAvailable() && storeKitCoordinator.hasPremiumAccess {
- titleRow.addArrangedSubview(makeSchedulePageAddButton())
- titleRow.setCustomSpacing(12, after: titleLabel)
- }
- titleRow.addArrangedSubview(titleRowSpacer)
- container.addArrangedSubview(titleRow)
- let filterRow = NSStackView()
- filterRow.translatesAutoresizingMaskIntoConstraints = false
- filterRow.userInterfaceLayoutDirection = .leftToRight
- filterRow.orientation = .horizontal
- filterRow.alignment = .centerY
- filterRow.spacing = 18
- filterRow.distribution = .fill
- let filterDropdown = makeSchedulePageFilterDropdown()
- schedulePageFilterDropdown = filterDropdown
- filterRow.addArrangedSubview(filterDropdown)
- filterRow.setCustomSpacing(20, after: filterDropdown)
- let (fromShell, fromPicker) = makeScheduleDatePicker(date: schedulePageFromDate)
- schedulePageFromDatePicker = fromPicker
- filterRow.addArrangedSubview(fromShell)
- filterRow.setCustomSpacing(16, after: fromShell)
- let (toShell, toPicker) = makeScheduleDatePicker(date: schedulePageToDate)
- schedulePageToDatePicker = toPicker
- filterRow.addArrangedSubview(toShell)
- NSLayoutConstraint.activate([
- fromShell.widthAnchor.constraint(equalTo: toShell.widthAnchor),
- fromShell.widthAnchor.constraint(greaterThanOrEqualToConstant: 152)
- ])
- let filterRowSpacer = NSView()
- filterRowSpacer.translatesAutoresizingMaskIntoConstraints = false
- filterRowSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- filterRowSpacer.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- filterRow.addArrangedSubview(filterRowSpacer)
- let applyButton = makeSchedulePagePillButton(title: "Apply", action: #selector(schedulePageApplyDateRangePressed(_:)))
- filterRow.addArrangedSubview(applyButton)
- filterRow.setCustomSpacing(22, after: applyButton)
- let resetButton = makeSchedulePagePillButton(title: "Reset", action: #selector(schedulePageResetFiltersPressed(_:)))
- filterRow.addArrangedSubview(resetButton)
- filterRow.setCustomSpacing(22, after: resetButton)
- filterRow.addArrangedSubview(makeScheduleRefreshButton())
- container.addArrangedSubview(filterRow)
- NSLayoutConstraint.activate([
- titleRow.widthAnchor.constraint(equalTo: container.widthAnchor),
- filterRow.widthAnchor.constraint(equalTo: container.widthAnchor)
- ])
- refreshSchedulePageDateFilterUI()
- return container
- }
- private func makeSchedulePageFilterDropdown() -> NSPopUpButton {
- let button = HoverPopUpButton(frame: .zero, pullsDown: false)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.autoenablesItems = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 8
- button.layer?.masksToBounds = true
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.filterText
- button.contentTintColor = palette.textSecondary
- button.target = self
- button.action = #selector(schedulePageFilterDropdownChanged(_:))
- button.heightAnchor.constraint(equalToConstant: 34).isActive = true
- button.widthAnchor.constraint(equalToConstant: 228).isActive = true
- button.removeAllItems()
- button.addItems(withTitles: ["All", "Today", "This week", "This month", "Custom range"])
- button.selectItem(at: schedulePageFilter.rawValue)
- if let menu = button.menu {
- for (index, item) in menu.items.enumerated() {
- item.tag = index
- }
- }
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- button.onHoverChanged = { [weak button] hovering in
- button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- button.onHoverChanged?(false)
- return button
- }
- /// Rounded shell matching `makeSchedulePageFilterDropdown` (34pt, 8pt corner, border + hover). Both pickers use the same field+stepper style inside the shell.
- private func makeFilterStyleDatePicker(date: Date, changeAction: Selector) -> (NSView, NSDatePicker) {
- let shell = HoverSurfaceView()
- shell.translatesAutoresizingMaskIntoConstraints = false
- shell.wantsLayer = true
- shell.layer?.cornerRadius = 8
- shell.layer?.masksToBounds = true
- shell.layer?.borderWidth = 1
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverBackground = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- func applyShellIdleAppearance() {
- shell.layer?.backgroundColor = baseColor.cgColor
- shell.layer?.borderColor = baseBorder.cgColor
- }
- applyShellIdleAppearance()
- shell.onHoverChanged = { [weak shell] hovering in
- guard let shell else { return }
- shell.layer?.backgroundColor = (hovering ? hoverBackground : baseColor).cgColor
- shell.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- let picker = NSDatePicker()
- picker.translatesAutoresizingMaskIntoConstraints = false
- picker.isBordered = false
- picker.drawsBackground = false
- picker.focusRingType = .none
- picker.datePickerStyle = .textFieldAndStepper
- picker.datePickerElements = [.yearMonthDay]
- picker.dateValue = date
- picker.font = typography.filterText
- picker.textColor = palette.textSecondary
- picker.setContentHuggingPriority(.defaultLow, for: .horizontal)
- picker.target = self
- picker.action = changeAction
- shell.addSubview(picker)
- NSLayoutConstraint.activate([
- shell.heightAnchor.constraint(equalToConstant: 34),
- picker.leadingAnchor.constraint(equalTo: shell.leadingAnchor, constant: 8),
- picker.trailingAnchor.constraint(equalTo: shell.trailingAnchor, constant: -8),
- picker.centerYAnchor.constraint(equalTo: shell.centerYAnchor)
- ])
- return (shell, picker)
- }
- private func makeScheduleDatePicker(date: Date) -> (NSView, NSDatePicker) {
- makeFilterStyleDatePicker(date: date, changeAction: #selector(schedulePageDatePickerChanged(_:)))
- }
- private func makeSchedulePagePillButton(title: String, action: Selector) -> NSButton {
- let button = makeSchedulePillButton(title: title)
- button.target = self
- button.action = action
- button.widthAnchor.constraint(equalToConstant: 100).isActive = true
- return button
- }
- private func makeSchedulePageCardsContainer() -> NSView {
- if let observer = schedulePageScrollObservation {
- NotificationCenter.default.removeObserver(observer)
- }
- schedulePageScrollObservation = nil
- let wrapper = NSView()
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- wrapper.userInterfaceLayoutDirection = .leftToRight
- let scroll = NSScrollView()
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.userInterfaceLayoutDirection = .leftToRight
- scroll.drawsBackground = false
- scroll.hasHorizontalScroller = false
- scroll.hasVerticalScroller = true
- scroll.autohidesScrollers = true
- scroll.borderType = .noBorder
- scroll.scrollerStyle = .overlay
- scroll.automaticallyAdjustsContentInsets = false
- let clip = TopAlignedClipView()
- clip.drawsBackground = false
- clip.postsBoundsChangedNotifications = true
- scroll.contentView = clip
- schedulePageCardsScrollView = scroll
- wrapper.addSubview(scroll)
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.userInterfaceLayoutDirection = .leftToRight
- stack.orientation = .vertical
- stack.spacing = schedulePageCardSpacing
- stack.alignment = .width
- schedulePageCardsStack = stack
- scroll.documentView = stack
- NSLayoutConstraint.activate([
- scroll.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor),
- scroll.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor),
- scroll.topAnchor.constraint(equalTo: wrapper.topAnchor),
- scroll.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor),
- scroll.heightAnchor.constraint(greaterThanOrEqualToConstant: 420),
- stack.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
- stack.trailingAnchor.constraint(equalTo: scroll.contentView.trailingAnchor),
- stack.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
- stack.widthAnchor.constraint(equalTo: scroll.contentView.widthAnchor)
- ])
- scroll.contentView.postsBoundsChangedNotifications = true
- schedulePageScrollObservation = NotificationCenter.default.addObserver(
- forName: NSView.boundsDidChangeNotification,
- object: scroll.contentView,
- queue: .main
- ) { [weak self] _ in
- self?.schedulePageScrolled()
- }
- renderSchedulePageCards()
- return wrapper
- }
- private func scheduleTopAuthRow() -> NSView {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.alignment = .centerY
- row.spacing = 10
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- row.addArrangedSubview(spacer)
- spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- let host = GoogleProfileAuthHostView()
- host.translatesAutoresizingMaskIntoConstraints = false
- let authButton = makeGoogleAuthButton()
- host.authButton = authButton
- scheduleGoogleAuthHostView = host
- scheduleGoogleAuthButton = authButton
- host.addSubview(authButton)
- NSLayoutConstraint.activate([
- authButton.centerXAnchor.constraint(equalTo: host.centerXAnchor),
- authButton.centerYAnchor.constraint(equalTo: host.centerYAnchor)
- ])
- let hostPadW = host.widthAnchor.constraint(equalTo: authButton.widthAnchor, constant: 0)
- let hostPadH = host.heightAnchor.constraint(equalTo: authButton.heightAnchor, constant: 0)
- hostPadW.isActive = true
- hostPadH.isActive = true
- scheduleGoogleAuthHostPadWidthConstraint = hostPadW
- scheduleGoogleAuthHostPadHeightConstraint = hostPadH
- updateGoogleAuthButtonTitle()
- row.addArrangedSubview(host)
- row.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
- return row
- }
- private func makeScheduleFilterDropdown() -> NSPopUpButton {
- let button = HoverPopUpButton(frame: .zero, pullsDown: false)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.autoenablesItems = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 8
- button.layer?.masksToBounds = true
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.filterText
- button.contentTintColor = palette.textSecondary
- button.target = self
- button.action = #selector(scheduleFilterDropdownChanged(_:))
- button.heightAnchor.constraint(equalToConstant: 34).isActive = true
- button.widthAnchor.constraint(equalToConstant: 156).isActive = true
- button.removeAllItems()
- button.addItems(withTitles: ["All", "Today", "This week"])
- button.selectItem(at: scheduleFilter.rawValue)
- if let menu = button.menu {
- for (index, item) in menu.items.enumerated() {
- item.tag = index
- }
- }
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- button.onHoverChanged = { [weak button] hovering in
- button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- button.onHoverChanged?(false)
- scheduleFilterDropdown = button
- return button
- }
- private func makeSchedulePillButton(title: String) -> NSButton {
- let button = NSButton(title: title, target: nil, action: nil)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 8
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.font = typography.filterText
- button.contentTintColor = palette.textSecondary
- button.setButtonType(.momentaryChange)
- button.heightAnchor.constraint(equalToConstant: 34).isActive = true
- button.widthAnchor.constraint(greaterThanOrEqualToConstant: 132).isActive = true
- return button
- }
- private func makeGoogleAuthButton() -> NSButton {
- let button = HoverButton(title: "", target: self, action: #selector(scheduleConnectButtonPressed(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 16
- button.layer?.borderWidth = 1
- button.font = NSFont.systemFont(ofSize: 14, weight: .semibold)
- button.imagePosition = .imageLeading
- button.alignment = .center
- button.imageHugsTitle = true
- button.lineBreakMode = .byTruncatingTail
- button.contentTintColor = palette.textPrimary
- button.imageScaling = .scaleNone
- button.layer?.masksToBounds = true
- let heightConstraint = button.heightAnchor.constraint(equalToConstant: 42)
- heightConstraint.isActive = true
- scheduleGoogleAuthButtonHeightConstraint = heightConstraint
- let widthConstraint = button.widthAnchor.constraint(equalToConstant: 248)
- widthConstraint.isActive = true
- scheduleGoogleAuthButtonWidthConstraint = widthConstraint
- button.onHoverChanged = { [weak self] hovering in
- self?.scheduleGoogleAuthHovering = hovering
- self?.scheduleGoogleAuthHostView?.setProfileHoverActive(hovering)
- self?.applyGoogleAuthButtonSurface()
- }
- button.onHoverChanged?(false)
- return button
- }
- private func makeSchedulePageAddButton() -> NSButton {
- let diameter: CGFloat = 30
- let button = HoverButton(title: "", target: self, action: #selector(schedulePageAddMeetingPressed(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = diameter / 2
- button.layer?.masksToBounds = true
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.setButtonType(.momentaryChange)
- button.contentTintColor = palette.textSecondary
- button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: "Schedule meeting")
- button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
- button.imagePosition = .imageOnly
- button.imageScaling = .scaleProportionallyDown
- button.focusRingType = .none
- button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
- button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- button.onHoverChanged = { [weak button] hovering in
- button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- button.onHoverChanged?(false)
- return button
- }
- private func makeScheduleRefreshButton(
- action: Selector = #selector(scheduleReloadButtonPressed(_:)),
- accessibilityDescription: String = "Refresh meetings"
- ) -> NSButton {
- let diameter: CGFloat = 30
- let button = HoverButton(title: "", target: self, action: action)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = diameter / 2
- button.layer?.masksToBounds = true
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.setButtonType(.momentaryChange)
- button.contentTintColor = palette.textSecondary
- button.image = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: accessibilityDescription)
- button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .semibold)
- button.imagePosition = .imageOnly
- button.imageScaling = .scaleProportionallyDown
- button.focusRingType = .none
- button.heightAnchor.constraint(equalToConstant: diameter).isActive = true
- button.widthAnchor.constraint(equalToConstant: diameter).isActive = true
- let baseColor = palette.inputBackground
- let baseBorder = palette.inputBorder
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- let hoverBorder = baseBorder.blended(withFraction: 0.16, of: hoverBlend) ?? baseBorder
- button.onHoverChanged = { [weak button] hovering in
- button?.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- button?.layer?.borderColor = (hovering ? hoverBorder : baseBorder).cgColor
- }
- button.onHoverChanged?(false)
- return button
- }
- func scheduleCardsRow(meetings: [ScheduledMeeting]) -> NSView {
- let cardWidth: CGFloat = 240
- let cardsPerViewport: CGFloat = 3
- let viewportWidth = (cardWidth * cardsPerViewport) + (12 * (cardsPerViewport - 1))
- let wrapper = NSStackView()
- wrapper.translatesAutoresizingMaskIntoConstraints = false
- wrapper.orientation = .horizontal
- wrapper.alignment = .centerY
- wrapper.spacing = 10
- let leftButton = makeScheduleScrollButton(systemSymbol: "chevron.left", action: #selector(scheduleScrollLeftPressed(_:)))
- scheduleScrollLeftButton = leftButton
- wrapper.addArrangedSubview(leftButton)
- let scroll = NSScrollView()
- scheduleCardsScrollView = scroll
- scroll.translatesAutoresizingMaskIntoConstraints = false
- scroll.drawsBackground = false
- scroll.hasHorizontalScroller = false
- scroll.hasVerticalScroller = false
- scroll.horizontalScrollElasticity = .allowed
- scroll.verticalScrollElasticity = .none
- scroll.autohidesScrollers = false
- scroll.borderType = .noBorder
- scroll.automaticallyAdjustsContentInsets = false
- scroll.heightAnchor.constraint(equalToConstant: 150).isActive = true
- scroll.widthAnchor.constraint(equalToConstant: viewportWidth).isActive = true
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.orientation = .horizontal
- row.spacing = 12
- row.alignment = .top
- row.distribution = .gravityAreas
- row.setContentHuggingPriority(.defaultHigh, for: .horizontal)
- row.heightAnchor.constraint(equalToConstant: 150).isActive = true
- scheduleCardsStack = row
- scroll.documentView = row
- scroll.contentView.postsBoundsChangedNotifications = true
- // Pin top/leading/trailing only; avoid bottom == clip so the horizontal stack is not stretched vertically inside the clip (same as Schedule cards scroll).
- NSLayoutConstraint.activate([
- row.leadingAnchor.constraint(equalTo: scroll.contentView.leadingAnchor),
- row.trailingAnchor.constraint(greaterThanOrEqualTo: scroll.contentView.trailingAnchor),
- row.topAnchor.constraint(equalTo: scroll.contentView.topAnchor),
- row.heightAnchor.constraint(equalToConstant: 150)
- ])
- renderScheduleCards(into: row, meetings: meetings)
- wrapper.addArrangedSubview(scroll)
- let rightButton = makeScheduleScrollButton(systemSymbol: "chevron.right", action: #selector(scheduleScrollRightPressed(_:)))
- scheduleScrollRightButton = rightButton
- wrapper.addArrangedSubview(rightButton)
- scroll.setContentHuggingPriority(.defaultLow, for: .horizontal)
- scroll.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- wrapper.widthAnchor.constraint(greaterThanOrEqualToConstant: 780).isActive = true
- return wrapper
- }
- func scheduleCard(meeting: ScheduledMeeting, useFlexibleWidth: Bool = false, contentHeight: CGFloat = 150) -> NSView {
- let cardWidth: CGFloat = 240
- let card = roundedContainer(cornerRadius: 12, color: palette.sectionCard)
- styleSurface(card, borderColor: palette.inputBorder, borderWidth: 1, shadow: true)
- card.translatesAutoresizingMaskIntoConstraints = false
- card.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
- if useFlexibleWidth {
- card.setContentHuggingPriority(.defaultLow, for: .horizontal)
- card.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- } else {
- card.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
- card.setContentHuggingPriority(.required, for: .horizontal)
- card.setContentCompressionResistancePriority(.required, for: .horizontal)
- }
- let icon = roundedContainer(cornerRadius: 8, color: palette.meetingBadge)
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.widthAnchor.constraint(equalToConstant: 28).isActive = true
- icon.heightAnchor.constraint(equalToConstant: 28).isActive = true
- let iconView = NSImageView()
- iconView.translatesAutoresizingMaskIntoConstraints = false
- iconView.image = NSImage(systemSymbolName: "video.circle.fill", accessibilityDescription: "Meeting")
- iconView.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 18, weight: .semibold)
- iconView.contentTintColor = .white
- icon.addSubview(iconView)
- NSLayoutConstraint.activate([
- iconView.centerXAnchor.constraint(equalTo: icon.centerXAnchor),
- iconView.centerYAnchor.constraint(equalTo: icon.centerYAnchor)
- ])
- let title = textLabel(meeting.title, font: typography.cardTitle, color: palette.textPrimary)
- title.lineBreakMode = .byTruncatingTail
- title.maximumNumberOfLines = 1
- title.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- let subtitle = textLabel(meeting.subtitle ?? "Google Calendar", font: typography.cardSubtitle, color: palette.textPrimary)
- let time = textLabel(scheduleTimeText(for: meeting), font: typography.cardTime, color: palette.textSecondary)
- let duration = textLabel(scheduleDurationText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .medium), color: palette.textMuted)
- let dayChip = roundedContainer(cornerRadius: 7, color: palette.inputBackground)
- dayChip.translatesAutoresizingMaskIntoConstraints = false
- dayChip.layer?.borderWidth = 1
- dayChip.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.8).cgColor
- let dayText = textLabel(scheduleDayText(for: meeting), font: NSFont.systemFont(ofSize: 11, weight: .semibold), color: palette.textSecondary)
- dayText.translatesAutoresizingMaskIntoConstraints = false
- dayChip.addSubview(dayText)
- NSLayoutConstraint.activate([
- dayText.leadingAnchor.constraint(equalTo: dayChip.leadingAnchor, constant: 8),
- dayText.trailingAnchor.constraint(equalTo: dayChip.trailingAnchor, constant: -8),
- dayText.topAnchor.constraint(equalTo: dayChip.topAnchor, constant: 4),
- dayText.bottomAnchor.constraint(equalTo: dayChip.bottomAnchor, constant: -4)
- ])
- card.addSubview(icon)
- card.addSubview(dayChip)
- card.addSubview(title)
- card.addSubview(subtitle)
- card.addSubview(time)
- card.addSubview(duration)
- var titleConstraints: [NSLayoutConstraint] = [
- icon.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
- icon.topAnchor.constraint(equalTo: card.topAnchor, constant: 10),
- dayChip.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -10),
- dayChip.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
- title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 6),
- title.centerYAnchor.constraint(equalTo: icon.centerYAnchor),
- title.trailingAnchor.constraint(lessThanOrEqualTo: dayChip.leadingAnchor, constant: -8)
- ]
- if !useFlexibleWidth {
- titleConstraints.append(title.widthAnchor.constraint(lessThanOrEqualToConstant: 130))
- }
- NSLayoutConstraint.activate(titleConstraints + [
- subtitle.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
- subtitle.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 10),
- subtitle.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
- time.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
- time.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 5),
- time.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10),
- duration.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 10),
- duration.topAnchor.constraint(equalTo: time.bottomAnchor, constant: 4),
- duration.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -10)
- ])
- let hit = HoverButton(title: "", target: self, action: #selector(scheduleCardButtonPressed(_:)))
- hit.translatesAutoresizingMaskIntoConstraints = false
- hit.isBordered = false
- hit.bezelStyle = .regularSquare
- hit.identifier = NSUserInterfaceItemIdentifier(meeting.meetURL.absoluteString)
- hit.heightAnchor.constraint(equalToConstant: contentHeight).isActive = true
- if useFlexibleWidth {
- hit.setContentHuggingPriority(.defaultLow, for: .horizontal)
- hit.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- } else {
- hit.widthAnchor.constraint(equalToConstant: cardWidth).isActive = true
- hit.setContentHuggingPriority(.required, for: .horizontal)
- hit.setContentCompressionResistancePriority(.required, for: .horizontal)
- }
- hit.addSubview(card)
- NSLayoutConstraint.activate([
- card.leadingAnchor.constraint(equalTo: hit.leadingAnchor),
- card.trailingAnchor.constraint(equalTo: hit.trailingAnchor),
- card.topAnchor.constraint(equalTo: hit.topAnchor),
- card.bottomAnchor.constraint(equalTo: hit.bottomAnchor)
- ])
- hit.onHoverChanged = { [weak self] hovering in
- guard let self else { return }
- let base = self.palette.sectionCard
- let hoverBlend = self.darkModeEnabled ? NSColor.white : NSColor.black
- let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
- if self.storeKitCoordinator.hasPremiumAccess {
- card.layer?.backgroundColor = (hovering ? hover : base).cgColor
- } else {
- card.layer?.backgroundColor = base.cgColor
- }
- }
- hit.onHoverChanged?(false)
- if !storeKitCoordinator.hasPremiumAccess {
- let lockOverlay = NSVisualEffectView()
- lockOverlay.translatesAutoresizingMaskIntoConstraints = false
- lockOverlay.material = darkModeEnabled ? .hudWindow : .popover
- lockOverlay.blendingMode = .withinWindow
- lockOverlay.state = .active
- lockOverlay.wantsLayer = true
- lockOverlay.layer?.cornerRadius = 12
- lockOverlay.layer?.masksToBounds = true
- lockOverlay.layer?.backgroundColor = NSColor.black.withAlphaComponent(darkModeEnabled ? 0.28 : 0.12).cgColor
- let lockLabel = textLabel("Get Premium to see events", font: NSFont.systemFont(ofSize: 12, weight: .semibold), color: darkModeEnabled ? .white : .black)
- lockLabel.alignment = .center
- card.addSubview(lockOverlay)
- lockOverlay.addSubview(lockLabel)
- NSLayoutConstraint.activate([
- lockOverlay.leadingAnchor.constraint(equalTo: card.leadingAnchor),
- lockOverlay.trailingAnchor.constraint(equalTo: card.trailingAnchor),
- lockOverlay.topAnchor.constraint(equalTo: card.topAnchor),
- lockOverlay.bottomAnchor.constraint(equalTo: card.bottomAnchor),
- lockLabel.centerXAnchor.constraint(equalTo: lockOverlay.centerXAnchor),
- lockLabel.centerYAnchor.constraint(equalTo: lockOverlay.centerYAnchor),
- lockLabel.leadingAnchor.constraint(greaterThanOrEqualTo: lockOverlay.leadingAnchor, constant: 10),
- lockLabel.trailingAnchor.constraint(lessThanOrEqualTo: lockOverlay.trailingAnchor, constant: -10)
- ])
- hit.toolTip = "Premium required. Click to open paywall."
- }
- return hit
- }
- private func makeScheduleScrollButton(systemSymbol: String, action: Selector) -> NSButton {
- let button = NSButton(title: "", target: self, action: action)
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 16
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.layer?.borderColor = palette.inputBorder.cgColor
- button.layer?.borderWidth = 1
- button.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Scroll meetings")
- button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
- button.imagePosition = .imageOnly
- button.imageScaling = .scaleProportionallyDown
- button.contentTintColor = palette.textSecondary
- button.focusRingType = .none
- button.heightAnchor.constraint(equalToConstant: 32).isActive = true
- button.widthAnchor.constraint(equalToConstant: 32).isActive = true
- return button
- }
- }
- private extension PremiumPlan {
- var displayName: String {
- switch self {
- case .weekly: return "Weekly"
- case .monthly: return "Monthly"
- case .yearly: return "Yearly"
- case .lifetime: return "Lifetime"
- }
- }
- }
- extension ViewController: NSTextFieldDelegate {
- func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
- if control === browseAddressField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
- browseOpenAddressClicked(nil)
- return true
- }
- return false
- }
- }
- extension ViewController: AVSpeechSynthesizerDelegate {
- func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
- DispatchQueue.main.async { [weak self] in
- guard let self else { return }
- guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
- guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }
- self.aiCompanionIsUsingSpeech = false
- self.aiCompanionCurrentlySpeakingButtonId = nil
- if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
- button.title = "Play Audio"
- }
- self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Finished"
- }
- }
- func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
- DispatchQueue.main.async { [weak self] in
- guard let self else { return }
- guard self.aiCompanionSpeechSynthesizer === synthesizer else { return }
- guard let buttonId = self.aiCompanionCurrentlySpeakingButtonId else { return }
- self.aiCompanionIsUsingSpeech = false
- self.aiCompanionCurrentlySpeakingButtonId = nil
- if let button = self.aiCompanionCurrentlyPlayingButton, ObjectIdentifier(button) == buttonId {
- button.title = "Play Audio"
- }
- self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Stopped"
- }
- }
- }
- extension ViewController: AVAudioPlayerDelegate {
- func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
- DispatchQueue.main.async { [weak self] in
- guard let self else { return }
- guard self.aiCompanionLocalAudioPlayer === player else { return }
- self.aiCompanionAudioDidFinish()
- }
- }
- func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
- DispatchQueue.main.async { [weak self] in
- guard let self else { return }
- guard self.aiCompanionLocalAudioPlayer === player else { return }
- if let button = self.aiCompanionCurrentlyPlayingButton {
- let buttonId = ObjectIdentifier(button)
- button.title = "Play Audio"
- self.aiCompanionAudioStatusLabelByView[buttonId]?.stringValue = "Failed: \(error?.localizedDescription ?? "decode error")"
- }
- self.aiCompanionAudioPlayer?.pause()
- self.aiCompanionAudioPlayer = nil
- self.aiCompanionLocalAudioPlayer?.stop()
- self.aiCompanionLocalAudioPlayer = nil
- self.aiCompanionCurrentlyPlayingURL = nil
- self.aiCompanionCurrentlyPlayingButton = nil
- self.aiCompanionTimeControlObserver = nil
- }
- }
- }
- extension ViewController: NSWindowDelegate {
- func windowWillClose(_ notification: Notification) {
- guard let closingWindow = notification.object as? NSWindow else { return }
- if closingWindow === aiCompanionNotesPanel {
- aiCompanionStopNotesOutsideClickMonitor()
- aiCompanionNotesPanel = nil
- aiCompanionNotesRootView = nil
- aiCompanionNotesHeaderView = nil
- aiCompanionNotesTitleLabel = nil
- aiCompanionNotesSubtitleLabel = nil
- aiCompanionNotesTextView = nil
- aiCompanionNotesCopyButton = nil
- aiCompanionNotesCloseButton = nil
- return
- }
- if closingWindow === paywallWindow {
- paywallWindow = nil
- paywallUpgradeFlowEnabled = false
- }
- }
- }
- @available(macOS 13.0, *)
- private final class MeetingSystemAudioRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
- private let outputURL: URL
- private var stream: SCStream?
- private var writer: AVAssetWriter?
- private var writerInput: AVAssetWriterInput?
- private let outputQueue = DispatchQueue(label: "meeting.system.audio.capture")
- private var didStartSession = false
- init(outputURL: URL) {
- self.outputURL = outputURL
- }
- func start() async throws {
- try? FileManager.default.removeItem(at: outputURL)
- let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
- guard let display = content.displays.first else {
- throw NSError(domain: "MeetingSystemAudioRecorder", code: 1, userInfo: [NSLocalizedDescriptionKey: "No display available for system audio capture."])
- }
- let writer = try AVAssetWriter(outputURL: outputURL, fileType: .m4a)
- let inputSettings: [String: Any] = [
- AVFormatIDKey: kAudioFormatMPEG4AAC,
- AVSampleRateKey: 48_000,
- AVNumberOfChannelsKey: 2,
- AVEncoderBitRateKey: 128_000
- ]
- let input = AVAssetWriterInput(mediaType: .audio, outputSettings: inputSettings)
- input.expectsMediaDataInRealTime = true
- guard writer.canAdd(input) else {
- throw NSError(domain: "MeetingSystemAudioRecorder", code: 2, userInfo: [NSLocalizedDescriptionKey: "Cannot add audio writer input."])
- }
- writer.add(input)
- self.writer = writer
- self.writerInput = input
- didStartSession = false
- let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: [])
- let config = SCStreamConfiguration()
- config.width = 2
- config.height = 2
- config.minimumFrameInterval = CMTime(value: 1, timescale: 2)
- config.queueDepth = 1
- config.capturesAudio = true
- config.sampleRate = 48_000
- config.channelCount = 2
- if #available(macOS 13.0, *) {
- config.excludesCurrentProcessAudio = true
- }
- let stream = SCStream(filter: filter, configuration: config, delegate: self)
- self.stream = stream
- try stream.addStreamOutput(self, type: .audio, sampleHandlerQueue: outputQueue)
- try await stream.startCapture()
- }
- func stop() async throws {
- if let stream {
- try? await stream.stopCapture()
- self.stream = nil
- }
- writerInput?.markAsFinished()
- guard let writer else { return }
- await withCheckedContinuation { continuation in
- writer.finishWriting {
- continuation.resume()
- }
- }
- self.writer = nil
- self.writerInput = nil
- }
- func stream(_ stream: SCStream, didStopWithError error: Error) {
- // Capture may stop on permission changes or display changes; caller handles lifecycle.
- }
- func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of outputType: SCStreamOutputType) {
- guard outputType == .audio else { return }
- guard CMSampleBufferDataIsReady(sampleBuffer) else { return }
- guard let writer = writer, let input = writerInput else { return }
- if writer.status == .unknown {
- writer.startWriting()
- }
- if writer.status == .writing {
- let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
- if !didStartSession {
- writer.startSession(atSourceTime: pts)
- didStartSession = true
- }
- if input.isReadyForMoreMediaData {
- input.append(sampleBuffer)
- }
- }
- }
- }
- /// 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.
- private final class TopAlignedClipView: NSClipView {
- override var isFlipped: Bool { true }
- }
- /// Wraps the Google auth control and draws a circular accent ring with a light pulse while the signed-in avatar is hovered.
- private final class GoogleProfileAuthHostView: NSView {
- weak var authButton: NSButton? {
- didSet { needsLayout = true }
- }
- private let ringLayer = CAShapeLayer()
- private var avatarRingMode = false
- private static let ringLineWidth: CGFloat = 2.25
- override init(frame frameRect: NSRect) {
- super.init(frame: frameRect)
- wantsLayer = true
- layer?.masksToBounds = false
- ringLayer.fillColor = nil
- ringLayer.strokeColor = NSColor.clear.cgColor
- ringLayer.lineWidth = Self.ringLineWidth
- ringLayer.lineCap = .round
- ringLayer.opacity = 0
- ringLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
- layer?.insertSublayer(ringLayer, at: 0)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- func setAvatarRingMode(_ enabled: Bool) {
- avatarRingMode = enabled
- if enabled == false {
- ringLayer.removeAllAnimations()
- ringLayer.opacity = 0
- ringLayer.lineWidth = Self.ringLineWidth
- }
- needsLayout = true
- }
- func updateRingAppearance(isDark: Bool, accent: NSColor) {
- let stroke = isDark
- ? accent.blended(withFraction: 0.22, of: NSColor.white) ?? accent
- : accent
- CATransaction.begin()
- CATransaction.setDisableActions(true)
- ringLayer.strokeColor = stroke.withAlphaComponent(0.95).cgColor
- CATransaction.commit()
- }
- func setProfileHoverActive(_ active: Bool) {
- guard avatarRingMode else { return }
- ringLayer.removeAnimation(forKey: "pulse")
- if active {
- layoutRingPathIfNeeded()
- CATransaction.begin()
- CATransaction.setAnimationDuration(0.22)
- ringLayer.opacity = 1
- CATransaction.commit()
- let pulse = CABasicAnimation(keyPath: "lineWidth")
- pulse.fromValue = Self.ringLineWidth * 0.88
- pulse.toValue = Self.ringLineWidth * 1.45
- pulse.duration = 0.72
- pulse.autoreverses = true
- pulse.repeatCount = .infinity
- pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- ringLayer.add(pulse, forKey: "pulse")
- } else {
- CATransaction.begin()
- CATransaction.setAnimationDuration(0.18)
- ringLayer.opacity = 0
- CATransaction.commit()
- ringLayer.lineWidth = Self.ringLineWidth
- }
- }
- private func layoutRingPathIfNeeded() {
- guard avatarRingMode, let btn = authButton else { return }
- let f = btn.frame
- guard f.width > 1, f.height > 1 else { return }
- let center = CGPoint(x: f.midX, y: f.midY)
- let avatarR = min(f.width, f.height) / 2
- let gap: CGFloat = 3.5
- let ringRadius = avatarR + gap
- let d = ringRadius * 2
- CATransaction.begin()
- CATransaction.setDisableActions(true)
- ringLayer.bounds = CGRect(x: 0, y: 0, width: d, height: d)
- ringLayer.position = center
- ringLayer.path = CGPath(ellipseIn: CGRect(origin: .zero, size: CGSize(width: d, height: d)), transform: nil)
- CATransaction.commit()
- }
- override func layout() {
- super.layout()
- layoutRingPathIfNeeded()
- }
- }
- /// Ensures `NSClickGestureRecognizer` on the row receives clicks instead of child label/image views swallowing them.
- private class RowHitTestView: NSView {
- override func hitTest(_ point: NSPoint) -> NSView? {
- return bounds.contains(point) ? self : nil
- }
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
- true
- }
- }
- private final class HoverTrackingView: RowHitTestView {
- var onHoverChanged: ((Bool) -> Void)?
- var onClick: (() -> Void)?
- var showsHandCursor = true
- private var trackingAreaRef: NSTrackingArea?
- private var isHovering = false {
- didSet {
- guard isHovering != oldValue else { return }
- onHoverChanged?(isHovering)
- }
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [
- .activeInKeyWindow,
- .inVisibleRect,
- .mouseEnteredAndExited
- ]
- let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- isHovering = true
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- isHovering = false
- }
- override func resetCursorRects() {
- super.resetCursorRects()
- guard showsHandCursor else { return }
- addCursorRect(bounds, cursor: .pointingHand)
- }
- override func mouseUp(with event: NSEvent) {
- super.mouseUp(with: event)
- guard event.type == .leftMouseUp else { return }
- onClick?()
- }
- }
- /// Hover tracking without overriding hit-testing; keeps controls like text fields interactive.
- private final class HoverSurfaceView: NSView {
- var onHoverChanged: ((Bool) -> Void)?
- private var trackingAreaRef: NSTrackingArea?
- private var isHovering = false {
- didSet {
- guard isHovering != oldValue else { return }
- onHoverChanged?(isHovering)
- }
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [
- .activeInKeyWindow,
- .inVisibleRect,
- .mouseEnteredAndExited
- ]
- let area = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
- addTrackingArea(area)
- trackingAreaRef = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- isHovering = true
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- isHovering = false
- }
- }
- private final class HoverButton: NSButton {
- var onHoverChanged: ((Bool) -> Void)?
- var showsHandCursor = true
- private var trackingAreaRef: NSTrackingArea?
- private var isHovering = false {
- didSet {
- guard isHovering != oldValue else { return }
- onHoverChanged?(isHovering)
- }
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [
- .activeInKeyWindow,
- .inVisibleRect,
- .mouseEnteredAndExited
- ]
- let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
- addTrackingArea(tracking)
- trackingAreaRef = tracking
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- if showsHandCursor {
- NSCursor.pointingHand.set()
- }
- isHovering = true
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- isHovering = false
- }
- }
- private final class HoverPopUpButton: NSPopUpButton {
- var onHoverChanged: ((Bool) -> Void)?
- private var trackingAreaRef: NSTrackingArea?
- private var isHovering = false {
- didSet {
- guard isHovering != oldValue else { return }
- onHoverChanged?(isHovering)
- }
- }
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let trackingAreaRef {
- removeTrackingArea(trackingAreaRef)
- }
- let options: NSTrackingArea.Options = [
- .activeInKeyWindow,
- .inVisibleRect,
- .mouseEnteredAndExited
- ]
- let tracking = NSTrackingArea(rect: bounds, options: options, owner: self, userInfo: nil)
- addTrackingArea(tracking)
- trackingAreaRef = tracking
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- isHovering = true
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- isHovering = false
- }
- }
- private func circularNSImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
- let size = NSSize(width: diameter, height: diameter)
- let result = NSImage(size: size)
- result.lockFocus()
- if let ctx = NSGraphicsContext.current {
- ctx.imageInterpolation = .high
- }
- let rect = NSRect(origin: .zero, size: size)
- let path = NSBezierPath(ovalIn: rect)
- path.addClip()
- let src = image.size.width > 0 && image.size.height > 0
- ? NSRect(origin: .zero, size: image.size)
- : NSRect(origin: .zero, size: size)
- image.draw(in: rect, from: src, operation: .copy, fraction: 1.0)
- result.unlockFocus()
- result.isTemplate = false
- return result
- }
- private final class GoogleAccountMenuViewController: NSViewController {
- private let palette: Palette
- private let darkModeEnabled: Bool
- private let displayName: String
- private let email: String
- private let avatar: NSImage?
- private let onSignOut: () -> Void
- init(
- palette: Palette,
- darkModeEnabled: Bool,
- displayName: String,
- email: String,
- avatar: NSImage?,
- onSignOut: @escaping () -> Void
- ) {
- self.palette = palette
- self.darkModeEnabled = darkModeEnabled
- self.displayName = displayName
- self.email = email
- self.avatar = avatar
- self.onSignOut = onSignOut
- super.init(nibName: nil, bundle: nil)
- view = makeContentView()
- view.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
- preferredContentSize = NSSize(width: 300, height: 158)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- private func makeContentView() -> NSView {
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- let card = NSView()
- card.translatesAutoresizingMaskIntoConstraints = false
- card.wantsLayer = true
- card.layer?.cornerRadius = 14
- card.layer?.backgroundColor = palette.sectionCard.cgColor
- card.layer?.borderColor = palette.inputBorder.cgColor
- card.layer?.borderWidth = 1
- card.layer?.shadowColor = NSColor.black.cgColor
- card.layer?.shadowOpacity = darkModeEnabled ? 0.5 : 0.2
- card.layer?.shadowOffset = CGSize(width: 0, height: 6)
- card.layer?.shadowRadius = 18
- card.layer?.masksToBounds = false
- root.addSubview(card)
- NSLayoutConstraint.activate([
- card.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 8),
- card.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -8),
- card.topAnchor.constraint(equalTo: root.topAnchor, constant: 8),
- card.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -8),
- root.widthAnchor.constraint(equalToConstant: 300)
- ])
- let inner = NSStackView()
- inner.translatesAutoresizingMaskIntoConstraints = false
- inner.orientation = .vertical
- inner.spacing = 0
- inner.alignment = .leading
- card.addSubview(inner)
- NSLayoutConstraint.activate([
- inner.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
- inner.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
- inner.topAnchor.constraint(equalTo: card.topAnchor, constant: 18),
- inner.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -10)
- ])
- let headerRow = NSView()
- headerRow.translatesAutoresizingMaskIntoConstraints = false
- let avatarBox = NSView()
- avatarBox.translatesAutoresizingMaskIntoConstraints = false
- avatarBox.wantsLayer = true
- avatarBox.layer?.cornerRadius = 24
- avatarBox.layer?.masksToBounds = true
- avatarBox.layer?.borderColor = palette.inputBorder.cgColor
- avatarBox.layer?.borderWidth = 1
- let avatarView = NSImageView()
- avatarView.translatesAutoresizingMaskIntoConstraints = false
- avatarView.imageScaling = .scaleAxesIndependently
- avatarView.image = resolvedAvatarImage()
- avatarBox.addSubview(avatarView)
- NSLayoutConstraint.activate([
- avatarBox.widthAnchor.constraint(equalToConstant: 48),
- avatarBox.heightAnchor.constraint(equalToConstant: 48),
- avatarView.leadingAnchor.constraint(equalTo: avatarBox.leadingAnchor),
- avatarView.trailingAnchor.constraint(equalTo: avatarBox.trailingAnchor),
- avatarView.topAnchor.constraint(equalTo: avatarBox.topAnchor),
- avatarView.bottomAnchor.constraint(equalTo: avatarBox.bottomAnchor)
- ])
- let textColumn = NSStackView()
- textColumn.translatesAutoresizingMaskIntoConstraints = false
- textColumn.orientation = .vertical
- textColumn.spacing = 3
- textColumn.alignment = .leading
- let nameField = NSTextField(labelWithString: displayName)
- nameField.translatesAutoresizingMaskIntoConstraints = false
- nameField.font = NSFont.systemFont(ofSize: 15, weight: .semibold)
- nameField.textColor = palette.textPrimary
- nameField.lineBreakMode = .byTruncatingTail
- nameField.maximumNumberOfLines = 1
- nameField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- let emailField = NSTextField(labelWithString: email)
- emailField.translatesAutoresizingMaskIntoConstraints = false
- emailField.font = NSFont.systemFont(ofSize: 12, weight: .regular)
- emailField.textColor = palette.textTertiary
- emailField.lineBreakMode = .byTruncatingTail
- emailField.maximumNumberOfLines = 1
- emailField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
- textColumn.addArrangedSubview(nameField)
- textColumn.addArrangedSubview(emailField)
- headerRow.addSubview(avatarBox)
- headerRow.addSubview(textColumn)
- NSLayoutConstraint.activate([
- avatarBox.leadingAnchor.constraint(equalTo: headerRow.leadingAnchor),
- avatarBox.topAnchor.constraint(equalTo: headerRow.topAnchor),
- avatarBox.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor),
- textColumn.leadingAnchor.constraint(equalTo: avatarBox.trailingAnchor, constant: 14),
- textColumn.trailingAnchor.constraint(equalTo: headerRow.trailingAnchor),
- textColumn.centerYAnchor.constraint(equalTo: avatarBox.centerYAnchor),
- textColumn.topAnchor.constraint(greaterThanOrEqualTo: headerRow.topAnchor),
- textColumn.bottomAnchor.constraint(lessThanOrEqualTo: headerRow.bottomAnchor)
- ])
- inner.addArrangedSubview(headerRow)
- headerRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
- inner.setCustomSpacing(14, after: headerRow)
- let separator = NSView()
- separator.translatesAutoresizingMaskIntoConstraints = false
- separator.wantsLayer = true
- separator.layer?.backgroundColor = palette.separator.cgColor
- separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
- inner.addArrangedSubview(separator)
- separator.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
- inner.setCustomSpacing(6, after: separator)
- let signOutRow = HoverTrackingView()
- signOutRow.translatesAutoresizingMaskIntoConstraints = false
- signOutRow.heightAnchor.constraint(equalToConstant: 44).isActive = true
- signOutRow.wantsLayer = true
- signOutRow.layer?.cornerRadius = 10
- let signOutIcon = NSImageView()
- signOutIcon.translatesAutoresizingMaskIntoConstraints = false
- signOutIcon.imageScaling = .scaleProportionallyDown
- if let sym = NSImage(systemSymbolName: "rectangle.portrait.and.arrow.right", accessibilityDescription: nil) {
- signOutIcon.image = sym
- signOutIcon.contentTintColor = palette.textSecondary
- signOutIcon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 14, weight: .medium)
- }
- let signOutLabel = NSTextField(labelWithString: "Log out")
- signOutLabel.translatesAutoresizingMaskIntoConstraints = false
- signOutLabel.font = NSFont.systemFont(ofSize: 14, weight: .medium)
- signOutLabel.textColor = palette.textPrimary
- signOutRow.addSubview(signOutIcon)
- signOutRow.addSubview(signOutLabel)
- NSLayoutConstraint.activate([
- signOutIcon.leadingAnchor.constraint(equalTo: signOutRow.leadingAnchor, constant: 10),
- signOutIcon.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
- signOutIcon.widthAnchor.constraint(equalToConstant: 20),
- signOutIcon.heightAnchor.constraint(equalToConstant: 20),
- signOutLabel.leadingAnchor.constraint(equalTo: signOutIcon.trailingAnchor, constant: 10),
- signOutLabel.centerYAnchor.constraint(equalTo: signOutRow.centerYAnchor),
- signOutLabel.trailingAnchor.constraint(lessThanOrEqualTo: signOutRow.trailingAnchor, constant: -10)
- ])
- let signOutClick = NSClickGestureRecognizer(target: self, action: #selector(signOutClicked))
- signOutRow.addGestureRecognizer(signOutClick)
- signOutRow.onHoverChanged = { [weak self] hovering in
- guard let self else { return }
- signOutRow.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
- }
- signOutRow.onHoverChanged?(false)
- inner.addArrangedSubview(signOutRow)
- signOutRow.widthAnchor.constraint(equalTo: inner.widthAnchor).isActive = true
- return root
- }
- private func resolvedAvatarImage() -> NSImage {
- if let a = avatar {
- return circularNSImage(a, diameter: 48)
- }
- return initialLetterAvatar()
- }
- private func initialLetterAvatar() -> NSImage {
- let d: CGFloat = 48
- let letter = displayName.trimmingCharacters(in: .whitespacesAndNewlines).first.map { String($0).uppercased() } ?? "?"
- let img = NSImage(size: NSSize(width: d, height: d))
- img.lockFocus()
- palette.primaryBlue.setFill()
- NSBezierPath(ovalIn: NSRect(x: 0, y: 0, width: d, height: d)).fill()
- let attrs: [NSAttributedString.Key: Any] = [
- .font: NSFont.systemFont(ofSize: 20, weight: .semibold),
- .foregroundColor: NSColor.white
- ]
- let sz = (letter as NSString).size(withAttributes: attrs)
- let origin = NSPoint(x: (d - sz.width) / 2, y: (d - sz.height) / 2)
- (letter as NSString).draw(at: origin, withAttributes: attrs)
- img.unlockFocus()
- img.isTemplate = false
- return img
- }
- @objc private func signOutClicked() {
- onSignOut()
- }
- }
- private final class SettingsMenuViewController: NSViewController {
- private let palette: Palette
- private let typography: Typography
- private let speechLocaleOptions: [SpeechLocaleOption]
- private let selectedPrimaryLanguageIdentifier: String?
- private let selectedSecondaryLanguageIdentifier: String?
- private let onToggleDarkMode: (Bool) -> Void
- private let onUpdatePreferredSpeechLanguages: (String, String?) -> Void
- private let onAction: (SettingsAction, NSView?, NSPoint?) -> Void
- private var darkToggle: NSSwitch?
- private var primaryLanguagePopup: NSPopUpButton?
- private var secondaryLanguagePopup: NSPopUpButton?
- init(
- palette: Palette,
- typography: Typography,
- darkModeEnabled: Bool,
- showRateUsInSettings: Bool,
- showUpgradeInSettings: Bool,
- speechLocaleOptions: [SpeechLocaleOption],
- selectedPrimaryLanguageIdentifier: String?,
- selectedSecondaryLanguageIdentifier: String?,
- onToggleDarkMode: @escaping (Bool) -> Void,
- onUpdatePreferredSpeechLanguages: @escaping (String, String?) -> Void,
- onAction: @escaping (SettingsAction, NSView?, NSPoint?) -> Void
- ) {
- self.palette = palette
- self.typography = typography
- self.speechLocaleOptions = speechLocaleOptions
- self.selectedPrimaryLanguageIdentifier = selectedPrimaryLanguageIdentifier
- self.selectedSecondaryLanguageIdentifier = selectedSecondaryLanguageIdentifier
- self.onToggleDarkMode = onToggleDarkMode
- self.onUpdatePreferredSpeechLanguages = onUpdatePreferredSpeechLanguages
- self.onAction = onAction
- super.init(nibName: nil, bundle: nil)
- self.view = makeView(
- darkModeEnabled: darkModeEnabled,
- showRateUsInSettings: showRateUsInSettings,
- showUpgradeInSettings: showUpgradeInSettings
- )
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- func setDarkModeEnabled(_ enabled: Bool) {
- darkToggle?.state = enabled ? .on : .off
- }
- private func makeView(
- darkModeEnabled: Bool,
- showRateUsInSettings: Bool,
- showUpgradeInSettings: Bool
- ) -> NSView {
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- let card = roundedCard()
- root.addSubview(card)
- NSLayoutConstraint.activate([
- card.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- card.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- card.topAnchor.constraint(equalTo: root.topAnchor),
- card.bottomAnchor.constraint(equalTo: root.bottomAnchor),
- root.widthAnchor.constraint(equalToConstant: 320)
- ])
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.orientation = .vertical
- stack.spacing = 6
- stack.alignment = .leading
- card.addSubview(stack)
- NSLayoutConstraint.activate([
- stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 14),
- stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -14),
- stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 14),
- stack.bottomAnchor.constraint(lessThanOrEqualTo: card.bottomAnchor, constant: -14)
- ])
- stack.addArrangedSubview(settingsDarkModeRow(enabled: darkModeEnabled))
- stack.addArrangedSubview(settingsSpeechLanguageRow(
- title: "AI Language 1",
- isPrimary: true
- ))
- stack.addArrangedSubview(settingsSpeechLanguageRow(
- title: "AI Language 2",
- isPrimary: false
- ))
- if showRateUsInSettings {
- stack.addArrangedSubview(settingsActionRow(icon: "★", title: "Rate Us", action: .rateUs))
- }
- stack.addArrangedSubview(settingsActionRow(icon: "🔒", title: "Privacy Policy", action: .privacyPolicy))
- stack.addArrangedSubview(settingsActionRow(icon: "💬", title: "Support", action: .support))
- stack.addArrangedSubview(settingsActionRow(icon: "📄", title: "Terms of Services", action: .termsOfServices))
- stack.addArrangedSubview(settingsActionRow(icon: "⤴︎", title: "Share App", action: .shareApp))
- if showUpgradeInSettings {
- stack.addArrangedSubview(settingsActionRow(icon: "⬆︎", title: "Upgrade", action: .upgrade))
- }
- for v in stack.arrangedSubviews {
- v.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- }
- return root
- }
- private func roundedCard() -> NSView {
- let view = NSView()
- view.translatesAutoresizingMaskIntoConstraints = false
- view.wantsLayer = true
- view.layer?.cornerRadius = 12
- view.layer?.backgroundColor = palette.sectionCard.cgColor
- view.layer?.borderColor = palette.inputBorder.cgColor
- view.layer?.borderWidth = 1
- view.layer?.shadowColor = NSColor.black.cgColor
- view.layer?.shadowOpacity = 0.28
- view.layer?.shadowOffset = CGSize(width: 0, height: -1)
- view.layer?.shadowRadius = 10
- return view
- }
- private func settingsDarkModeRow(enabled: Bool) -> NSView {
- let row = NSView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 44).isActive = true
- row.wantsLayer = true
- row.layer?.cornerRadius = 10
- let icon = NSTextField(labelWithString: "◐")
- icon.translatesAutoresizingMaskIntoConstraints = false
- icon.font = NSFont.systemFont(ofSize: 18, weight: .medium)
- icon.textColor = palette.textPrimary
- let title = NSTextField(labelWithString: "Dark Mode")
- title.translatesAutoresizingMaskIntoConstraints = false
- title.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
- title.textColor = palette.textPrimary
- let toggle = NSSwitch()
- toggle.translatesAutoresizingMaskIntoConstraints = false
- toggle.state = enabled ? .on : .off
- toggle.target = self
- toggle.action = #selector(darkModeToggled(_:))
- darkToggle = toggle
- row.addSubview(icon)
- row.addSubview(title)
- row.addSubview(toggle)
- row.layer?.backgroundColor = NSColor.clear.cgColor
- NSLayoutConstraint.activate([
- icon.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
- icon.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 10),
- title.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- toggle.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
- toggle.centerYAnchor.constraint(equalTo: row.centerYAnchor)
- ])
- return row
- }
- private func settingsActionRow(icon: String, title: String, action: SettingsAction) -> NSView {
- let row = HoverButton(title: "", target: self, action: #selector(settingsActionButtonPressed(_:)))
- row.tag = action.rawValue
- row.isBordered = false
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 42).isActive = true
- row.wantsLayer = true
- row.layer?.cornerRadius = 10
- row.layer?.backgroundColor = NSColor.clear.cgColor
- let iconLabel = NSTextField(labelWithString: icon)
- iconLabel.translatesAutoresizingMaskIntoConstraints = false
- iconLabel.font = NSFont.systemFont(ofSize: 18, weight: .medium)
- iconLabel.textColor = palette.textPrimary
- let titleLabel = NSTextField(labelWithString: title)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- titleLabel.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
- titleLabel.textColor = palette.textPrimary
- row.addSubview(iconLabel)
- row.addSubview(titleLabel)
- NSLayoutConstraint.activate([
- iconLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
- iconLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor),
- titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 10),
- titleLabel.centerYAnchor.constraint(equalTo: row.centerYAnchor)
- ])
- row.onHoverChanged = { hovering in
- row.layer?.backgroundColor = (hovering ? self.palette.inputBackground : NSColor.clear).cgColor
- }
- row.onHoverChanged?(false)
- return row
- }
- private func settingsSpeechLanguageRow(title: String, isPrimary: Bool) -> NSView {
- let row = NSView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.heightAnchor.constraint(equalToConstant: 62).isActive = true
- row.wantsLayer = true
- row.layer?.cornerRadius = 10
- row.layer?.backgroundColor = NSColor.clear.cgColor
- let titleLabel = NSTextField(labelWithString: title)
- titleLabel.translatesAutoresizingMaskIntoConstraints = false
- titleLabel.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
- titleLabel.textColor = palette.textPrimary
- let popup = NSPopUpButton(frame: .zero, pullsDown: false)
- popup.translatesAutoresizingMaskIntoConstraints = false
- popup.target = self
- popup.action = #selector(speechLanguageChanged(_:))
- if isPrimary {
- for option in speechLocaleOptions {
- popup.addItem(withTitle: option.displayName)
- popup.lastItem?.representedObject = option.identifier
- }
- let preferred = selectedPrimaryLanguageIdentifier ?? speechLocaleOptions.first?.identifier
- if let preferred {
- selectLocale(identifier: preferred, in: popup)
- }
- primaryLanguagePopup = popup
- } else {
- popup.addItem(withTitle: "None")
- popup.lastItem?.representedObject = ""
- for option in speechLocaleOptions {
- popup.addItem(withTitle: option.displayName)
- popup.lastItem?.representedObject = option.identifier
- }
- if let secondary = selectedSecondaryLanguageIdentifier,
- secondary.isEmpty == false {
- selectLocale(identifier: secondary, in: popup)
- } else {
- popup.selectItem(at: 0)
- }
- secondaryLanguagePopup = popup
- }
- row.addSubview(titleLabel)
- row.addSubview(popup)
- NSLayoutConstraint.activate([
- titleLabel.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
- titleLabel.topAnchor.constraint(equalTo: row.topAnchor, constant: 6),
- titleLabel.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -4),
- popup.leadingAnchor.constraint(equalTo: row.leadingAnchor, constant: 4),
- popup.trailingAnchor.constraint(equalTo: row.trailingAnchor, constant: -2),
- popup.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 6),
- popup.heightAnchor.constraint(equalToConstant: 28)
- ])
- return row
- }
- private func selectLocale(identifier: String, in popup: NSPopUpButton) {
- for item in popup.itemArray {
- if let represented = item.representedObject as? String, represented == identifier {
- popup.select(item)
- return
- }
- }
- }
- @objc private func speechLanguageChanged(_ sender: NSPopUpButton) {
- guard let primary = primaryLanguagePopup?.selectedItem?.representedObject as? String,
- primary.isEmpty == false else { return }
- var normalizedSecondary: String? = secondaryLanguagePopup?.selectedItem?.representedObject as? String
- if normalizedSecondary?.isEmpty == true {
- normalizedSecondary = nil
- }
- if let secondaryValue = normalizedSecondary,
- secondaryValue.replacingOccurrences(of: "_", with: "-").lowercased() == primary.replacingOccurrences(of: "_", with: "-").lowercased() {
- normalizedSecondary = nil
- secondaryLanguagePopup?.selectItem(at: 0)
- }
- onUpdatePreferredSpeechLanguages(primary, normalizedSecondary)
- }
- @objc private func darkModeToggled(_ sender: NSSwitch) {
- onToggleDarkMode(sender.state == .on)
- }
- @objc private func settingsActionButtonPressed(_ sender: NSButton) {
- guard let action = SettingsAction(rawValue: sender.tag) else { return }
- let clickPoint: NSPoint?
- if let event = NSApp.currentEvent {
- let pointInWindow = event.locationInWindow
- clickPoint = sender.convert(pointInWindow, from: nil)
- } else {
- clickPoint = nil
- }
- onAction(action, sender, clickPoint)
- }
- }
- private extension ViewController {
- private func hasGoogleSessionAvailable() -> Bool {
- guard let tokens = googleOAuth.loadTokens() else { return false }
- if tokens.expiresAt.timeIntervalSinceNow > 60 {
- return true
- }
- return (tokens.refreshToken?.isEmpty == false)
- }
- private func requireGoogleLoginForCalendarScheduling() -> Bool {
- guard hasGoogleSessionAvailable() else {
- showSimpleAlert(
- title: "Connect Google",
- message: "Sign in with Google first to schedule a meeting from Calendar."
- )
- return false
- }
- return true
- }
- func roundedContainer(cornerRadius: CGFloat, color: NSColor) -> NSView {
- let view = NSView()
- view.wantsLayer = true
- view.layer?.backgroundColor = color.cgColor
- view.layer?.cornerRadius = cornerRadius
- return view
- }
- func styleSurface(_ view: NSView, borderColor: NSColor, borderWidth: CGFloat, shadow: Bool) {
- view.layer?.borderColor = borderColor.cgColor
- view.layer?.borderWidth = borderWidth
- if shadow {
- view.layer?.shadowColor = NSColor.black.cgColor
- view.layer?.shadowOpacity = 0.18
- view.layer?.shadowOffset = CGSize(width: 0, height: -1)
- view.layer?.shadowRadius = 5
- }
- }
- func textLabel(_ text: String, font: NSFont, color: NSColor) -> NSTextField {
- let label = NSTextField(labelWithString: text)
- label.translatesAutoresizingMaskIntoConstraints = false
- label.textColor = color
- label.font = font
- return label
- }
- func iconLabel(_ text: String, size: CGFloat) -> NSTextField {
- let label = NSTextField(labelWithString: text)
- label.translatesAutoresizingMaskIntoConstraints = false
- label.font = NSFont.systemFont(ofSize: size)
- return label
- }
- func sidebarSectionTitle(_ text: String) -> NSTextField {
- let sectionColor = darkModeEnabled ? palette.textMuted : NSColor(calibratedWhite: 0.14, alpha: 1.0)
- let field = textLabel(text, font: typography.sidebarSection, color: sectionColor)
- field.alignment = .left
- return field
- }
- 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 {
- let item = HoverButton(title: "", target: self, action: #selector(sidebarButtonClicked(_:)))
- item.tag = page.rawValue
- item.isBordered = false
- item.wantsLayer = true
- item.layer?.cornerRadius = 10
- item.layer?.backgroundColor = NSColor.clear.cgColor
- item.translatesAutoresizingMaskIntoConstraints = false
- item.heightAnchor.constraint(equalToConstant: 36).isActive = true
- item.layer?.borderWidth = 0
- sidebarPageByView[ObjectIdentifier(item)] = page
- let leadingView: NSView
- if let name = logoImageName, let logo = NSImage(named: name) {
- logo.isTemplate = true
- let imageView = NSImageView(image: logo)
- imageView.translatesAutoresizingMaskIntoConstraints = false
- imageView.imageScaling = .scaleProportionallyDown
- imageView.imageAlignment = .alignCenter
- imageView.isEditable = false
- leadingView = imageView
- } else if let symbolName = systemSymbolName, let symbol = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) {
- symbol.isTemplate = true
- let imageView = NSImageView(image: symbol)
- imageView.translatesAutoresizingMaskIntoConstraints = false
- imageView.imageScaling = .scaleProportionallyDown
- imageView.imageAlignment = .alignCenter
- imageView.isEditable = false
- leadingView = imageView
- } else {
- leadingView = textLabel(icon, font: typography.sidebarIcon, color: palette.textSecondary)
- }
- let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
- let titleLabel = textLabel(text, font: typography.sidebarItem, color: baseSidebarTextColor)
- titleLabel.alignment = .left
- item.addSubview(leadingView)
- item.addSubview(titleLabel)
- var constraints: [NSLayoutConstraint] = [
- leadingView.leadingAnchor.constraint(equalTo: item.leadingAnchor, constant: 12),
- leadingView.centerYAnchor.constraint(equalTo: item.centerYAnchor),
- titleLabel.leadingAnchor.constraint(equalTo: leadingView.trailingAnchor, constant: 8),
- titleLabel.centerYAnchor.constraint(equalTo: item.centerYAnchor)
- ]
- if showsDisclosure {
- let chevron = textLabel("›", font: NSFont.systemFont(ofSize: 22, weight: .semibold), color: baseSidebarTextColor)
- chevron.translatesAutoresizingMaskIntoConstraints = false
- chevron.alignment = .right
- item.addSubview(chevron)
- constraints.append(contentsOf: [
- chevron.trailingAnchor.constraint(equalTo: item.trailingAnchor, constant: -10),
- chevron.centerYAnchor.constraint(equalTo: item.centerYAnchor),
- titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: chevron.leadingAnchor, constant: -8)
- ])
- } else {
- constraints.append(titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: item.trailingAnchor, constant: -10))
- }
- if logoImageName != nil || systemSymbolName != nil {
- let h = logoIconWidth * logoHeightMultiplier
- constraints.append(contentsOf: [
- leadingView.widthAnchor.constraint(equalToConstant: logoIconWidth),
- leadingView.heightAnchor.constraint(equalToConstant: h)
- ])
- }
- NSLayoutConstraint.activate(constraints)
- applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate)
- item.onHoverChanged = { [weak self, weak item] hovering in
- guard let self, let item else { return }
- self.applySidebarRowStyle(item, page: page, logoTemplate: logoTemplate, hovering: hovering)
- }
- return item
- }
- func applySidebarRowStyle(_ item: NSView, page: SidebarPage, logoTemplate: Bool, hovering: Bool = false) {
- let selected = (page == selectedSidebarPage)
- let hoverColor = darkModeEnabled ? NSColor(calibratedWhite: 1, alpha: 0.07) : NSColor(calibratedWhite: 0, alpha: 0.08)
- item.layer?.backgroundColor = (selected ? palette.primaryBlue : (hovering ? hoverColor : NSColor.clear)).cgColor
- let baseSidebarTextColor = darkModeEnabled ? palette.textSecondary : NSColor(calibratedWhite: 0.08, alpha: 1.0)
- let tint = selected ? NSColor.white : baseSidebarTextColor
- let sidebarIconTint = darkModeEnabled ? tint : baseSidebarTextColor
- guard item.subviews.count >= 2 else { return }
- let leading = item.subviews[0]
- let title = item.subviews.first { $0 is NSTextField } as? NSTextField
- title?.textColor = tint
- // Optional disclosure chevron (if present) is the last text field.
- if let chevron = item.subviews.last as? NSTextField, chevron !== title {
- chevron.textColor = sidebarIconTint
- }
- if let imageView = leading as? NSImageView {
- if logoTemplate {
- imageView.contentTintColor = sidebarIconTint
- }
- } else if let iconField = leading as? NSTextField {
- iconField.textColor = sidebarIconTint
- }
- }
- func actionButton(title: String, color: NSColor, textColor: NSColor, width: CGFloat) -> NSView {
- let button = HoverTrackingView()
- button.wantsLayer = true
- button.layer?.cornerRadius = 9
- button.layer?.backgroundColor = color.cgColor
- button.translatesAutoresizingMaskIntoConstraints = false
- button.widthAnchor.constraint(equalToConstant: width).isActive = true
- button.heightAnchor.constraint(equalToConstant: 36).isActive = true
- styleSurface(button, borderColor: title == "Cancel" ? palette.inputBorder : palette.primaryBlueBorder, borderWidth: 1, shadow: false)
- if title == "Cancel" {
- button.layer?.backgroundColor = palette.cancelButton.cgColor
- }
- let label = textLabel(title, font: typography.buttonText, color: textColor)
- button.addSubview(label)
- NSLayoutConstraint.activate([
- label.centerXAnchor.constraint(equalTo: button.centerXAnchor),
- label.centerYAnchor.constraint(equalTo: button.centerYAnchor)
- ])
- let baseColor = (title == "Cancel") ? palette.cancelButton : color
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.12, of: hoverBlend) ?? baseColor
- button.onHoverChanged = { hovering in
- button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- }
- button.onHoverChanged?(false)
- return button
- }
- func iconRoundButton(systemSymbol: String, size: CGFloat, iconPointSize: CGFloat = 16, onClick: (() -> Void)? = nil) -> NSView {
- let button = HoverTrackingView()
- button.wantsLayer = true
- button.layer?.cornerRadius = size / 2
- button.layer?.backgroundColor = palette.inputBackground.cgColor
- button.translatesAutoresizingMaskIntoConstraints = false
- button.widthAnchor.constraint(equalToConstant: size).isActive = true
- button.heightAnchor.constraint(equalToConstant: size).isActive = true
- styleSurface(button, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let symbolConfig = NSImage.SymbolConfiguration(pointSize: iconPointSize, weight: .semibold)
- let iconView = NSImageView()
- iconView.translatesAutoresizingMaskIntoConstraints = false
- iconView.image = NSImage(systemSymbolName: systemSymbol, accessibilityDescription: "Refresh")
- iconView.symbolConfiguration = symbolConfig
- iconView.contentTintColor = palette.textSecondary
- button.addSubview(iconView)
- NSLayoutConstraint.activate([
- iconView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
- iconView.centerYAnchor.constraint(equalTo: button.centerYAnchor)
- ])
- let baseColor = palette.inputBackground
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hoverColor = baseColor.blended(withFraction: 0.10, of: hoverBlend) ?? baseColor
- button.onHoverChanged = { hovering in
- button.layer?.backgroundColor = (hovering ? hoverColor : baseColor).cgColor
- }
- button.onHoverChanged?(false)
- button.onClick = onClick
- return button
- }
- }
- private let calendarDayKeyFormatter: DateFormatter = {
- let f = DateFormatter()
- f.calendar = Calendar(identifier: .gregorian)
- f.locale = Locale(identifier: "en_US_POSIX")
- f.timeZone = TimeZone.current
- f.dateFormat = "yyyy-MM-dd"
- return f
- }()
- // MARK: - Calendar page actions + rendering
- private extension ViewController {
- private func makeCalendarHeaderPillButton(title: String, action: Selector) -> NSButton {
- let button = makeSchedulePillButton(title: title)
- button.target = self
- button.action = action
- button.heightAnchor.constraint(equalToConstant: 30).isActive = true
- return button
- }
- private func calendarStartOfMonth(for date: Date) -> Date {
- let calendar = Calendar.current
- let comps = calendar.dateComponents([.year, .month], from: date)
- return calendar.date(from: comps) ?? calendar.startOfDay(for: date)
- }
- private func calendarMonthTitleText(for monthAnchor: Date) -> String {
- let f = DateFormatter()
- f.locale = Locale.current
- f.timeZone = TimeZone.current
- f.dateFormat = "MMMM yyyy"
- return f.string(from: monthAnchor)
- }
- private func calendarWeekdaySymbolsStartingAtFirstWeekday() -> [String] {
- // Align weekday header to Calendar.current.firstWeekday
- let calendar = Calendar.current
- var symbols = DateFormatter().veryShortWeekdaySymbols ?? ["S", "M", "T", "W", "T", "F", "S"]
- // veryShortWeekdaySymbols starts with Sunday in most locales; rotate to firstWeekday.
- let first = max(1, min(7, calendar.firstWeekday)) // 1..7
- let shift = (first - 1) % 7
- if shift == 0 { return symbols }
- let head = Array(symbols[shift...])
- let tail = Array(symbols[..<shift])
- symbols = head + tail
- return symbols
- }
- @objc func calendarPrevMonthPressed(_ sender: NSButton) {
- let calendar = Calendar.current
- calendarPageMonthAnchor = calendar.date(byAdding: .month, value: -1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- }
- @objc func calendarNextMonthPressed(_ sender: NSButton) {
- let calendar = Calendar.current
- calendarPageMonthAnchor = calendar.date(byAdding: .month, value: 1, to: calendarPageMonthAnchor).map(calendarStartOfMonth(for:)) ?? calendarPageMonthAnchor
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- }
- @objc func calendarRefreshPressed(_ sender: NSButton) {
- Task { [weak self] in
- await self?.loadSchedule()
- }
- }
- @objc func calendarDayCellPressed(_ sender: NSButton) {
- guard requireGoogleLoginForCalendarScheduling() else { return }
- guard let raw = sender.identifier?.rawValue,
- let date = calendarDayKeyFormatter.date(from: raw) else { return }
- calendarPageSelectedDate = Calendar.current.startOfDay(for: date)
- renderCalendarMonthGrid()
- renderCalendarSelectedDay()
- if let refreshedButton = calendarButton(forDateKey: raw) {
- showCalendarDayActionPopover(relativeTo: refreshedButton)
- }
- }
- private func showCalendarDayActionPopover(relativeTo anchor: NSView) {
- guard anchor.window != nil else { return }
- calendarPageActionPopover?.performClose(nil)
- let popover = NSPopover()
- popover.behavior = .transient
- popover.animates = true
- popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
- popover.contentViewController = CalendarDayActionMenuViewController(
- palette: palette,
- onSchedule: { [weak self] in
- self?.calendarPageActionPopover?.performClose(nil)
- self?.calendarPageActionPopover = nil
- self?.presentCreateMeetingPopover(relativeTo: anchor)
- }
- )
- calendarPageActionPopover = popover
- popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
- }
- private func presentCreateMeetingPopover(relativeTo anchor: NSView) {
- guard anchor.window != nil else { return }
- calendarPageCreatePopover?.performClose(nil)
- let popover = NSPopover()
- popover.behavior = .transient
- popover.animates = true
- popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
- let selectedDate = Calendar.current.startOfDay(for: calendarPageSelectedDate)
- let vc = CreateMeetingPopoverViewController(
- palette: palette,
- typography: typography,
- selectedDate: selectedDate,
- onCancel: { [weak self] in
- self?.calendarPageCreatePopover?.performClose(nil)
- self?.calendarPageCreatePopover = nil
- },
- onSave: { [weak self] draft in
- guard let self else { return }
- self.calendarPageCreatePopover?.performClose(nil)
- self.calendarPageCreatePopover = nil
- self.calendarCreateMeeting(title: draft.title, notes: draft.notes, start: draft.startDate, end: draft.endDate)
- }
- )
- popover.contentViewController = vc
- calendarPageCreatePopover = popover
- popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY)
- }
- private func calendarCreateMeeting(title: String, notes: String?, start: Date, end: Date) {
- Task { [weak self] in
- guard let self else { return }
- do {
- try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
- let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
- _ = try await self.calendarClient.createEvent(
- accessToken: token,
- title: title,
- description: notes,
- start: start,
- end: end,
- timeZone: .current
- )
- await self.loadSchedule()
- await MainActor.run {
- let calendar = Calendar.current
- self.calendarPageSelectedDate = calendar.startOfDay(for: start)
- self.calendarPageMonthAnchor = self.calendarStartOfMonth(for: start)
- self.calendarPageMonthLabel?.stringValue = self.calendarMonthTitleText(for: self.calendarPageMonthAnchor)
- self.renderCalendarMonthGrid()
- self.renderCalendarSelectedDay()
- self.showTopToast(message: "Meeting added successfully.", isError: false)
- }
- } catch {
- await MainActor.run {
- self.showTopToast(message: "An issue occurred. Please try again.", isError: true)
- }
- }
- }
- }
- private func renderCalendarMonthGrid() {
- guard let gridStack = calendarPageGridStack else { return }
- gridStack.arrangedSubviews.forEach { v in
- gridStack.removeArrangedSubview(v)
- v.removeFromSuperview()
- }
- let calendar = Calendar.current
- let monthStart = calendarStartOfMonth(for: calendarPageMonthAnchor)
- guard let dayRange = calendar.range(of: .day, in: .month, for: monthStart),
- let monthEnd = calendar.date(byAdding: DateComponents(month: 1, day: 0), to: monthStart) else { return }
- let firstWeekday = calendar.component(.weekday, from: monthStart) // 1..7
- let leadingEmpty = (firstWeekday - calendar.firstWeekday + 7) % 7
- let totalDays = dayRange.count
- let totalCells = leadingEmpty + totalDays
- let rowCount = Int(ceil(Double(totalCells) / 7.0))
- let rowHeight: CGFloat = 56
- let rowSpacing: CGFloat = 12
- let verticalPadding: CGFloat = 32
- calendarPageGridHeightConstraint?.constant = verticalPadding + (CGFloat(rowCount) * rowHeight) + (CGFloat(max(0, rowCount - 1)) * rowSpacing)
- let meetingCounts = calendarMeetingCountsByDay(from: scheduleCachedMeetings, monthStart: monthStart, monthEnd: monthEnd)
- var day = 1
- for _ in 0..<rowCount {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.userInterfaceLayoutDirection = .leftToRight
- row.orientation = .horizontal
- row.alignment = .top
- row.distribution = .fillEqually
- row.spacing = rowSpacing
- row.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true
- for col in 0..<7 {
- let cellIndex = (gridStack.arrangedSubviews.count * 7) + col
- if cellIndex < leadingEmpty || day > totalDays {
- row.addArrangedSubview(calendarEmptyDayCell())
- continue
- }
- guard let date = calendar.date(byAdding: .day, value: day - 1, to: monthStart) else {
- row.addArrangedSubview(calendarEmptyDayCell())
- continue
- }
- let isSelected = calendar.isDate(date, inSameDayAs: calendarPageSelectedDate)
- let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: date))
- let count = meetingCounts[key] ?? 0
- row.addArrangedSubview(calendarDayCell(dayNumber: day, dateKey: key, meetingCount: count, isSelected: isSelected))
- day += 1
- }
- gridStack.addArrangedSubview(row)
- row.widthAnchor.constraint(equalTo: gridStack.widthAnchor).isActive = true
- }
- }
- private func calendarButton(forDateKey key: String) -> NSButton? {
- guard let gridStack = calendarPageGridStack else { return nil }
- for rowView in gridStack.arrangedSubviews {
- guard let row = rowView as? NSStackView else { continue }
- for cell in row.arrangedSubviews {
- if let button = cell as? NSButton, button.identifier?.rawValue == key {
- return button
- }
- }
- }
- return nil
- }
- private func renderCalendarSelectedDay() {
- let calendar = Calendar.current
- let selectedDay = calendar.startOfDay(for: calendarPageSelectedDate)
- let nextDay = calendar.date(byAdding: .day, value: 1, to: selectedDay) ?? selectedDay.addingTimeInterval(86400)
- let meetings = scheduleCachedMeetings
- .filter { $0.startDate >= selectedDay && $0.startDate < nextDay }
- .sorted(by: { $0.startDate < $1.startDate })
- let f = DateFormatter()
- f.locale = Locale.current
- f.timeZone = TimeZone.current
- f.dateFormat = "EEE, d MMM"
- if meetings.isEmpty {
- calendarPageDaySummaryLabel?.stringValue = hasGoogleSessionAvailable() == false
- ? "Connect Google to see meetings"
- : "No meetings on \(f.string(from: selectedDay))"
- } else if meetings.count == 1 {
- calendarPageDaySummaryLabel?.stringValue = "1 meeting on \(f.string(from: selectedDay))"
- } else {
- calendarPageDaySummaryLabel?.stringValue = "\(meetings.count) meetings on \(f.string(from: selectedDay))"
- }
- }
- private func calendarMeetingCountsByDay(from meetings: [ScheduledMeeting], monthStart: Date, monthEnd: Date) -> [String: Int] {
- let calendar = Calendar.current
- var counts: [String: Int] = [:]
- for meeting in meetings {
- guard meeting.startDate >= monthStart && meeting.startDate < monthEnd else { continue }
- let key = calendarDayKeyFormatter.string(from: calendar.startOfDay(for: meeting.startDate))
- counts[key, default: 0] += 1
- }
- return counts
- }
- private func calendarEmptyDayCell() -> NSView {
- let v = NSView()
- v.translatesAutoresizingMaskIntoConstraints = false
- v.heightAnchor.constraint(equalToConstant: 56).isActive = true
- return v
- }
- private func calendarDayCell(dayNumber: Int, dateKey: String, meetingCount: Int, isSelected: Bool) -> NSButton {
- let button = HoverButton(title: "", target: self, action: #selector(calendarDayCellPressed(_:)))
- button.translatesAutoresizingMaskIntoConstraints = false
- button.isBordered = false
- button.bezelStyle = .regularSquare
- button.wantsLayer = true
- button.layer?.cornerRadius = 12
- button.layer?.masksToBounds = true
- button.identifier = NSUserInterfaceItemIdentifier(dateKey)
- button.heightAnchor.constraint(equalToConstant: 56).isActive = true
- button.setContentHuggingPriority(.required, for: .vertical)
- button.setContentCompressionResistancePriority(.required, for: .vertical)
- button.alignment = .left
- button.imagePosition = .noImage
- let base = palette.inputBackground
- let hoverBlend = darkModeEnabled ? NSColor.white : NSColor.black
- let hover = base.blended(withFraction: 0.10, of: hoverBlend) ?? base
- let selectedBackground = darkModeEnabled
- ? NSColor(calibratedRed: 30.0 / 255.0, green: 34.0 / 255.0, blue: 42.0 / 255.0, alpha: 1)
- : NSColor(calibratedRed: 255.0 / 255.0, green: 246.0 / 255.0, blue: 236.0 / 255.0, alpha: 1)
- let borderIdle = palette.inputBorder
- let borderSelected = palette.primaryBlueBorder
- func applyAppearance(hovering: Bool) {
- button.layer?.backgroundColor = (isSelected ? selectedBackground : (hovering ? hover : base)).cgColor
- button.layer?.borderWidth = isSelected ? 1.5 : 1
- button.layer?.borderColor = (isSelected ? borderSelected : borderIdle).cgColor
- }
- applyAppearance(hovering: false)
- button.onHoverChanged = { hovering in
- applyAppearance(hovering: hovering)
- }
- button.attributedTitle = NSAttributedString(
- string: " \(dayNumber)",
- attributes: [
- .font: NSFont.systemFont(ofSize: 14, weight: .bold),
- .foregroundColor: palette.textPrimary
- ]
- )
- if meetingCount > 0 {
- let dot = roundedContainer(cornerRadius: 4, color: palette.meetingBadge)
- dot.translatesAutoresizingMaskIntoConstraints = false
- dot.layer?.borderWidth = 0
- button.addSubview(dot)
- NSLayoutConstraint.activate([
- dot.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -10),
- dot.centerYAnchor.constraint(equalTo: button.centerYAnchor),
- dot.widthAnchor.constraint(equalToConstant: 8),
- dot.heightAnchor.constraint(equalToConstant: 8)
- ])
- }
- return button
- }
- }
- private final class CalendarDayActionMenuViewController: NSViewController {
- private let palette: Palette
- private let onSchedule: () -> Void
- init(palette: Palette, onSchedule: @escaping () -> Void) {
- self.palette = palette
- self.onSchedule = onSchedule
- super.init(nibName: nil, bundle: nil)
- }
- required init?(coder: NSCoder) { nil }
- override func loadView() {
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.orientation = .vertical
- stack.alignment = .leading
- stack.spacing = 10
- let title = NSTextField(labelWithString: "Actions")
- title.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
- title.textColor = palette.textMuted
- let schedule = NSButton(title: "Schedule meeting", target: self, action: #selector(schedulePressed(_:)))
- schedule.bezelStyle = .rounded
- schedule.font = NSFont.systemFont(ofSize: 13, weight: .medium)
- stack.addArrangedSubview(title)
- stack.addArrangedSubview(schedule)
- root.addSubview(stack)
- NSLayoutConstraint.activate([
- root.widthAnchor.constraint(equalToConstant: 220),
- root.heightAnchor.constraint(greaterThanOrEqualToConstant: 86),
- stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14),
- stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -14),
- stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 12),
- stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -12)
- ])
- view = root
- }
- @objc private func schedulePressed(_ sender: NSButton) {
- onSchedule()
- }
- }
- private final class CreateMeetingPopoverViewController: NSViewController, NSTextViewDelegate {
- struct Draft {
- let title: String
- let notes: String?
- let startDate: Date
- let endDate: Date
- }
- private let palette: Palette
- private let typography: Typography
- private let selectedDate: Date
- private let onCancel: () -> Void
- private let onSave: (Draft) -> Void
- private var titleField: NSTextField?
- private var timePicker: NSDatePicker?
- private var durationField: NSTextField?
- private var notesView: NSTextView?
- private var notesScrollView: NSScrollView?
- private var errorLabel: NSTextField?
- private var notesBorderIdle = NSColor.clear
- private var notesBorderHover = NSColor.clear
- private var notesBorderFocused = NSColor.clear
- private var notesIsHovered = false
- private var notesIsFocused = false
- init(palette: Palette,
- typography: Typography,
- selectedDate: Date,
- onCancel: @escaping () -> Void,
- onSave: @escaping (Draft) -> Void) {
- self.palette = palette
- self.typography = typography
- self.selectedDate = selectedDate
- self.onCancel = onCancel
- self.onSave = onSave
- super.init(nibName: nil, bundle: nil)
- }
- required init?(coder: NSCoder) { nil }
- override func loadView() {
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- root.userInterfaceLayoutDirection = .leftToRight
- root.wantsLayer = true
- root.layer?.cornerRadius = 14
- root.layer?.masksToBounds = true
- root.layer?.backgroundColor = palette.sectionCard.cgColor
- root.layer?.borderWidth = 1
- root.layer?.borderColor = palette.inputBorder.withAlphaComponent(0.9).cgColor
- let stack = NSStackView()
- stack.translatesAutoresizingMaskIntoConstraints = false
- stack.orientation = .vertical
- stack.alignment = .leading
- stack.spacing = 14
- stack.userInterfaceLayoutDirection = .leftToRight
- let inputSurface = palette.inputBackground.blended(withFraction: 0.18, of: palette.sectionCard) ?? palette.inputBackground
- let fieldBorder = palette.textSecondary.withAlphaComponent(0.4)
- notesBorderIdle = fieldBorder
- notesBorderHover = palette.textSecondary.withAlphaComponent(0.72)
- notesBorderFocused = palette.primaryBlueBorder
- let header = NSTextField(labelWithString: "Schedule meeting")
- header.font = NSFont.systemFont(ofSize: 16, weight: .semibold)
- header.textColor = palette.textPrimary
- header.alignment = .left
- header.userInterfaceLayoutDirection = .leftToRight
- header.baseWritingDirection = .leftToRight
- let titleLabel = NSTextField(labelWithString: "Title")
- titleLabel.font = typography.fieldLabel
- titleLabel.textColor = palette.textSecondary
- titleLabel.alignment = .left
- titleLabel.userInterfaceLayoutDirection = .leftToRight
- titleLabel.baseWritingDirection = .leftToRight
- let titleShell = NSView()
- titleShell.translatesAutoresizingMaskIntoConstraints = false
- titleShell.wantsLayer = true
- titleShell.layer?.cornerRadius = 8
- titleShell.layer?.backgroundColor = inputSurface.cgColor
- titleShell.layer?.borderColor = fieldBorder.cgColor
- titleShell.layer?.borderWidth = 1.2
- titleShell.heightAnchor.constraint(equalToConstant: 40).isActive = true
- let titleField = NSTextField(string: "")
- titleField.translatesAutoresizingMaskIntoConstraints = false
- titleField.isBordered = false
- titleField.drawsBackground = false
- titleField.focusRingType = .none
- titleField.font = NSFont.systemFont(ofSize: 14, weight: .regular)
- titleField.textColor = palette.textPrimary
- titleField.placeholderString = "Team sync"
- titleShell.addSubview(titleField)
- NSLayoutConstraint.activate([
- titleField.leadingAnchor.constraint(equalTo: titleShell.leadingAnchor, constant: 10),
- titleField.trailingAnchor.constraint(equalTo: titleShell.trailingAnchor, constant: -10),
- titleField.centerYAnchor.constraint(equalTo: titleShell.centerYAnchor)
- ])
- self.titleField = titleField
- let timeRow = NSStackView()
- timeRow.translatesAutoresizingMaskIntoConstraints = false
- timeRow.orientation = .horizontal
- timeRow.alignment = .centerY
- timeRow.spacing = 10
- timeRow.distribution = .fill
- let startLabel = NSTextField(labelWithString: "Start")
- startLabel.font = typography.fieldLabel
- startLabel.textColor = palette.textSecondary
- startLabel.alignment = .left
- startLabel.userInterfaceLayoutDirection = .leftToRight
- startLabel.baseWritingDirection = .leftToRight
- let pickerShell = NSView()
- pickerShell.translatesAutoresizingMaskIntoConstraints = false
- pickerShell.wantsLayer = true
- pickerShell.layer?.cornerRadius = 8
- pickerShell.layer?.backgroundColor = inputSurface.cgColor
- pickerShell.layer?.borderColor = fieldBorder.cgColor
- pickerShell.layer?.borderWidth = 1.2
- pickerShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
- let timePicker = NSDatePicker()
- timePicker.translatesAutoresizingMaskIntoConstraints = false
- timePicker.isBordered = false
- timePicker.drawsBackground = false
- timePicker.focusRingType = .none
- timePicker.datePickerStyle = .textFieldAndStepper
- timePicker.datePickerElements = [.hourMinute]
- timePicker.font = typography.filterText
- timePicker.textColor = palette.textSecondary
- timePicker.dateValue = Date()
- pickerShell.addSubview(timePicker)
- NSLayoutConstraint.activate([
- timePicker.leadingAnchor.constraint(equalTo: pickerShell.leadingAnchor, constant: 8),
- timePicker.trailingAnchor.constraint(equalTo: pickerShell.trailingAnchor, constant: -8),
- timePicker.centerYAnchor.constraint(equalTo: pickerShell.centerYAnchor)
- ])
- self.timePicker = timePicker
- let durationLabel = NSTextField(labelWithString: "Duration (min)")
- durationLabel.font = typography.fieldLabel
- durationLabel.textColor = palette.textSecondary
- durationLabel.alignment = .left
- durationLabel.userInterfaceLayoutDirection = .leftToRight
- durationLabel.baseWritingDirection = .leftToRight
- let durationShell = NSView()
- durationShell.translatesAutoresizingMaskIntoConstraints = false
- durationShell.wantsLayer = true
- durationShell.layer?.cornerRadius = 8
- durationShell.layer?.backgroundColor = inputSurface.cgColor
- durationShell.layer?.borderColor = fieldBorder.cgColor
- durationShell.layer?.borderWidth = 1.2
- durationShell.heightAnchor.constraint(equalToConstant: 34).isActive = true
- let durationField = NSTextField(string: "30")
- durationField.translatesAutoresizingMaskIntoConstraints = false
- durationField.isBordered = false
- durationField.drawsBackground = false
- durationField.focusRingType = .none
- durationField.font = typography.filterText
- durationField.textColor = palette.textSecondary
- durationField.formatter = NumberFormatter()
- durationShell.addSubview(durationField)
- NSLayoutConstraint.activate([
- durationField.leadingAnchor.constraint(equalTo: durationShell.leadingAnchor, constant: 8),
- durationField.trailingAnchor.constraint(equalTo: durationShell.trailingAnchor, constant: -8),
- durationField.centerYAnchor.constraint(equalTo: durationShell.centerYAnchor)
- ])
- self.durationField = durationField
- let startGroup = NSStackView(views: [startLabel, pickerShell])
- startGroup.translatesAutoresizingMaskIntoConstraints = false
- startGroup.orientation = .vertical
- startGroup.alignment = .leading
- startGroup.spacing = 6
- let durationGroup = NSStackView(views: [durationLabel, durationShell])
- durationGroup.translatesAutoresizingMaskIntoConstraints = false
- durationGroup.orientation = .vertical
- durationGroup.alignment = .leading
- durationGroup.spacing = 6
- timeRow.addArrangedSubview(startGroup)
- timeRow.addArrangedSubview(durationGroup)
- startGroup.widthAnchor.constraint(equalTo: durationGroup.widthAnchor).isActive = true
- let notesLabel = NSTextField(labelWithString: "Notes")
- notesLabel.font = typography.fieldLabel
- notesLabel.textColor = palette.textSecondary
- notesLabel.alignment = .left
- notesLabel.userInterfaceLayoutDirection = .leftToRight
- notesLabel.baseWritingDirection = .leftToRight
- let notesScroll = HoverFocusScrollView()
- notesScroll.translatesAutoresizingMaskIntoConstraints = false
- notesScroll.drawsBackground = true
- notesScroll.backgroundColor = inputSurface
- notesScroll.hasVerticalScroller = true
- notesScroll.hasHorizontalScroller = false
- notesScroll.borderType = .noBorder
- notesScroll.wantsLayer = true
- notesScroll.layer?.cornerRadius = 8
- notesScroll.layer?.masksToBounds = true
- notesScroll.layer?.borderWidth = 1.2
- notesScroll.layer?.borderColor = notesBorderIdle.cgColor
- notesScroll.heightAnchor.constraint(equalToConstant: 100).isActive = true
- notesScroll.onHoverChanged = { [weak self] hovering in
- guard let self else { return }
- self.notesIsHovered = hovering
- self.updateNotesBorderAppearance()
- }
- notesScroll.onMouseDown = { [weak self] in
- guard let self, let notesView = self.notesView as? ImmediateFocusTextView else { return }
- self.view.window?.makeFirstResponder(notesView)
- notesView.ensureCaretVisibleImmediately()
- self.notesIsFocused = true
- self.updateNotesBorderAppearance()
- }
- let notesView = ImmediateFocusTextView(frame: .zero)
- notesView.drawsBackground = false
- notesView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
- notesView.textColor = palette.textPrimary
- notesView.insertionPointColor = palette.textPrimary
- notesView.isEditable = true
- notesView.isSelectable = true
- notesView.isRichText = false
- notesView.importsGraphics = false
- notesView.isHorizontallyResizable = false
- notesView.isVerticallyResizable = true
- notesView.autoresizingMask = [.width]
- notesView.textContainerInset = NSSize(width: 6, height: 6)
- notesView.textContainer?.widthTracksTextView = true
- notesView.textContainer?.containerSize = NSSize(
- width: notesScroll.contentSize.width,
- height: CGFloat.greatestFiniteMagnitude
- )
- notesView.delegate = self
- notesScroll.documentView = notesView
- self.notesView = notesView
- self.notesScrollView = notesScroll
- let error = NSTextField(labelWithString: "")
- error.translatesAutoresizingMaskIntoConstraints = false
- error.textColor = NSColor.systemRed
- error.font = NSFont.systemFont(ofSize: 12, weight: .semibold)
- error.isHidden = true
- self.errorLabel = error
- let actions = NSStackView()
- actions.translatesAutoresizingMaskIntoConstraints = false
- actions.orientation = .horizontal
- actions.alignment = .centerY
- actions.spacing = 10
- let cancel = NSButton(title: "Cancel", target: self, action: #selector(cancelPressed(_:)))
- cancel.bezelStyle = .rounded
- let save = NSButton(title: "Save", target: self, action: #selector(savePressed(_:)))
- save.bezelStyle = .rounded
- save.keyEquivalent = "\r"
- let actionsSpacer = NSView()
- actionsSpacer.translatesAutoresizingMaskIntoConstraints = false
- actionsSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- actions.addArrangedSubview(cancel)
- actions.addArrangedSubview(actionsSpacer)
- actions.addArrangedSubview(save)
- stack.addArrangedSubview(header)
- stack.addArrangedSubview(titleLabel)
- stack.addArrangedSubview(titleShell)
- stack.addArrangedSubview(timeRow)
- stack.addArrangedSubview(notesLabel)
- stack.addArrangedSubview(notesScroll)
- stack.addArrangedSubview(error)
- stack.addArrangedSubview(actions)
- root.addSubview(stack)
- NSLayoutConstraint.activate([
- root.widthAnchor.constraint(equalToConstant: 372),
- stack.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 16),
- stack.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -16),
- stack.topAnchor.constraint(equalTo: root.topAnchor, constant: 16),
- stack.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -16),
- titleShell.widthAnchor.constraint(equalTo: stack.widthAnchor),
- timeRow.widthAnchor.constraint(equalTo: stack.widthAnchor),
- notesScroll.widthAnchor.constraint(equalTo: stack.widthAnchor),
- error.widthAnchor.constraint(equalTo: stack.widthAnchor),
- actions.widthAnchor.constraint(equalTo: stack.widthAnchor)
- ])
- view = root
- }
- @objc private func cancelPressed(_ sender: NSButton) {
- onCancel()
- }
- @objc private func savePressed(_ sender: NSButton) {
- setError(nil)
- let title = (titleField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- if title.isEmpty {
- setError("Please enter a title.")
- return
- }
- let durationText = (durationField?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- let durationMinutes = Int(durationText) ?? 0
- if durationMinutes <= 0 {
- setError("Duration must be a positive number of minutes.")
- return
- }
- let time = timePicker?.dateValue ?? Date()
- let calendar = Calendar.current
- let dateParts = calendar.dateComponents([.year, .month, .day], from: selectedDate)
- let timeParts = calendar.dateComponents([.hour, .minute], from: time)
- var merged = DateComponents()
- merged.year = dateParts.year
- merged.month = dateParts.month
- merged.day = dateParts.day
- merged.hour = timeParts.hour
- merged.minute = timeParts.minute
- guard let start = calendar.date(from: merged) else {
- setError("Invalid start time.")
- return
- }
- let end = start.addingTimeInterval(TimeInterval(durationMinutes * 60))
- let notes = notesView?.string.trimmingCharacters(in: .whitespacesAndNewlines)
- let cleanedNotes = (notes?.isEmpty == false) ? notes : nil
- onSave(Draft(title: title, notes: cleanedNotes, startDate: start, endDate: end))
- }
- private func updateNotesBorderAppearance() {
- let color: NSColor
- let width: CGFloat
- if notesIsFocused {
- color = notesBorderFocused
- width = 1.6
- } else if notesIsHovered {
- color = notesBorderHover
- width = 1.4
- } else {
- color = notesBorderIdle
- width = 1.2
- }
- notesScrollView?.layer?.borderColor = color.cgColor
- notesScrollView?.layer?.borderWidth = width
- }
- private func setError(_ message: String?) {
- guard let errorLabel else { return }
- errorLabel.stringValue = message ?? ""
- errorLabel.isHidden = message == nil
- }
- func textDidBeginEditing(_ notification: Notification) {
- guard let current = notification.object as? NSTextView, current === notesView else { return }
- notesIsFocused = true
- updateNotesBorderAppearance()
- }
- func textDidEndEditing(_ notification: Notification) {
- guard let current = notification.object as? NSTextView, current === notesView else { return }
- notesIsFocused = false
- updateNotesBorderAppearance()
- }
- }
- private final class HoverFocusScrollView: NSScrollView {
- var onHoverChanged: ((Bool) -> Void)?
- var onMouseDown: (() -> Void)?
- private var hoverTrackingArea: NSTrackingArea?
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- if let hoverTrackingArea {
- removeTrackingArea(hoverTrackingArea)
- }
- let area = NSTrackingArea(
- rect: bounds,
- options: [.activeInActiveApp, .inVisibleRect, .mouseEnteredAndExited],
- owner: self,
- userInfo: nil
- )
- addTrackingArea(area)
- hoverTrackingArea = area
- }
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
- onHoverChanged?(true)
- }
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
- onHoverChanged?(false)
- }
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
- true
- }
- override func mouseDown(with event: NSEvent) {
- onMouseDown?()
- if let window, !window.isKeyWindow {
- window.makeKeyAndOrderFront(nil)
- return
- }
- // Forward the click straight to the text view so caret placement/blink starts immediately.
- if let textView = documentView as? NSTextView {
- window?.makeFirstResponder(textView)
- textView.mouseDown(with: event)
- return
- }
- super.mouseDown(with: event)
- }
- }
- private final class ImmediateFocusTextView: NSTextView {
- override var acceptsFirstResponder: Bool { true }
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
- true
- }
- @discardableResult
- override func becomeFirstResponder() -> Bool {
- let accepted = super.becomeFirstResponder()
- if accepted {
- ensureCaretVisibleImmediately()
- }
- return accepted
- }
- override func mouseDown(with event: NSEvent) {
- window?.makeFirstResponder(self)
- super.mouseDown(with: event)
- ensureCaretVisibleImmediately()
- }
- func ensureCaretVisibleImmediately() {
- var range = selectedRange()
- if range.location == NSNotFound {
- range = NSRange(location: string.utf16.count, length: 0)
- }
- setSelectedRange(range)
- scrollRangeToVisible(range)
- needsDisplay = true
- displayIfNeeded()
- }
- }
- // MARK: - Schedule actions (OAuth entry)
- private extension ViewController {
- @objc func scheduleReloadButtonPressed(_ sender: NSButton) {
- scheduleReloadClicked()
- }
- @objc func scheduleScrollLeftPressed(_ sender: NSButton) {
- scrollScheduleCards(direction: -1)
- }
- @objc func scheduleScrollRightPressed(_ sender: NSButton) {
- scrollScheduleCards(direction: 1)
- }
- @objc func scheduleCardButtonPressed(_ sender: NSButton) {
- guard storeKitCoordinator.hasPremiumAccess else {
- showPaywall()
- return
- }
- guard let raw = sender.identifier?.rawValue,
- let url = URL(string: raw) else { return }
- let meeting = scheduleCachedMeetings.first(where: { $0.meetURL.absoluteString == raw })
- openMeetingURL(url, meeting: meeting)
- }
- @objc func scheduleConnectButtonPressed(_ sender: NSButton) {
- scheduleConnectClicked()
- }
- @objc func schedulePageLoadMorePressed(_ sender: NSButton) {
- appendSchedulePageBatchIfNeeded()
- }
- private func scheduleInitialHeadingText() -> String {
- hasGoogleSessionAvailable() ? "Loading…" : "Connect Google to see meetings"
- }
- private func schedulePageInitialHeadingText() -> String {
- hasGoogleSessionAvailable() ? "Loading schedule…" : "Connect Google to see meetings"
- }
- @objc func scheduleFilterDropdownChanged(_ sender: NSPopUpButton) {
- guard let selectedItem = sender.selectedItem,
- let filter = ScheduleFilter(rawValue: selectedItem.tag) else { return }
- applyScheduleFilter(filter)
- }
- private func applyScheduleFilter(_ filter: ScheduleFilter) {
- scheduleFilter = filter
- scheduleFilterDropdown?.selectItem(at: filter.rawValue)
- Task { [weak self] in
- await self?.loadSchedule()
- }
- }
- @objc func schedulePageFilterDropdownChanged(_ sender: NSPopUpButton) {
- guard let selectedItem = sender.selectedItem,
- let filter = SchedulePageFilter(rawValue: selectedItem.tag) else { return }
- schedulePageFilter = filter
- refreshSchedulePageDateFilterUI()
- applySchedulePageFiltersAndRender()
- }
- @objc func schedulePageDatePickerChanged(_ sender: NSDatePicker) {
- schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
- schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
- }
- @objc func schedulePageApplyDateRangePressed(_ sender: NSButton) {
- if let selectedItem = schedulePageFilterDropdown?.selectedItem,
- let selectedFilter = SchedulePageFilter(rawValue: selectedItem.tag) {
- schedulePageFilter = selectedFilter
- }
- refreshSchedulePageDateFilterUI()
- applySchedulePageFiltersAndRender()
- }
- @objc func schedulePageResetFiltersPressed(_ sender: NSButton) {
- schedulePageFilter = .all
- schedulePageFilterDropdown?.selectItem(at: SchedulePageFilter.all.rawValue)
- let today = Calendar.current.startOfDay(for: Date())
- schedulePageFromDate = today
- schedulePageToDate = today
- schedulePageFromDatePicker?.dateValue = today
- schedulePageToDatePicker?.dateValue = today
- refreshSchedulePageDateFilterUI()
- applySchedulePageFiltersAndRender()
- }
- @objc private func aiCompanionRecordingsFilterChanged(_ sender: NSPopUpButton) {
- guard let selectedItem = sender.selectedItem,
- let filter = AiCompanionRecordingsFilter(rawValue: selectedItem.tag) else { return }
- aiCompanionRecordingsFilter = filter
- if filter != .customRange {
- setAiCompanionRecordingsRangeError(nil)
- }
- refreshAiCompanionRecordingsFilterChrome()
- redrawAiCompanionPageIfNeeded()
- }
- @objc private func aiCompanionFilterDatePickerChanged(_ sender: NSDatePicker) {
- aiCompanionFilterFromDate = aiCompanionFilterFromDatePicker?.dateValue ?? aiCompanionFilterFromDate
- aiCompanionFilterToDate = aiCompanionFilterToDatePicker?.dateValue ?? aiCompanionFilterToDate
- }
- @objc private func aiCompanionRecordingsApplyPressed(_ sender: NSButton) {
- aiCompanionFilterFromDate = aiCompanionFilterFromDatePicker?.dateValue ?? aiCompanionFilterFromDate
- aiCompanionFilterToDate = aiCompanionFilterToDatePicker?.dateValue ?? aiCompanionFilterToDate
- if let selectedItem = aiCompanionRecordingsFilterDropdown?.selectedItem,
- let filter = AiCompanionRecordingsFilter(rawValue: selectedItem.tag) {
- aiCompanionRecordingsFilter = filter
- }
- if aiCompanionRecordingsFilter == .customRange && !aiCompanionHasValidCustomFilterRange() {
- setAiCompanionRecordingsRangeError("Start date must be on or before end date.")
- } else {
- setAiCompanionRecordingsRangeError(nil)
- }
- refreshAiCompanionRecordingsFilterChrome()
- redrawAiCompanionPageIfNeeded()
- }
- @objc private func aiCompanionRecordingsResetPressed(_ sender: NSButton) {
- aiCompanionRecordingsFilter = .today
- aiCompanionRecordingsFilterDropdown?.selectItem(at: AiCompanionRecordingsFilter.today.rawValue)
- let today = Calendar.current.startOfDay(for: Date())
- aiCompanionFilterFromDate = today
- aiCompanionFilterToDate = today
- aiCompanionFilterFromDatePicker?.dateValue = today
- aiCompanionFilterToDatePicker?.dateValue = today
- setAiCompanionRecordingsRangeError(nil)
- refreshAiCompanionRecordingsFilterChrome()
- redrawAiCompanionPageIfNeeded()
- }
- @objc private func aiCompanionRecordingsRefreshPressed(_ sender: NSButton) {
- loadAiCompanionLocalRecordings()
- redrawAiCompanionPageIfNeeded()
- }
- @objc func schedulePageAddMeetingPressed(_ sender: NSButton) {
- guard requireGoogleLoginForCalendarScheduling() else { return }
- let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 230, height: 28))
- let datePicker = NSDatePicker(frame: accessory.bounds)
- datePicker.autoresizingMask = [.width, .height]
- datePicker.datePickerMode = .single
- datePicker.datePickerStyle = .textFieldAndStepper
- datePicker.datePickerElements = [.yearMonthDay]
- datePicker.dateValue = Calendar.current.startOfDay(for: Date())
- accessory.addSubview(datePicker)
- let alert = NSAlert()
- alert.messageText = "Select date"
- alert.informativeText = "Choose a date to schedule your meeting."
- alert.alertStyle = .informational
- alert.accessoryView = accessory
- alert.addButton(withTitle: "Continue")
- alert.addButton(withTitle: "Cancel")
- guard alert.runModal() == .alertFirstButtonReturn else { return }
- calendarPageSelectedDate = Calendar.current.startOfDay(for: datePicker.dateValue)
- presentCreateMeetingPopover(relativeTo: sender)
- }
- private func scheduleTimeText(for meeting: ScheduledMeeting) -> String {
- if meeting.isAllDay { return "All day" }
- let f = DateFormatter()
- f.locale = Locale.current
- f.timeZone = TimeZone.current
- f.dateStyle = .none
- f.timeStyle = .short
- return "\(f.string(from: meeting.startDate)) - \(f.string(from: meeting.endDate))"
- }
- private func scheduleDayText(for meeting: ScheduledMeeting) -> String {
- let f = DateFormatter()
- f.locale = Locale.current
- f.timeZone = TimeZone.current
- f.dateFormat = "EEE, d MMM"
- return f.string(from: meeting.startDate)
- }
- private func scheduleDurationText(for meeting: ScheduledMeeting) -> String {
- if meeting.isAllDay { return "Duration: all day" }
- let duration = max(0, meeting.endDate.timeIntervalSince(meeting.startDate))
- let totalMinutes = Int(duration / 60)
- let hours = totalMinutes / 60
- let minutes = totalMinutes % 60
- if hours > 0, minutes > 0 { return "Duration: \(hours)h \(minutes)m" }
- if hours > 0 { return "Duration: \(hours)h" }
- return "Duration: \(minutes)m"
- }
- private func scheduleHeadingText(for meetings: [ScheduledMeeting]) -> String {
- guard let first = meetings.first else {
- return hasGoogleSessionAvailable() ? "No upcoming meetings" : "Connect Google to see meetings"
- }
- let day = Calendar.current.startOfDay(for: first.startDate)
- let f = DateFormatter()
- f.locale = Locale.current
- f.timeZone = TimeZone.current
- f.dateFormat = "EEEE, d MMM"
- return f.string(from: day)
- }
- private func openMeetingURL(_ url: URL, meeting: ScheduledMeeting? = nil) {
- let title = meeting?.title ?? "Scheduled Meeting"
- let shouldOpenMeeting = beginMeetingRecordingIfConsented(meetingTitle: title, meetingURL: url)
- guard shouldOpenMeeting else { return }
- NSWorkspace.shared.open(url)
- }
- private func renderScheduleCards(into stack: NSStackView, meetings: [ScheduledMeeting]) {
- displayedScheduleMeetings = meetings
- let shouldShowScrollControls = meetings.count > 3
- scheduleScrollLeftButton?.isHidden = !shouldShowScrollControls
- scheduleScrollRightButton?.isHidden = !shouldShowScrollControls
- scheduleCardsScrollView?.contentView.setBoundsOrigin(.zero)
- if let scroll = scheduleCardsScrollView {
- scroll.reflectScrolledClipView(scroll.contentView)
- }
- stack.arrangedSubviews.forEach { v in
- stack.removeArrangedSubview(v)
- v.removeFromSuperview()
- }
- if meetings.isEmpty {
- let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
- empty.translatesAutoresizingMaskIntoConstraints = false
- empty.widthAnchor.constraint(equalToConstant: 240).isActive = true
- empty.heightAnchor.constraint(equalToConstant: 150).isActive = true
- styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let label = textLabel(hasGoogleSessionAvailable() ? "No meetings" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
- label.translatesAutoresizingMaskIntoConstraints = false
- empty.addSubview(label)
- NSLayoutConstraint.activate([
- label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
- label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
- ])
- stack.addArrangedSubview(empty)
- return
- }
- for meeting in meetings {
- stack.addArrangedSubview(scheduleCard(meeting: meeting))
- }
- }
- private func filteredMeetings(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
- let now = Date()
- switch scheduleFilter {
- case .all:
- return meetings.filter { $0.endDate >= now }
- case .today:
- let start = Calendar.current.startOfDay(for: now)
- let end = Calendar.current.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
- return meetings.filter { $0.startDate >= start && $0.startDate < end }
- case .week:
- let end = Calendar.current.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
- return meetings.filter { $0.startDate >= now && $0.startDate <= end }
- }
- }
- private func filteredMeetingsForSchedulePage(_ meetings: [ScheduledMeeting]) -> [ScheduledMeeting] {
- let calendar = Calendar.current
- let now = Date()
- switch schedulePageFilter {
- case .all:
- return meetings.filter { $0.endDate >= now }
- case .today:
- let start = calendar.startOfDay(for: now)
- let end = calendar.date(byAdding: .day, value: 1, to: start) ?? start.addingTimeInterval(86400)
- return meetings.filter { $0.startDate >= start && $0.startDate < end }
- case .week:
- let end = calendar.date(byAdding: .day, value: 7, to: now) ?? now.addingTimeInterval(7 * 86400)
- return meetings.filter { $0.startDate >= now && $0.startDate <= end }
- case .month:
- let end = calendar.date(byAdding: .month, value: 1, to: now) ?? now.addingTimeInterval(30 * 86400)
- return meetings.filter { $0.startDate >= now && $0.startDate <= end }
- case .customRange:
- let start = calendar.startOfDay(for: schedulePageFromDate)
- let inclusiveEndDay = calendar.startOfDay(for: schedulePageToDate)
- guard let end = calendar.date(byAdding: .day, value: 1, to: inclusiveEndDay) else {
- return meetings
- }
- return meetings.filter { $0.startDate >= start && $0.startDate < end }
- }
- }
- private func refreshSchedulePageDateFilterUI() {
- let isCustom = schedulePageFilter == .customRange
- schedulePageFromDatePicker?.isEnabled = isCustom
- schedulePageToDatePicker?.isEnabled = isCustom
- let dim: CGFloat = isCustom ? 1.0 : 0.65
- schedulePageFromDatePicker?.alphaValue = 1
- schedulePageToDatePicker?.alphaValue = 1
- schedulePageFromDatePicker?.superview?.alphaValue = dim
- schedulePageToDatePicker?.superview?.alphaValue = dim
- }
- private func schedulePageHasValidCustomRange() -> Bool {
- let start = Calendar.current.startOfDay(for: schedulePageFromDate)
- let end = Calendar.current.startOfDay(for: schedulePageToDate)
- return start <= end
- }
- private func setSchedulePageRangeError(_ message: String?) {
- guard let label = schedulePageRangeErrorLabel else { return }
- label.stringValue = message ?? ""
- label.isHidden = message == nil
- }
- private func applySchedulePageFiltersAndRender() {
- schedulePageFromDate = schedulePageFromDatePicker?.dateValue ?? schedulePageFromDate
- schedulePageToDate = schedulePageToDatePicker?.dateValue ?? schedulePageToDate
- if schedulePageFilter == .customRange && !schedulePageHasValidCustomRange() {
- setSchedulePageRangeError("Start date must be on or before end date.")
- schedulePageFilteredMeetings = []
- schedulePageVisibleCount = 0
- renderSchedulePageCards()
- schedulePageDateHeadingLabel?.stringValue = "Invalid custom date range"
- return
- }
- setSchedulePageRangeError(nil)
- schedulePageFilteredMeetings = filteredMeetingsForSchedulePage(scheduleCachedMeetings)
- schedulePageVisibleCount = min(schedulePageBatchSize, schedulePageFilteredMeetings.count)
- renderSchedulePageCards()
- schedulePageDateHeadingLabel?.stringValue = scheduleHeadingText(for: schedulePageFilteredMeetings)
- }
- private func appendSchedulePageBatchIfNeeded() {
- guard schedulePageVisibleCount < schedulePageFilteredMeetings.count else { return }
- let nextCount = min(schedulePageVisibleCount + schedulePageBatchSize, schedulePageFilteredMeetings.count)
- guard nextCount > schedulePageVisibleCount else { return }
- schedulePageVisibleCount = nextCount
- renderSchedulePageCards()
- // If we're still near the bottom after adding a batch (large viewport),
- // immediately evaluate again so pagination keeps advancing in chunks of 6.
- DispatchQueue.main.async { [weak self] in
- self?.schedulePageScrolled()
- }
- }
- private func schedulePageScrolled() {
- guard let scroll = schedulePageCardsScrollView else { return }
- let contentBounds = scroll.contentView.bounds
- let contentHeight = scroll.documentView?.bounds.height ?? 0
- guard contentHeight > 0 else { return }
- let remaining = contentHeight - (contentBounds.origin.y + contentBounds.height)
- if remaining <= 200 {
- appendSchedulePageBatchIfNeeded()
- }
- }
- private func renderSchedulePageCards() {
- guard let stack = schedulePageCardsStack else { return }
- stack.arrangedSubviews.forEach { v in
- stack.removeArrangedSubview(v)
- v.removeFromSuperview()
- }
- let visibleMeetings = Array(schedulePageFilteredMeetings.prefix(schedulePageVisibleCount))
- if visibleMeetings.isEmpty {
- let empty = roundedContainer(cornerRadius: 10, color: palette.sectionCard)
- empty.translatesAutoresizingMaskIntoConstraints = false
- empty.heightAnchor.constraint(equalToConstant: 140).isActive = true
- styleSurface(empty, borderColor: palette.inputBorder, borderWidth: 1, shadow: false)
- let label = textLabel(hasGoogleSessionAvailable() ? "No meetings for selected filters" : "Connect to load schedule", font: typography.cardSubtitle, color: palette.textSecondary)
- label.translatesAutoresizingMaskIntoConstraints = false
- empty.addSubview(label)
- NSLayoutConstraint.activate([
- label.centerXAnchor.constraint(equalTo: empty.centerXAnchor),
- label.centerYAnchor.constraint(equalTo: empty.centerYAnchor)
- ])
- stack.addArrangedSubview(empty)
- empty.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- return
- }
- var index = 0
- while index < visibleMeetings.count {
- let row = NSStackView()
- row.translatesAutoresizingMaskIntoConstraints = false
- row.userInterfaceLayoutDirection = .leftToRight
- row.orientation = .horizontal
- row.alignment = .top
- row.spacing = schedulePageCardSpacing
- row.distribution = .fillEqually
- let rowEnd = min(index + schedulePageCardsPerRow, visibleMeetings.count)
- for meeting in visibleMeetings[index..<rowEnd] {
- row.addArrangedSubview(scheduleCard(meeting: meeting, useFlexibleWidth: true, contentHeight: schedulePageCardHeight))
- }
- stack.addArrangedSubview(row)
- row.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- index = rowEnd
- }
- if schedulePageVisibleCount < schedulePageFilteredMeetings.count {
- let pagination = NSStackView()
- pagination.translatesAutoresizingMaskIntoConstraints = false
- pagination.orientation = .horizontal
- pagination.alignment = .centerY
- pagination.spacing = 10
- let moreLabel = textLabel(
- "Showing \(schedulePageVisibleCount) of \(schedulePageFilteredMeetings.count)",
- font: NSFont.systemFont(ofSize: 12, weight: .medium),
- color: palette.textMuted
- )
- pagination.addArrangedSubview(moreLabel)
- let spacer = NSView()
- spacer.translatesAutoresizingMaskIntoConstraints = false
- spacer.setContentHuggingPriority(.defaultLow, for: .horizontal)
- pagination.addArrangedSubview(spacer)
- stack.addArrangedSubview(pagination)
- pagination.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
- }
- }
- private func scrollScheduleCards(direction: Int) {
- guard let scroll = scheduleCardsScrollView else { return }
- let contentBounds = scroll.contentView.bounds
- let step = max(220, contentBounds.width * 0.7)
- let proposedX = contentBounds.origin.x + (CGFloat(direction) * step)
- let maxX = max(0, scroll.documentView?.bounds.width ?? 0 - contentBounds.width)
- let nextX = min(max(0, proposedX), maxX)
- scroll.contentView.animator().setBoundsOrigin(NSPoint(x: nextX, y: 0))
- scroll.reflectScrolledClipView(scroll.contentView)
- }
- private func loadSchedule() async {
- do {
- if hasGoogleSessionAvailable() == false {
- await MainActor.run {
- updateGoogleAuthButtonTitle()
- applyGoogleProfile(nil)
- scheduleDateHeadingLabel?.stringValue = "Connect Google to see meetings"
- schedulePageDateHeadingLabel?.stringValue = "Connect Google to see meetings"
- if let stack = scheduleCardsStack {
- renderScheduleCards(into: stack, meetings: [])
- }
- scheduleCachedMeetings = []
- pageCache[.aiCompanion] = nil
- publishWidgetMeetingsSnapshot(from: [])
- DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
- MeetingReminderManager.shared.cancelAllReminders()
- applySchedulePageFiltersAndRender()
- if calendarPageGridStack != nil {
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- renderCalendarSelectedDay()
- }
- }
- return
- }
- let token = try await googleOAuth.validAccessToken(presentingWindow: view.window)
- let profile = try? await googleOAuth.fetchUserProfile(accessToken: token)
- let meetings = try await calendarClient.fetchUpcomingMeetings(accessToken: token)
- let filtered = filteredMeetings(meetings)
- await MainActor.run {
- updateGoogleAuthButtonTitle()
- applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
- scheduleDateHeadingLabel?.stringValue = scheduleHeadingText(for: filtered)
- if let stack = scheduleCardsStack {
- renderScheduleCards(into: stack, meetings: filtered)
- }
- scheduleCachedMeetings = meetings
- pageCache[.aiCompanion] = nil
- publishWidgetMeetingsSnapshot(from: filtered)
- DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
- if storeKitCoordinator.hasPremiumAccess {
- MeetingReminderManager.shared.scheduleReminders(for: meetings)
- }
- applySchedulePageFiltersAndRender()
- if calendarPageGridStack != nil {
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- renderCalendarSelectedDay()
- }
- }
- } catch {
- await MainActor.run {
- updateGoogleAuthButtonTitle()
- if hasGoogleSessionAvailable() == false {
- applyGoogleProfile(nil)
- }
- scheduleDateHeadingLabel?.stringValue = "Couldn’t load schedule"
- schedulePageDateHeadingLabel?.stringValue = "Couldn’t load schedule"
- if let stack = scheduleCardsStack {
- renderScheduleCards(into: stack, meetings: [])
- }
- scheduleCachedMeetings = []
- pageCache[.aiCompanion] = nil
- publishWidgetMeetingsSnapshot(from: [])
- DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
- MeetingReminderManager.shared.cancelAllReminders()
- applySchedulePageFiltersAndRender()
- if calendarPageGridStack != nil {
- calendarPageMonthLabel?.stringValue = calendarMonthTitleText(for: calendarPageMonthAnchor)
- renderCalendarMonthGrid()
- renderCalendarSelectedDay()
- }
- showSimpleError("Couldn’t load schedule.", error: error)
- }
- }
- }
- private func publishWidgetMeetingsSnapshot(from meetings: [ScheduledMeeting]) {
- let formatter = DateFormatter()
- formatter.dateFormat = "EEE, h:mm a"
- formatter.locale = Locale.current
- let payload = meetings.prefix(widgetSnapshotLimit).map { meeting in
- let endText = DateFormatter.localizedString(from: meeting.endDate, dateStyle: .none, timeStyle: .short)
- return WidgetMeetingSnapshot(
- id: meeting.id,
- title: meeting.title,
- timeText: "\(formatter.string(from: meeting.startDate)) - \(endText)",
- joinLink: meeting.meetURL.absoluteString
- )
- }
- if let data = try? JSONEncoder().encode(payload) {
- UserDefaults.standard.set(data, forKey: WidgetMeetingStore.key)
- } else {
- UserDefaults.standard.removeObject(forKey: WidgetMeetingStore.key)
- }
- NotificationCenter.default.post(name: .meetingsSnapshotUpdated, object: nil)
- }
- func showScheduleHelp() {
- let alert = NSAlert()
- alert.messageText = "Google schedule"
- 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."
- alert.addButton(withTitle: "OK")
- alert.runModal()
- }
- func scheduleReloadClicked() {
- Task { [weak self] in
- guard let self else { return }
- do {
- try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
- _ = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
- await MainActor.run {
- self.scheduleDateHeadingLabel?.stringValue = "Refreshing…"
- self.pageCache[.joinMeetings] = nil
- self.pageCache[.photo] = nil
- self.pageCache[.widgets] = nil
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(self.selectedSidebarPage)
- }
- await self.loadSchedule()
- } catch {
- await MainActor.run {
- self.showSimpleError("Couldn’t refresh schedule.", error: error)
- }
- }
- }
- }
- func scheduleConnectClicked() {
- Task { [weak self] in
- guard let self else { return }
- do {
- if self.hasGoogleSessionAvailable() {
- await MainActor.run { self.showGoogleAccountMenu() }
- return
- }
- try await self.ensureGoogleClientIdConfigured(presentingWindow: self.view.window)
- let token = try await self.googleOAuth.validAccessToken(presentingWindow: self.view.window)
- let profile = try? await self.googleOAuth.fetchUserProfile(accessToken: token)
- await MainActor.run {
- self.updateGoogleAuthButtonTitle()
- self.applyGoogleProfile(profile.map { self.makeGoogleProfileDisplay(from: $0) })
- self.pageCache[.joinMeetings] = nil
- self.pageCache[.photo] = nil
- self.pageCache[.video] = nil
- self.pageCache[.widgets] = nil
- self.pageCache[.settings] = nil
- self.pageCache[.aiCompanion] = nil
- self.showSidebarPage(self.selectedSidebarPage)
- }
- // Ensure desktop widgets refresh immediately with the newly available meetings.
- await self.loadSchedule()
- } catch {
- self.showSimpleError("Couldn’t connect Google account.", error: error)
- }
- }
- }
- private func showGoogleAccountMenu() {
- guard let button = scheduleGoogleAuthButton else { return }
- if googleAccountPopover?.isShown == true {
- googleAccountPopover?.performClose(nil)
- googleAccountPopover = nil
- return
- }
- let popover = NSPopover()
- popover.behavior = .transient
- popover.animates = true
- popover.appearance = NSAppearance(named: darkModeEnabled ? .darkAqua : .aqua)
- let name = scheduleCurrentProfile?.name ?? "Google account"
- let email = scheduleCurrentProfile?.email ?? "Signed in"
- let avatar = scheduleProfileMenuAvatar
- popover.contentViewController = GoogleAccountMenuViewController(
- palette: palette,
- darkModeEnabled: darkModeEnabled,
- displayName: name,
- email: email,
- avatar: avatar,
- onSignOut: { [weak self] in
- self?.googleAccountPopover?.performClose(nil)
- self?.googleAccountPopover = nil
- self?.performGoogleSignOut()
- }
- )
- googleAccountPopover = popover
- popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
- }
- private func performGoogleSignOut() {
- do {
- MeetingReminderManager.shared.cancelAllReminders()
- try googleOAuth.signOut()
- applyGoogleProfile(nil)
- publishWidgetMeetingsSnapshot(from: [])
- DesktopWidgetWindowManager.shared.refreshForAuthStateChange()
- updateGoogleAuthButtonTitle()
- pageCache[.joinMeetings] = nil
- pageCache[.photo] = nil
- pageCache[.video] = nil
- pageCache[.widgets] = nil
- pageCache[.settings] = nil
- pageCache[.aiCompanion] = nil
- showSidebarPage(selectedSidebarPage)
- Task { [weak self] in
- await self?.loadSchedule()
- }
- } catch {
- showSimpleError("Couldn’t logout Google account.", error: error)
- }
- }
- private func updateGoogleAuthButtonTitle() {
- let signedIn = hasGoogleSessionAvailable()
- guard let button = scheduleGoogleAuthButton else { return }
- let profileName = scheduleCurrentProfile?.name ?? "Google account"
- let ringHostInset: CGFloat = signedIn ? 14 : 0
- scheduleGoogleAuthHostPadWidthConstraint?.constant = ringHostInset
- scheduleGoogleAuthHostPadHeightConstraint?.constant = ringHostInset
- scheduleGoogleAuthHostView?.setAvatarRingMode(signedIn)
- scheduleGoogleAuthHostView?.updateRingAppearance(isDark: darkModeEnabled, accent: palette.primaryBlue)
- if signedIn == false {
- scheduleGoogleAuthHostView?.setProfileHoverActive(false)
- }
- if signedIn {
- button.setAccessibilityLabel("\(profileName), Google account")
- button.attributedTitle = NSAttributedString(string: "")
- button.imagePosition = .imageOnly
- button.imageScaling = .scaleProportionallyDown
- button.symbolConfiguration = nil
- scheduleGoogleAuthButtonHeightConstraint?.constant = scheduleGoogleSignedInAvatarSize
- scheduleGoogleAuthButtonWidthConstraint?.constant = scheduleGoogleSignedInAvatarSize
- button.layer?.cornerRadius = scheduleGoogleSignedInAvatarSize / 2
- let symbol = NSImage(systemSymbolName: "person.crop.circle.fill", accessibilityDescription: "Profile")
- if let symbol {
- let sized = resizedImage(symbol, to: NSSize(width: scheduleGoogleSignedInAvatarSize, height: scheduleGoogleSignedInAvatarSize))
- button.image = sized
- button.contentTintColor = palette.textSecondary
- } else {
- button.image = nil
- button.contentTintColor = nil
- }
- scheduleProfileMenuAvatar = button.image
- } else {
- button.setAccessibilityLabel("Sign in with Google")
- let title = "Sign in with Google"
- let titleFont = NSFont.systemFont(ofSize: 14, weight: .medium)
- let titleColor = darkModeEnabled ? NSColor(calibratedWhite: 0.96, alpha: 1) : NSColor(calibratedRed: 0.13, green: 0.14, blue: 0.16, alpha: 1)
- button.attributedTitle = NSAttributedString(string: title, attributes: [
- .font: titleFont,
- .foregroundColor: titleColor
- ])
- let textWidth = (title as NSString).size(withAttributes: [.font: titleFont]).width
- let idealWidth = ceil(textWidth + 80)
- scheduleGoogleAuthButtonWidthConstraint?.constant = min(320, max(188, idealWidth))
- scheduleGoogleAuthButtonHeightConstraint?.constant = 42
- button.layer?.cornerRadius = 21
- button.imagePosition = .imageLeading
- button.imageScaling = .scaleNone
- if let g = NSImage(named: "GoogleGLogo") {
- button.image = paddedTrailingImage(g, iconSize: NSSize(width: 22, height: 22), trailingPadding: 8)
- } else {
- button.image = nil
- }
- button.contentTintColor = nil
- }
- applyGoogleAuthButtonSurface()
- }
- private func makeGoogleProfileDisplay(from profile: GoogleUserProfile) -> GoogleProfileDisplay {
- let cleanedName = profile.name?.trimmingCharacters(in: .whitespacesAndNewlines)
- let cleanedEmail = profile.email?.trimmingCharacters(in: .whitespacesAndNewlines)
- return GoogleProfileDisplay(
- name: (cleanedName?.isEmpty == false ? cleanedName : nil) ?? "Google User",
- email: (cleanedEmail?.isEmpty == false ? cleanedEmail : nil) ?? "Signed in",
- pictureURL: profile.picture.flatMap(URL.init(string:))
- )
- }
- private func applyGoogleProfile(_ profile: GoogleProfileDisplay?) {
- scheduleProfileImageTask?.cancel()
- scheduleProfileImageTask = nil
- if profile == nil {
- scheduleProfileMenuAvatar = nil
- }
- scheduleCurrentProfile = profile
- updateGoogleAuthButtonTitle()
- guard let profile, let pictureURL = profile.pictureURL else { return }
- let avatarDiameter = scheduleGoogleSignedInAvatarSize
- scheduleProfileImageTask = Task { [weak self] in
- do {
- let (data, _) = try await URLSession.shared.data(from: pictureURL)
- if Task.isCancelled { return }
- guard let image = NSImage(data: data) else { return }
- await MainActor.run { [weak self] in
- guard let self else { return }
- let rounded = self.circularProfileImage(image, diameter: avatarDiameter)
- self.scheduleProfileMenuAvatar = circularNSImage(rounded, diameter: 48)
- self.scheduleGoogleAuthButton?.image = rounded
- self.scheduleGoogleAuthButton?.contentTintColor = nil
- }
- } catch {
- // Keep placeholder avatar if image fetch fails.
- }
- }
- }
- private func resizedImage(_ image: NSImage, to size: NSSize) -> NSImage {
- let result = NSImage(size: size)
- result.lockFocus()
- image.draw(in: NSRect(origin: .zero, size: size),
- from: NSRect(origin: .zero, size: image.size),
- operation: .copy,
- fraction: 1.0)
- result.unlockFocus()
- result.isTemplate = false
- return result
- }
- /// Clips a photo to a circle for the signed-in avatar (Google userinfo `picture` URLs are usually square).
- private func circularProfileImage(_ image: NSImage, diameter: CGFloat) -> NSImage {
- circularNSImage(image, diameter: diameter)
- }
- private func paddedTrailingImage(_ image: NSImage, iconSize: NSSize, trailingPadding: CGFloat) -> NSImage {
- let base = resizedImage(image, to: iconSize)
- let canvas = NSSize(width: iconSize.width + trailingPadding, height: iconSize.height)
- let result = NSImage(size: canvas)
- result.lockFocus()
- base.draw(in: NSRect(x: 0, y: 0, width: iconSize.width, height: iconSize.height),
- from: NSRect(origin: .zero, size: base.size),
- operation: .copy,
- fraction: 1.0)
- result.unlockFocus()
- result.isTemplate = false
- return result
- }
- private func applyGoogleAuthButtonSurface() {
- guard let button = scheduleGoogleAuthButton else { return }
- let signedIn = hasGoogleSessionAvailable()
- let isDark = darkModeEnabled
- if signedIn {
- button.layer?.backgroundColor = NSColor.clear.cgColor
- button.layer?.borderWidth = 0
- scheduleGoogleAuthHostView?.updateRingAppearance(isDark: isDark, accent: palette.primaryBlue)
- return
- }
- let baseBackground = isDark
- ? NSColor(calibratedRed: 8.0 / 255.0, green: 14.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
- : NSColor.white
- let hoverBlend = isDark ? NSColor.white : NSColor.black
- let hoverBackground = baseBackground.blended(withFraction: 0.07, of: hoverBlend) ?? baseBackground
- let baseBorder = isDark
- ? NSColor(calibratedWhite: 0.50, alpha: 1)
- : NSColor(calibratedWhite: 0.72, alpha: 1)
- let hoverBorder = isDark
- ? NSColor(calibratedWhite: 0.62, alpha: 1)
- : NSColor(calibratedWhite: 0.56, alpha: 1)
- button.layer?.borderWidth = 1
- button.layer?.backgroundColor = (scheduleGoogleAuthHovering ? hoverBackground : baseBackground).cgColor
- button.layer?.borderColor = (scheduleGoogleAuthHovering ? hoverBorder : baseBorder).cgColor
- }
- @MainActor
- func ensureGoogleClientIdConfigured(presentingWindow: NSWindow?) async throws {
- _ = presentingWindow
- guard googleOAuth.configuredClientId() != nil else { throw GoogleOAuthError.missingClientId }
- guard googleOAuth.configuredClientSecret() != nil else { throw GoogleOAuthError.missingClientSecret }
- }
- func showSimpleError(_ title: String, error: Error) {
- DispatchQueue.main.async {
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = title
- alert.informativeText = error.localizedDescription
- alert.addButton(withTitle: "OK")
- alert.runModal()
- }
- }
- }
- private struct Palette {
- let pageBackground: NSColor
- let sidebarBackground: NSColor
- let sectionCard: NSColor
- let tabBarBackground: NSColor
- let tabIdleBackground: NSColor
- let inputBackground: NSColor
- let inputBorder: NSColor
- let primaryBlue: NSColor
- let primaryBlueBorder: NSColor
- let cancelButton: NSColor
- let meetingBadge: NSColor
- let separator: NSColor
- let textPrimary: NSColor
- let textSecondary: NSColor
- let textTertiary: NSColor
- let textMuted: NSColor
- init(isDarkMode: Bool) {
- if isDarkMode {
- pageBackground = NSColor(calibratedRed: 10.0 / 255.0, green: 11.0 / 255.0, blue: 12.0 / 255.0, alpha: 1)
- sidebarBackground = NSColor(calibratedRed: 16.0 / 255.0, green: 17.0 / 255.0, blue: 19.0 / 255.0, alpha: 1)
- sectionCard = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
- tabBarBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
- tabIdleBackground = NSColor(calibratedRed: 22.0 / 255.0, green: 23.0 / 255.0, blue: 26.0 / 255.0, alpha: 1)
- inputBackground = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
- inputBorder = NSColor(calibratedRed: 38.0 / 255.0, green: 40.0 / 255.0, blue: 44.0 / 255.0, alpha: 1)
- primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
- primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
- cancelButton = NSColor(calibratedRed: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1)
- meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
- separator = NSColor(calibratedRed: 26.0 / 255.0, green: 27.0 / 255.0, blue: 30.0 / 255.0, alpha: 1)
- textPrimary = NSColor(calibratedWhite: 0.98, alpha: 1)
- textSecondary = NSColor(calibratedWhite: 0.78, alpha: 1)
- textTertiary = NSColor(calibratedWhite: 0.66, alpha: 1)
- textMuted = NSColor(calibratedWhite: 0.44, alpha: 1)
- } else {
- pageBackground = NSColor(calibratedRed: 244.0 / 255.0, green: 246.0 / 255.0, blue: 249.0 / 255.0, alpha: 1)
- sidebarBackground = NSColor(calibratedRed: 232.0 / 255.0, green: 236.0 / 255.0, blue: 242.0 / 255.0, alpha: 1)
- sectionCard = NSColor.white
- tabBarBackground = NSColor.white
- tabIdleBackground = NSColor.white
- inputBackground = NSColor(calibratedRed: 247.0 / 255.0, green: 249.0 / 255.0, blue: 252.0 / 255.0, alpha: 1)
- inputBorder = NSColor(calibratedRed: 211.0 / 255.0, green: 218.0 / 255.0, blue: 228.0 / 255.0, alpha: 1)
- primaryBlue = NSColor(calibratedRed: 27.0 / 255.0, green: 115.0 / 255.0, blue: 232.0 / 255.0, alpha: 1)
- primaryBlueBorder = NSColor(calibratedRed: 42.0 / 255.0, green: 118.0 / 255.0, blue: 220.0 / 255.0, alpha: 1)
- cancelButton = NSColor(calibratedRed: 240.0 / 255.0, green: 243.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
- meetingBadge = NSColor(calibratedRed: 0.88, green: 0.66, blue: 0.14, alpha: 1)
- separator = NSColor(calibratedRed: 212.0 / 255.0, green: 219.0 / 255.0, blue: 229.0 / 255.0, alpha: 1)
- textPrimary = NSColor(calibratedRed: 32.0 / 255.0, green: 38.0 / 255.0, blue: 47.0 / 255.0, alpha: 1)
- textSecondary = NSColor(calibratedRed: 82.0 / 255.0, green: 92.0 / 255.0, blue: 107.0 / 255.0, alpha: 1)
- textTertiary = NSColor(calibratedRed: 110.0 / 255.0, green: 120.0 / 255.0, blue: 136.0 / 255.0, alpha: 1)
- textMuted = NSColor(calibratedRed: 134.0 / 255.0, green: 145.0 / 255.0, blue: 162.0 / 255.0, alpha: 1)
- }
- }
- }
- private struct Typography {
- let sidebarBrand = NSFont.systemFont(ofSize: 26, weight: .bold)
- let sidebarSection = NSFont.systemFont(ofSize: 11, weight: .medium)
- let sidebarIcon = NSFont.systemFont(ofSize: 12, weight: .medium)
- let sidebarItem = NSFont.systemFont(ofSize: 16, weight: .medium)
- let pageTitle = NSFont.systemFont(ofSize: 27, weight: .semibold)
- let joinWithURLTitle = NSFont.systemFont(ofSize: 17, weight: .semibold)
- let sectionTitleBold = NSFont.systemFont(ofSize: 25, weight: .bold)
- let dateHeading = NSFont.systemFont(ofSize: 18, weight: .medium)
- let tabIcon = NSFont.systemFont(ofSize: 13, weight: .regular)
- let tabTitle = NSFont.systemFont(ofSize: 31 / 2, weight: .semibold)
- let fieldLabel = NSFont.systemFont(ofSize: 15, weight: .medium)
- let inputPlaceholder = NSFont.systemFont(ofSize: 14, weight: .regular)
- let buttonText = NSFont.systemFont(ofSize: 16, weight: .medium)
- let filterText = NSFont.systemFont(ofSize: 15, weight: .regular)
- let filterArrow = NSFont.systemFont(ofSize: 12, weight: .regular)
- let iconButton = NSFont.systemFont(ofSize: 14, weight: .medium)
- let cardIcon = NSFont.systemFont(ofSize: 8, weight: .bold)
- let cardTitle = NSFont.systemFont(ofSize: 15, weight: .semibold)
- let cardSubtitle = NSFont.systemFont(ofSize: 13, weight: .bold)
- let cardTime = NSFont.systemFont(ofSize: 12, weight: .regular)
- }
- // MARK: - In-app browser (macOS WKWebView + chrome)
- // Note: This target is AppKit/macOS. iOS would use WKWebView or SFSafariViewController; Android would use WebView or Custom Tabs.
- private enum InAppBrowserURLPolicy: Equatable {
- case allowAll
- case whitelist(hostSuffixes: [String])
- }
- private func inAppBrowserURLAllowed(_ url: URL, policy: InAppBrowserURLPolicy) -> Bool {
- let scheme = (url.scheme ?? "").lowercased()
- if scheme == "about" { return true }
- guard scheme == "http" || scheme == "https" else { return false }
- guard let host = url.host?.lowercased() else { return false }
- switch policy {
- case .allowAll:
- return true
- case .whitelist(let suffixes):
- for suffix in suffixes {
- let s = suffix.lowercased()
- if host == s || host.hasSuffix("." + s) { return true }
- }
- return false
- }
- }
- private enum InAppBrowserWebKitSupport {
- static func makeWebViewConfiguration() -> WKWebViewConfiguration {
- let config = WKWebViewConfiguration()
- config.websiteDataStore = .default()
- config.preferences.javaScriptCanOpenWindowsAutomatically = true
- if #available(macOS 12.3, *) {
- config.preferences.isElementFullscreenEnabled = true
- }
- config.mediaTypesRequiringUserActionForPlayback = []
- if #available(macOS 11.0, *) {
- config.defaultWebpagePreferences.allowsContentJavaScript = true
- }
- config.applicationNameForUserAgent = "MeetingsApp/1.0"
- return config
- }
- }
- private final class InAppBrowserWindowController: NSWindowController {
- private static let defaultContentSize = NSSize(width: 1100, height: 760)
- private static let minimumContentSize = NSSize(width: 800, height: 520)
- private let browserViewController = InAppBrowserContainerViewController()
- init() {
- let browserWindow = NSWindow(
- contentRect: NSRect(origin: .zero, size: Self.defaultContentSize),
- styleMask: [.titled, .closable, .miniaturizable, .resizable],
- backing: .buffered,
- defer: false
- )
- browserWindow.title = "Browser"
- browserWindow.isRestorable = false
- browserWindow.setFrameAutosaveName("")
- browserWindow.minSize = browserWindow.frameRect(forContentRect: NSRect(origin: .zero, size: Self.minimumContentSize)).size
- browserWindow.center()
- browserWindow.contentViewController = browserViewController
- super.init(window: browserWindow)
- }
- @available(*, unavailable)
- required init?(coder: NSCoder) {
- nil
- }
- /// Resets size and position each time the browser is shown so a previously tiny window is never reused.
- func applyDefaultFrameCenteredOnVisibleScreen() {
- guard let w = window, let screen = w.screen ?? NSScreen.main else { return }
- let windowFrame = w.frameRect(forContentRect: NSRect(origin: .zero, size: Self.defaultContentSize))
- let vf = screen.visibleFrame
- var frame = windowFrame
- frame.origin.x = vf.midX - frame.width / 2
- frame.origin.y = vf.midY - frame.height / 2
- if frame.maxX > vf.maxX { frame.origin.x = vf.maxX - frame.width }
- if frame.minX < vf.minX { frame.origin.x = vf.minX }
- if frame.maxY > vf.maxY { frame.origin.y = vf.maxY - frame.height }
- if frame.minY < vf.minY { frame.origin.y = vf.minY }
- w.setFrame(frame, display: true)
- }
- func load(url: URL, policy: InAppBrowserURLPolicy) {
- browserViewController.setNavigationPolicy(policy)
- browserViewController.load(url: url)
- }
- }
- private final class InAppBrowserContainerViewController: NSViewController, WKNavigationDelegate, WKUIDelegate, NSTextFieldDelegate {
- private var webView: WKWebView!
- private var webContainerView: NSView!
- private weak var urlField: NSTextField?
- private var backButton: NSButton!
- private var forwardButton: NSButton!
- private var reloadStopButton: NSButton!
- private var goButton: NSButton!
- private var progressBar: NSProgressIndicator!
- private var lastLoadedURL: URL?
- private var navigationPolicy: InAppBrowserURLPolicy = .allowAll
- private var processTerminateRetryCount = 0
- /// Includes fresh WKWebView instances so each retry gets a new WebContent process after a crash.
- private let maxProcessTerminateRetries = 3
- private var kvoTokens: [NSKeyValueObservation] = []
- deinit {
- kvoTokens.removeAll()
- }
- func setNavigationPolicy(_ policy: InAppBrowserURLPolicy) {
- navigationPolicy = policy
- }
- override func loadView() {
- let root = NSView()
- root.translatesAutoresizingMaskIntoConstraints = false
- let wv = makeWebView()
- webView = wv
- let webHost = NSView()
- webHost.translatesAutoresizingMaskIntoConstraints = false
- webHost.wantsLayer = true
- webHost.addSubview(wv)
- NSLayoutConstraint.activate([
- wv.leadingAnchor.constraint(equalTo: webHost.leadingAnchor),
- wv.trailingAnchor.constraint(equalTo: webHost.trailingAnchor),
- wv.topAnchor.constraint(equalTo: webHost.topAnchor),
- wv.bottomAnchor.constraint(equalTo: webHost.bottomAnchor)
- ])
- webContainerView = webHost
- let toolbar = NSStackView()
- toolbar.translatesAutoresizingMaskIntoConstraints = false
- toolbar.orientation = .horizontal
- toolbar.spacing = 8
- toolbar.alignment = .centerY
- toolbar.edgeInsets = NSEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)
- backButton = makeToolbarButton(title: "◀", symbolName: "chevron.backward", accessibilityDescription: "Back")
- backButton.target = self
- backButton.action = #selector(goBack)
- forwardButton = makeToolbarButton(title: "▶", symbolName: "chevron.forward", accessibilityDescription: "Forward")
- forwardButton.target = self
- forwardButton.action = #selector(goForward)
- reloadStopButton = makeToolbarButton(title: "Reload", symbolName: "arrow.clockwise", accessibilityDescription: "Reload")
- reloadStopButton.target = self
- reloadStopButton.action = #selector(reloadOrStop)
- let field = NSTextField(string: "")
- field.translatesAutoresizingMaskIntoConstraints = false
- field.font = NSFont.systemFont(ofSize: 13, weight: .regular)
- field.placeholderString = "Address"
- field.cell?.sendsActionOnEndEditing = false
- field.delegate = self
- urlField = field
- goButton = NSButton(title: "Go", target: self, action: #selector(addressFieldSubmitted))
- goButton.translatesAutoresizingMaskIntoConstraints = false
- goButton.bezelStyle = .rounded
- toolbar.addArrangedSubview(backButton)
- toolbar.addArrangedSubview(forwardButton)
- toolbar.addArrangedSubview(reloadStopButton)
- toolbar.addArrangedSubview(field)
- toolbar.addArrangedSubview(goButton)
- field.widthAnchor.constraint(greaterThanOrEqualToConstant: 240).isActive = true
- let bar = NSProgressIndicator()
- bar.translatesAutoresizingMaskIntoConstraints = false
- bar.style = .bar
- bar.isIndeterminate = false
- bar.minValue = 0
- bar.maxValue = 1
- bar.doubleValue = 0
- bar.isHidden = true
- progressBar = bar
- let separator = NSBox()
- separator.translatesAutoresizingMaskIntoConstraints = false
- separator.boxType = .separator
- webView.navigationDelegate = self
- webView.uiDelegate = self
- root.addSubview(toolbar)
- root.addSubview(bar)
- root.addSubview(separator)
- root.addSubview(webHost)
- NSLayoutConstraint.activate([
- toolbar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- toolbar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- toolbar.topAnchor.constraint(equalTo: root.topAnchor),
- bar.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- bar.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- bar.topAnchor.constraint(equalTo: toolbar.bottomAnchor),
- bar.heightAnchor.constraint(equalToConstant: 3),
- separator.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- separator.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- separator.topAnchor.constraint(equalTo: bar.bottomAnchor),
- webHost.leadingAnchor.constraint(equalTo: root.leadingAnchor),
- webHost.trailingAnchor.constraint(equalTo: root.trailingAnchor),
- webHost.topAnchor.constraint(equalTo: separator.bottomAnchor),
- webHost.bottomAnchor.constraint(equalTo: root.bottomAnchor)
- ])
- view = root
- installWebViewObservers()
- syncToolbarFromWebView()
- }
- private func makeWebView() -> WKWebView {
- let wv = WKWebView(frame: .zero, configuration: InAppBrowserWebKitSupport.makeWebViewConfiguration())
- wv.translatesAutoresizingMaskIntoConstraints = false
- return wv
- }
- private func teardownWebViewObservers() {
- kvoTokens.removeAll()
- }
- /// New `WKWebView` = new WebContent process (helps after GPU/JS crashes on heavy sites like Meet).
- private func replaceWebViewAndLoad(url: URL) {
- teardownWebViewObservers()
- webView.navigationDelegate = nil
- webView.uiDelegate = nil
- webView.removeFromSuperview()
- let wv = makeWebView()
- webView = wv
- webContainerView.addSubview(wv)
- NSLayoutConstraint.activate([
- wv.leadingAnchor.constraint(equalTo: webContainerView.leadingAnchor),
- wv.trailingAnchor.constraint(equalTo: webContainerView.trailingAnchor),
- wv.topAnchor.constraint(equalTo: webContainerView.topAnchor),
- wv.bottomAnchor.constraint(equalTo: webContainerView.bottomAnchor)
- ])
- webView.navigationDelegate = self
- webView.uiDelegate = self
- installWebViewObservers()
- syncToolbarFromWebView()
- webView.load(URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData))
- }
- private func makeToolbarButton(title: String, symbolName: String, accessibilityDescription: String) -> NSButton {
- let b = NSButton()
- b.translatesAutoresizingMaskIntoConstraints = false
- b.bezelStyle = .texturedRounded
- b.setAccessibilityLabel(accessibilityDescription)
- if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: symbolName, accessibilityDescription: accessibilityDescription) {
- b.image = img
- b.imagePosition = .imageOnly
- } else {
- b.title = title
- }
- b.widthAnchor.constraint(greaterThanOrEqualToConstant: 32).isActive = true
- return b
- }
- private func installWebViewObservers() {
- kvoTokens.append(webView.observe(\.canGoBack, options: [.new]) { [weak self] _, _ in
- self?.syncToolbarFromWebView()
- })
- kvoTokens.append(webView.observe(\.canGoForward, options: [.new]) { [weak self] _, _ in
- self?.syncToolbarFromWebView()
- })
- kvoTokens.append(webView.observe(\.isLoading, options: [.new]) { [weak self] _, _ in
- self?.syncToolbarFromWebView()
- })
- kvoTokens.append(webView.observe(\.estimatedProgress, options: [.new]) { [weak self] _, _ in
- self?.syncProgressFromWebView()
- })
- kvoTokens.append(webView.observe(\.title, options: [.new]) { [weak self] _, _ in
- self?.syncWindowTitle()
- })
- kvoTokens.append(webView.observe(\.url, options: [.new]) { [weak self] _, _ in
- self?.syncAddressFieldFromWebView()
- })
- }
- private func syncToolbarFromWebView() {
- backButton?.isEnabled = webView.canGoBack
- forwardButton?.isEnabled = webView.canGoForward
- if webView.isLoading {
- if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Stop") {
- reloadStopButton.image = img
- reloadStopButton.imagePosition = .imageOnly
- reloadStopButton.title = ""
- } else {
- reloadStopButton.title = "Stop"
- }
- } else {
- if #available(macOS 11.0, *), let img = NSImage(systemSymbolName: "arrow.clockwise", accessibilityDescription: "Reload") {
- reloadStopButton.image = img
- reloadStopButton.imagePosition = .imageOnly
- reloadStopButton.title = ""
- } else {
- reloadStopButton.title = "Reload"
- }
- }
- syncProgressFromWebView()
- }
- private func syncProgressFromWebView() {
- guard let progressBar else { return }
- if webView.isLoading {
- progressBar.isHidden = false
- progressBar.doubleValue = webView.estimatedProgress
- } else {
- progressBar.isHidden = true
- progressBar.doubleValue = 0
- }
- }
- private func syncAddressFieldFromWebView() {
- guard let urlField, urlField.currentEditor() == nil, let url = webView.url else { return }
- urlField.stringValue = url.absoluteString
- }
- private func syncWindowTitle() {
- let t = webView.title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- let host = webView.url?.host ?? ""
- view.window?.title = t.isEmpty ? (host.isEmpty ? "Browser" : host) : t
- }
- func load(url: URL) {
- lastLoadedURL = url
- processTerminateRetryCount = 0
- urlField?.stringValue = url.absoluteString
- webView.load(URLRequest(url: url))
- syncWindowTitle()
- }
- @objc private func goBack() {
- webView.goBack()
- }
- @objc private func goForward() {
- webView.goForward()
- }
- @objc private func reloadOrStop() {
- if webView.isLoading {
- webView.stopLoading()
- } else {
- webView.reload()
- }
- }
- @objc private func addressFieldSubmitted() {
- let raw = urlField?.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
- guard raw.isEmpty == false else { return }
- var normalized = raw
- if normalized.lowercased().hasPrefix("http://") == false && normalized.lowercased().hasPrefix("https://") == false {
- normalized = "https://\(normalized)"
- }
- guard let url = URL(string: normalized),
- let scheme = url.scheme?.lowercased(),
- scheme == "http" || scheme == "https",
- url.host != nil
- else {
- let alert = NSAlert()
- alert.messageText = "Invalid address"
- alert.informativeText = "Enter a valid web address, for example https://example.com"
- alert.addButton(withTitle: "OK")
- alert.runModal()
- return
- }
- guard inAppBrowserURLAllowed(url, policy: navigationPolicy) else {
- presentBlockedHostAlert()
- return
- }
- load(url: url)
- }
- private func presentBlockedHostAlert() {
- let alert = NSAlert()
- alert.messageText = "Address not allowed"
- alert.informativeText = "This URL is not permitted with the current in-app browser policy (whitelist)."
- alert.addButton(withTitle: "OK")
- alert.runModal()
- }
- func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
- processTerminateRetryCount = 0
- syncAddressFieldFromWebView()
- syncWindowTitle()
- }
- func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
- let nsError = error as NSError
- if nsError.code == NSURLErrorCancelled {
- return
- }
- let alert = NSAlert()
- alert.messageText = "Unable to load page"
- alert.informativeText = "Could not load this page in the in-app browser.\n\n\(error.localizedDescription)"
- alert.addButton(withTitle: "Try Again")
- alert.addButton(withTitle: "OK")
- if alert.runModal() == .alertFirstButtonReturn, let url = lastLoadedURL {
- processTerminateRetryCount = 0
- webView.load(URLRequest(url: url))
- }
- }
- func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
- guard let url = lastLoadedURL else { return }
- if processTerminateRetryCount < maxProcessTerminateRetries {
- processTerminateRetryCount += 1
- replaceWebViewAndLoad(url: url)
- return
- }
- let alert = NSAlert()
- alert.messageText = "Page stopped loading"
- alert.informativeText =
- "The in-app browser closed this page unexpectedly. You can try loading it again in this same window."
- alert.addButton(withTitle: "Try Again")
- alert.addButton(withTitle: "OK")
- if alert.runModal() == .alertFirstButtonReturn {
- processTerminateRetryCount = 0
- replaceWebViewAndLoad(url: url)
- }
- }
- func webView(
- _ webView: WKWebView,
- decidePolicyFor navigationAction: WKNavigationAction,
- decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
- ) {
- guard let url = navigationAction.request.url else {
- decisionHandler(.allow)
- return
- }
- let scheme = (url.scheme ?? "").lowercased()
- if scheme == "mailto" || scheme == "tel" {
- decisionHandler(.cancel)
- return
- }
- if inAppBrowserURLAllowed(url, policy: navigationPolicy) == false {
- if navigationAction.targetFrame?.isMainFrame != false {
- DispatchQueue.main.async { [weak self] in
- self?.presentBlockedHostAlert()
- }
- }
- decisionHandler(.cancel)
- return
- }
- decisionHandler(.allow)
- }
- func webView(
- _ webView: WKWebView,
- createWebViewWith configuration: WKWebViewConfiguration,
- for navigationAction: WKNavigationAction,
- windowFeatures: WKWindowFeatures
- ) -> WKWebView? {
- if navigationAction.targetFrame == nil, let requestURL = navigationAction.request.url {
- if inAppBrowserURLAllowed(requestURL, policy: navigationPolicy) {
- webView.load(URLRequest(url: requestURL))
- } else {
- presentBlockedHostAlert()
- }
- }
- return nil
- }
- func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
- if control === urlField, commandSelector == #selector(NSResponder.insertNewline(_:)) {
- addressFieldSubmitted()
- return true
- }
- return false
- }
- }
|