window-basic-main.cpp 301 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. Zachary Lund <[email protected]>
  4. Philippe Groarke <[email protected]>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ******************************************************************************/
  16. #include "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <unordered_set>
  21. #include <obs-data.h>
  22. #include <obs.h>
  23. #include <obs.hpp>
  24. #include <QGuiApplication>
  25. #include <QMessageBox>
  26. #include <QShowEvent>
  27. #include <QDesktopServices>
  28. #include <QFileDialog>
  29. #include <QScreen>
  30. #include <QColorDialog>
  31. #include <QSizePolicy>
  32. #include <QScrollBar>
  33. #include <QTextStream>
  34. #include <QActionGroup>
  35. #include <util/dstr.h>
  36. #include <util/util.hpp>
  37. #include <util/platform.h>
  38. #include <util/profiler.hpp>
  39. #include <util/dstr.hpp>
  40. #include "obs-app.hpp"
  41. #include "platform.hpp"
  42. #include "visibility-item-widget.hpp"
  43. #include "item-widget-helpers.hpp"
  44. #include "window-basic-settings.hpp"
  45. #include "window-namedialog.hpp"
  46. #include "window-basic-auto-config.hpp"
  47. #include "window-basic-source-select.hpp"
  48. #include "window-basic-main.hpp"
  49. #include "window-basic-stats.hpp"
  50. #include "window-basic-main-outputs.hpp"
  51. #include "window-basic-vcam-config.hpp"
  52. #include "window-log-reply.hpp"
  53. #ifdef __APPLE__
  54. #include "window-permissions.hpp"
  55. #endif
  56. #include "window-projector.hpp"
  57. #include "window-remux.hpp"
  58. #ifdef YOUTUBE_ENABLED
  59. #include "auth-youtube.hpp"
  60. #include "window-youtube-actions.hpp"
  61. #include "youtube-api-wrappers.hpp"
  62. #endif
  63. #include "qt-wrappers.hpp"
  64. #include "context-bar-controls.hpp"
  65. #include "obs-proxy-style.hpp"
  66. #include "display-helpers.hpp"
  67. #include "volume-control.hpp"
  68. #include "remote-text.hpp"
  69. #include "ui-validation.hpp"
  70. #include "media-controls.hpp"
  71. #include "undo-stack-obs.hpp"
  72. #include <fstream>
  73. #include <sstream>
  74. #ifdef _WIN32
  75. #include "update/win-update.hpp"
  76. #include "update/shared-update.hpp"
  77. #include "windows.h"
  78. #endif
  79. #ifdef WHATSNEW_ENABLED
  80. #include "update/models/whatsnew.hpp"
  81. #endif
  82. #if !defined(_WIN32) && defined(WHATSNEW_ENABLED)
  83. #include "update/shared-update.hpp"
  84. #endif
  85. #ifdef ENABLE_SPARKLE_UPDATER
  86. #include "update/mac-update.hpp"
  87. #endif
  88. #include "ui_OBSBasic.h"
  89. #include "ui_ColorSelect.h"
  90. #include <QWindow>
  91. #ifdef ENABLE_WAYLAND
  92. #include <obs-nix-platform.h>
  93. #endif
  94. using namespace std;
  95. #ifdef BROWSER_AVAILABLE
  96. #include <browser-panel.hpp>
  97. #endif
  98. #include "ui-config.h"
  99. struct QCef;
  100. struct QCefCookieManager;
  101. QCef *cef = nullptr;
  102. QCefCookieManager *panel_cookies = nullptr;
  103. bool cef_js_avail = false;
  104. void DestroyPanelCookieManager();
  105. namespace {
  106. template<typename OBSRef> struct SignalContainer {
  107. OBSRef ref;
  108. vector<shared_ptr<OBSSignal>> handlers;
  109. };
  110. } // namespace
  111. extern volatile long insideEventLoop;
  112. Q_DECLARE_METATYPE(OBSScene);
  113. Q_DECLARE_METATYPE(OBSSceneItem);
  114. Q_DECLARE_METATYPE(OBSSource);
  115. Q_DECLARE_METATYPE(obs_order_movement);
  116. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  117. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  118. {
  119. out << v.ref;
  120. return out;
  121. }
  122. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  123. {
  124. in >> v.ref;
  125. return in;
  126. }
  127. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  128. {
  129. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  130. }
  131. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  132. {
  133. item->setData(static_cast<int>(QtDataRole::OBSRef),
  134. QVariant::fromValue(val));
  135. }
  136. static void AddExtraModulePaths()
  137. {
  138. string plugins_path, plugins_data_path;
  139. char *s;
  140. s = getenv("OBS_PLUGINS_PATH");
  141. if (s)
  142. plugins_path = s;
  143. s = getenv("OBS_PLUGINS_DATA_PATH");
  144. if (s)
  145. plugins_data_path = s;
  146. if (!plugins_path.empty() && !plugins_data_path.empty()) {
  147. string data_path_with_module_suffix;
  148. data_path_with_module_suffix += plugins_data_path;
  149. data_path_with_module_suffix += "/%module%";
  150. obs_add_module_path(plugins_path.c_str(),
  151. data_path_with_module_suffix.c_str());
  152. }
  153. if (portable_mode)
  154. return;
  155. char base_module_dir[512];
  156. #if defined(_WIN32)
  157. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  158. "obs-studio/plugins/%module%");
  159. #elif defined(__APPLE__)
  160. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  161. "obs-studio/plugins/%module%.plugin");
  162. #else
  163. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  164. "obs-studio/plugins/%module%");
  165. #endif
  166. if (ret <= 0)
  167. return;
  168. string path = base_module_dir;
  169. #if defined(__APPLE__)
  170. /* User Application Support Search Path */
  171. obs_add_module_path((path + "/Contents/MacOS").c_str(),
  172. (path + "/Contents/Resources").c_str());
  173. #ifndef __aarch64__
  174. /* Legacy System Library Search Path */
  175. char system_legacy_module_dir[PATH_MAX];
  176. GetProgramDataPath(system_legacy_module_dir,
  177. sizeof(system_legacy_module_dir),
  178. "obs-studio/plugins/%module%");
  179. std::string path_system_legacy = system_legacy_module_dir;
  180. obs_add_module_path((path_system_legacy + "/bin").c_str(),
  181. (path_system_legacy + "/data").c_str());
  182. /* Legacy User Application Support Search Path */
  183. char user_legacy_module_dir[PATH_MAX];
  184. GetConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir),
  185. "obs-studio/plugins/%module%");
  186. std::string path_user_legacy = user_legacy_module_dir;
  187. obs_add_module_path((path_user_legacy + "/bin").c_str(),
  188. (path_user_legacy + "/data").c_str());
  189. #endif
  190. #else
  191. #if ARCH_BITS == 64
  192. obs_add_module_path((path + "/bin/64bit").c_str(),
  193. (path + "/data").c_str());
  194. #else
  195. obs_add_module_path((path + "/bin/32bit").c_str(),
  196. (path + "/data").c_str());
  197. #endif
  198. #endif
  199. }
  200. /* First-party modules considered to be potentially unsafe to load in Safe Mode
  201. * due to them allowing external code (e.g. scripts) to modify OBS's state. */
  202. static const unordered_set<string> unsafe_modules = {
  203. "frontend-tools", // Scripting
  204. "obs-websocket", // Allows outside modifications
  205. };
  206. static void SetSafeModuleNames()
  207. {
  208. #ifndef SAFE_MODULES
  209. return;
  210. #else
  211. string module;
  212. stringstream modules(SAFE_MODULES);
  213. while (getline(modules, module, '|')) {
  214. /* When only disallowing third-party plugins, still add
  215. * "unsafe" bundled modules to the safe list. */
  216. if (disable_3p_plugins || !unsafe_modules.count(module))
  217. obs_add_safe_module(module.c_str());
  218. }
  219. #endif
  220. }
  221. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  222. void assignDockToggle(QDockWidget *dock, QAction *action)
  223. {
  224. auto handleWindowToggle = [action](bool vis) {
  225. action->blockSignals(true);
  226. action->setChecked(vis);
  227. action->blockSignals(false);
  228. };
  229. auto handleMenuToggle = [dock](bool check) {
  230. dock->blockSignals(true);
  231. dock->setVisible(check);
  232. dock->blockSignals(false);
  233. };
  234. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  235. handleWindowToggle);
  236. dock->connect(action, &QAction::toggled, handleMenuToggle);
  237. }
  238. void setupDockAction(QDockWidget *dock)
  239. {
  240. QAction *action = dock->toggleViewAction();
  241. auto neverDisable = [action]() {
  242. QSignalBlocker block(action);
  243. action->setEnabled(true);
  244. };
  245. auto newToggleView = [dock](bool check) {
  246. QSignalBlocker block(dock);
  247. dock->setVisible(check);
  248. };
  249. // Replace the slot connected by default
  250. QObject::disconnect(action, &QAction::triggered, nullptr, 0);
  251. dock->connect(action, &QAction::triggered, newToggleView);
  252. // Make the action unable to be disabled
  253. action->connect(action, &QAction::enabledChanged, neverDisable);
  254. }
  255. extern void RegisterTwitchAuth();
  256. extern void RegisterRestreamAuth();
  257. #ifdef YOUTUBE_ENABLED
  258. extern void RegisterYoutubeAuth();
  259. #endif
  260. OBSBasic::OBSBasic(QWidget *parent)
  261. : OBSMainWindow(parent),
  262. undo_s(ui),
  263. ui(new Ui::OBSBasic)
  264. {
  265. setAttribute(Qt::WA_NativeWindow);
  266. #ifdef TWITCH_ENABLED
  267. RegisterTwitchAuth();
  268. #endif
  269. #ifdef RESTREAM_ENABLED
  270. RegisterRestreamAuth();
  271. #endif
  272. #ifdef YOUTUBE_ENABLED
  273. RegisterYoutubeAuth();
  274. #endif
  275. setAcceptDrops(true);
  276. setContextMenuPolicy(Qt::CustomContextMenu);
  277. api = InitializeAPIInterface(this);
  278. ui->setupUi(this);
  279. ui->previewDisabledWidget->setVisible(false);
  280. QStyle *contextBarStyle = new OBSContextBarProxyStyle();
  281. contextBarStyle->setParent(ui->contextContainer);
  282. ui->contextContainer->setStyle(contextBarStyle);
  283. ui->broadcastButton->setVisible(false);
  284. startingDockLayout = saveState();
  285. statsDock = new OBSDock();
  286. statsDock->setObjectName(QStringLiteral("statsDock"));
  287. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  288. QDockWidget::DockWidgetMovable |
  289. QDockWidget::DockWidgetFloatable);
  290. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  291. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  292. statsDock->setVisible(false);
  293. statsDock->setFloating(true);
  294. statsDock->resize(700, 200);
  295. copyActionsDynamicProperties();
  296. qRegisterMetaType<int64_t>("int64_t");
  297. qRegisterMetaType<uint32_t>("uint32_t");
  298. qRegisterMetaType<OBSScene>("OBSScene");
  299. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  300. qRegisterMetaType<OBSSource>("OBSSource");
  301. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  302. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  303. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  304. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  305. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  306. "gridMode");
  307. ui->scenes->SetGridMode(sceneGrid);
  308. if (sceneGrid)
  309. ui->actionSceneGridMode->setChecked(true);
  310. else
  311. ui->actionSceneListMode->setChecked(true);
  312. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  313. auto displayResize = [this]() {
  314. struct obs_video_info ovi;
  315. if (obs_get_video_info(&ovi))
  316. ResizePreview(ovi.base_width, ovi.base_height);
  317. UpdateContextBarVisibility();
  318. dpi = devicePixelRatioF();
  319. };
  320. dpi = devicePixelRatioF();
  321. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  322. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  323. delete shortcutFilter;
  324. shortcutFilter = CreateShortcutFilter();
  325. installEventFilter(shortcutFilter);
  326. stringstream name;
  327. name << "OBS " << App()->GetVersionString();
  328. blog(LOG_INFO, "%s", name.str().c_str());
  329. blog(LOG_INFO, "---------------------------------");
  330. UpdateTitleBar();
  331. connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor,
  332. this, &OBSBasic::SceneNameEdited);
  333. cpuUsageInfo = os_cpu_usage_info_start();
  334. cpuUsageTimer = new QTimer(this);
  335. connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar,
  336. &OBSBasicStatusBar::UpdateCPUUsage);
  337. cpuUsageTimer->start(3000);
  338. diskFullTimer = new QTimer(this);
  339. connect(diskFullTimer, &QTimer::timeout, this,
  340. &OBSBasic::CheckDiskSpaceRemaining);
  341. renameScene = new QAction(QTStr("Rename"), ui->scenesDock);
  342. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  343. connect(renameScene, &QAction::triggered, this,
  344. &OBSBasic::EditSceneName);
  345. ui->scenesDock->addAction(renameScene);
  346. renameSource = new QAction(QTStr("Rename"), ui->sourcesDock);
  347. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  348. connect(renameSource, &QAction::triggered, this,
  349. &OBSBasic::EditSceneItemName);
  350. ui->sourcesDock->addAction(renameSource);
  351. #ifdef __APPLE__
  352. renameScene->setShortcut({Qt::Key_Return});
  353. renameSource->setShortcut({Qt::Key_Return});
  354. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  355. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  356. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  357. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  358. ui->actionShowMacPermissions->setMenuRole(
  359. QAction::ApplicationSpecificRole);
  360. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  361. #else
  362. renameScene->setShortcut({Qt::Key_F2});
  363. renameSource->setShortcut({Qt::Key_F2});
  364. #endif
  365. #ifdef __linux__
  366. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  367. #endif
  368. auto addNudge = [this](const QKeySequence &seq, MoveDir direction,
  369. int distance) {
  370. QAction *nudge = new QAction(ui->preview);
  371. nudge->setShortcut(seq);
  372. nudge->setShortcutContext(Qt::WidgetShortcut);
  373. ui->preview->addAction(nudge);
  374. connect(nudge, &QAction::triggered,
  375. [this, distance, direction]() {
  376. Nudge(distance, direction);
  377. });
  378. };
  379. addNudge(Qt::Key_Up, MoveDir::Up, 1);
  380. addNudge(Qt::Key_Down, MoveDir::Down, 1);
  381. addNudge(Qt::Key_Left, MoveDir::Left, 1);
  382. addNudge(Qt::Key_Right, MoveDir::Right, 1);
  383. addNudge(Qt::SHIFT | Qt::Key_Up, MoveDir::Up, 10);
  384. addNudge(Qt::SHIFT | Qt::Key_Down, MoveDir::Down, 10);
  385. addNudge(Qt::SHIFT | Qt::Key_Left, MoveDir::Left, 10);
  386. addNudge(Qt::SHIFT | Qt::Key_Right, MoveDir::Right, 10);
  387. /* Setup dock toggle action
  388. * And hide all docks before restoring parent geometry */
  389. #define SETUP_DOCK(dock) \
  390. setupDockAction(dock); \
  391. ui->menuDocks->addAction(dock->toggleViewAction()); \
  392. dock->setVisible(false);
  393. SETUP_DOCK(ui->scenesDock);
  394. SETUP_DOCK(ui->sourcesDock);
  395. SETUP_DOCK(ui->mixerDock);
  396. SETUP_DOCK(ui->transitionsDock);
  397. SETUP_DOCK(ui->controlsDock);
  398. SETUP_DOCK(statsDock);
  399. #undef SETUP_DOCK
  400. // Register shortcuts for Undo/Redo
  401. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  402. QList<QKeySequence> shrt;
  403. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  404. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  405. ui->actionMainRedo->setShortcuts(shrt);
  406. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  407. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  408. QPoint curPos;
  409. //restore parent window geometry
  410. const char *geometry = config_get_string(App()->GlobalConfig(),
  411. "BasicWindow", "geometry");
  412. if (geometry != NULL) {
  413. QByteArray byteArray =
  414. QByteArray::fromBase64(QByteArray(geometry));
  415. restoreGeometry(byteArray);
  416. QRect windowGeometry = normalGeometry();
  417. if (!WindowPositionValid(windowGeometry)) {
  418. QRect rect =
  419. QGuiApplication::primaryScreen()->geometry();
  420. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  421. Qt::AlignCenter, size(),
  422. rect));
  423. }
  424. curPos = pos();
  425. } else {
  426. QRect desktopRect =
  427. QGuiApplication::primaryScreen()->geometry();
  428. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  429. curPos = QPoint(adjSize.width(), adjSize.height());
  430. }
  431. QPoint curSize(width(), height());
  432. QPoint statsDockSize(statsDock->width(), statsDock->height());
  433. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  434. QPoint newPos = curPos + statsDockPos;
  435. statsDock->move(newPos);
  436. #ifdef HAVE_OBSCONFIG_H
  437. ui->actionReleaseNotes->setVisible(true);
  438. #endif
  439. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  440. connect(ui->enablePreviewButton, &QPushButton::clicked, this,
  441. &OBSBasic::TogglePreview);
  442. connect(ui->scenes, &SceneTree::scenesReordered,
  443. []() { OBSProjector::UpdateMultiviewProjectors(); });
  444. connect(ui->broadcastButton, &QPushButton::clicked, this,
  445. &OBSBasic::BroadcastButtonClicked);
  446. connect(App(), &OBSApp::StyleChanged, this, &OBSBasic::ThemeChanged);
  447. QActionGroup *actionGroup = new QActionGroup(this);
  448. actionGroup->addAction(ui->actionSceneListMode);
  449. actionGroup->addAction(ui->actionSceneGridMode);
  450. UpdatePreviewSafeAreas();
  451. UpdatePreviewSpacingHelpers();
  452. UpdatePreviewOverflowSettings();
  453. }
  454. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  455. vector<OBSSource> &audioSources)
  456. {
  457. OBSSourceAutoRelease source = obs_get_output_source(channel);
  458. if (!source)
  459. return;
  460. audioSources.push_back(source.Get());
  461. OBSDataAutoRelease data = obs_save_source(source);
  462. obs_data_set_obj(parent, name, data);
  463. }
  464. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  465. obs_data_array_t *quickTransitionData,
  466. int transitionDuration,
  467. obs_data_array_t *transitions,
  468. OBSScene &scene, OBSSource &curProgramScene,
  469. obs_data_array_t *savedProjectorList)
  470. {
  471. obs_data_t *saveData = obs_data_create();
  472. vector<OBSSource> audioSources;
  473. audioSources.reserve(6);
  474. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  475. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  476. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  477. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  478. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  479. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  480. /* -------------------------------- */
  481. /* save non-group sources */
  482. auto FilterAudioSources = [&](obs_source_t *source) {
  483. if (obs_source_is_group(source))
  484. return false;
  485. return find(begin(audioSources), end(audioSources), source) ==
  486. end(audioSources);
  487. };
  488. using FilterAudioSources_t = decltype(FilterAudioSources);
  489. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  490. [](void *data, obs_source_t *source) {
  491. auto &func = *static_cast<FilterAudioSources_t *>(data);
  492. return func(source);
  493. },
  494. static_cast<void *>(&FilterAudioSources));
  495. /* -------------------------------- */
  496. /* save group sources separately */
  497. /* saving separately ensures they won't be loaded in older versions */
  498. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  499. [](void *, obs_source_t *source) {
  500. return obs_source_is_group(source);
  501. },
  502. nullptr);
  503. /* -------------------------------- */
  504. OBSSourceAutoRelease transition = obs_get_output_source(0);
  505. obs_source_t *currentScene = obs_scene_get_source(scene);
  506. const char *sceneName = obs_source_get_name(currentScene);
  507. const char *programName = obs_source_get_name(curProgramScene);
  508. const char *sceneCollection = config_get_string(
  509. App()->GlobalConfig(), "Basic", "SceneCollection");
  510. obs_data_set_string(saveData, "current_scene", sceneName);
  511. obs_data_set_string(saveData, "current_program_scene", programName);
  512. obs_data_set_array(saveData, "scene_order", sceneOrder);
  513. obs_data_set_string(saveData, "name", sceneCollection);
  514. obs_data_set_array(saveData, "sources", sourcesArray);
  515. obs_data_set_array(saveData, "groups", groupsArray);
  516. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  517. obs_data_set_array(saveData, "transitions", transitions);
  518. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  519. obs_data_array_release(sourcesArray);
  520. obs_data_array_release(groupsArray);
  521. obs_data_set_string(saveData, "current_transition",
  522. obs_source_get_name(transition));
  523. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  524. return saveData;
  525. }
  526. void OBSBasic::copyActionsDynamicProperties()
  527. {
  528. // Themes need the QAction dynamic properties
  529. for (QAction *x : ui->scenesToolbar->actions()) {
  530. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  531. if (!temp)
  532. continue;
  533. for (QByteArray &y : x->dynamicPropertyNames()) {
  534. temp->setProperty(y, x->property(y));
  535. }
  536. }
  537. for (QAction *x : ui->sourcesToolbar->actions()) {
  538. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  539. if (!temp)
  540. continue;
  541. for (QByteArray &y : x->dynamicPropertyNames()) {
  542. temp->setProperty(y, x->property(y));
  543. }
  544. }
  545. for (QAction *x : ui->mixerToolbar->actions()) {
  546. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  547. if (!temp)
  548. continue;
  549. for (QByteArray &y : x->dynamicPropertyNames()) {
  550. temp->setProperty(y, x->property(y));
  551. }
  552. }
  553. }
  554. void OBSBasic::UpdateVolumeControlsDecayRate()
  555. {
  556. double meterDecayRate =
  557. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  558. for (size_t i = 0; i < volumes.size(); i++) {
  559. volumes[i]->SetMeterDecayRate(meterDecayRate);
  560. }
  561. }
  562. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  563. {
  564. uint32_t peakMeterTypeIdx =
  565. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  566. enum obs_peak_meter_type peakMeterType;
  567. switch (peakMeterTypeIdx) {
  568. case 0:
  569. peakMeterType = SAMPLE_PEAK_METER;
  570. break;
  571. case 1:
  572. peakMeterType = TRUE_PEAK_METER;
  573. break;
  574. default:
  575. peakMeterType = SAMPLE_PEAK_METER;
  576. break;
  577. }
  578. for (size_t i = 0; i < volumes.size(); i++) {
  579. volumes[i]->setPeakMeterType(peakMeterType);
  580. }
  581. }
  582. void OBSBasic::ClearVolumeControls()
  583. {
  584. for (VolControl *vol : volumes)
  585. delete vol;
  586. volumes.clear();
  587. }
  588. void OBSBasic::RefreshVolumeColors()
  589. {
  590. for (VolControl *vol : volumes) {
  591. vol->refreshColors();
  592. }
  593. }
  594. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  595. {
  596. obs_data_array_t *sceneOrder = obs_data_array_create();
  597. for (int i = 0; i < ui->scenes->count(); i++) {
  598. OBSDataAutoRelease data = obs_data_create();
  599. obs_data_set_string(data, "name",
  600. QT_TO_UTF8(ui->scenes->item(i)->text()));
  601. obs_data_array_push_back(sceneOrder, data);
  602. }
  603. return sceneOrder;
  604. }
  605. obs_data_array_t *OBSBasic::SaveProjectors()
  606. {
  607. obs_data_array_t *savedProjectors = obs_data_array_create();
  608. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  609. if (!projector)
  610. return;
  611. OBSDataAutoRelease data = obs_data_create();
  612. ProjectorType type = projector->GetProjectorType();
  613. switch (type) {
  614. case ProjectorType::Scene:
  615. case ProjectorType::Source: {
  616. OBSSource source = projector->GetSource();
  617. const char *name = obs_source_get_name(source);
  618. obs_data_set_string(data, "name", name);
  619. break;
  620. }
  621. default:
  622. break;
  623. }
  624. obs_data_set_int(data, "monitor", projector->GetMonitor());
  625. obs_data_set_int(data, "type", static_cast<int>(type));
  626. obs_data_set_string(
  627. data, "geometry",
  628. projector->saveGeometry().toBase64().constData());
  629. if (projector->IsAlwaysOnTopOverridden())
  630. obs_data_set_bool(data, "alwaysOnTop",
  631. projector->IsAlwaysOnTop());
  632. obs_data_set_bool(data, "alwaysOnTopOverridden",
  633. projector->IsAlwaysOnTopOverridden());
  634. obs_data_array_push_back(savedProjectors, data);
  635. };
  636. for (size_t i = 0; i < projectors.size(); i++)
  637. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  638. return savedProjectors;
  639. }
  640. void OBSBasic::Save(const char *file)
  641. {
  642. OBSScene scene = GetCurrentScene();
  643. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  644. if (!curProgramScene)
  645. curProgramScene = obs_scene_get_source(scene);
  646. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  647. OBSDataArrayAutoRelease transitions = SaveTransitions();
  648. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  649. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  650. OBSDataAutoRelease saveData = GenerateSaveData(
  651. sceneOrder, quickTrData, ui->transitionDuration->value(),
  652. transitions, scene, curProgramScene, savedProjectorList);
  653. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  654. obs_data_set_bool(saveData, "scaling_enabled",
  655. ui->preview->IsFixedScaling());
  656. obs_data_set_int(saveData, "scaling_level",
  657. ui->preview->GetScalingLevel());
  658. obs_data_set_double(saveData, "scaling_off_x",
  659. ui->preview->GetScrollX());
  660. obs_data_set_double(saveData, "scaling_off_y",
  661. ui->preview->GetScrollY());
  662. if (vcamEnabled) {
  663. OBSDataAutoRelease obj = obs_data_create();
  664. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  665. switch (vcamConfig.type) {
  666. case VCamOutputType::Invalid:
  667. case VCamOutputType::ProgramView:
  668. case VCamOutputType::PreviewOutput:
  669. break;
  670. case VCamOutputType::SceneOutput:
  671. obs_data_set_string(obj, "scene",
  672. vcamConfig.scene.c_str());
  673. break;
  674. case VCamOutputType::SourceOutput:
  675. obs_data_set_string(obj, "source",
  676. vcamConfig.source.c_str());
  677. break;
  678. }
  679. obs_data_set_obj(saveData, "virtual-camera", obj);
  680. }
  681. if (api) {
  682. if (safeModeModuleData) {
  683. /* If we're in Safe Mode and have retained unloaded
  684. * plugin data, update the existing data object instead
  685. * of creating a new one. */
  686. api->on_save(safeModeModuleData);
  687. obs_data_set_obj(saveData, "modules",
  688. safeModeModuleData);
  689. } else {
  690. OBSDataAutoRelease moduleObj = obs_data_create();
  691. api->on_save(moduleObj);
  692. obs_data_set_obj(saveData, "modules", moduleObj);
  693. }
  694. }
  695. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  696. blog(LOG_ERROR, "Could not save scene data to %s", file);
  697. }
  698. void OBSBasic::DeferSaveBegin()
  699. {
  700. os_atomic_inc_long(&disableSaving);
  701. }
  702. void OBSBasic::DeferSaveEnd()
  703. {
  704. long result = os_atomic_dec_long(&disableSaving);
  705. if (result == 0) {
  706. SaveProject();
  707. }
  708. }
  709. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  710. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  711. {
  712. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  713. if (!data)
  714. return;
  715. OBSSourceAutoRelease source = obs_load_source(data);
  716. if (!source)
  717. return;
  718. obs_set_output_source(channel, source);
  719. const char *source_name = obs_source_get_name(source);
  720. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  721. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  722. obs_monitoring_type monitoring_type =
  723. obs_source_get_monitoring_type(source);
  724. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  725. const char *type =
  726. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  727. ? "monitor only"
  728. : "monitor and output";
  729. blog(LOG_INFO, " - monitoring: %s", type);
  730. }
  731. }
  732. static inline bool HasAudioDevices(const char *source_id)
  733. {
  734. const char *output_id = source_id;
  735. obs_properties_t *props = obs_get_source_properties(output_id);
  736. size_t count = 0;
  737. if (!props)
  738. return false;
  739. obs_property_t *devices = obs_properties_get(props, "device_id");
  740. if (devices)
  741. count = obs_property_list_item_count(devices);
  742. obs_properties_destroy(props);
  743. return count != 0;
  744. }
  745. void OBSBasic::CreateFirstRunSources()
  746. {
  747. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  748. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  749. if (hasDesktopAudio)
  750. ResetAudioDevice(App()->OutputAudioSource(), "default",
  751. Str("Basic.DesktopDevice1"), 1);
  752. if (hasInputAudio)
  753. ResetAudioDevice(App()->InputAudioSource(), "default",
  754. Str("Basic.AuxDevice1"), 3);
  755. }
  756. void OBSBasic::CreateDefaultScene(bool firstStart)
  757. {
  758. disableSaving++;
  759. ClearSceneData();
  760. InitDefaultTransitions();
  761. CreateDefaultQuickTransitions();
  762. ui->transitionDuration->setValue(300);
  763. SetTransition(fadeTransition);
  764. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  765. if (firstStart)
  766. CreateFirstRunSources();
  767. SetCurrentScene(scene, true);
  768. disableSaving--;
  769. }
  770. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  771. {
  772. for (int i = 0; i < lw->count(); i++) {
  773. QListWidgetItem *item = lw->item(i);
  774. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  775. if (newIndex != i) {
  776. item = lw->takeItem(i);
  777. lw->insertItem(newIndex, item);
  778. }
  779. break;
  780. }
  781. }
  782. }
  783. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  784. {
  785. size_t num = obs_data_array_count(array);
  786. for (size_t i = 0; i < num; i++) {
  787. OBSDataAutoRelease data = obs_data_array_item(array, i);
  788. const char *name = obs_data_get_string(data, "name");
  789. ReorderItemByName(ui->scenes, name, (int)i);
  790. }
  791. }
  792. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  793. {
  794. for (SavedProjectorInfo *info : savedProjectorsArray) {
  795. delete info;
  796. }
  797. savedProjectorsArray.clear();
  798. size_t num = obs_data_array_count(array);
  799. for (size_t i = 0; i < num; i++) {
  800. OBSDataAutoRelease data = obs_data_array_item(array, i);
  801. SavedProjectorInfo *info = new SavedProjectorInfo();
  802. info->monitor = obs_data_get_int(data, "monitor");
  803. info->type = static_cast<ProjectorType>(
  804. obs_data_get_int(data, "type"));
  805. info->geometry =
  806. std::string(obs_data_get_string(data, "geometry"));
  807. info->name = std::string(obs_data_get_string(data, "name"));
  808. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  809. info->alwaysOnTopOverridden =
  810. obs_data_get_bool(data, "alwaysOnTopOverridden");
  811. savedProjectorsArray.emplace_back(info);
  812. }
  813. }
  814. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  815. {
  816. const char *name = obs_source_get_name(filter);
  817. const char *id = obs_source_get_id(filter);
  818. int val = (int)(intptr_t)v_val;
  819. string indent;
  820. for (int i = 0; i < val; i++)
  821. indent += " ";
  822. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  823. }
  824. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  825. {
  826. obs_source_t *source = obs_sceneitem_get_source(item);
  827. const char *name = obs_source_get_name(source);
  828. const char *id = obs_source_get_id(source);
  829. int indent_count = (int)(intptr_t)v_val;
  830. string indent;
  831. for (int i = 0; i < indent_count; i++)
  832. indent += " ";
  833. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  834. obs_monitoring_type monitoring_type =
  835. obs_source_get_monitoring_type(source);
  836. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  837. const char *type =
  838. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  839. ? "monitor only"
  840. : "monitor and output";
  841. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  842. }
  843. int child_indent = 1 + indent_count;
  844. obs_source_enum_filters(source, LogFilter,
  845. (void *)(intptr_t)child_indent);
  846. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  847. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  848. if (show_tn)
  849. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  850. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  851. if (hide_tn)
  852. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  853. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  854. if (obs_sceneitem_is_group(item))
  855. obs_sceneitem_group_enum_items(item, LogSceneItem,
  856. (void *)(intptr_t)child_indent);
  857. return true;
  858. }
  859. void OBSBasic::LogScenes()
  860. {
  861. blog(LOG_INFO, "------------------------------------------------");
  862. blog(LOG_INFO, "Loaded scenes:");
  863. for (int i = 0; i < ui->scenes->count(); i++) {
  864. QListWidgetItem *item = ui->scenes->item(i);
  865. OBSScene scene = GetOBSRef<OBSScene>(item);
  866. obs_source_t *source = obs_scene_get_source(scene);
  867. const char *name = obs_source_get_name(source);
  868. blog(LOG_INFO, "- scene '%s':", name);
  869. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  870. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  871. }
  872. blog(LOG_INFO, "------------------------------------------------");
  873. }
  874. void OBSBasic::Load(const char *file)
  875. {
  876. disableSaving++;
  877. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  878. if (!data) {
  879. disableSaving--;
  880. blog(LOG_INFO, "No scene file found, creating default scene");
  881. CreateDefaultScene(true);
  882. SaveProject();
  883. return;
  884. }
  885. LoadData(data, file);
  886. }
  887. static inline void AddMissingFiles(void *data, obs_source_t *source)
  888. {
  889. obs_missing_files_t *f = (obs_missing_files_t *)data;
  890. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  891. obs_missing_files_append(f, sf);
  892. obs_missing_files_destroy(sf);
  893. }
  894. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  895. {
  896. ClearSceneData();
  897. ClearContextBar();
  898. /* Exit OBS if clearing scene data failed for some reason. */
  899. if (clearingFailed) {
  900. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"),
  901. QTStr("SourceLeak.Text"));
  902. close();
  903. return;
  904. }
  905. InitDefaultTransitions();
  906. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  907. devicePropertiesThread->wait();
  908. devicePropertiesThread.reset();
  909. }
  910. QApplication::sendPostedEvents(nullptr);
  911. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  912. if (api)
  913. api->on_preload(modulesObj);
  914. if (safe_mode || disable_3p_plugins) {
  915. /* Keep a reference to "modules" data so plugins that are not
  916. * loaded do not have their collection specific data lost. */
  917. safeModeModuleData = obs_data_get_obj(data, "modules");
  918. }
  919. OBSDataArrayAutoRelease sceneOrder =
  920. obs_data_get_array(data, "scene_order");
  921. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  922. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  923. OBSDataArrayAutoRelease transitions =
  924. obs_data_get_array(data, "transitions");
  925. const char *sceneName = obs_data_get_string(data, "current_scene");
  926. const char *programSceneName =
  927. obs_data_get_string(data, "current_program_scene");
  928. const char *transitionName =
  929. obs_data_get_string(data, "current_transition");
  930. if (!opt_starting_scene.empty()) {
  931. programSceneName = opt_starting_scene.c_str();
  932. if (!IsPreviewProgramMode())
  933. sceneName = opt_starting_scene.c_str();
  934. }
  935. int newDuration = obs_data_get_int(data, "transition_duration");
  936. if (!newDuration)
  937. newDuration = 300;
  938. if (!transitionName)
  939. transitionName = obs_source_get_name(fadeTransition);
  940. const char *curSceneCollection = config_get_string(
  941. App()->GlobalConfig(), "Basic", "SceneCollection");
  942. obs_data_set_default_string(data, "name", curSceneCollection);
  943. const char *name = obs_data_get_string(data, "name");
  944. OBSSourceAutoRelease curScene;
  945. OBSSourceAutoRelease curProgramScene;
  946. obs_source_t *curTransition;
  947. if (!name || !*name)
  948. name = curSceneCollection;
  949. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  950. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  951. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  952. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  953. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  954. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  955. if (!sources) {
  956. sources = std::move(groups);
  957. } else {
  958. obs_data_array_push_back_array(sources, groups);
  959. }
  960. obs_missing_files_t *files = obs_missing_files_create();
  961. obs_load_sources(sources, AddMissingFiles, files);
  962. if (transitions)
  963. LoadTransitions(transitions, AddMissingFiles, files);
  964. if (sceneOrder)
  965. LoadSceneListOrder(sceneOrder);
  966. curTransition = FindTransition(transitionName);
  967. if (!curTransition)
  968. curTransition = fadeTransition;
  969. ui->transitionDuration->setValue(newDuration);
  970. SetTransition(curTransition);
  971. retryScene:
  972. curScene = obs_get_source_by_name(sceneName);
  973. curProgramScene = obs_get_source_by_name(programSceneName);
  974. /* if the starting scene command line parameter is bad at all,
  975. * fall back to original settings */
  976. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  977. sceneName = obs_data_get_string(data, "current_scene");
  978. programSceneName =
  979. obs_data_get_string(data, "current_program_scene");
  980. opt_starting_scene.clear();
  981. goto retryScene;
  982. }
  983. SetCurrentScene(curScene.Get(), true);
  984. if (!curProgramScene)
  985. curProgramScene = std::move(curScene);
  986. if (IsPreviewProgramMode())
  987. TransitionToScene(curProgramScene.Get(), true);
  988. /* ------------------- */
  989. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  990. "SaveProjectors");
  991. if (projectorSave) {
  992. OBSDataArrayAutoRelease savedProjectors =
  993. obs_data_get_array(data, "saved_projectors");
  994. if (savedProjectors) {
  995. LoadSavedProjectors(savedProjectors);
  996. OpenSavedProjectors();
  997. activateWindow();
  998. }
  999. }
  1000. /* ------------------- */
  1001. std::string file_base = strrchr(file, '/') + 1;
  1002. file_base.erase(file_base.size() - 5, 5);
  1003. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  1004. name);
  1005. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  1006. file_base.c_str());
  1007. OBSDataArrayAutoRelease quickTransitionData =
  1008. obs_data_get_array(data, "quick_transitions");
  1009. LoadQuickTransitions(quickTransitionData);
  1010. RefreshQuickTransitions();
  1011. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1012. ui->preview->SetLocked(previewLocked);
  1013. ui->actionLockPreview->setChecked(previewLocked);
  1014. /* ---------------------- */
  1015. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1016. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1017. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1018. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1019. if (fixedScaling) {
  1020. ui->preview->SetScalingLevel(scalingLevel);
  1021. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1022. }
  1023. ui->preview->SetFixedScaling(fixedScaling);
  1024. emit ui->preview->DisplayResized();
  1025. if (vcamEnabled) {
  1026. OBSDataAutoRelease obj =
  1027. obs_data_get_obj(data, "virtual-camera");
  1028. vcamConfig.type =
  1029. (VCamOutputType)obs_data_get_int(obj, "type2");
  1030. if (vcamConfig.type == VCamOutputType::Invalid)
  1031. vcamConfig.type =
  1032. (VCamOutputType)obs_data_get_int(obj, "type");
  1033. if (vcamConfig.type == VCamOutputType::Invalid) {
  1034. VCamInternalType internal =
  1035. (VCamInternalType)obs_data_get_int(obj,
  1036. "internal");
  1037. switch (internal) {
  1038. case VCamInternalType::Default:
  1039. vcamConfig.type = VCamOutputType::ProgramView;
  1040. break;
  1041. case VCamInternalType::Preview:
  1042. vcamConfig.type = VCamOutputType::PreviewOutput;
  1043. break;
  1044. }
  1045. }
  1046. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1047. vcamConfig.source = obs_data_get_string(obj, "source");
  1048. }
  1049. /* ---------------------- */
  1050. if (api)
  1051. api->on_load(modulesObj);
  1052. obs_data_release(data);
  1053. if (!opt_starting_scene.empty())
  1054. opt_starting_scene.clear();
  1055. if (opt_start_streaming && !safe_mode) {
  1056. blog(LOG_INFO, "Starting stream due to command line parameter");
  1057. QMetaObject::invokeMethod(this, "StartStreaming",
  1058. Qt::QueuedConnection);
  1059. opt_start_streaming = false;
  1060. }
  1061. if (opt_start_recording && !safe_mode) {
  1062. blog(LOG_INFO,
  1063. "Starting recording due to command line parameter");
  1064. QMetaObject::invokeMethod(this, "StartRecording",
  1065. Qt::QueuedConnection);
  1066. opt_start_recording = false;
  1067. }
  1068. if (opt_start_replaybuffer && !safe_mode) {
  1069. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  1070. Qt::QueuedConnection);
  1071. opt_start_replaybuffer = false;
  1072. }
  1073. if (opt_start_virtualcam && !safe_mode) {
  1074. QMetaObject::invokeMethod(this, "StartVirtualCam",
  1075. Qt::QueuedConnection);
  1076. opt_start_virtualcam = false;
  1077. }
  1078. LogScenes();
  1079. if (!App()->IsMissingFilesCheckDisabled())
  1080. ShowMissingFilesDialog(files);
  1081. disableSaving--;
  1082. if (vcamEnabled)
  1083. outputHandler->UpdateVirtualCamOutputSource();
  1084. if (api) {
  1085. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1086. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1087. }
  1088. }
  1089. #define SERVICE_PATH "service.json"
  1090. void OBSBasic::SaveService()
  1091. {
  1092. if (!service)
  1093. return;
  1094. char serviceJsonPath[512];
  1095. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1096. SERVICE_PATH);
  1097. if (ret <= 0)
  1098. return;
  1099. OBSDataAutoRelease data = obs_data_create();
  1100. OBSDataAutoRelease settings = obs_service_get_settings(service);
  1101. obs_data_set_string(data, "type", obs_service_get_type(service));
  1102. obs_data_set_obj(data, "settings", settings);
  1103. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  1104. blog(LOG_WARNING, "Failed to save service");
  1105. }
  1106. bool OBSBasic::LoadService()
  1107. {
  1108. const char *type;
  1109. char serviceJsonPath[512];
  1110. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1111. SERVICE_PATH);
  1112. if (ret <= 0)
  1113. return false;
  1114. OBSDataAutoRelease data =
  1115. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  1116. if (!data)
  1117. return false;
  1118. obs_data_set_default_string(data, "type", "rtmp_common");
  1119. type = obs_data_get_string(data, "type");
  1120. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  1121. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  1122. service = obs_service_create(type, "default_service", settings,
  1123. hotkey_data);
  1124. obs_service_release(service);
  1125. if (!service)
  1126. return false;
  1127. /* Enforce Opus on FTL if needed */
  1128. if (strcmp(obs_service_get_protocol(service), "FTL") == 0 ||
  1129. strcmp(obs_service_get_protocol(service), "WHIP") == 0) {
  1130. const char *option = config_get_string(
  1131. basicConfig, "SimpleOutput", "StreamAudioEncoder");
  1132. if (strcmp(option, "opus") != 0)
  1133. config_set_string(basicConfig, "SimpleOutput",
  1134. "StreamAudioEncoder", "opus");
  1135. option = config_get_string(basicConfig, "AdvOut",
  1136. "AudioEncoder");
  1137. if (strcmp(obs_get_encoder_codec(option), "opus") != 0)
  1138. config_set_string(basicConfig, "AdvOut", "AudioEncoder",
  1139. "ffmpeg_opus");
  1140. }
  1141. return true;
  1142. }
  1143. bool OBSBasic::InitService()
  1144. {
  1145. ProfileScope("OBSBasic::InitService");
  1146. if (LoadService())
  1147. return true;
  1148. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1149. nullptr);
  1150. if (!service)
  1151. return false;
  1152. obs_service_release(service);
  1153. return true;
  1154. }
  1155. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1156. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1157. 2.5, 2.75, 3.0, 0.0};
  1158. extern void CheckExistingCookieId();
  1159. #if OBS_RELEASE_CANDIDATE == 0 && OBS_BETA == 0
  1160. #define DEFAULT_CONTAINER "mkv"
  1161. #elif defined(__APPLE__)
  1162. #define DEFAULT_CONTAINER "fragmented_mov"
  1163. #else
  1164. #define DEFAULT_CONTAINER "fragmented_mp4"
  1165. #endif
  1166. bool OBSBasic::InitBasicConfigDefaults()
  1167. {
  1168. QList<QScreen *> screens = QGuiApplication::screens();
  1169. if (!screens.size()) {
  1170. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1171. "technically shouldn't be possible.");
  1172. return false;
  1173. }
  1174. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1175. uint32_t cx = primaryScreen->size().width();
  1176. uint32_t cy = primaryScreen->size().height();
  1177. cx *= devicePixelRatioF();
  1178. cy *= devicePixelRatioF();
  1179. bool oldResolutionDefaults = config_get_bool(
  1180. App()->GlobalConfig(), "General", "Pre19Defaults");
  1181. /* use 1920x1080 for new default base res if main monitor is above
  1182. * 1920x1080, but don't apply for people from older builds -- only to
  1183. * new users */
  1184. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1185. cx = 1920;
  1186. cy = 1080;
  1187. }
  1188. bool changed = false;
  1189. /* ----------------------------------------------------- */
  1190. /* move over old FFmpeg track settings */
  1191. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1192. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1193. int track = (int)config_get_int(basicConfig, "AdvOut",
  1194. "FFAudioTrack");
  1195. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1196. 1LL << (track - 1));
  1197. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1198. changed = true;
  1199. }
  1200. /* ----------------------------------------------------- */
  1201. /* move over mixer values in advanced if older config */
  1202. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1203. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1204. uint64_t track =
  1205. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1206. track = 1ULL << (track - 1);
  1207. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1208. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1209. changed = true;
  1210. }
  1211. /* ----------------------------------------------------- */
  1212. /* set twitch chat extensions to "both" if prev version */
  1213. /* is under 24.1 */
  1214. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1215. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1216. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1217. changed = true;
  1218. }
  1219. /* ----------------------------------------------------- */
  1220. /* move bitrate enforcement setting to new value */
  1221. if (config_has_user_value(basicConfig, "SimpleOutput",
  1222. "EnforceBitrate") &&
  1223. !config_has_user_value(basicConfig, "Stream1",
  1224. "IgnoreRecommended") &&
  1225. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1226. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1227. "EnforceBitrate");
  1228. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1229. !enforce);
  1230. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1231. true);
  1232. changed = true;
  1233. }
  1234. /* ----------------------------------------------------- */
  1235. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1236. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1237. int retryDelay =
  1238. config_get_uint(basicConfig, "Output", "RetryDelay");
  1239. if (retryDelay < 1) {
  1240. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1241. changed = true;
  1242. }
  1243. }
  1244. /* ----------------------------------------------------- */
  1245. /* Migrate old container selection (if any) to new key. */
  1246. auto MigrateFormat = [&](const char *section) {
  1247. bool has_old_key = config_has_user_value(basicConfig, section,
  1248. "RecFormat");
  1249. bool has_new_key = config_has_user_value(basicConfig, section,
  1250. "RecFormat2");
  1251. if (!has_new_key && !has_old_key)
  1252. return;
  1253. string old_format = config_get_string(
  1254. basicConfig, section,
  1255. has_new_key ? "RecFormat2" : "RecFormat");
  1256. string new_format = old_format;
  1257. if (old_format == "ts")
  1258. new_format = "mpegts";
  1259. else if (old_format == "m3u8")
  1260. new_format = "hls";
  1261. else if (old_format == "fmp4")
  1262. new_format = "fragmented_mp4";
  1263. else if (old_format == "fmov")
  1264. new_format = "fragmented_mov";
  1265. if (new_format != old_format || !has_new_key) {
  1266. config_set_string(basicConfig, section, "RecFormat2",
  1267. new_format.c_str());
  1268. changed = true;
  1269. }
  1270. };
  1271. MigrateFormat("AdvOut");
  1272. MigrateFormat("SimpleOutput");
  1273. /* ----------------------------------------------------- */
  1274. if (changed)
  1275. config_save_safe(basicConfig, "tmp", nullptr);
  1276. /* ----------------------------------------------------- */
  1277. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1278. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1279. false);
  1280. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1281. GetDefaultVideoSavePath().c_str());
  1282. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat2",
  1283. DEFAULT_CONTAINER);
  1284. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1285. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1286. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1287. false);
  1288. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1289. "veryfast");
  1290. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset2",
  1291. "p5");
  1292. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1293. "Stream");
  1294. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1295. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1296. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1297. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1298. "Replay");
  1299. config_set_default_string(basicConfig, "SimpleOutput",
  1300. "StreamAudioEncoder", "aac");
  1301. config_set_default_string(basicConfig, "SimpleOutput",
  1302. "RecAudioEncoder", "aac");
  1303. config_set_default_uint(basicConfig, "SimpleOutput", "RecTracks",
  1304. (1 << 0));
  1305. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1306. true);
  1307. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1308. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1309. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1310. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1311. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1312. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1313. GetDefaultVideoSavePath().c_str());
  1314. config_set_default_string(basicConfig, "AdvOut", "RecFormat2",
  1315. DEFAULT_CONTAINER);
  1316. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1317. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1318. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1319. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1320. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1321. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1322. GetDefaultVideoSavePath().c_str());
  1323. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1324. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1325. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1326. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1327. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1328. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1329. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1330. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1331. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1332. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1333. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1334. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1335. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1336. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1337. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1338. 2048);
  1339. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1340. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1341. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1342. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1343. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1344. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1345. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1346. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1347. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1348. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1349. config_save_safe(basicConfig, "tmp", nullptr);
  1350. }
  1351. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1352. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1353. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1354. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1355. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1356. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1357. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1358. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1359. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1360. config_set_default_string(basicConfig, "Output", "IPFamily",
  1361. "IPv4+IPv6");
  1362. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1363. false);
  1364. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1365. false);
  1366. int i = 0;
  1367. uint32_t scale_cx = cx;
  1368. uint32_t scale_cy = cy;
  1369. /* use a default scaled resolution that has a pixel count no higher
  1370. * than 1280x720 */
  1371. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1372. double scale = scaled_vals[i++];
  1373. scale_cx = uint32_t(double(cx) / scale);
  1374. scale_cy = uint32_t(double(cy) / scale);
  1375. }
  1376. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1377. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1378. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1379. * changing */
  1380. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1381. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1382. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1383. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1384. config_save_safe(basicConfig, "tmp", nullptr);
  1385. }
  1386. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1387. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1388. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1389. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1390. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1391. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1392. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1393. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1394. config_set_default_string(basicConfig, "Video", "ColorRange",
  1395. "Partial");
  1396. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1397. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1398. 1000);
  1399. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1400. "default");
  1401. config_set_default_string(
  1402. basicConfig, "Audio", "MonitoringDeviceName",
  1403. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1404. ".Default"));
  1405. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1406. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1407. "Stereo");
  1408. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1409. VOLUME_METER_DECAY_FAST);
  1410. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1411. CheckExistingCookieId();
  1412. return true;
  1413. }
  1414. extern bool EncoderAvailable(const char *encoder);
  1415. extern bool update_nvenc_presets(ConfigFile &config);
  1416. void OBSBasic::InitBasicConfigDefaults2()
  1417. {
  1418. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1419. "Pre23Defaults");
  1420. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1421. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1422. useNV ? SIMPLE_ENCODER_NVENC
  1423. : SIMPLE_ENCODER_X264);
  1424. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1425. useNV ? SIMPLE_ENCODER_NVENC
  1426. : SIMPLE_ENCODER_X264);
  1427. const char *aac_default = "ffmpeg_aac";
  1428. if (EncoderAvailable("CoreAudio_AAC"))
  1429. aac_default = "CoreAudio_AAC";
  1430. else if (EncoderAvailable("libfdk_aac"))
  1431. aac_default = "libfdk_aac";
  1432. config_set_default_string(basicConfig, "AdvOut", "AudioEncoder",
  1433. aac_default);
  1434. config_set_default_string(basicConfig, "AdvOut", "RecAudioEncoder",
  1435. aac_default);
  1436. if (update_nvenc_presets(basicConfig))
  1437. config_save_safe(basicConfig, "tmp", nullptr);
  1438. }
  1439. bool OBSBasic::InitBasicConfig()
  1440. {
  1441. ProfileScope("OBSBasic::InitBasicConfig");
  1442. char configPath[512];
  1443. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1444. if (ret <= 0) {
  1445. OBSErrorBox(nullptr, "Failed to get profile path");
  1446. return false;
  1447. }
  1448. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1449. OBSErrorBox(nullptr, "Failed to create profile path");
  1450. return false;
  1451. }
  1452. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1453. if (ret <= 0) {
  1454. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1455. return false;
  1456. }
  1457. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1458. if (code != CONFIG_SUCCESS) {
  1459. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1460. return false;
  1461. }
  1462. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1463. const char *curName = config_get_string(App()->GlobalConfig(),
  1464. "Basic", "Profile");
  1465. config_set_string(basicConfig, "General", "Name", curName);
  1466. basicConfig.SaveSafe("tmp");
  1467. }
  1468. return InitBasicConfigDefaults();
  1469. }
  1470. void OBSBasic::InitOBSCallbacks()
  1471. {
  1472. ProfileScope("OBSBasic::InitOBSCallbacks");
  1473. signalHandlers.reserve(signalHandlers.size() + 7);
  1474. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1475. OBSBasic::SourceCreated, this);
  1476. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1477. OBSBasic::SourceRemoved, this);
  1478. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1479. OBSBasic::SourceActivated, this);
  1480. signalHandlers.emplace_back(obs_get_signal_handler(),
  1481. "source_deactivate",
  1482. OBSBasic::SourceDeactivated, this);
  1483. signalHandlers.emplace_back(obs_get_signal_handler(),
  1484. "source_audio_activate",
  1485. OBSBasic::SourceAudioActivated, this);
  1486. signalHandlers.emplace_back(obs_get_signal_handler(),
  1487. "source_audio_deactivate",
  1488. OBSBasic::SourceAudioDeactivated, this);
  1489. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1490. OBSBasic::SourceRenamed, this);
  1491. }
  1492. void OBSBasic::InitPrimitives()
  1493. {
  1494. ProfileScope("OBSBasic::InitPrimitives");
  1495. obs_enter_graphics();
  1496. gs_render_start(true);
  1497. gs_vertex2f(0.0f, 0.0f);
  1498. gs_vertex2f(0.0f, 1.0f);
  1499. gs_vertex2f(1.0f, 0.0f);
  1500. gs_vertex2f(1.0f, 1.0f);
  1501. box = gs_render_save();
  1502. gs_render_start(true);
  1503. gs_vertex2f(0.0f, 0.0f);
  1504. gs_vertex2f(0.0f, 1.0f);
  1505. boxLeft = gs_render_save();
  1506. gs_render_start(true);
  1507. gs_vertex2f(0.0f, 0.0f);
  1508. gs_vertex2f(1.0f, 0.0f);
  1509. boxTop = gs_render_save();
  1510. gs_render_start(true);
  1511. gs_vertex2f(1.0f, 0.0f);
  1512. gs_vertex2f(1.0f, 1.0f);
  1513. boxRight = gs_render_save();
  1514. gs_render_start(true);
  1515. gs_vertex2f(0.0f, 1.0f);
  1516. gs_vertex2f(1.0f, 1.0f);
  1517. boxBottom = gs_render_save();
  1518. gs_render_start(true);
  1519. for (int i = 0; i <= 360; i += (360 / 20)) {
  1520. float pos = RAD(float(i));
  1521. gs_vertex2f(cosf(pos), sinf(pos));
  1522. }
  1523. circle = gs_render_save();
  1524. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1525. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1526. obs_leave_graphics();
  1527. }
  1528. void OBSBasic::ReplayBufferClicked()
  1529. {
  1530. if (outputHandler->ReplayBufferActive())
  1531. StopReplayBuffer();
  1532. else
  1533. StartReplayBuffer();
  1534. };
  1535. void OBSBasic::AddVCamButton()
  1536. {
  1537. vcamButton = new ControlsSplitButton(
  1538. QTStr("Basic.Main.StartVirtualCam"), "vcamButton",
  1539. &OBSBasic::VCamButtonClicked);
  1540. vcamButton->addIcon(QTStr("Basic.Main.VirtualCamConfig"),
  1541. QStringLiteral("configIconSmall"),
  1542. &OBSBasic::VCamConfigButtonClicked);
  1543. vcamButton->insert(2);
  1544. }
  1545. void OBSBasic::ResetOutputs()
  1546. {
  1547. ProfileScope("OBSBasic::ResetOutputs");
  1548. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1549. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1550. if (!outputHandler || !outputHandler->Active()) {
  1551. outputHandler.reset();
  1552. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1553. : CreateSimpleOutputHandler(this));
  1554. delete replayBufferButton;
  1555. if (outputHandler->replayBuffer) {
  1556. replayBufferButton = new ControlsSplitButton(
  1557. QTStr("Basic.Main.StartReplayBuffer"),
  1558. "replayBufferButton",
  1559. &OBSBasic::ReplayBufferClicked);
  1560. replayBufferButton->insert(2);
  1561. }
  1562. if (sysTrayReplayBuffer)
  1563. sysTrayReplayBuffer->setEnabled(
  1564. !!outputHandler->replayBuffer);
  1565. } else {
  1566. outputHandler->Update();
  1567. }
  1568. }
  1569. #define STARTUP_SEPARATOR \
  1570. "==== Startup complete ==============================================="
  1571. #define SHUTDOWN_SEPARATOR \
  1572. "==== Shutting down =================================================="
  1573. #define UNSUPPORTED_ERROR \
  1574. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1575. "not found. Your GPU may not be supported."
  1576. #define UNKNOWN_ERROR \
  1577. "Failed to initialize video. Your GPU may not be supported, " \
  1578. "or your graphics drivers may need to be updated."
  1579. void OBSBasic::OBSInit()
  1580. {
  1581. ProfileScope("OBSBasic::OBSInit");
  1582. const char *sceneCollection = config_get_string(
  1583. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1584. char savePath[1024];
  1585. char fileName[1024];
  1586. int ret;
  1587. if (!sceneCollection)
  1588. throw "Failed to get scene collection name";
  1589. ret = snprintf(fileName, sizeof(fileName),
  1590. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1591. if (ret <= 0)
  1592. throw "Failed to create scene collection file name";
  1593. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1594. if (ret <= 0)
  1595. throw "Failed to get scene collection json file path";
  1596. if (!InitBasicConfig())
  1597. throw "Failed to load basic.ini";
  1598. if (!ResetAudio())
  1599. throw "Failed to initialize audio";
  1600. ret = ResetVideo();
  1601. switch (ret) {
  1602. case OBS_VIDEO_MODULE_NOT_FOUND:
  1603. throw "Failed to initialize video: Graphics module not found";
  1604. case OBS_VIDEO_NOT_SUPPORTED:
  1605. throw UNSUPPORTED_ERROR;
  1606. case OBS_VIDEO_INVALID_PARAM:
  1607. throw "Failed to initialize video: Invalid parameters";
  1608. default:
  1609. if (ret != OBS_VIDEO_SUCCESS)
  1610. throw UNKNOWN_ERROR;
  1611. }
  1612. /* load audio monitoring */
  1613. if (obs_audio_monitoring_available()) {
  1614. const char *device_name = config_get_string(
  1615. basicConfig, "Audio", "MonitoringDeviceName");
  1616. const char *device_id = config_get_string(basicConfig, "Audio",
  1617. "MonitoringDeviceId");
  1618. obs_set_audio_monitoring_device(device_name, device_id);
  1619. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1620. device_name, device_id);
  1621. }
  1622. InitOBSCallbacks();
  1623. InitHotkeys();
  1624. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1625. * to ship with */
  1626. #if defined(_WIN32) && !defined(_DEBUG)
  1627. LoadLibraryW(L"Qt6Network");
  1628. #endif
  1629. struct obs_module_failure_info mfi;
  1630. /* Safe Mode disables third-party plugins so we don't need to add earch
  1631. * paths outside the OBS bundle/installation. */
  1632. if (safe_mode || disable_3p_plugins) {
  1633. SetSafeModuleNames();
  1634. } else {
  1635. AddExtraModulePaths();
  1636. }
  1637. blog(LOG_INFO, "---------------------------------");
  1638. obs_load_all_modules2(&mfi);
  1639. blog(LOG_INFO, "---------------------------------");
  1640. obs_log_loaded_modules();
  1641. blog(LOG_INFO, "---------------------------------");
  1642. obs_post_load_modules();
  1643. BPtr<char *> failed_modules = mfi.failed_modules;
  1644. #ifdef BROWSER_AVAILABLE
  1645. cef = obs_browser_init_panel();
  1646. cef_js_avail = cef && obs_browser_qcef_version() >= 3;
  1647. #endif
  1648. OBSDataAutoRelease obsData = obs_get_private_data();
  1649. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1650. if (vcamEnabled) {
  1651. AddVCamButton();
  1652. }
  1653. InitBasicConfigDefaults2();
  1654. CheckForSimpleModeX264Fallback();
  1655. blog(LOG_INFO, STARTUP_SEPARATOR);
  1656. if (!InitService())
  1657. throw "Failed to initialize service";
  1658. ResetOutputs();
  1659. CreateHotkeys();
  1660. InitPrimitives();
  1661. sceneDuplicationMode = config_get_bool(
  1662. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1663. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1664. "SwapScenesMode");
  1665. editPropertiesMode = config_get_bool(
  1666. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1667. if (!opt_studio_mode) {
  1668. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1669. "BasicWindow",
  1670. "PreviewProgramMode"));
  1671. } else {
  1672. SetPreviewProgramMode(true);
  1673. opt_studio_mode = false;
  1674. }
  1675. #define SET_VISIBILITY(name, control) \
  1676. do { \
  1677. if (config_has_user_value(App()->GlobalConfig(), \
  1678. "BasicWindow", name)) { \
  1679. bool visible = config_get_bool(App()->GlobalConfig(), \
  1680. "BasicWindow", name); \
  1681. ui->control->setChecked(visible); \
  1682. } \
  1683. } while (false)
  1684. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1685. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1686. #undef SET_VISIBILITY
  1687. bool sourceIconsVisible = config_get_bool(
  1688. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1689. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1690. bool contextVisible = config_get_bool(
  1691. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1692. ui->toggleContextBar->setChecked(contextVisible);
  1693. ui->contextContainer->setVisible(contextVisible);
  1694. if (contextVisible)
  1695. UpdateContextBar(true);
  1696. UpdateEditMenu();
  1697. {
  1698. ProfileScope("OBSBasic::Load");
  1699. disableSaving--;
  1700. Load(savePath);
  1701. disableSaving++;
  1702. }
  1703. loaded = true;
  1704. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1705. "PreviewEnabled");
  1706. if (!previewEnabled && !IsPreviewProgramMode())
  1707. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1708. Qt::QueuedConnection,
  1709. Q_ARG(bool, previewEnabled));
  1710. else if (!previewEnabled && IsPreviewProgramMode())
  1711. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1712. Qt::QueuedConnection,
  1713. Q_ARG(bool, true));
  1714. RefreshSceneCollections();
  1715. RefreshProfiles();
  1716. disableSaving--;
  1717. auto addDisplay = [this](OBSQTDisplay *window) {
  1718. obs_display_add_draw_callback(window->GetDisplay(),
  1719. OBSBasic::RenderMain, this);
  1720. struct obs_video_info ovi;
  1721. if (obs_get_video_info(&ovi))
  1722. ResizePreview(ovi.base_width, ovi.base_height);
  1723. };
  1724. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1725. /* Show the main window, unless the tray icon isn't available
  1726. * or neither the setting nor flag for starting minimized is set. */
  1727. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1728. "BasicWindow", "SysTrayEnabled");
  1729. bool sysTrayWhenStarted = config_get_bool(
  1730. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1731. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1732. sysTrayEnabled &&
  1733. (opt_minimize_tray || sysTrayWhenStarted);
  1734. #ifdef _WIN32
  1735. SetWin32DropStyle(this);
  1736. if (!hideWindowOnStart)
  1737. show();
  1738. #endif
  1739. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1740. "AlwaysOnTop");
  1741. #ifdef ENABLE_WAYLAND
  1742. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1743. #else
  1744. bool isWayland = false;
  1745. #endif
  1746. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1747. SetAlwaysOnTop(this, true);
  1748. ui->actionAlwaysOnTop->setChecked(true);
  1749. } else if (isWayland) {
  1750. if (opt_always_on_top)
  1751. blog(LOG_INFO,
  1752. "Always On Top not available on Wayland, ignoring.");
  1753. ui->actionAlwaysOnTop->setEnabled(false);
  1754. ui->actionAlwaysOnTop->setVisible(false);
  1755. }
  1756. #ifndef _WIN32
  1757. if (!hideWindowOnStart)
  1758. show();
  1759. #endif
  1760. /* setup stats dock */
  1761. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1762. statsDock->setWidget(statsDlg);
  1763. /* ----------------------------- */
  1764. /* add custom browser docks */
  1765. #if defined(BROWSER_AVAILABLE) && defined(YOUTUBE_ENABLED)
  1766. YouTubeAppDock::CleanupYouTubeUrls();
  1767. #endif
  1768. #ifdef BROWSER_AVAILABLE
  1769. if (cef) {
  1770. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1771. "CustomBrowserDocks"),
  1772. this);
  1773. ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(),
  1774. action);
  1775. connect(action, &QAction::triggered, this,
  1776. &OBSBasic::ManageExtraBrowserDocks);
  1777. ui->menuDocks->insertSeparator(
  1778. ui->scenesDock->toggleViewAction());
  1779. LoadExtraBrowserDocks();
  1780. }
  1781. #endif
  1782. #ifdef YOUTUBE_ENABLED
  1783. /* setup YouTube app dock */
  1784. if (YouTubeAppDock::IsYTServiceSelected())
  1785. NewYouTubeAppDock();
  1786. #endif
  1787. const char *dockStateStr = config_get_string(
  1788. App()->GlobalConfig(), "BasicWindow", "DockState");
  1789. if (!dockStateStr) {
  1790. on_resetDocks_triggered(true);
  1791. } else {
  1792. QByteArray dockState =
  1793. QByteArray::fromBase64(QByteArray(dockStateStr));
  1794. if (!restoreState(dockState))
  1795. on_resetDocks_triggered(true);
  1796. }
  1797. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1798. "Pre23Defaults");
  1799. if (pre23Defaults) {
  1800. bool resetDockLock23 = config_get_bool(
  1801. App()->GlobalConfig(), "General", "ResetDockLock23");
  1802. if (!resetDockLock23) {
  1803. config_set_bool(App()->GlobalConfig(), "General",
  1804. "ResetDockLock23", true);
  1805. config_remove_value(App()->GlobalConfig(),
  1806. "BasicWindow", "DocksLocked");
  1807. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1808. }
  1809. }
  1810. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1811. "DocksLocked");
  1812. on_lockDocks_toggled(docksLocked);
  1813. ui->lockDocks->blockSignals(true);
  1814. ui->lockDocks->setChecked(docksLocked);
  1815. ui->lockDocks->blockSignals(false);
  1816. bool sideDocks = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1817. "SideDocks");
  1818. on_sideDocks_toggled(sideDocks);
  1819. ui->sideDocks->blockSignals(true);
  1820. ui->sideDocks->setChecked(sideDocks);
  1821. ui->sideDocks->blockSignals(false);
  1822. SystemTray(true);
  1823. TaskbarOverlayInit();
  1824. #ifdef __APPLE__
  1825. disableColorSpaceConversion(this);
  1826. #endif
  1827. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1828. "General", "LastVersion");
  1829. bool first_run =
  1830. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1831. if (!first_run) {
  1832. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1833. true);
  1834. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1835. }
  1836. if (!first_run && !has_last_version && !Active())
  1837. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1838. Qt::QueuedConnection);
  1839. #if (defined(_WIN32) || defined(__APPLE__)) && \
  1840. (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0)
  1841. /* Automatically set branch to "beta" the first time a pre-release build is run. */
  1842. if (!config_get_bool(App()->GlobalConfig(), "General",
  1843. "AutoBetaOptIn")) {
  1844. config_set_string(App()->GlobalConfig(), "General",
  1845. "UpdateBranch", "beta");
  1846. config_set_bool(App()->GlobalConfig(), "General",
  1847. "AutoBetaOptIn", true);
  1848. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1849. }
  1850. #endif
  1851. TimedCheckForUpdates();
  1852. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1853. "VerticalVolControl"));
  1854. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1855. on_stats_triggered();
  1856. OBSBasicStats::InitializeValues();
  1857. /* ----------------------- */
  1858. /* Add multiview menu */
  1859. ui->viewMenu->addSeparator();
  1860. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  1861. &OBSBasic::OpenMultiviewProjector);
  1862. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1863. &OBSBasic::UpdateMultiviewProjectorMenu);
  1864. ui->sources->UpdateIcons();
  1865. #if !defined(_WIN32)
  1866. delete ui->actionShowCrashLogs;
  1867. delete ui->actionUploadLastCrashLog;
  1868. delete ui->menuCrashLogs;
  1869. delete ui->actionRepair;
  1870. ui->actionShowCrashLogs = nullptr;
  1871. ui->actionUploadLastCrashLog = nullptr;
  1872. ui->menuCrashLogs = nullptr;
  1873. ui->actionRepair = nullptr;
  1874. #if !defined(__APPLE__)
  1875. delete ui->actionCheckForUpdates;
  1876. ui->actionCheckForUpdates = nullptr;
  1877. #endif
  1878. #endif
  1879. #ifdef __APPLE__
  1880. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1881. delete ui->actionFullscreenInterface;
  1882. ui->actionFullscreenInterface = nullptr;
  1883. #else
  1884. /* Don't show menu to raise macOS-only permissions dialog */
  1885. delete ui->actionShowMacPermissions;
  1886. ui->actionShowMacPermissions = nullptr;
  1887. #endif
  1888. #if defined(_WIN32) || defined(__APPLE__)
  1889. if (App()->IsUpdaterDisabled()) {
  1890. ui->actionCheckForUpdates->setEnabled(false);
  1891. #if defined(_WIN32)
  1892. ui->actionRepair->setEnabled(false);
  1893. #endif
  1894. }
  1895. #endif
  1896. #ifndef WHATSNEW_ENABLED
  1897. delete ui->actionShowWhatsNew;
  1898. ui->actionShowWhatsNew = nullptr;
  1899. #endif
  1900. if (safe_mode) {
  1901. ui->actionRestartSafe->setText(
  1902. QTStr("Basic.MainMenu.Help.RestartNormal"));
  1903. }
  1904. UpdatePreviewProgramIndicators();
  1905. OnFirstLoad();
  1906. if (!hideWindowOnStart)
  1907. activateWindow();
  1908. /* ------------------------------------------- */
  1909. /* display warning message for failed modules */
  1910. if (mfi.count) {
  1911. QString failed_plugins;
  1912. char **plugin = mfi.failed_modules;
  1913. while (*plugin) {
  1914. failed_plugins += *plugin;
  1915. failed_plugins += "\n";
  1916. plugin++;
  1917. }
  1918. QString failed_msg =
  1919. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  1920. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  1921. failed_msg);
  1922. }
  1923. }
  1924. void OBSBasic::OnFirstLoad()
  1925. {
  1926. if (api)
  1927. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1928. #ifdef WHATSNEW_ENABLED
  1929. /* Attempt to load init screen if available */
  1930. if (cef) {
  1931. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1932. connect(wnit, &WhatsNewInfoThread::Result, this,
  1933. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  1934. introCheckThread.reset(wnit);
  1935. introCheckThread->start();
  1936. }
  1937. #endif
  1938. Auth::Load();
  1939. bool showLogViewerOnStartup = config_get_bool(
  1940. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1941. if (showLogViewerOnStartup)
  1942. on_actionViewCurrentLog_triggered();
  1943. }
  1944. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1945. #define CUR_VER \
  1946. ((uint64_t)OBS_RELEASE_CANDIDATE_VER << 16ULL | OBS_RELEASE_CANDIDATE)
  1947. #define LAST_INFO_VERSION_STRING "InfoLastRCVersion"
  1948. #elif OBS_BETA > 0
  1949. #define CUR_VER ((uint64_t)OBS_BETA_VER << 16ULL | OBS_BETA)
  1950. #define LAST_INFO_VERSION_STRING "InfoLastBetaVersion"
  1951. #else
  1952. #define CUR_VER ((uint64_t)LIBOBS_API_VER << 16ULL)
  1953. #define LAST_INFO_VERSION_STRING "InfoLastVersion"
  1954. #endif
  1955. /* shows a "what's new" page on startup of new versions using CEF */
  1956. void OBSBasic::ReceivedIntroJson(const QString &text)
  1957. {
  1958. #ifdef WHATSNEW_ENABLED
  1959. if (closing)
  1960. return;
  1961. WhatsNewList items;
  1962. try {
  1963. nlohmann::json json = nlohmann::json::parse(text.toStdString());
  1964. items = json.get<WhatsNewList>();
  1965. } catch (nlohmann::json::exception &e) {
  1966. blog(LOG_WARNING, "Parsing whatsnew data failed: %s", e.what());
  1967. return;
  1968. }
  1969. std::string info_url;
  1970. int info_increment = -1;
  1971. /* check to see if there's an info page for this version */
  1972. for (const WhatsNewItem &item : items) {
  1973. if (item.os) {
  1974. WhatsNewPlatforms platforms = *item.os;
  1975. #ifdef _WIN32
  1976. if (!platforms.windows)
  1977. continue;
  1978. #elif defined(__APPLE__)
  1979. if (!platforms.macos)
  1980. continue;
  1981. #else
  1982. if (!platforms.linux)
  1983. continue;
  1984. #endif
  1985. }
  1986. int major = 0;
  1987. int minor = 0;
  1988. sscanf(item.version.c_str(), "%d.%d", &major, &minor);
  1989. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1990. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1991. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1992. item.RC == OBS_RELEASE_CANDIDATE) {
  1993. #elif OBS_BETA > 0
  1994. if (major == OBS_BETA_MAJOR && minor == OBS_BETA_MINOR &&
  1995. item.Beta == OBS_BETA) {
  1996. #else
  1997. if (major == LIBOBS_API_MAJOR_VER &&
  1998. minor == LIBOBS_API_MINOR_VER && item.RC == 0 &&
  1999. item.Beta == 0) {
  2000. #endif
  2001. info_url = item.url;
  2002. info_increment = item.increment;
  2003. }
  2004. }
  2005. /* this version was not found, or no info for this version */
  2006. if (info_increment == -1) {
  2007. return;
  2008. }
  2009. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  2010. LAST_INFO_VERSION_STRING);
  2011. int current_version_increment = -1;
  2012. if ((lastVersion & ~0xFFFF0000ULL) < (CUR_VER & ~0xFFFF0000ULL)) {
  2013. config_set_int(App()->GlobalConfig(), "General",
  2014. "InfoIncrement", -1);
  2015. config_set_uint(App()->GlobalConfig(), "General",
  2016. LAST_INFO_VERSION_STRING, CUR_VER);
  2017. } else {
  2018. current_version_increment = config_get_int(
  2019. App()->GlobalConfig(), "General", "InfoIncrement");
  2020. }
  2021. if (info_increment <= current_version_increment) {
  2022. return;
  2023. }
  2024. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  2025. info_increment);
  2026. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2027. cef->init_browser();
  2028. WhatsNewBrowserInitThread *wnbit =
  2029. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  2030. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  2031. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  2032. whatsNewInitThread.reset(wnbit);
  2033. whatsNewInitThread->start();
  2034. #else
  2035. UNUSED_PARAMETER(text);
  2036. #endif
  2037. }
  2038. #undef CUR_VER
  2039. #undef LAST_INFO_VERSION_STRING
  2040. void OBSBasic::ShowWhatsNew(const QString &url)
  2041. {
  2042. #ifdef BROWSER_AVAILABLE
  2043. if (closing)
  2044. return;
  2045. std::string info_url = QT_TO_UTF8(url);
  2046. QDialog *dlg = new QDialog(this);
  2047. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  2048. dlg->setWindowTitle("What's New");
  2049. dlg->resize(700, 600);
  2050. Qt::WindowFlags flags = dlg->windowFlags();
  2051. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  2052. dlg->setWindowFlags(flags & (~helpFlag));
  2053. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  2054. if (!cefWidget) {
  2055. return;
  2056. }
  2057. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  2058. SLOT(setWindowTitle(const QString &)));
  2059. QPushButton *close = new QPushButton(QTStr("Close"));
  2060. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  2061. QHBoxLayout *bottomLayout = new QHBoxLayout();
  2062. bottomLayout->addStretch();
  2063. bottomLayout->addWidget(close);
  2064. bottomLayout->addStretch();
  2065. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  2066. topLayout->addWidget(cefWidget);
  2067. topLayout->addLayout(bottomLayout);
  2068. dlg->show();
  2069. #else
  2070. UNUSED_PARAMETER(url);
  2071. #endif
  2072. }
  2073. void OBSBasic::UpdateMultiviewProjectorMenu()
  2074. {
  2075. ui->multiviewProjectorMenu->clear();
  2076. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2077. &OBSBasic::OpenMultiviewProjector);
  2078. }
  2079. void OBSBasic::InitHotkeys()
  2080. {
  2081. ProfileScope("OBSBasic::InitHotkeys");
  2082. struct obs_hotkeys_translations t = {};
  2083. t.insert = Str("Hotkeys.Insert");
  2084. t.del = Str("Hotkeys.Delete");
  2085. t.home = Str("Hotkeys.Home");
  2086. t.end = Str("Hotkeys.End");
  2087. t.page_up = Str("Hotkeys.PageUp");
  2088. t.page_down = Str("Hotkeys.PageDown");
  2089. t.num_lock = Str("Hotkeys.NumLock");
  2090. t.scroll_lock = Str("Hotkeys.ScrollLock");
  2091. t.caps_lock = Str("Hotkeys.CapsLock");
  2092. t.backspace = Str("Hotkeys.Backspace");
  2093. t.tab = Str("Hotkeys.Tab");
  2094. t.print = Str("Hotkeys.Print");
  2095. t.pause = Str("Hotkeys.Pause");
  2096. t.left = Str("Hotkeys.Left");
  2097. t.right = Str("Hotkeys.Right");
  2098. t.up = Str("Hotkeys.Up");
  2099. t.down = Str("Hotkeys.Down");
  2100. #ifdef _WIN32
  2101. t.meta = Str("Hotkeys.Windows");
  2102. #else
  2103. t.meta = Str("Hotkeys.Super");
  2104. #endif
  2105. t.menu = Str("Hotkeys.Menu");
  2106. t.space = Str("Hotkeys.Space");
  2107. t.numpad_num = Str("Hotkeys.NumpadNum");
  2108. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  2109. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  2110. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  2111. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  2112. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  2113. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  2114. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  2115. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  2116. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  2117. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  2118. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  2119. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  2120. t.mouse_num = Str("Hotkeys.MouseButton");
  2121. t.escape = Str("Hotkeys.Escape");
  2122. obs_hotkeys_set_translations(&t);
  2123. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  2124. Str("Push-to-mute"),
  2125. Str("Push-to-talk"));
  2126. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  2127. Str("SceneItemHide"));
  2128. obs_hotkey_enable_callback_rerouting(true);
  2129. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  2130. }
  2131. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  2132. {
  2133. obs_hotkey_trigger_routed_callback(id, pressed);
  2134. }
  2135. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  2136. {
  2137. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2138. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  2139. Q_ARG(obs_hotkey_id, id),
  2140. Q_ARG(bool, pressed));
  2141. }
  2142. void OBSBasic::CreateHotkeys()
  2143. {
  2144. ProfileScope("OBSBasic::CreateHotkeys");
  2145. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  2146. const char *info =
  2147. config_get_string(basicConfig, "Hotkeys", name);
  2148. if (!info)
  2149. return {};
  2150. OBSDataAutoRelease data = obs_data_create_from_json(info);
  2151. if (!data)
  2152. return {};
  2153. return data.Get();
  2154. };
  2155. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  2156. OBSDataArrayAutoRelease array =
  2157. obs_data_get_array(LoadHotkeyData(name), "bindings");
  2158. obs_hotkey_load(id, array);
  2159. };
  2160. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  2161. const char *name1,
  2162. const char *oldName = NULL) {
  2163. if (oldName) {
  2164. const auto info = config_get_string(basicConfig,
  2165. "Hotkeys", oldName);
  2166. if (info) {
  2167. config_set_string(basicConfig, "Hotkeys", name0,
  2168. info);
  2169. config_set_string(basicConfig, "Hotkeys", name1,
  2170. info);
  2171. config_remove_value(basicConfig, "Hotkeys",
  2172. oldName);
  2173. config_save(basicConfig);
  2174. }
  2175. }
  2176. OBSDataArrayAutoRelease array0 =
  2177. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  2178. OBSDataArrayAutoRelease array1 =
  2179. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  2180. obs_hotkey_pair_load(id, array0, array1);
  2181. };
  2182. #define MAKE_CALLBACK(pred, method, log_action) \
  2183. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  2184. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  2185. if ((pred) && pressed) { \
  2186. blog(LOG_INFO, log_action " due to hotkey"); \
  2187. method(); \
  2188. return true; \
  2189. } \
  2190. return false; \
  2191. }
  2192. streamingHotkeys = obs_hotkey_pair_register_frontend(
  2193. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  2194. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  2195. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  2196. basic.ui->streamButton->isEnabled(),
  2197. basic.StartStreaming, "Starting stream"),
  2198. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  2199. basic.ui->streamButton->isEnabled(),
  2200. basic.StopStreaming, "Stopping stream"),
  2201. this, this);
  2202. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  2203. "OBSBasic.StopStreaming");
  2204. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2205. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2206. if (basic.outputHandler->StreamingActive() && pressed) {
  2207. basic.ForceStopStreaming();
  2208. }
  2209. };
  2210. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  2211. "OBSBasic.ForceStopStreaming",
  2212. Str("Basic.Main.ForceStopStreaming"), cb, this);
  2213. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  2214. recordingHotkeys = obs_hotkey_pair_register_frontend(
  2215. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  2216. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  2217. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  2218. !basic.ui->recordButton->isChecked(),
  2219. basic.StartRecording, "Starting recording"),
  2220. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  2221. basic.ui->recordButton->isChecked(),
  2222. basic.StopRecording, "Stopping recording"),
  2223. this, this);
  2224. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  2225. "OBSBasic.StopRecording");
  2226. pauseHotkeys = obs_hotkey_pair_register_frontend(
  2227. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2228. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2229. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  2230. basic.PauseRecording, "Pausing recording"),
  2231. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  2232. basic.UnpauseRecording, "Unpausing recording"),
  2233. this, this);
  2234. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2235. "OBSBasic.UnpauseRecording");
  2236. splitFileHotkey = obs_hotkey_register_frontend(
  2237. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2238. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2239. if (pressed)
  2240. obs_frontend_recording_split_file();
  2241. },
  2242. this);
  2243. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2244. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2245. "OBSBasic.StartReplayBuffer",
  2246. Str("Basic.Main.StartReplayBuffer"),
  2247. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2248. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2249. basic.StartReplayBuffer,
  2250. "Starting replay buffer"),
  2251. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2252. basic.StopReplayBuffer, "Stopping replay buffer"),
  2253. this, this);
  2254. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2255. "OBSBasic.StopReplayBuffer");
  2256. if (vcamEnabled) {
  2257. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2258. "OBSBasic.StartVirtualCam",
  2259. Str("Basic.Main.StartVirtualCam"),
  2260. "OBSBasic.StopVirtualCam",
  2261. Str("Basic.Main.StopVirtualCam"),
  2262. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2263. basic.StartVirtualCam,
  2264. "Starting virtual camera"),
  2265. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2266. basic.StopVirtualCam,
  2267. "Stopping virtual camera"),
  2268. this, this);
  2269. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2270. "OBSBasic.StopVirtualCam");
  2271. }
  2272. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2273. "OBSBasic.EnablePreview",
  2274. Str("Basic.Main.PreviewConextMenu.Enable"),
  2275. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2276. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2277. "Enabling preview"),
  2278. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2279. "Disabling preview"),
  2280. this, this);
  2281. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2282. "OBSBasic.DisablePreview");
  2283. togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend(
  2284. "OBSBasic.EnablePreviewProgram",
  2285. Str("Basic.EnablePreviewProgramMode"),
  2286. "OBSBasic.DisablePreviewProgram",
  2287. Str("Basic.DisablePreviewProgramMode"),
  2288. MAKE_CALLBACK(!basic.IsPreviewProgramMode(),
  2289. basic.EnablePreviewProgram,
  2290. "Enabling preview program"),
  2291. MAKE_CALLBACK(basic.IsPreviewProgramMode(),
  2292. basic.DisablePreviewProgram,
  2293. "Disabling preview program"),
  2294. this, this);
  2295. LoadHotkeyPair(togglePreviewProgramHotkeys,
  2296. "OBSBasic.EnablePreviewProgram",
  2297. "OBSBasic.DisablePreviewProgram",
  2298. "OBSBasic.TogglePreviewProgram");
  2299. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2300. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2301. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2302. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2303. basic.ShowContextBar, "Showing Context Bar"),
  2304. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2305. basic.HideContextBar, "Hiding Context Bar"),
  2306. this, this);
  2307. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2308. "OBSBasic.HideContextBar");
  2309. #undef MAKE_CALLBACK
  2310. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2311. bool pressed) {
  2312. if (pressed)
  2313. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2314. "TransitionClicked",
  2315. Qt::QueuedConnection);
  2316. };
  2317. transitionHotkey = obs_hotkey_register_frontend(
  2318. "OBSBasic.Transition", Str("Transition"), transition, this);
  2319. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2320. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2321. bool pressed) {
  2322. if (pressed)
  2323. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2324. "ResetStatsHotkey",
  2325. Qt::QueuedConnection);
  2326. };
  2327. statsHotkey = obs_hotkey_register_frontend(
  2328. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2329. resetStats, this);
  2330. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2331. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2332. bool pressed) {
  2333. if (pressed)
  2334. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2335. "Screenshot",
  2336. Qt::QueuedConnection);
  2337. };
  2338. screenshotHotkey = obs_hotkey_register_frontend(
  2339. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2340. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2341. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2342. bool pressed) {
  2343. if (pressed)
  2344. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2345. "ScreenshotSelectedSource",
  2346. Qt::QueuedConnection);
  2347. };
  2348. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2349. "OBSBasic.SelectedSourceScreenshot",
  2350. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2351. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2352. }
  2353. void OBSBasic::ClearHotkeys()
  2354. {
  2355. obs_hotkey_pair_unregister(streamingHotkeys);
  2356. obs_hotkey_pair_unregister(recordingHotkeys);
  2357. obs_hotkey_pair_unregister(pauseHotkeys);
  2358. obs_hotkey_unregister(splitFileHotkey);
  2359. obs_hotkey_pair_unregister(replayBufHotkeys);
  2360. obs_hotkey_pair_unregister(vcamHotkeys);
  2361. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2362. obs_hotkey_pair_unregister(contextBarHotkeys);
  2363. obs_hotkey_pair_unregister(togglePreviewProgramHotkeys);
  2364. obs_hotkey_unregister(forceStreamingStopHotkey);
  2365. obs_hotkey_unregister(transitionHotkey);
  2366. obs_hotkey_unregister(statsHotkey);
  2367. obs_hotkey_unregister(screenshotHotkey);
  2368. obs_hotkey_unregister(sourceScreenshotHotkey);
  2369. }
  2370. OBSBasic::~OBSBasic()
  2371. {
  2372. /* clear out UI event queue */
  2373. QApplication::sendPostedEvents(nullptr);
  2374. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2375. if (updateCheckThread && updateCheckThread->isRunning())
  2376. updateCheckThread->wait();
  2377. if (patronJsonThread && patronJsonThread->isRunning())
  2378. patronJsonThread->wait();
  2379. delete screenshotData;
  2380. delete previewProjector;
  2381. delete studioProgramProjector;
  2382. delete previewProjectorSource;
  2383. delete previewProjectorMain;
  2384. delete sourceProjector;
  2385. delete sceneProjectorMenu;
  2386. delete scaleFilteringMenu;
  2387. delete blendingModeMenu;
  2388. delete colorMenu;
  2389. delete colorWidgetAction;
  2390. delete colorSelect;
  2391. delete deinterlaceMenu;
  2392. delete perSceneTransitionMenu;
  2393. delete shortcutFilter;
  2394. delete trayMenu;
  2395. delete programOptions;
  2396. delete program;
  2397. /* XXX: any obs data must be released before calling obs_shutdown.
  2398. * currently, we can't automate this with C++ RAII because of the
  2399. * delicate nature of obs_shutdown needing to be freed before the UI
  2400. * can be freed, and we have no control over the destruction order of
  2401. * the Qt UI stuff, so we have to manually clear any references to
  2402. * libobs. */
  2403. delete cpuUsageTimer;
  2404. os_cpu_usage_info_destroy(cpuUsageInfo);
  2405. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2406. ClearHotkeys();
  2407. service = nullptr;
  2408. outputHandler.reset();
  2409. delete interaction;
  2410. delete properties;
  2411. delete filters;
  2412. delete transformWindow;
  2413. delete advAudioWindow;
  2414. delete about;
  2415. delete remux;
  2416. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2417. OBSBasic::RenderMain, this);
  2418. obs_enter_graphics();
  2419. gs_vertexbuffer_destroy(box);
  2420. gs_vertexbuffer_destroy(boxLeft);
  2421. gs_vertexbuffer_destroy(boxTop);
  2422. gs_vertexbuffer_destroy(boxRight);
  2423. gs_vertexbuffer_destroy(boxBottom);
  2424. gs_vertexbuffer_destroy(circle);
  2425. gs_vertexbuffer_destroy(actionSafeMargin);
  2426. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2427. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2428. gs_vertexbuffer_destroy(leftLine);
  2429. gs_vertexbuffer_destroy(topLine);
  2430. gs_vertexbuffer_destroy(rightLine);
  2431. obs_leave_graphics();
  2432. /* When shutting down, sometimes source references can get in to the
  2433. * event queue, and if we don't forcibly process those events they
  2434. * won't get processed until after obs_shutdown has been called. I
  2435. * really wish there were a more elegant way to deal with this via C++,
  2436. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2437. * normal C++ behavior for your data to be freed in the order that you
  2438. * expect or want it to. */
  2439. QApplication::sendPostedEvents(nullptr);
  2440. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2441. LIBOBS_API_VER);
  2442. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  2443. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2444. OBS_RELEASE_CANDIDATE_VER);
  2445. #elif OBS_BETA > 0
  2446. config_set_int(App()->GlobalConfig(), "General", "LastBetaVersion",
  2447. OBS_BETA_VER);
  2448. #endif
  2449. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2450. previewEnabled);
  2451. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2452. ui->actionAlwaysOnTop->isChecked());
  2453. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2454. "SceneDuplicationMode", sceneDuplicationMode);
  2455. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2456. swapScenesMode);
  2457. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2458. "EditPropertiesMode", editPropertiesMode);
  2459. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2460. "PreviewProgramMode", IsPreviewProgramMode());
  2461. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2462. ui->lockDocks->isChecked());
  2463. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SideDocks",
  2464. ui->sideDocks->isChecked());
  2465. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2466. #ifdef BROWSER_AVAILABLE
  2467. DestroyPanelCookieManager();
  2468. delete cef;
  2469. cef = nullptr;
  2470. #endif
  2471. }
  2472. void OBSBasic::SaveProjectNow()
  2473. {
  2474. if (disableSaving)
  2475. return;
  2476. projectChanged = true;
  2477. SaveProjectDeferred();
  2478. }
  2479. void OBSBasic::SaveProject()
  2480. {
  2481. if (disableSaving)
  2482. return;
  2483. projectChanged = true;
  2484. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2485. Qt::QueuedConnection);
  2486. }
  2487. void OBSBasic::SaveProjectDeferred()
  2488. {
  2489. if (disableSaving)
  2490. return;
  2491. if (!projectChanged)
  2492. return;
  2493. projectChanged = false;
  2494. const char *sceneCollection = config_get_string(
  2495. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2496. char savePath[1024];
  2497. char fileName[1024];
  2498. int ret;
  2499. if (!sceneCollection)
  2500. return;
  2501. ret = snprintf(fileName, sizeof(fileName),
  2502. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2503. if (ret <= 0)
  2504. return;
  2505. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2506. if (ret <= 0)
  2507. return;
  2508. Save(savePath);
  2509. }
  2510. OBSSource OBSBasic::GetProgramSource()
  2511. {
  2512. return OBSGetStrongRef(programScene);
  2513. }
  2514. OBSScene OBSBasic::GetCurrentScene()
  2515. {
  2516. return currentScene.load();
  2517. }
  2518. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2519. {
  2520. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2521. }
  2522. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2523. {
  2524. return ui->sources->Get(GetTopSelectedSourceItem());
  2525. }
  2526. void OBSBasic::UpdatePreviewScalingMenu()
  2527. {
  2528. bool fixedScaling = ui->preview->IsFixedScaling();
  2529. float scalingAmount = ui->preview->GetScalingAmount();
  2530. if (!fixedScaling) {
  2531. ui->actionScaleWindow->setChecked(true);
  2532. ui->actionScaleCanvas->setChecked(false);
  2533. ui->actionScaleOutput->setChecked(false);
  2534. return;
  2535. }
  2536. obs_video_info ovi;
  2537. obs_get_video_info(&ovi);
  2538. ui->actionScaleWindow->setChecked(false);
  2539. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2540. ui->actionScaleOutput->setChecked(scalingAmount ==
  2541. float(ovi.output_width) /
  2542. float(ovi.base_width));
  2543. }
  2544. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2545. {
  2546. bool closed = true;
  2547. if (interaction)
  2548. closed = interaction->close();
  2549. if (!closed)
  2550. return;
  2551. interaction = new OBSBasicInteraction(this, source);
  2552. interaction->Init();
  2553. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2554. }
  2555. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2556. {
  2557. bool closed = true;
  2558. if (properties)
  2559. closed = properties->close();
  2560. if (!closed)
  2561. return;
  2562. properties = new OBSBasicProperties(this, source);
  2563. properties->Init();
  2564. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2565. }
  2566. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2567. {
  2568. bool closed = true;
  2569. if (filters)
  2570. closed = filters->close();
  2571. if (!closed)
  2572. return;
  2573. filters = new OBSBasicFilters(this, source);
  2574. filters->Init();
  2575. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2576. }
  2577. /* Qt callbacks for invokeMethod */
  2578. void OBSBasic::AddScene(OBSSource source)
  2579. {
  2580. const char *name = obs_source_get_name(source);
  2581. obs_scene_t *scene = obs_scene_from_source(source);
  2582. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2583. SetOBSRef(item, OBSScene(scene));
  2584. ui->scenes->insertItem(ui->scenes->currentRow() + 1, item);
  2585. obs_hotkey_register_source(
  2586. source, "OBSBasic.SelectScene",
  2587. Str("Basic.Hotkeys.SelectScene"),
  2588. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2589. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2590. App()->GetMainWindow());
  2591. auto potential_source =
  2592. static_cast<obs_source_t *>(data);
  2593. OBSSourceAutoRelease source =
  2594. obs_source_get_ref(potential_source);
  2595. if (source && pressed)
  2596. main->SetCurrentScene(source.Get());
  2597. },
  2598. static_cast<obs_source_t *>(source));
  2599. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2600. SignalContainer<OBSScene> container;
  2601. container.ref = scene;
  2602. container.handlers.assign({
  2603. std::make_shared<OBSSignal>(handler, "item_add",
  2604. OBSBasic::SceneItemAdded, this),
  2605. std::make_shared<OBSSignal>(handler, "reorder",
  2606. OBSBasic::SceneReordered, this),
  2607. std::make_shared<OBSSignal>(handler, "refresh",
  2608. OBSBasic::SceneRefreshed, this),
  2609. });
  2610. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2611. QVariant::fromValue(container));
  2612. /* if the scene already has items (a duplicated scene) add them */
  2613. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2614. AddSceneItem(item);
  2615. };
  2616. using addSceneItem_t = decltype(addSceneItem);
  2617. obs_scene_enum_items(
  2618. scene,
  2619. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2620. addSceneItem_t *func;
  2621. func = reinterpret_cast<addSceneItem_t *>(param);
  2622. (*func)(item);
  2623. return true;
  2624. },
  2625. &addSceneItem);
  2626. SaveProject();
  2627. if (!disableSaving) {
  2628. obs_source_t *source = obs_scene_get_source(scene);
  2629. blog(LOG_INFO, "User added scene '%s'",
  2630. obs_source_get_name(source));
  2631. OBSProjector::UpdateMultiviewProjectors();
  2632. }
  2633. if (api)
  2634. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2635. }
  2636. void OBSBasic::RemoveScene(OBSSource source)
  2637. {
  2638. obs_scene_t *scene = obs_scene_from_source(source);
  2639. QListWidgetItem *sel = nullptr;
  2640. int count = ui->scenes->count();
  2641. for (int i = 0; i < count; i++) {
  2642. auto item = ui->scenes->item(i);
  2643. auto cur_scene = GetOBSRef<OBSScene>(item);
  2644. if (cur_scene != scene)
  2645. continue;
  2646. sel = item;
  2647. break;
  2648. }
  2649. if (sel != nullptr) {
  2650. if (sel == ui->scenes->currentItem())
  2651. ui->sources->Clear();
  2652. delete sel;
  2653. }
  2654. SaveProject();
  2655. if (!disableSaving) {
  2656. blog(LOG_INFO, "User Removed scene '%s'",
  2657. obs_source_get_name(source));
  2658. OBSProjector::UpdateMultiviewProjectors();
  2659. }
  2660. if (api)
  2661. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2662. }
  2663. static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item,
  2664. void *param)
  2665. {
  2666. obs_sceneitem_t *selectedItem =
  2667. reinterpret_cast<obs_sceneitem_t *>(param);
  2668. if (obs_sceneitem_is_group(item))
  2669. obs_sceneitem_group_enum_items(item, select_one, param);
  2670. obs_sceneitem_select(item, (selectedItem == item));
  2671. return true;
  2672. }
  2673. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2674. {
  2675. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2676. if (GetCurrentScene() == scene)
  2677. ui->sources->Add(item);
  2678. SaveProject();
  2679. if (!disableSaving) {
  2680. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2681. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2682. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2683. obs_source_get_name(itemSource),
  2684. obs_source_get_id(itemSource),
  2685. obs_source_get_name(sceneSource));
  2686. obs_scene_enum_items(scene, select_one,
  2687. (obs_sceneitem_t *)item);
  2688. }
  2689. }
  2690. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2691. const QString &prevName)
  2692. {
  2693. QList<QListWidgetItem *> items =
  2694. listWidget->findItems(prevName, Qt::MatchExactly);
  2695. for (int i = 0; i < items.count(); i++)
  2696. items[i]->setText(newName);
  2697. }
  2698. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2699. QString prevName)
  2700. {
  2701. RenameListValues(ui->scenes, newName, prevName);
  2702. for (size_t i = 0; i < volumes.size(); i++) {
  2703. if (volumes[i]->GetName().compare(prevName) == 0)
  2704. volumes[i]->SetName(newName);
  2705. }
  2706. for (size_t i = 0; i < projectors.size(); i++) {
  2707. if (projectors[i]->GetSource() == source)
  2708. projectors[i]->RenameProjector(prevName, newName);
  2709. }
  2710. if (vcamConfig.type == VCamOutputType::SourceOutput &&
  2711. prevName == QString::fromStdString(vcamConfig.source))
  2712. vcamConfig.source = newName.toStdString();
  2713. if (vcamConfig.type == VCamOutputType::SceneOutput &&
  2714. prevName == QString::fromStdString(vcamConfig.scene))
  2715. vcamConfig.scene = newName.toStdString();
  2716. SaveProject();
  2717. obs_scene_t *scene = obs_scene_from_source(source);
  2718. if (scene)
  2719. OBSProjector::UpdateMultiviewProjectors();
  2720. UpdateContextBar();
  2721. UpdatePreviewProgramIndicators();
  2722. }
  2723. void OBSBasic::ClearContextBar()
  2724. {
  2725. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2726. if (la) {
  2727. delete la->widget();
  2728. ui->emptySpace->layout()->removeItem(la);
  2729. }
  2730. }
  2731. void OBSBasic::UpdateContextBarVisibility()
  2732. {
  2733. int width = ui->centralwidget->size().width();
  2734. ContextBarSize contextBarSizeNew;
  2735. if (width >= 740) {
  2736. contextBarSizeNew = ContextBarSize_Normal;
  2737. } else if (width >= 600) {
  2738. contextBarSizeNew = ContextBarSize_Reduced;
  2739. } else {
  2740. contextBarSizeNew = ContextBarSize_Minimized;
  2741. }
  2742. if (contextBarSize == contextBarSizeNew)
  2743. return;
  2744. contextBarSize = contextBarSizeNew;
  2745. UpdateContextBarDeferred();
  2746. }
  2747. static bool is_network_media_source(obs_source_t *source, const char *id)
  2748. {
  2749. if (strcmp(id, "ffmpeg_source") != 0)
  2750. return false;
  2751. OBSDataAutoRelease s = obs_source_get_settings(source);
  2752. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2753. return !is_local_file;
  2754. }
  2755. void OBSBasic::UpdateContextBarDeferred(bool force)
  2756. {
  2757. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2758. Qt::QueuedConnection, Q_ARG(bool, force));
  2759. }
  2760. void OBSBasic::SourceToolBarActionsSetEnabled()
  2761. {
  2762. bool enable = false;
  2763. bool disableProps = false;
  2764. OBSSceneItem item = GetCurrentSceneItem();
  2765. if (item) {
  2766. OBSSource source = obs_sceneitem_get_source(item);
  2767. disableProps = !obs_source_configurable(source);
  2768. enable = true;
  2769. }
  2770. if (disableProps)
  2771. ui->actionSourceProperties->setEnabled(false);
  2772. else
  2773. ui->actionSourceProperties->setEnabled(enable);
  2774. ui->actionRemoveSource->setEnabled(enable);
  2775. ui->actionSourceUp->setEnabled(enable);
  2776. ui->actionSourceDown->setEnabled(enable);
  2777. RefreshToolBarStyling(ui->sourcesToolbar);
  2778. }
  2779. void OBSBasic::UpdateContextBar(bool force)
  2780. {
  2781. SourceToolBarActionsSetEnabled();
  2782. if (!ui->contextContainer->isVisible() && !force)
  2783. return;
  2784. OBSSceneItem item = GetCurrentSceneItem();
  2785. if (item) {
  2786. obs_source_t *source = obs_sceneitem_get_source(item);
  2787. bool updateNeeded = true;
  2788. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2789. if (la) {
  2790. if (SourceToolbar *toolbar =
  2791. dynamic_cast<SourceToolbar *>(
  2792. la->widget())) {
  2793. if (toolbar->GetSource() == source)
  2794. updateNeeded = false;
  2795. } else if (MediaControls *toolbar =
  2796. dynamic_cast<MediaControls *>(
  2797. la->widget())) {
  2798. if (toolbar->GetSource() == source)
  2799. updateNeeded = false;
  2800. }
  2801. }
  2802. const char *id = obs_source_get_unversioned_id(source);
  2803. uint32_t flags = obs_source_get_output_flags(source);
  2804. ui->sourceInteractButton->setVisible(flags &
  2805. OBS_SOURCE_INTERACTION);
  2806. if (contextBarSize >= ContextBarSize_Reduced &&
  2807. (updateNeeded || force)) {
  2808. ClearContextBar();
  2809. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2810. if (!is_network_media_source(source, id)) {
  2811. MediaControls *mediaControls =
  2812. new MediaControls(
  2813. ui->emptySpace);
  2814. mediaControls->SetSource(source);
  2815. ui->emptySpace->layout()->addWidget(
  2816. mediaControls);
  2817. }
  2818. } else if (strcmp(id, "browser_source") == 0) {
  2819. BrowserToolbar *c = new BrowserToolbar(
  2820. ui->emptySpace, source);
  2821. ui->emptySpace->layout()->addWidget(c);
  2822. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2823. strcmp(id, "wasapi_output_capture") == 0 ||
  2824. strcmp(id, "coreaudio_input_capture") == 0 ||
  2825. strcmp(id, "coreaudio_output_capture") ==
  2826. 0 ||
  2827. strcmp(id, "pulse_input_capture") == 0 ||
  2828. strcmp(id, "pulse_output_capture") == 0 ||
  2829. strcmp(id, "alsa_input_capture") == 0) {
  2830. AudioCaptureToolbar *c =
  2831. new AudioCaptureToolbar(ui->emptySpace,
  2832. source);
  2833. c->Init();
  2834. ui->emptySpace->layout()->addWidget(c);
  2835. } else if (strcmp(id,
  2836. "wasapi_process_output_capture") ==
  2837. 0) {
  2838. ApplicationAudioCaptureToolbar *c =
  2839. new ApplicationAudioCaptureToolbar(
  2840. ui->emptySpace, source);
  2841. c->Init();
  2842. ui->emptySpace->layout()->addWidget(c);
  2843. } else if (strcmp(id, "window_capture") == 0 ||
  2844. strcmp(id, "xcomposite_input") == 0) {
  2845. WindowCaptureToolbar *c =
  2846. new WindowCaptureToolbar(ui->emptySpace,
  2847. source);
  2848. c->Init();
  2849. ui->emptySpace->layout()->addWidget(c);
  2850. } else if (strcmp(id, "monitor_capture") == 0 ||
  2851. strcmp(id, "display_capture") == 0 ||
  2852. strcmp(id, "xshm_input") == 0) {
  2853. DisplayCaptureToolbar *c =
  2854. new DisplayCaptureToolbar(
  2855. ui->emptySpace, source);
  2856. c->Init();
  2857. ui->emptySpace->layout()->addWidget(c);
  2858. } else if (strcmp(id, "dshow_input") == 0) {
  2859. DeviceCaptureToolbar *c =
  2860. new DeviceCaptureToolbar(ui->emptySpace,
  2861. source);
  2862. ui->emptySpace->layout()->addWidget(c);
  2863. } else if (strcmp(id, "game_capture") == 0) {
  2864. GameCaptureToolbar *c = new GameCaptureToolbar(
  2865. ui->emptySpace, source);
  2866. ui->emptySpace->layout()->addWidget(c);
  2867. } else if (strcmp(id, "image_source") == 0) {
  2868. ImageSourceToolbar *c = new ImageSourceToolbar(
  2869. ui->emptySpace, source);
  2870. ui->emptySpace->layout()->addWidget(c);
  2871. } else if (strcmp(id, "color_source") == 0) {
  2872. ColorSourceToolbar *c = new ColorSourceToolbar(
  2873. ui->emptySpace, source);
  2874. ui->emptySpace->layout()->addWidget(c);
  2875. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2876. strcmp(id, "text_gdiplus") == 0) {
  2877. TextSourceToolbar *c = new TextSourceToolbar(
  2878. ui->emptySpace, source);
  2879. ui->emptySpace->layout()->addWidget(c);
  2880. }
  2881. } else if (contextBarSize == ContextBarSize_Minimized) {
  2882. ClearContextBar();
  2883. }
  2884. QIcon icon;
  2885. if (strcmp(id, "scene") == 0)
  2886. icon = GetSceneIcon();
  2887. else if (strcmp(id, "group") == 0)
  2888. icon = GetGroupIcon();
  2889. else
  2890. icon = GetSourceIcon(id);
  2891. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2892. ui->contextSourceIcon->setPixmap(pixmap);
  2893. ui->contextSourceIconSpacer->hide();
  2894. ui->contextSourceIcon->show();
  2895. const char *name = obs_source_get_name(source);
  2896. ui->contextSourceLabel->setText(name);
  2897. ui->sourceFiltersButton->setEnabled(true);
  2898. ui->sourcePropertiesButton->setEnabled(
  2899. obs_source_configurable(source));
  2900. } else {
  2901. ClearContextBar();
  2902. ui->contextSourceIcon->hide();
  2903. ui->contextSourceIconSpacer->show();
  2904. ui->contextSourceLabel->setText(
  2905. QTStr("ContextBar.NoSelectedSource"));
  2906. ui->sourceFiltersButton->setEnabled(false);
  2907. ui->sourcePropertiesButton->setEnabled(false);
  2908. ui->sourceInteractButton->setVisible(false);
  2909. }
  2910. if (contextBarSize == ContextBarSize_Normal) {
  2911. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2912. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2913. ui->sourceInteractButton->setText(QTStr("Interact"));
  2914. } else {
  2915. ui->sourcePropertiesButton->setText("");
  2916. ui->sourceFiltersButton->setText("");
  2917. ui->sourceInteractButton->setText("");
  2918. }
  2919. }
  2920. static inline bool SourceMixerHidden(obs_source_t *source)
  2921. {
  2922. OBSDataAutoRelease priv_settings =
  2923. obs_source_get_private_settings(source);
  2924. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2925. return hidden;
  2926. }
  2927. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2928. {
  2929. OBSDataAutoRelease priv_settings =
  2930. obs_source_get_private_settings(source);
  2931. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2932. }
  2933. void OBSBasic::GetAudioSourceFilters()
  2934. {
  2935. QAction *action = reinterpret_cast<QAction *>(sender());
  2936. VolControl *vol = action->property("volControl").value<VolControl *>();
  2937. obs_source_t *source = vol->GetSource();
  2938. CreateFiltersWindow(source);
  2939. }
  2940. void OBSBasic::GetAudioSourceProperties()
  2941. {
  2942. QAction *action = reinterpret_cast<QAction *>(sender());
  2943. VolControl *vol = action->property("volControl").value<VolControl *>();
  2944. obs_source_t *source = vol->GetSource();
  2945. CreatePropertiesWindow(source);
  2946. }
  2947. void OBSBasic::HideAudioControl()
  2948. {
  2949. QAction *action = reinterpret_cast<QAction *>(sender());
  2950. VolControl *vol = action->property("volControl").value<VolControl *>();
  2951. obs_source_t *source = vol->GetSource();
  2952. if (!SourceMixerHidden(source)) {
  2953. SetSourceMixerHidden(source, true);
  2954. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  2955. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  2956. * the next event loop to hide it. Doesn't seem to be a problem
  2957. * with newer versions of QT. */
  2958. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  2959. Qt::QueuedConnection,
  2960. Q_ARG(OBSSource, OBSSource(source)));
  2961. }
  2962. }
  2963. void OBSBasic::UnhideAllAudioControls()
  2964. {
  2965. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2966. {
  2967. if (!obs_source_active(source))
  2968. return true;
  2969. if (!SourceMixerHidden(source))
  2970. return true;
  2971. SetSourceMixerHidden(source, false);
  2972. ActivateAudioSource(source);
  2973. return true;
  2974. };
  2975. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2976. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2977. {
  2978. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2979. };
  2980. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2981. }
  2982. void OBSBasic::ToggleHideMixer()
  2983. {
  2984. OBSSceneItem item = GetCurrentSceneItem();
  2985. OBSSource source = obs_sceneitem_get_source(item);
  2986. if (!SourceMixerHidden(source)) {
  2987. SetSourceMixerHidden(source, true);
  2988. DeactivateAudioSource(source);
  2989. } else {
  2990. SetSourceMixerHidden(source, false);
  2991. ActivateAudioSource(source);
  2992. }
  2993. }
  2994. void OBSBasic::MixerRenameSource()
  2995. {
  2996. QAction *action = reinterpret_cast<QAction *>(sender());
  2997. VolControl *vol = action->property("volControl").value<VolControl *>();
  2998. OBSSource source = vol->GetSource();
  2999. const char *prevName = obs_source_get_name(source);
  3000. for (;;) {
  3001. string name;
  3002. bool accepted = NameDialog::AskForName(
  3003. this, QTStr("Basic.Main.MixerRename.Title"),
  3004. QTStr("Basic.Main.MixerRename.Text"), name,
  3005. QT_UTF8(prevName));
  3006. if (!accepted)
  3007. return;
  3008. if (name.empty()) {
  3009. OBSMessageBox::warning(this,
  3010. QTStr("NoNameEntered.Title"),
  3011. QTStr("NoNameEntered.Text"));
  3012. continue;
  3013. }
  3014. OBSSourceAutoRelease sourceTest =
  3015. obs_get_source_by_name(name.c_str());
  3016. if (sourceTest) {
  3017. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3018. QTStr("NameExists.Text"));
  3019. continue;
  3020. }
  3021. obs_source_set_name(source, name.c_str());
  3022. break;
  3023. }
  3024. }
  3025. static inline bool SourceVolumeLocked(obs_source_t *source)
  3026. {
  3027. OBSDataAutoRelease priv_settings =
  3028. obs_source_get_private_settings(source);
  3029. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  3030. return lock;
  3031. }
  3032. void OBSBasic::LockVolumeControl(bool lock)
  3033. {
  3034. QAction *action = reinterpret_cast<QAction *>(sender());
  3035. VolControl *vol = action->property("volControl").value<VolControl *>();
  3036. obs_source_t *source = vol->GetSource();
  3037. OBSDataAutoRelease priv_settings =
  3038. obs_source_get_private_settings(source);
  3039. obs_data_set_bool(priv_settings, "volume_locked", lock);
  3040. vol->EnableSlider(!lock);
  3041. }
  3042. void OBSBasic::VolControlContextMenu()
  3043. {
  3044. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  3045. /* ------------------- */
  3046. QAction lockAction(QTStr("LockVolume"), this);
  3047. lockAction.setCheckable(true);
  3048. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  3049. QAction hideAction(QTStr("Hide"), this);
  3050. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3051. QAction mixerRenameAction(QTStr("Rename"), this);
  3052. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  3053. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  3054. QAction filtersAction(QTStr("Filters"), this);
  3055. QAction propertiesAction(QTStr("Properties"), this);
  3056. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3057. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3058. toggleControlLayoutAction.setCheckable(true);
  3059. toggleControlLayoutAction.setChecked(config_get_bool(
  3060. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3061. /* ------------------- */
  3062. connect(&hideAction, &QAction::triggered, this,
  3063. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  3064. connect(&unhideAllAction, &QAction::triggered, this,
  3065. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3066. connect(&lockAction, &QAction::toggled, this,
  3067. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  3068. connect(&mixerRenameAction, &QAction::triggered, this,
  3069. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  3070. connect(&copyFiltersAction, &QAction::triggered, this,
  3071. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  3072. connect(&pasteFiltersAction, &QAction::triggered, this,
  3073. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  3074. connect(&filtersAction, &QAction::triggered, this,
  3075. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  3076. connect(&propertiesAction, &QAction::triggered, this,
  3077. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  3078. connect(&advPropAction, &QAction::triggered, this,
  3079. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3080. Qt::DirectConnection);
  3081. /* ------------------- */
  3082. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3083. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3084. /* ------------------- */
  3085. hideAction.setProperty("volControl",
  3086. QVariant::fromValue<VolControl *>(vol));
  3087. lockAction.setProperty("volControl",
  3088. QVariant::fromValue<VolControl *>(vol));
  3089. mixerRenameAction.setProperty("volControl",
  3090. QVariant::fromValue<VolControl *>(vol));
  3091. copyFiltersAction.setProperty("volControl",
  3092. QVariant::fromValue<VolControl *>(vol));
  3093. pasteFiltersAction.setProperty("volControl",
  3094. QVariant::fromValue<VolControl *>(vol));
  3095. filtersAction.setProperty("volControl",
  3096. QVariant::fromValue<VolControl *>(vol));
  3097. propertiesAction.setProperty("volControl",
  3098. QVariant::fromValue<VolControl *>(vol));
  3099. /* ------------------- */
  3100. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  3101. 0);
  3102. OBSSourceAutoRelease source =
  3103. obs_weak_source_get_source(copyFiltersSource);
  3104. if (source) {
  3105. pasteFiltersAction.setEnabled(true);
  3106. } else {
  3107. pasteFiltersAction.setEnabled(false);
  3108. }
  3109. QMenu popup;
  3110. vol->SetContextMenu(&popup);
  3111. popup.addAction(&lockAction);
  3112. popup.addSeparator();
  3113. popup.addAction(&unhideAllAction);
  3114. popup.addAction(&hideAction);
  3115. popup.addAction(&mixerRenameAction);
  3116. popup.addSeparator();
  3117. popup.addAction(&copyFiltersAction);
  3118. popup.addAction(&pasteFiltersAction);
  3119. popup.addSeparator();
  3120. popup.addAction(&toggleControlLayoutAction);
  3121. popup.addSeparator();
  3122. popup.addAction(&filtersAction);
  3123. popup.addAction(&propertiesAction);
  3124. popup.addAction(&advPropAction);
  3125. // toggleControlLayoutAction deletes and re-creates the volume controls
  3126. // meaning that "vol" would be pointing to freed memory.
  3127. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  3128. vol->SetContextMenu(nullptr);
  3129. }
  3130. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  3131. {
  3132. StackedMixerAreaContextMenuRequested();
  3133. }
  3134. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  3135. {
  3136. StackedMixerAreaContextMenuRequested();
  3137. }
  3138. void OBSBasic::StackedMixerAreaContextMenuRequested()
  3139. {
  3140. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3141. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3142. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3143. toggleControlLayoutAction.setCheckable(true);
  3144. toggleControlLayoutAction.setChecked(config_get_bool(
  3145. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3146. /* ------------------- */
  3147. connect(&unhideAllAction, &QAction::triggered, this,
  3148. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3149. connect(&advPropAction, &QAction::triggered, this,
  3150. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3151. Qt::DirectConnection);
  3152. /* ------------------- */
  3153. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3154. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3155. /* ------------------- */
  3156. QMenu popup;
  3157. popup.addAction(&unhideAllAction);
  3158. popup.addSeparator();
  3159. popup.addAction(&toggleControlLayoutAction);
  3160. popup.addSeparator();
  3161. popup.addAction(&advPropAction);
  3162. popup.exec(QCursor::pos());
  3163. }
  3164. void OBSBasic::ToggleMixerLayout(bool vertical)
  3165. {
  3166. if (vertical) {
  3167. ui->stackedMixerArea->setMinimumSize(180, 220);
  3168. ui->stackedMixerArea->setCurrentIndex(1);
  3169. } else {
  3170. ui->stackedMixerArea->setMinimumSize(220, 0);
  3171. ui->stackedMixerArea->setCurrentIndex(0);
  3172. }
  3173. }
  3174. void OBSBasic::ToggleVolControlLayout()
  3175. {
  3176. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  3177. "VerticalVolControl");
  3178. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  3179. vertical);
  3180. ToggleMixerLayout(vertical);
  3181. // We need to store it so we can delete current and then add
  3182. // at the right order
  3183. vector<OBSSource> sources;
  3184. for (size_t i = 0; i != volumes.size(); i++)
  3185. sources.emplace_back(volumes[i]->GetSource());
  3186. ClearVolumeControls();
  3187. for (const auto &source : sources)
  3188. ActivateAudioSource(source);
  3189. }
  3190. void OBSBasic::ActivateAudioSource(OBSSource source)
  3191. {
  3192. if (SourceMixerHidden(source))
  3193. return;
  3194. if (!obs_source_active(source))
  3195. return;
  3196. if (!obs_source_audio_active(source))
  3197. return;
  3198. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3199. "VerticalVolControl");
  3200. VolControl *vol = new VolControl(source, true, vertical);
  3201. vol->EnableSlider(!SourceVolumeLocked(source));
  3202. double meterDecayRate =
  3203. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  3204. vol->SetMeterDecayRate(meterDecayRate);
  3205. uint32_t peakMeterTypeIdx =
  3206. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  3207. enum obs_peak_meter_type peakMeterType;
  3208. switch (peakMeterTypeIdx) {
  3209. case 0:
  3210. peakMeterType = SAMPLE_PEAK_METER;
  3211. break;
  3212. case 1:
  3213. peakMeterType = TRUE_PEAK_METER;
  3214. break;
  3215. default:
  3216. peakMeterType = SAMPLE_PEAK_METER;
  3217. break;
  3218. }
  3219. vol->setPeakMeterType(peakMeterType);
  3220. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  3221. connect(vol, &QWidget::customContextMenuRequested, this,
  3222. &OBSBasic::VolControlContextMenu);
  3223. connect(vol, &VolControl::ConfigClicked, this,
  3224. &OBSBasic::VolControlContextMenu);
  3225. InsertQObjectByName(volumes, vol);
  3226. for (auto volume : volumes) {
  3227. if (vertical)
  3228. ui->vVolControlLayout->addWidget(volume);
  3229. else
  3230. ui->hVolControlLayout->addWidget(volume);
  3231. }
  3232. }
  3233. void OBSBasic::DeactivateAudioSource(OBSSource source)
  3234. {
  3235. for (size_t i = 0; i < volumes.size(); i++) {
  3236. if (volumes[i]->GetSource() == source) {
  3237. delete volumes[i];
  3238. volumes.erase(volumes.begin() + i);
  3239. break;
  3240. }
  3241. }
  3242. }
  3243. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  3244. {
  3245. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  3246. !obs_source_is_group(source)) {
  3247. int count = ui->scenes->count();
  3248. if (count == 1) {
  3249. OBSMessageBox::information(this,
  3250. QTStr("FinalScene.Title"),
  3251. QTStr("FinalScene.Text"));
  3252. return false;
  3253. }
  3254. }
  3255. const char *name = obs_source_get_name(source);
  3256. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3257. QMessageBox remove_source(this);
  3258. remove_source.setText(text);
  3259. QPushButton *Yes =
  3260. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3261. remove_source.setDefaultButton(Yes);
  3262. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3263. remove_source.setIcon(QMessageBox::Question);
  3264. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3265. remove_source.exec();
  3266. return Yes == remove_source.clickedButton();
  3267. }
  3268. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3269. void OBSBasic::TimedCheckForUpdates()
  3270. {
  3271. if (App()->IsUpdaterDisabled())
  3272. return;
  3273. if (!config_get_bool(App()->GlobalConfig(), "General",
  3274. "EnableAutoUpdates"))
  3275. return;
  3276. #if defined(ENABLE_SPARKLE_UPDATER)
  3277. CheckForUpdates(false);
  3278. #elif _WIN32
  3279. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3280. "LastUpdateCheck");
  3281. uint32_t lastVersion =
  3282. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3283. if (lastVersion < LIBOBS_API_VER) {
  3284. lastUpdate = 0;
  3285. config_set_int(App()->GlobalConfig(), "General",
  3286. "LastUpdateCheck", 0);
  3287. }
  3288. long long t = (long long)time(nullptr);
  3289. long long secs = t - lastUpdate;
  3290. if (secs > UPDATE_CHECK_INTERVAL)
  3291. CheckForUpdates(false);
  3292. #endif
  3293. }
  3294. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3295. {
  3296. #if _WIN32
  3297. ui->actionCheckForUpdates->setEnabled(false);
  3298. ui->actionRepair->setEnabled(false);
  3299. if (updateCheckThread && updateCheckThread->isRunning())
  3300. return;
  3301. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3302. updateCheckThread->start();
  3303. #elif defined(ENABLE_SPARKLE_UPDATER)
  3304. ui->actionCheckForUpdates->setEnabled(false);
  3305. if (updateCheckThread && updateCheckThread->isRunning())
  3306. return;
  3307. MacUpdateThread *mut = new MacUpdateThread(manualUpdate);
  3308. connect(mut, &MacUpdateThread::Result, this,
  3309. &OBSBasic::MacBranchesFetched, Qt::QueuedConnection);
  3310. updateCheckThread.reset(mut);
  3311. updateCheckThread->start();
  3312. #else
  3313. UNUSED_PARAMETER(manualUpdate);
  3314. #endif
  3315. }
  3316. void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate)
  3317. {
  3318. #ifdef ENABLE_SPARKLE_UPDATER
  3319. static OBSSparkle *updater;
  3320. if (!updater) {
  3321. updater = new OBSSparkle(QT_TO_UTF8(branch),
  3322. ui->actionCheckForUpdates);
  3323. return;
  3324. }
  3325. updater->setBranch(QT_TO_UTF8(branch));
  3326. updater->checkForUpdates(manualUpdate);
  3327. #else
  3328. UNUSED_PARAMETER(branch);
  3329. UNUSED_PARAMETER(manualUpdate);
  3330. #endif
  3331. }
  3332. void OBSBasic::updateCheckFinished()
  3333. {
  3334. ui->actionCheckForUpdates->setEnabled(true);
  3335. ui->actionRepair->setEnabled(true);
  3336. }
  3337. void OBSBasic::DuplicateSelectedScene()
  3338. {
  3339. OBSScene curScene = GetCurrentScene();
  3340. if (!curScene)
  3341. return;
  3342. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3343. QString format{obs_source_get_name(curSceneSource)};
  3344. format += " %1";
  3345. int i = 2;
  3346. QString placeHolderText = format.arg(i);
  3347. OBSSourceAutoRelease source = nullptr;
  3348. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3349. placeHolderText = format.arg(++i);
  3350. }
  3351. for (;;) {
  3352. string name;
  3353. bool accepted = NameDialog::AskForName(
  3354. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3355. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3356. placeHolderText);
  3357. if (!accepted)
  3358. return;
  3359. if (name.empty()) {
  3360. OBSMessageBox::warning(this,
  3361. QTStr("NoNameEntered.Title"),
  3362. QTStr("NoNameEntered.Text"));
  3363. continue;
  3364. }
  3365. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3366. if (source) {
  3367. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3368. QTStr("NameExists.Text"));
  3369. obs_source_release(source);
  3370. continue;
  3371. }
  3372. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3373. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3374. source = obs_scene_get_source(scene);
  3375. SetCurrentScene(source, true);
  3376. auto undo = [](const std::string &data) {
  3377. OBSSourceAutoRelease source =
  3378. obs_get_source_by_name(data.c_str());
  3379. obs_source_remove(source);
  3380. };
  3381. auto redo = [this, name](const std::string &data) {
  3382. OBSSourceAutoRelease source =
  3383. obs_get_source_by_name(data.c_str());
  3384. obs_scene_t *scene = obs_scene_from_source(source);
  3385. scene = obs_scene_duplicate(scene, name.c_str(),
  3386. OBS_SCENE_DUP_REFS);
  3387. source = obs_scene_get_source(scene);
  3388. SetCurrentScene(source.Get(), true);
  3389. };
  3390. undo_s.add_action(
  3391. QTStr("Undo.Scene.Duplicate")
  3392. .arg(obs_source_get_name(source)),
  3393. undo, redo, obs_source_get_name(source),
  3394. obs_source_get_name(obs_scene_get_source(curScene)));
  3395. break;
  3396. }
  3397. }
  3398. static bool save_undo_source_enum(obs_scene_t * /* scene */,
  3399. obs_sceneitem_t *item, void *p)
  3400. {
  3401. obs_source_t *source = obs_sceneitem_get_source(item);
  3402. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3403. return true;
  3404. obs_data_array_t *array = (obs_data_array_t *)p;
  3405. /* check if the source is already stored in the array */
  3406. const char *name = obs_source_get_name(source);
  3407. const size_t count = obs_data_array_count(array);
  3408. for (size_t i = 0; i < count; i++) {
  3409. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3410. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3411. return true;
  3412. }
  3413. if (obs_source_is_group(source))
  3414. obs_scene_enum_items(obs_group_from_source(source),
  3415. save_undo_source_enum, p);
  3416. OBSDataAutoRelease source_data = obs_save_source(source);
  3417. obs_data_array_push_back(array, source_data);
  3418. return true;
  3419. }
  3420. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3421. {
  3422. obs_source_remove(source);
  3423. auto cb = [](void *, obs_source_t *source) {
  3424. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3425. obs_scene_prune_sources(obs_scene_from_source(source));
  3426. return true;
  3427. };
  3428. obs_enum_scenes(cb, NULL);
  3429. }
  3430. void OBSBasic::RemoveSelectedScene()
  3431. {
  3432. OBSScene scene = GetCurrentScene();
  3433. obs_source_t *source = obs_scene_get_source(scene);
  3434. if (!source || !QueryRemoveSource(source)) {
  3435. return;
  3436. }
  3437. /* ------------------------------ */
  3438. /* save all sources in scene */
  3439. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3440. obs_data_array_create();
  3441. obs_scene_enum_items(scene, save_undo_source_enum,
  3442. sources_in_deleted_scene);
  3443. OBSDataAutoRelease scene_data = obs_save_source(source);
  3444. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3445. /* ----------------------------------------------- */
  3446. /* save all scenes and groups the scene is used in */
  3447. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3448. obs_data_array_create();
  3449. struct other_scenes_cb_data {
  3450. obs_source_t *oldScene;
  3451. obs_data_array_t *scene_used_in_other_scenes;
  3452. } other_scenes_cb_data;
  3453. other_scenes_cb_data.oldScene = source;
  3454. other_scenes_cb_data.scene_used_in_other_scenes =
  3455. scene_used_in_other_scenes;
  3456. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3457. struct other_scenes_cb_data *data =
  3458. (struct other_scenes_cb_data *)data_ptr;
  3459. if (strcmp(obs_source_get_name(scene),
  3460. obs_source_get_name(data->oldScene)) == 0)
  3461. return true;
  3462. obs_sceneitem_t *item = obs_scene_find_source(
  3463. obs_group_or_scene_from_source(scene),
  3464. obs_source_get_name(data->oldScene));
  3465. if (item) {
  3466. OBSDataAutoRelease scene_data =
  3467. obs_save_source(obs_scene_get_source(
  3468. obs_sceneitem_get_scene(item)));
  3469. obs_data_array_push_back(
  3470. data->scene_used_in_other_scenes, scene_data);
  3471. }
  3472. return true;
  3473. };
  3474. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3475. /* --------------------------- */
  3476. /* undo/redo */
  3477. auto undo = [this](const std::string &json) {
  3478. OBSDataAutoRelease base =
  3479. obs_data_create_from_json(json.c_str());
  3480. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3481. obs_data_get_array(base, "sources_in_deleted_scene");
  3482. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3483. obs_data_get_array(base, "scene_used_in_other_scenes");
  3484. int savedIndex = (int)obs_data_get_int(base, "index");
  3485. std::vector<OBSSource> sources;
  3486. /* create missing sources */
  3487. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3488. sources.reserve(count);
  3489. for (size_t i = 0; i < count; i++) {
  3490. OBSDataAutoRelease data = obs_data_array_item(
  3491. sources_in_deleted_scene, i);
  3492. const char *name = obs_data_get_string(data, "name");
  3493. OBSSourceAutoRelease source =
  3494. obs_get_source_by_name(name);
  3495. if (!source) {
  3496. source = obs_load_source(data);
  3497. sources.push_back(source.Get());
  3498. }
  3499. }
  3500. /* actually load sources now */
  3501. for (obs_source_t *source : sources)
  3502. obs_source_load2(source);
  3503. /* Add scene to scenes and groups it was nested in */
  3504. for (size_t i = 0;
  3505. i < obs_data_array_count(scene_used_in_other_scenes);
  3506. i++) {
  3507. OBSDataAutoRelease data = obs_data_array_item(
  3508. scene_used_in_other_scenes, i);
  3509. const char *name = obs_data_get_string(data, "name");
  3510. OBSSourceAutoRelease source =
  3511. obs_get_source_by_name(name);
  3512. OBSDataAutoRelease settings =
  3513. obs_data_get_obj(data, "settings");
  3514. OBSDataArrayAutoRelease items =
  3515. obs_data_get_array(settings, "items");
  3516. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3517. std::vector<OBSSource> existing_sources;
  3518. auto cb = [](obs_scene_t *, obs_sceneitem_t *item,
  3519. void *data) {
  3520. std::vector<OBSSource> *existing =
  3521. (std::vector<OBSSource> *)data;
  3522. OBSSource source =
  3523. obs_sceneitem_get_source(item);
  3524. obs_sceneitem_remove(item);
  3525. existing->push_back(source);
  3526. return true;
  3527. };
  3528. obs_scene_enum_items(
  3529. obs_group_or_scene_from_source(source), cb,
  3530. (void *)&existing_sources);
  3531. /* Re-add sources to the scene */
  3532. obs_sceneitems_add(
  3533. obs_group_or_scene_from_source(source), items);
  3534. }
  3535. obs_source_t *scene_source = sources.back();
  3536. OBSScene scene = obs_scene_from_source(scene_source);
  3537. SetCurrentScene(scene, true);
  3538. /* set original index in list box */
  3539. ui->scenes->blockSignals(true);
  3540. int curIndex = ui->scenes->currentRow();
  3541. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3542. ui->scenes->insertItem(savedIndex, item);
  3543. ui->scenes->setCurrentRow(savedIndex);
  3544. currentScene = scene.Get();
  3545. ui->scenes->blockSignals(false);
  3546. };
  3547. auto redo = [](const std::string &name) {
  3548. OBSSourceAutoRelease source =
  3549. obs_get_source_by_name(name.c_str());
  3550. RemoveSceneAndReleaseNested(source);
  3551. };
  3552. OBSDataAutoRelease data = obs_data_create();
  3553. obs_data_set_array(data, "sources_in_deleted_scene",
  3554. sources_in_deleted_scene);
  3555. obs_data_set_array(data, "scene_used_in_other_scenes",
  3556. scene_used_in_other_scenes);
  3557. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3558. const char *scene_name = obs_source_get_name(source);
  3559. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3560. obs_data_get_json(data), scene_name);
  3561. /* --------------------------- */
  3562. /* remove */
  3563. RemoveSceneAndReleaseNested(source);
  3564. if (api)
  3565. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3566. }
  3567. void OBSBasic::ReorderSources(OBSScene scene)
  3568. {
  3569. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3570. return;
  3571. ui->sources->ReorderItems();
  3572. SaveProject();
  3573. }
  3574. void OBSBasic::RefreshSources(OBSScene scene)
  3575. {
  3576. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3577. return;
  3578. ui->sources->RefreshItems();
  3579. SaveProject();
  3580. }
  3581. /* OBS Callbacks */
  3582. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3583. {
  3584. OBSBasic *window = static_cast<OBSBasic *>(data);
  3585. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3586. QMetaObject::invokeMethod(window, "ReorderSources",
  3587. Q_ARG(OBSScene, OBSScene(scene)));
  3588. }
  3589. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3590. {
  3591. OBSBasic *window = static_cast<OBSBasic *>(data);
  3592. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3593. QMetaObject::invokeMethod(window, "RefreshSources",
  3594. Q_ARG(OBSScene, OBSScene(scene)));
  3595. }
  3596. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3597. {
  3598. OBSBasic *window = static_cast<OBSBasic *>(data);
  3599. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3600. QMetaObject::invokeMethod(window, "AddSceneItem",
  3601. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3602. }
  3603. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3604. {
  3605. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3606. if (obs_scene_from_source(source) != NULL)
  3607. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3608. "AddScene", WaitConnection(),
  3609. Q_ARG(OBSSource, OBSSource(source)));
  3610. }
  3611. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3612. {
  3613. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3614. if (obs_scene_from_source(source) != NULL)
  3615. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3616. "RemoveScene",
  3617. Q_ARG(OBSSource, OBSSource(source)));
  3618. }
  3619. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3620. {
  3621. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3622. uint32_t flags = obs_source_get_output_flags(source);
  3623. if (flags & OBS_SOURCE_AUDIO)
  3624. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3625. "ActivateAudioSource",
  3626. Q_ARG(OBSSource, OBSSource(source)));
  3627. }
  3628. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3629. {
  3630. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3631. uint32_t flags = obs_source_get_output_flags(source);
  3632. if (flags & OBS_SOURCE_AUDIO)
  3633. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3634. "DeactivateAudioSource",
  3635. Q_ARG(OBSSource, OBSSource(source)));
  3636. }
  3637. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3638. {
  3639. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3640. if (obs_source_active(source))
  3641. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3642. "ActivateAudioSource",
  3643. Q_ARG(OBSSource, OBSSource(source)));
  3644. }
  3645. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3646. {
  3647. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3648. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3649. "DeactivateAudioSource",
  3650. Q_ARG(OBSSource, OBSSource(source)));
  3651. }
  3652. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3653. {
  3654. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3655. const char *newName = calldata_string(params, "new_name");
  3656. const char *prevName = calldata_string(params, "prev_name");
  3657. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3658. "RenameSources", Q_ARG(OBSSource, source),
  3659. Q_ARG(QString, QT_UTF8(newName)),
  3660. Q_ARG(QString, QT_UTF8(prevName)));
  3661. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3662. }
  3663. void OBSBasic::DrawBackdrop(float cx, float cy)
  3664. {
  3665. if (!box)
  3666. return;
  3667. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3668. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3669. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3670. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3671. vec4 colorVal;
  3672. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3673. gs_effect_set_vec4(color, &colorVal);
  3674. gs_technique_begin(tech);
  3675. gs_technique_begin_pass(tech, 0);
  3676. gs_matrix_push();
  3677. gs_matrix_identity();
  3678. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3679. gs_load_vertexbuffer(box);
  3680. gs_draw(GS_TRISTRIP, 0, 0);
  3681. gs_matrix_pop();
  3682. gs_technique_end_pass(tech);
  3683. gs_technique_end(tech);
  3684. gs_load_vertexbuffer(nullptr);
  3685. GS_DEBUG_MARKER_END();
  3686. }
  3687. void OBSBasic::RenderMain(void *data, uint32_t, uint32_t)
  3688. {
  3689. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3690. OBSBasic *window = static_cast<OBSBasic *>(data);
  3691. obs_video_info ovi;
  3692. obs_get_video_info(&ovi);
  3693. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3694. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3695. gs_viewport_push();
  3696. gs_projection_push();
  3697. obs_display_t *display = window->ui->preview->GetDisplay();
  3698. uint32_t width, height;
  3699. obs_display_size(display, &width, &height);
  3700. float right = float(width) - window->previewX;
  3701. float bottom = float(height) - window->previewY;
  3702. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3703. 100.0f);
  3704. window->ui->preview->DrawOverflow();
  3705. /* --------------------------------------- */
  3706. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3707. -100.0f, 100.0f);
  3708. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3709. window->previewCY);
  3710. if (window->IsPreviewProgramMode()) {
  3711. window->DrawBackdrop(float(ovi.base_width),
  3712. float(ovi.base_height));
  3713. OBSScene scene = window->GetCurrentScene();
  3714. obs_source_t *source = obs_scene_get_source(scene);
  3715. if (source)
  3716. obs_source_video_render(source);
  3717. } else {
  3718. obs_render_main_texture_src_color_only();
  3719. }
  3720. gs_load_vertexbuffer(nullptr);
  3721. /* --------------------------------------- */
  3722. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3723. 100.0f);
  3724. gs_reset_viewport();
  3725. uint32_t targetCX = window->previewCX;
  3726. uint32_t targetCY = window->previewCY;
  3727. if (window->drawSafeAreas) {
  3728. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3729. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3730. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3731. targetCY);
  3732. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3733. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3734. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3735. }
  3736. window->ui->preview->DrawSceneEditing();
  3737. if (window->drawSpacingHelpers)
  3738. window->ui->preview->DrawSpacingHelpers();
  3739. /* --------------------------------------- */
  3740. gs_projection_pop();
  3741. gs_viewport_pop();
  3742. GS_DEBUG_MARKER_END();
  3743. }
  3744. /* Main class functions */
  3745. obs_service_t *OBSBasic::GetService()
  3746. {
  3747. if (!service) {
  3748. service =
  3749. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3750. obs_service_release(service);
  3751. }
  3752. return service;
  3753. }
  3754. void OBSBasic::SetService(obs_service_t *newService)
  3755. {
  3756. if (newService) {
  3757. service = newService;
  3758. }
  3759. }
  3760. int OBSBasic::GetTransitionDuration()
  3761. {
  3762. return ui->transitionDuration->value();
  3763. }
  3764. bool OBSBasic::Active() const
  3765. {
  3766. if (!outputHandler)
  3767. return false;
  3768. return outputHandler->Active();
  3769. }
  3770. #ifdef _WIN32
  3771. #define IS_WIN32 1
  3772. #else
  3773. #define IS_WIN32 0
  3774. #endif
  3775. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3776. {
  3777. return obs_reset_video(ovi);
  3778. }
  3779. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3780. {
  3781. const char *scaleTypeStr =
  3782. config_get_string(basicConfig, "Video", "ScaleType");
  3783. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3784. return OBS_SCALE_BILINEAR;
  3785. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3786. return OBS_SCALE_LANCZOS;
  3787. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3788. return OBS_SCALE_AREA;
  3789. else
  3790. return OBS_SCALE_BICUBIC;
  3791. }
  3792. static inline enum video_format GetVideoFormatFromName(const char *name)
  3793. {
  3794. if (astrcmpi(name, "I420") == 0)
  3795. return VIDEO_FORMAT_I420;
  3796. else if (astrcmpi(name, "NV12") == 0)
  3797. return VIDEO_FORMAT_NV12;
  3798. else if (astrcmpi(name, "I444") == 0)
  3799. return VIDEO_FORMAT_I444;
  3800. else if (astrcmpi(name, "I010") == 0)
  3801. return VIDEO_FORMAT_I010;
  3802. else if (astrcmpi(name, "P010") == 0)
  3803. return VIDEO_FORMAT_P010;
  3804. else if (astrcmpi(name, "P216") == 0)
  3805. return VIDEO_FORMAT_P216;
  3806. else if (astrcmpi(name, "P416") == 0)
  3807. return VIDEO_FORMAT_P416;
  3808. #if 0 //currently unsupported
  3809. else if (astrcmpi(name, "YVYU") == 0)
  3810. return VIDEO_FORMAT_YVYU;
  3811. else if (astrcmpi(name, "YUY2") == 0)
  3812. return VIDEO_FORMAT_YUY2;
  3813. else if (astrcmpi(name, "UYVY") == 0)
  3814. return VIDEO_FORMAT_UYVY;
  3815. #endif
  3816. else
  3817. return VIDEO_FORMAT_BGRA;
  3818. }
  3819. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3820. {
  3821. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3822. if (strcmp(name, "601") == 0)
  3823. colorspace = VIDEO_CS_601;
  3824. else if (strcmp(name, "709") == 0)
  3825. colorspace = VIDEO_CS_709;
  3826. else if (strcmp(name, "2100PQ") == 0)
  3827. colorspace = VIDEO_CS_2100_PQ;
  3828. else if (strcmp(name, "2100HLG") == 0)
  3829. colorspace = VIDEO_CS_2100_HLG;
  3830. return colorspace;
  3831. }
  3832. void OBSBasic::ResetUI()
  3833. {
  3834. bool studioPortraitLayout = config_get_bool(
  3835. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3836. if (studioPortraitLayout)
  3837. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3838. else
  3839. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3840. UpdatePreviewProgramIndicators();
  3841. }
  3842. int OBSBasic::ResetVideo()
  3843. {
  3844. if (outputHandler && outputHandler->Active())
  3845. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3846. ProfileScope("OBSBasic::ResetVideo");
  3847. struct obs_video_info ovi;
  3848. int ret;
  3849. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3850. const char *colorFormat =
  3851. config_get_string(basicConfig, "Video", "ColorFormat");
  3852. const char *colorSpace =
  3853. config_get_string(basicConfig, "Video", "ColorSpace");
  3854. const char *colorRange =
  3855. config_get_string(basicConfig, "Video", "ColorRange");
  3856. ovi.graphics_module = App()->GetRenderModule();
  3857. ovi.base_width =
  3858. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3859. ovi.base_height =
  3860. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3861. ovi.output_width =
  3862. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3863. ovi.output_height =
  3864. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3865. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3866. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3867. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3868. : VIDEO_RANGE_PARTIAL;
  3869. ovi.adapter =
  3870. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3871. ovi.gpu_conversion = true;
  3872. ovi.scale_type = GetScaleType(basicConfig);
  3873. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3874. ovi.base_width = 1920;
  3875. ovi.base_height = 1080;
  3876. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3877. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3878. }
  3879. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3880. ovi.output_width = ovi.base_width;
  3881. ovi.output_height = ovi.base_height;
  3882. config_set_uint(basicConfig, "Video", "OutputCX",
  3883. ovi.base_width);
  3884. config_set_uint(basicConfig, "Video", "OutputCY",
  3885. ovi.base_height);
  3886. }
  3887. ret = AttemptToResetVideo(&ovi);
  3888. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3889. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3890. blog(LOG_WARNING, "Tried to reset when "
  3891. "already active");
  3892. return ret;
  3893. }
  3894. /* Try OpenGL if DirectX fails on windows */
  3895. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3896. blog(LOG_WARNING,
  3897. "Failed to initialize obs video (%d) "
  3898. "with graphics_module='%s', retrying "
  3899. "with graphics_module='%s'",
  3900. ret, ovi.graphics_module, DL_OPENGL);
  3901. ovi.graphics_module = DL_OPENGL;
  3902. ret = AttemptToResetVideo(&ovi);
  3903. }
  3904. } else if (ret == OBS_VIDEO_SUCCESS) {
  3905. ResizePreview(ovi.base_width, ovi.base_height);
  3906. if (program)
  3907. ResizeProgram(ovi.base_width, ovi.base_height);
  3908. }
  3909. if (ret == OBS_VIDEO_SUCCESS) {
  3910. const float sdr_white_level = (float)config_get_uint(
  3911. basicConfig, "Video", "SdrWhiteLevel");
  3912. const float hdr_nominal_peak_level = (float)config_get_uint(
  3913. basicConfig, "Video", "HdrNominalPeakLevel");
  3914. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  3915. OBSBasicStats::InitializeValues();
  3916. OBSProjector::UpdateMultiviewProjectors();
  3917. }
  3918. return ret;
  3919. }
  3920. bool OBSBasic::ResetAudio()
  3921. {
  3922. ProfileScope("OBSBasic::ResetAudio");
  3923. struct obs_audio_info2 ai = {};
  3924. ai.samples_per_sec =
  3925. config_get_uint(basicConfig, "Audio", "SampleRate");
  3926. const char *channelSetupStr =
  3927. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3928. if (strcmp(channelSetupStr, "Mono") == 0)
  3929. ai.speakers = SPEAKERS_MONO;
  3930. else if (strcmp(channelSetupStr, "2.1") == 0)
  3931. ai.speakers = SPEAKERS_2POINT1;
  3932. else if (strcmp(channelSetupStr, "4.0") == 0)
  3933. ai.speakers = SPEAKERS_4POINT0;
  3934. else if (strcmp(channelSetupStr, "4.1") == 0)
  3935. ai.speakers = SPEAKERS_4POINT1;
  3936. else if (strcmp(channelSetupStr, "5.1") == 0)
  3937. ai.speakers = SPEAKERS_5POINT1;
  3938. else if (strcmp(channelSetupStr, "7.1") == 0)
  3939. ai.speakers = SPEAKERS_7POINT1;
  3940. else
  3941. ai.speakers = SPEAKERS_STEREO;
  3942. bool lowLatencyAudioBuffering = config_get_bool(
  3943. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  3944. if (lowLatencyAudioBuffering) {
  3945. ai.max_buffering_ms = 20;
  3946. ai.fixed_buffering = true;
  3947. }
  3948. return obs_reset_audio2(&ai);
  3949. }
  3950. extern char *get_new_source_name(const char *name, const char *format);
  3951. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3952. const char *deviceDesc, int channel)
  3953. {
  3954. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3955. OBSSourceAutoRelease source;
  3956. OBSDataAutoRelease settings;
  3957. source = obs_get_output_source(channel);
  3958. if (source) {
  3959. if (disable) {
  3960. obs_set_output_source(channel, nullptr);
  3961. } else {
  3962. settings = obs_source_get_settings(source);
  3963. const char *oldId =
  3964. obs_data_get_string(settings, "device_id");
  3965. if (strcmp(oldId, deviceId) != 0) {
  3966. obs_data_set_string(settings, "device_id",
  3967. deviceId);
  3968. obs_source_update(source, settings);
  3969. }
  3970. }
  3971. } else if (!disable) {
  3972. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  3973. settings = obs_data_create();
  3974. obs_data_set_string(settings, "device_id", deviceId);
  3975. source = obs_source_create(sourceId, name, settings, nullptr);
  3976. obs_set_output_source(channel, source);
  3977. }
  3978. }
  3979. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3980. {
  3981. QSize targetSize;
  3982. bool isFixedScaling;
  3983. obs_video_info ovi;
  3984. /* resize preview panel to fix to the top section of the window */
  3985. targetSize = GetPixelSize(ui->preview);
  3986. isFixedScaling = ui->preview->IsFixedScaling();
  3987. obs_get_video_info(&ovi);
  3988. if (isFixedScaling) {
  3989. ui->preview->ClampScrollingOffsets();
  3990. previewScale = ui->preview->GetScalingAmount();
  3991. GetCenterPosFromFixedScale(
  3992. int(cx), int(cy),
  3993. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3994. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3995. previewY, previewScale);
  3996. previewX += ui->preview->GetScrollX();
  3997. previewY += ui->preview->GetScrollY();
  3998. } else {
  3999. GetScaleAndCenterPos(int(cx), int(cy),
  4000. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4001. targetSize.height() -
  4002. PREVIEW_EDGE_SIZE * 2,
  4003. previewX, previewY, previewScale);
  4004. }
  4005. previewX += float(PREVIEW_EDGE_SIZE);
  4006. previewY += float(PREVIEW_EDGE_SIZE);
  4007. }
  4008. void OBSBasic::CloseDialogs()
  4009. {
  4010. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  4011. if (!childDialogs.isEmpty()) {
  4012. for (int i = 0; i < childDialogs.size(); ++i) {
  4013. childDialogs.at(i)->close();
  4014. }
  4015. }
  4016. if (!stats.isNull())
  4017. stats->close(); //call close to save Stats geometry
  4018. if (!remux.isNull())
  4019. remux->close();
  4020. }
  4021. void OBSBasic::EnumDialogs()
  4022. {
  4023. visDialogs.clear();
  4024. modalDialogs.clear();
  4025. visMsgBoxes.clear();
  4026. /* fill list of Visible dialogs and Modal dialogs */
  4027. QList<QDialog *> dialogs = findChildren<QDialog *>();
  4028. for (QDialog *dialog : dialogs) {
  4029. if (dialog->isVisible())
  4030. visDialogs.append(dialog);
  4031. if (dialog->isModal())
  4032. modalDialogs.append(dialog);
  4033. }
  4034. /* fill list of Visible message boxes */
  4035. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  4036. for (QMessageBox *msgbox : msgBoxes) {
  4037. if (msgbox->isVisible())
  4038. visMsgBoxes.append(msgbox);
  4039. }
  4040. }
  4041. void OBSBasic::ClearProjectors()
  4042. {
  4043. for (size_t i = 0; i < projectors.size(); i++) {
  4044. if (projectors[i])
  4045. delete projectors[i];
  4046. }
  4047. projectors.clear();
  4048. }
  4049. void OBSBasic::ClearSceneData()
  4050. {
  4051. disableSaving++;
  4052. setCursor(Qt::WaitCursor);
  4053. CloseDialogs();
  4054. ClearVolumeControls();
  4055. ClearListItems(ui->scenes);
  4056. ui->sources->Clear();
  4057. ClearQuickTransitions();
  4058. ui->transitions->clear();
  4059. ClearProjectors();
  4060. for (int i = 0; i < MAX_CHANNELS; i++)
  4061. obs_set_output_source(i, nullptr);
  4062. /* Reset VCam to default to clear its private scene and any references
  4063. * it holds. It will be reconfigured during loading. */
  4064. if (vcamEnabled) {
  4065. vcamConfig.type = VCamOutputType::ProgramView;
  4066. outputHandler->UpdateVirtualCamOutputSource();
  4067. }
  4068. safeModeModuleData = nullptr;
  4069. lastScene = nullptr;
  4070. swapScene = nullptr;
  4071. programScene = nullptr;
  4072. prevFTBSource = nullptr;
  4073. clipboard.clear();
  4074. copyFiltersSource = nullptr;
  4075. copyFilter = nullptr;
  4076. auto cb = [](void *, obs_source_t *source) {
  4077. obs_source_remove(source);
  4078. return true;
  4079. };
  4080. obs_enum_scenes(cb, nullptr);
  4081. obs_enum_sources(cb, nullptr);
  4082. if (api)
  4083. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  4084. undo_s.clear();
  4085. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  4086. * that deleteLater events are processed at this point */
  4087. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  4088. do {
  4089. QApplication::sendPostedEvents(nullptr);
  4090. } while (obs_wait_for_destroy_queue());
  4091. /* Pump Qt events one final time to give remaining signals time to be
  4092. * processed (since this happens after the destroy thread finishes and
  4093. * the audio/video threads have processed their tasks). */
  4094. QApplication::sendPostedEvents(nullptr);
  4095. unsetCursor();
  4096. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  4097. * reference, they will still be in the hash table, enumerate them and
  4098. * store the names for logging purposes. */
  4099. auto cb2 = [](void *param, obs_source_t *source) {
  4100. auto orphans = static_cast<vector<string> *>(param);
  4101. orphans->push_back(obs_source_get_name(source));
  4102. return true;
  4103. };
  4104. vector<string> orphan_sources;
  4105. obs_enum_sources(cb2, &orphan_sources);
  4106. if (!orphan_sources.empty()) {
  4107. /* Avoid logging list twice in case it gets called after
  4108. * setting the flag the first time. */
  4109. if (!clearingFailed) {
  4110. /* This ugly mess exists to join a vector of strings
  4111. * with a user-defined delimiter. */
  4112. string orphan_names = std::accumulate(
  4113. orphan_sources.begin(), orphan_sources.end(),
  4114. string(""), [](string a, string b) {
  4115. return std::move(a) + "\n- " + b;
  4116. });
  4117. blog(LOG_ERROR,
  4118. "Not all sources were cleared when clearing scene data:\n%s\n",
  4119. orphan_names.c_str());
  4120. }
  4121. /* We do not decrement disableSaving here to avoid OBS
  4122. * overwriting user data with garbage. */
  4123. clearingFailed = true;
  4124. } else {
  4125. disableSaving--;
  4126. blog(LOG_INFO, "All scene data cleared");
  4127. blog(LOG_INFO,
  4128. "------------------------------------------------");
  4129. }
  4130. }
  4131. void OBSBasic::closeEvent(QCloseEvent *event)
  4132. {
  4133. /* Do not close window if inside of a temporary event loop because we
  4134. * could be inside of an Auth::LoadUI call. Keep trying once per
  4135. * second until we've exit any known sub-loops. */
  4136. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4137. QTimer::singleShot(1000, this, &OBSBasic::close);
  4138. event->ignore();
  4139. return;
  4140. }
  4141. #ifdef YOUTUBE_ENABLED
  4142. /* Also don't close the window if the youtube stream check is active */
  4143. if (youtubeStreamCheckThread) {
  4144. QTimer::singleShot(1000, this, &OBSBasic::close);
  4145. event->ignore();
  4146. return;
  4147. }
  4148. #endif
  4149. if (isVisible())
  4150. config_set_string(App()->GlobalConfig(), "BasicWindow",
  4151. "geometry",
  4152. saveGeometry().toBase64().constData());
  4153. bool confirmOnExit =
  4154. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  4155. if (confirmOnExit && outputHandler && outputHandler->Active() &&
  4156. !clearingFailed) {
  4157. SetShowing(true);
  4158. QMessageBox::StandardButton button = OBSMessageBox::question(
  4159. this, QTStr("ConfirmExit.Title"),
  4160. QTStr("ConfirmExit.Text"));
  4161. if (button == QMessageBox::No) {
  4162. event->ignore();
  4163. restart = false;
  4164. return;
  4165. }
  4166. }
  4167. if (remux && !remux->close()) {
  4168. event->ignore();
  4169. restart = false;
  4170. return;
  4171. }
  4172. QWidget::closeEvent(event);
  4173. if (!event->isAccepted())
  4174. return;
  4175. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  4176. closing = true;
  4177. /* While closing, a resize event to OBSQTDisplay could be triggered.
  4178. * The graphics thread on macOS dispatches a lambda function to be
  4179. * executed asynchronously in the main thread. However, the display is
  4180. * sometimes deleted before the lambda function is actually executed.
  4181. * To avoid such a case, destroy displays earlier than others such as
  4182. * deleting browser docks. */
  4183. ui->preview->DestroyDisplay();
  4184. if (program)
  4185. program->DestroyDisplay();
  4186. if (outputHandler->VirtualCamActive())
  4187. outputHandler->StopVirtualCam();
  4188. if (introCheckThread)
  4189. introCheckThread->wait();
  4190. if (whatsNewInitThread)
  4191. whatsNewInitThread->wait();
  4192. if (updateCheckThread)
  4193. updateCheckThread->wait();
  4194. if (logUploadThread)
  4195. logUploadThread->wait();
  4196. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  4197. devicePropertiesThread->wait();
  4198. devicePropertiesThread.reset();
  4199. }
  4200. QApplication::sendPostedEvents(nullptr);
  4201. signalHandlers.clear();
  4202. Auth::Save();
  4203. SaveProjectNow();
  4204. auth.reset();
  4205. delete extraBrowsers;
  4206. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  4207. saveState().toBase64().constData());
  4208. #ifdef BROWSER_AVAILABLE
  4209. if (cef)
  4210. SaveExtraBrowserDocks();
  4211. ClearExtraBrowserDocks();
  4212. #endif
  4213. if (api)
  4214. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  4215. disableSaving++;
  4216. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  4217. * sources, etc) so that all references are released before shutdown */
  4218. ClearSceneData();
  4219. if (api)
  4220. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  4221. // Destroys the frontend API so plugins can't continue calling it
  4222. obs_frontend_set_callbacks_internal(nullptr);
  4223. api = nullptr;
  4224. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  4225. }
  4226. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  4227. {
  4228. #ifdef _WIN32
  4229. const MSG &msg = *static_cast<MSG *>(message);
  4230. switch (msg.message) {
  4231. case WM_MOVE:
  4232. for (OBSQTDisplay *const display :
  4233. findChildren<OBSQTDisplay *>()) {
  4234. display->OnMove();
  4235. }
  4236. break;
  4237. case WM_DISPLAYCHANGE:
  4238. for (OBSQTDisplay *const display :
  4239. findChildren<OBSQTDisplay *>()) {
  4240. display->OnDisplayChange();
  4241. }
  4242. }
  4243. #else
  4244. UNUSED_PARAMETER(message);
  4245. #endif
  4246. return false;
  4247. }
  4248. void OBSBasic::changeEvent(QEvent *event)
  4249. {
  4250. if (event->type() == QEvent::WindowStateChange) {
  4251. QWindowStateChangeEvent *stateEvent =
  4252. (QWindowStateChangeEvent *)event;
  4253. if (isMinimized()) {
  4254. if (trayIcon && trayIcon->isVisible() &&
  4255. sysTrayMinimizeToTray()) {
  4256. ToggleShowHide();
  4257. return;
  4258. }
  4259. if (previewEnabled)
  4260. EnablePreviewDisplay(false);
  4261. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  4262. isVisible()) {
  4263. if (previewEnabled)
  4264. EnablePreviewDisplay(true);
  4265. }
  4266. }
  4267. }
  4268. void OBSBasic::on_actionShow_Recordings_triggered()
  4269. {
  4270. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4271. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  4272. const char *adv_path =
  4273. strcmp(type, "Standard")
  4274. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  4275. : config_get_string(basicConfig, "AdvOut",
  4276. "RecFilePath");
  4277. const char *path = strcmp(mode, "Advanced")
  4278. ? config_get_string(basicConfig,
  4279. "SimpleOutput",
  4280. "FilePath")
  4281. : adv_path;
  4282. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4283. }
  4284. void OBSBasic::on_actionRemux_triggered()
  4285. {
  4286. if (!remux.isNull()) {
  4287. remux->show();
  4288. remux->raise();
  4289. return;
  4290. }
  4291. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4292. const char *path = strcmp(mode, "Advanced")
  4293. ? config_get_string(basicConfig,
  4294. "SimpleOutput",
  4295. "FilePath")
  4296. : config_get_string(basicConfig, "AdvOut",
  4297. "RecFilePath");
  4298. OBSRemux *remuxDlg;
  4299. remuxDlg = new OBSRemux(path, this);
  4300. remuxDlg->show();
  4301. remux = remuxDlg;
  4302. }
  4303. void OBSBasic::on_action_Settings_triggered()
  4304. {
  4305. static bool settings_already_executing = false;
  4306. /* Do not load settings window if inside of a temporary event loop
  4307. * because we could be inside of an Auth::LoadUI call. Keep trying
  4308. * once per second until we've exit any known sub-loops. */
  4309. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4310. QTimer::singleShot(1000, this,
  4311. &OBSBasic::on_action_Settings_triggered);
  4312. return;
  4313. }
  4314. if (settings_already_executing) {
  4315. return;
  4316. }
  4317. settings_already_executing = true;
  4318. {
  4319. OBSBasicSettings settings(this);
  4320. settings.exec();
  4321. }
  4322. settings_already_executing = false;
  4323. if (restart) {
  4324. QMessageBox::StandardButton button = OBSMessageBox::question(
  4325. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4326. if (button == QMessageBox::Yes)
  4327. close();
  4328. else
  4329. restart = false;
  4330. }
  4331. }
  4332. void OBSBasic::on_actionShowMacPermissions_triggered()
  4333. {
  4334. #ifdef __APPLE__
  4335. OBSPermissions check(this, CheckPermission(kScreenCapture),
  4336. CheckPermission(kVideoDeviceAccess),
  4337. CheckPermission(kAudioDeviceAccess),
  4338. CheckPermission(kAccessibility));
  4339. check.exec();
  4340. #endif
  4341. }
  4342. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4343. {
  4344. if (obs_missing_files_count(files) > 0) {
  4345. /* When loading the missing files dialog on launch, the
  4346. * window hasn't fully initialized by this point on macOS,
  4347. * so put this at the end of the current task queue. Fixes
  4348. * a bug where the window is behind OBS on startup. */
  4349. QTimer::singleShot(0, [this, files] {
  4350. missDialog = new OBSMissingFiles(files, this);
  4351. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4352. missDialog->show();
  4353. missDialog->raise();
  4354. });
  4355. } else {
  4356. obs_missing_files_destroy(files);
  4357. /* Only raise dialog if triggered manually */
  4358. if (!disableSaving)
  4359. OBSMessageBox::information(
  4360. this, QTStr("MissingFiles.NoMissing.Title"),
  4361. QTStr("MissingFiles.NoMissing.Text"));
  4362. }
  4363. }
  4364. void OBSBasic::on_actionShowMissingFiles_triggered()
  4365. {
  4366. obs_missing_files_t *files = obs_missing_files_create();
  4367. auto cb_sources = [](void *data, obs_source_t *source) {
  4368. AddMissingFiles(data, source);
  4369. return true;
  4370. };
  4371. obs_enum_all_sources(cb_sources, files);
  4372. ShowMissingFilesDialog(files);
  4373. }
  4374. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4375. {
  4376. if (advAudioWindow != nullptr) {
  4377. advAudioWindow->raise();
  4378. return;
  4379. }
  4380. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4381. "BasicWindow", "ShowSourceIcons");
  4382. advAudioWindow = new OBSBasicAdvAudio(this);
  4383. advAudioWindow->show();
  4384. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4385. advAudioWindow->SetIconsVisible(iconsVisible);
  4386. }
  4387. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4388. {
  4389. on_actionAdvAudioProperties_triggered();
  4390. }
  4391. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4392. {
  4393. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4394. connect(&unhideAllAction, &QAction::triggered, this,
  4395. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4396. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4397. toggleControlLayoutAction.setCheckable(true);
  4398. toggleControlLayoutAction.setChecked(config_get_bool(
  4399. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4400. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4401. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4402. QMenu popup;
  4403. popup.addAction(&unhideAllAction);
  4404. popup.addSeparator();
  4405. popup.addAction(&toggleControlLayoutAction);
  4406. popup.exec(QCursor::pos());
  4407. }
  4408. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4409. QListWidgetItem *)
  4410. {
  4411. OBSSource source;
  4412. if (current) {
  4413. OBSScene scene = GetOBSRef<OBSScene>(current);
  4414. source = obs_scene_get_source(scene);
  4415. currentScene = scene;
  4416. } else {
  4417. currentScene = NULL;
  4418. }
  4419. SetCurrentScene(source);
  4420. if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput)
  4421. outputHandler->UpdateVirtualCamOutputSource();
  4422. if (api)
  4423. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4424. UpdateContextBar();
  4425. }
  4426. void OBSBasic::EditSceneName()
  4427. {
  4428. ui->scenesDock->removeAction(renameScene);
  4429. QListWidgetItem *item = ui->scenes->currentItem();
  4430. Qt::ItemFlags flags = item->flags();
  4431. item->setFlags(flags | Qt::ItemIsEditable);
  4432. ui->scenes->editItem(item);
  4433. item->setFlags(flags);
  4434. }
  4435. QList<QString> OBSBasic::GetProjectorMenuMonitorsFormatted()
  4436. {
  4437. QList<QString> projectorsFormatted;
  4438. QList<QScreen *> screens = QGuiApplication::screens();
  4439. for (int i = 0; i < screens.size(); i++) {
  4440. QScreen *screen = screens[i];
  4441. QRect screenGeometry = screen->geometry();
  4442. qreal ratio = screen->devicePixelRatio();
  4443. QString name = "";
  4444. #if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  4445. QTextStream fullname(&name);
  4446. fullname << GetMonitorName(screen->name());
  4447. fullname << " (";
  4448. fullname << (i + 1);
  4449. fullname << ")";
  4450. #elif defined(__APPLE__) || defined(_WIN32)
  4451. name = screen->name();
  4452. #else
  4453. name = screen->model().simplified();
  4454. if (name.length() > 1 && name.endsWith("-"))
  4455. name.chop(1);
  4456. #endif
  4457. name = name.simplified();
  4458. if (name.length() == 0) {
  4459. name = QString("%1 %2")
  4460. .arg(QTStr("Display"))
  4461. .arg(QString::number(i + 1));
  4462. }
  4463. QString str =
  4464. QString("%1: %2x%3 @ %4,%5")
  4465. .arg(name,
  4466. QString::number(screenGeometry.width() *
  4467. ratio),
  4468. QString::number(screenGeometry.height() *
  4469. ratio),
  4470. QString::number(screenGeometry.x()),
  4471. QString::number(screenGeometry.y()));
  4472. projectorsFormatted.push_back(str);
  4473. }
  4474. return projectorsFormatted;
  4475. }
  4476. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4477. {
  4478. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4479. QMenu popup(this);
  4480. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4481. popup.addAction(QTStr("Add"), this,
  4482. &OBSBasic::on_actionAddScene_triggered);
  4483. if (item) {
  4484. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4485. copyFilters->setEnabled(false);
  4486. connect(copyFilters, &QAction::triggered, this,
  4487. &OBSBasic::SceneCopyFilters);
  4488. QAction *pasteFilters =
  4489. new QAction(QTStr("Paste.Filters"), this);
  4490. pasteFilters->setEnabled(
  4491. !obs_weak_source_expired(copyFiltersSource));
  4492. connect(pasteFilters, &QAction::triggered, this,
  4493. &OBSBasic::ScenePasteFilters);
  4494. popup.addSeparator();
  4495. popup.addAction(QTStr("Duplicate"), this,
  4496. &OBSBasic::DuplicateSelectedScene);
  4497. popup.addAction(copyFilters);
  4498. popup.addAction(pasteFilters);
  4499. popup.addSeparator();
  4500. popup.addAction(renameScene);
  4501. popup.addAction(ui->actionRemoveScene);
  4502. popup.addSeparator();
  4503. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4504. &OBSBasic::on_actionSceneUp_triggered);
  4505. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4506. this, &OBSBasic::on_actionSceneDown_triggered);
  4507. order.addSeparator();
  4508. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4509. this, &OBSBasic::MoveSceneToTop);
  4510. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4511. this, &OBSBasic::MoveSceneToBottom);
  4512. popup.addMenu(&order);
  4513. popup.addSeparator();
  4514. delete sceneProjectorMenu;
  4515. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4516. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4517. &OBSBasic::OpenSceneProjector);
  4518. popup.addMenu(sceneProjectorMenu);
  4519. QAction *sceneWindow = popup.addAction(
  4520. QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow);
  4521. popup.addAction(sceneWindow);
  4522. popup.addAction(QTStr("Screenshot.Scene"), this,
  4523. &OBSBasic::ScreenshotScene);
  4524. popup.addSeparator();
  4525. popup.addAction(QTStr("Filters"), this,
  4526. &OBSBasic::OpenSceneFilters);
  4527. popup.addSeparator();
  4528. delete perSceneTransitionMenu;
  4529. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4530. popup.addMenu(perSceneTransitionMenu);
  4531. /* ---------------------- */
  4532. QAction *multiviewAction =
  4533. popup.addAction(QTStr("ShowInMultiview"));
  4534. OBSSource source = GetCurrentSceneSource();
  4535. OBSDataAutoRelease data =
  4536. obs_source_get_private_settings(source);
  4537. obs_data_set_default_bool(data, "show_in_multiview", true);
  4538. bool show = obs_data_get_bool(data, "show_in_multiview");
  4539. multiviewAction->setCheckable(true);
  4540. multiviewAction->setChecked(show);
  4541. auto showInMultiview = [](OBSData data) {
  4542. bool show =
  4543. obs_data_get_bool(data, "show_in_multiview");
  4544. obs_data_set_bool(data, "show_in_multiview", !show);
  4545. OBSProjector::UpdateMultiviewProjectors();
  4546. };
  4547. connect(multiviewAction, &QAction::triggered,
  4548. std::bind(showInMultiview, data.Get()));
  4549. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4550. }
  4551. popup.addSeparator();
  4552. bool grid = ui->scenes->GetGridMode();
  4553. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4554. : QTStr("Basic.Main.GridMode"),
  4555. this);
  4556. connect(gridAction, &QAction::triggered, this,
  4557. &OBSBasic::GridActionClicked);
  4558. popup.addAction(gridAction);
  4559. popup.exec(QCursor::pos());
  4560. }
  4561. void OBSBasic::on_actionSceneListMode_triggered()
  4562. {
  4563. ui->scenes->SetGridMode(false);
  4564. }
  4565. void OBSBasic::on_actionSceneGridMode_triggered()
  4566. {
  4567. ui->scenes->SetGridMode(true);
  4568. }
  4569. void OBSBasic::GridActionClicked()
  4570. {
  4571. bool gridMode = !ui->scenes->GetGridMode();
  4572. ui->scenes->SetGridMode(gridMode);
  4573. if (gridMode)
  4574. ui->actionSceneGridMode->setChecked(true);
  4575. else
  4576. ui->actionSceneListMode->setChecked(true);
  4577. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4578. gridMode);
  4579. }
  4580. void OBSBasic::on_actionAddScene_triggered()
  4581. {
  4582. string name;
  4583. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4584. int i = 2;
  4585. QString placeHolderText = format.arg(i);
  4586. OBSSourceAutoRelease source = nullptr;
  4587. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4588. placeHolderText = format.arg(++i);
  4589. }
  4590. bool accepted = NameDialog::AskForName(
  4591. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4592. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4593. if (accepted) {
  4594. if (name.empty()) {
  4595. OBSMessageBox::warning(this,
  4596. QTStr("NoNameEntered.Title"),
  4597. QTStr("NoNameEntered.Text"));
  4598. on_actionAddScene_triggered();
  4599. return;
  4600. }
  4601. OBSSourceAutoRelease source =
  4602. obs_get_source_by_name(name.c_str());
  4603. if (source) {
  4604. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4605. QTStr("NameExists.Text"));
  4606. on_actionAddScene_triggered();
  4607. return;
  4608. }
  4609. auto undo_fn = [](const std::string &data) {
  4610. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4611. if (t) {
  4612. obs_source_remove(t);
  4613. obs_source_release(t);
  4614. }
  4615. };
  4616. auto redo_fn = [this](const std::string &data) {
  4617. OBSSceneAutoRelease scene =
  4618. obs_scene_create(data.c_str());
  4619. obs_source_t *source = obs_scene_get_source(scene);
  4620. SetCurrentScene(source, true);
  4621. };
  4622. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4623. undo_fn, redo_fn, name, name);
  4624. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4625. obs_source_t *scene_source = obs_scene_get_source(scene);
  4626. SetCurrentScene(scene_source);
  4627. }
  4628. }
  4629. void OBSBasic::on_actionRemoveScene_triggered()
  4630. {
  4631. RemoveSelectedScene();
  4632. }
  4633. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4634. {
  4635. int idx = ui->scenes->currentRow();
  4636. if (idx == -1 || idx == invalidIdx)
  4637. return;
  4638. ui->scenes->blockSignals(true);
  4639. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4640. if (!relative)
  4641. idx = 0;
  4642. ui->scenes->insertItem(idx + offset, item);
  4643. ui->scenes->setCurrentRow(idx + offset);
  4644. item->setSelected(true);
  4645. currentScene = GetOBSRef<OBSScene>(item).Get();
  4646. ui->scenes->blockSignals(false);
  4647. OBSProjector::UpdateMultiviewProjectors();
  4648. }
  4649. void OBSBasic::on_actionSceneUp_triggered()
  4650. {
  4651. ChangeSceneIndex(true, -1, 0);
  4652. }
  4653. void OBSBasic::on_actionSceneDown_triggered()
  4654. {
  4655. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4656. }
  4657. void OBSBasic::MoveSceneToTop()
  4658. {
  4659. ChangeSceneIndex(false, 0, 0);
  4660. }
  4661. void OBSBasic::MoveSceneToBottom()
  4662. {
  4663. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4664. ui->scenes->count() - 1);
  4665. }
  4666. void OBSBasic::EditSceneItemName()
  4667. {
  4668. int idx = GetTopSelectedSourceItem();
  4669. ui->sources->Edit(idx);
  4670. }
  4671. void OBSBasic::SetDeinterlacingMode()
  4672. {
  4673. QAction *action = reinterpret_cast<QAction *>(sender());
  4674. obs_deinterlace_mode mode =
  4675. (obs_deinterlace_mode)action->property("mode").toInt();
  4676. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4677. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4678. obs_source_set_deinterlace_mode(source, mode);
  4679. }
  4680. void OBSBasic::SetDeinterlacingOrder()
  4681. {
  4682. QAction *action = reinterpret_cast<QAction *>(sender());
  4683. obs_deinterlace_field_order order =
  4684. (obs_deinterlace_field_order)action->property("order").toInt();
  4685. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4686. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4687. obs_source_set_deinterlace_field_order(source, order);
  4688. }
  4689. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4690. {
  4691. obs_deinterlace_mode deinterlaceMode =
  4692. obs_source_get_deinterlace_mode(source);
  4693. obs_deinterlace_field_order deinterlaceOrder =
  4694. obs_source_get_deinterlace_field_order(source);
  4695. QAction *action;
  4696. #define ADD_MODE(name, mode) \
  4697. action = menu->addAction(QTStr("" name), this, \
  4698. &OBSBasic::SetDeinterlacingMode); \
  4699. action->setProperty("mode", (int)mode); \
  4700. action->setCheckable(true); \
  4701. action->setChecked(deinterlaceMode == mode);
  4702. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4703. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4704. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4705. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4706. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4707. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4708. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4709. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4710. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4711. #undef ADD_MODE
  4712. menu->addSeparator();
  4713. #define ADD_ORDER(name, order) \
  4714. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4715. &OBSBasic::SetDeinterlacingOrder); \
  4716. action->setProperty("order", (int)order); \
  4717. action->setCheckable(true); \
  4718. action->setChecked(deinterlaceOrder == order);
  4719. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4720. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4721. #undef ADD_ORDER
  4722. return menu;
  4723. }
  4724. void OBSBasic::SetScaleFilter()
  4725. {
  4726. QAction *action = reinterpret_cast<QAction *>(sender());
  4727. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4728. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4729. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4730. }
  4731. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4732. {
  4733. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4734. QAction *action;
  4735. #define ADD_MODE(name, mode) \
  4736. action = menu->addAction(QTStr("" name), this, \
  4737. &OBSBasic::SetScaleFilter); \
  4738. action->setProperty("mode", (int)mode); \
  4739. action->setCheckable(true); \
  4740. action->setChecked(scaleFilter == mode);
  4741. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4742. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4743. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4744. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4745. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4746. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4747. #undef ADD_MODE
  4748. return menu;
  4749. }
  4750. void OBSBasic::SetBlendingMethod()
  4751. {
  4752. QAction *action = reinterpret_cast<QAction *>(sender());
  4753. obs_blending_method method =
  4754. (obs_blending_method)action->property("method").toInt();
  4755. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4756. obs_sceneitem_set_blending_method(sceneItem, method);
  4757. }
  4758. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4759. {
  4760. obs_blending_method blendingMethod =
  4761. obs_sceneitem_get_blending_method(item);
  4762. QAction *action;
  4763. #define ADD_MODE(name, method) \
  4764. action = menu->addAction(QTStr("" name), this, \
  4765. &OBSBasic::SetBlendingMethod); \
  4766. action->setProperty("method", (int)method); \
  4767. action->setCheckable(true); \
  4768. action->setChecked(blendingMethod == method);
  4769. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4770. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4771. #undef ADD_MODE
  4772. return menu;
  4773. }
  4774. void OBSBasic::SetBlendingMode()
  4775. {
  4776. QAction *action = reinterpret_cast<QAction *>(sender());
  4777. obs_blending_type mode =
  4778. (obs_blending_type)action->property("mode").toInt();
  4779. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4780. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4781. }
  4782. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4783. {
  4784. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4785. QAction *action;
  4786. #define ADD_MODE(name, mode) \
  4787. action = menu->addAction(QTStr("" name), this, \
  4788. &OBSBasic::SetBlendingMode); \
  4789. action->setProperty("mode", (int)mode); \
  4790. action->setCheckable(true); \
  4791. action->setChecked(blendingMode == mode);
  4792. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4793. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4794. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4795. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4796. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4797. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4798. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4799. #undef ADD_MODE
  4800. return menu;
  4801. }
  4802. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4803. QWidgetAction *widgetAction,
  4804. ColorSelect *select,
  4805. obs_sceneitem_t *item)
  4806. {
  4807. QAction *action;
  4808. menu->setStyleSheet(QString(
  4809. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4810. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4811. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4812. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4813. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4814. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4815. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4816. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4817. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4818. obs_data_release(privData);
  4819. obs_data_set_default_int(privData, "color-preset", 0);
  4820. int preset = obs_data_get_int(privData, "color-preset");
  4821. action = menu->addAction(QTStr("Clear"), this, &OBSBasic::ColorChange);
  4822. action->setCheckable(true);
  4823. action->setProperty("bgColor", 0);
  4824. action->setChecked(preset == 0);
  4825. action = menu->addAction(QTStr("CustomColor"), this,
  4826. &OBSBasic::ColorChange);
  4827. action->setCheckable(true);
  4828. action->setProperty("bgColor", 1);
  4829. action->setChecked(preset == 1);
  4830. menu->addSeparator();
  4831. widgetAction->setDefaultWidget(select);
  4832. for (int i = 1; i < 9; i++) {
  4833. stringstream button;
  4834. button << "preset" << i;
  4835. QPushButton *colorButton =
  4836. select->findChild<QPushButton *>(button.str().c_str());
  4837. if (preset == i + 1)
  4838. colorButton->setStyleSheet("border: 2px solid black");
  4839. colorButton->setProperty("bgColor", i);
  4840. select->connect(colorButton, &QPushButton::released, this,
  4841. &OBSBasic::ColorChange);
  4842. }
  4843. menu->addAction(widgetAction);
  4844. return menu;
  4845. }
  4846. ColorSelect::ColorSelect(QWidget *parent)
  4847. : QWidget(parent),
  4848. ui(new Ui::ColorSelect)
  4849. {
  4850. ui->setupUi(this);
  4851. }
  4852. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4853. {
  4854. QMenu popup(this);
  4855. delete previewProjectorSource;
  4856. delete sourceProjector;
  4857. delete scaleFilteringMenu;
  4858. delete blendingMethodMenu;
  4859. delete blendingModeMenu;
  4860. delete colorMenu;
  4861. delete colorWidgetAction;
  4862. delete colorSelect;
  4863. delete deinterlaceMenu;
  4864. if (preview) {
  4865. QAction *action = popup.addAction(
  4866. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4867. &OBSBasic::TogglePreview);
  4868. action->setCheckable(true);
  4869. action->setChecked(
  4870. obs_display_enabled(ui->preview->GetDisplay()));
  4871. if (IsPreviewProgramMode())
  4872. action->setEnabled(false);
  4873. popup.addAction(ui->actionLockPreview);
  4874. popup.addMenu(ui->scalingMenu);
  4875. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4876. AddProjectorMenuMonitors(previewProjectorSource, this,
  4877. &OBSBasic::OpenPreviewProjector);
  4878. popup.addMenu(previewProjectorSource);
  4879. QAction *previewWindow =
  4880. popup.addAction(QTStr("PreviewWindow"), this,
  4881. &OBSBasic::OpenPreviewWindow);
  4882. popup.addAction(previewWindow);
  4883. popup.addAction(QTStr("Screenshot.Preview"), this,
  4884. &OBSBasic::ScreenshotScene);
  4885. popup.addSeparator();
  4886. }
  4887. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4888. if (addSourceMenu)
  4889. popup.addMenu(addSourceMenu);
  4890. if (ui->sources->MultipleBaseSelected()) {
  4891. popup.addSeparator();
  4892. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4893. &SourceTree::GroupSelectedItems);
  4894. } else if (ui->sources->GroupsSelected()) {
  4895. popup.addSeparator();
  4896. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4897. &SourceTree::UngroupSelectedGroups);
  4898. }
  4899. popup.addSeparator();
  4900. popup.addAction(ui->actionCopySource);
  4901. popup.addAction(ui->actionPasteRef);
  4902. popup.addAction(ui->actionPasteDup);
  4903. popup.addSeparator();
  4904. popup.addSeparator();
  4905. popup.addAction(ui->actionCopyFilters);
  4906. popup.addAction(ui->actionPasteFilters);
  4907. popup.addSeparator();
  4908. if (idx != -1) {
  4909. if (addSourceMenu)
  4910. popup.addSeparator();
  4911. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4912. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4913. uint32_t flags = obs_source_get_output_flags(source);
  4914. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4915. OBS_SOURCE_ASYNC_VIDEO;
  4916. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4917. bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO;
  4918. colorMenu = new QMenu(QTStr("ChangeBG"));
  4919. colorWidgetAction = new QWidgetAction(colorMenu);
  4920. colorSelect = new ColorSelect(colorMenu);
  4921. popup.addMenu(AddBackgroundColorMenu(
  4922. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4923. popup.addAction(renameSource);
  4924. popup.addAction(ui->actionRemoveSource);
  4925. popup.addSeparator();
  4926. popup.addMenu(ui->orderMenu);
  4927. if (hasVideo)
  4928. popup.addMenu(ui->transformMenu);
  4929. popup.addSeparator();
  4930. if (hasAudio) {
  4931. QAction *actionHideMixer =
  4932. popup.addAction(QTStr("HideMixer"), this,
  4933. &OBSBasic::ToggleHideMixer);
  4934. actionHideMixer->setCheckable(true);
  4935. actionHideMixer->setChecked(SourceMixerHidden(source));
  4936. popup.addSeparator();
  4937. }
  4938. if (hasVideo) {
  4939. QAction *resizeOutput = popup.addAction(
  4940. QTStr("ResizeOutputSizeOfSource"), this,
  4941. &OBSBasic::ResizeOutputSizeOfSource);
  4942. int width = obs_source_get_width(source);
  4943. int height = obs_source_get_height(source);
  4944. resizeOutput->setEnabled(!obs_video_active());
  4945. if (width < 8 || height < 8)
  4946. resizeOutput->setEnabled(false);
  4947. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4948. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu,
  4949. sceneItem));
  4950. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4951. popup.addMenu(AddBlendingModeMenu(blendingModeMenu,
  4952. sceneItem));
  4953. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4954. popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu,
  4955. sceneItem));
  4956. if (isAsyncVideo) {
  4957. deinterlaceMenu =
  4958. new QMenu(QTStr("Deinterlacing"));
  4959. popup.addMenu(AddDeinterlacingMenu(
  4960. deinterlaceMenu, source));
  4961. }
  4962. popup.addSeparator();
  4963. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4964. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4965. popup.addSeparator();
  4966. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4967. AddProjectorMenuMonitors(
  4968. sourceProjector, this,
  4969. &OBSBasic::OpenSourceProjector);
  4970. popup.addMenu(sourceProjector);
  4971. popup.addAction(QTStr("SourceWindow"), this,
  4972. &OBSBasic::OpenSourceWindow);
  4973. popup.addAction(QTStr("Screenshot.Source"), this,
  4974. &OBSBasic::ScreenshotSelectedSource);
  4975. }
  4976. popup.addSeparator();
  4977. if (flags & OBS_SOURCE_INTERACTION)
  4978. popup.addAction(QTStr("Interact"), this,
  4979. &OBSBasic::on_actionInteract_triggered);
  4980. popup.addAction(QTStr("Filters"), this,
  4981. [&]() { OpenFilters(); });
  4982. QAction *action = popup.addAction(
  4983. QTStr("Properties"), this,
  4984. &OBSBasic::on_actionSourceProperties_triggered);
  4985. action->setEnabled(obs_source_configurable(source));
  4986. }
  4987. popup.exec(QCursor::pos());
  4988. }
  4989. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4990. {
  4991. if (ui->scenes->count()) {
  4992. QModelIndex idx = ui->sources->indexAt(pos);
  4993. CreateSourcePopupMenu(idx.row(), false);
  4994. }
  4995. }
  4996. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4997. {
  4998. if (!witem)
  4999. return;
  5000. if (IsPreviewProgramMode()) {
  5001. bool doubleClickSwitch =
  5002. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  5003. "TransitionOnDoubleClick");
  5004. if (doubleClickSwitch)
  5005. TransitionClicked();
  5006. }
  5007. }
  5008. static inline bool should_show_properties(obs_source_t *source, const char *id)
  5009. {
  5010. if (!source)
  5011. return false;
  5012. if (strcmp(id, "group") == 0)
  5013. return false;
  5014. if (!obs_source_configurable(source))
  5015. return false;
  5016. uint32_t caps = obs_source_get_output_flags(source);
  5017. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  5018. return false;
  5019. return true;
  5020. }
  5021. void OBSBasic::AddSource(const char *id)
  5022. {
  5023. if (id && *id) {
  5024. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  5025. sourceSelect.exec();
  5026. if (should_show_properties(sourceSelect.newSource, id)) {
  5027. CreatePropertiesWindow(sourceSelect.newSource);
  5028. }
  5029. }
  5030. }
  5031. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  5032. {
  5033. const char *unversioned_type;
  5034. const char *type;
  5035. bool foundValues = false;
  5036. bool foundDeprecated = false;
  5037. size_t idx = 0;
  5038. QMenu *popup = new QMenu(QTStr("Add"), this);
  5039. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  5040. auto getActionAfter = [](QMenu *menu, const QString &name) {
  5041. QList<QAction *> actions = menu->actions();
  5042. for (QAction *menuAction : actions) {
  5043. if (menuAction->text().compare(
  5044. name, Qt::CaseInsensitive) >= 0)
  5045. return menuAction;
  5046. }
  5047. return (QAction *)nullptr;
  5048. };
  5049. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  5050. const char *name) {
  5051. QString qname = QT_UTF8(name);
  5052. QAction *popupItem = new QAction(qname, this);
  5053. connect(popupItem, &QAction::triggered,
  5054. [this, type]() { AddSource(type); });
  5055. QIcon icon;
  5056. if (strcmp(type, "scene") == 0)
  5057. icon = GetSceneIcon();
  5058. else
  5059. icon = GetSourceIcon(type);
  5060. popupItem->setIcon(icon);
  5061. QAction *after = getActionAfter(popup, qname);
  5062. popup->insertAction(after, popupItem);
  5063. };
  5064. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  5065. const char *name = obs_source_get_display_name(type);
  5066. uint32_t caps = obs_get_source_output_flags(type);
  5067. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  5068. continue;
  5069. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  5070. addSource(popup, unversioned_type, name);
  5071. } else {
  5072. addSource(deprecated, unversioned_type, name);
  5073. foundDeprecated = true;
  5074. }
  5075. foundValues = true;
  5076. }
  5077. addSource(popup, "scene", Str("Basic.Scene"));
  5078. popup->addSeparator();
  5079. QAction *addGroup = new QAction(QTStr("Group"), this);
  5080. addGroup->setIcon(GetGroupIcon());
  5081. connect(addGroup, &QAction::triggered,
  5082. [this]() { AddSource("group"); });
  5083. popup->addAction(addGroup);
  5084. if (!foundDeprecated) {
  5085. delete deprecated;
  5086. deprecated = nullptr;
  5087. }
  5088. if (!foundValues) {
  5089. delete popup;
  5090. popup = nullptr;
  5091. } else if (foundDeprecated) {
  5092. popup->addSeparator();
  5093. popup->addMenu(deprecated);
  5094. }
  5095. return popup;
  5096. }
  5097. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  5098. {
  5099. if (!GetCurrentScene()) {
  5100. // Tell the user he needs a scene first (help beginners).
  5101. OBSMessageBox::information(
  5102. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  5103. QTStr("Basic.Main.AddSourceHelp.Text"));
  5104. return;
  5105. }
  5106. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  5107. if (popup)
  5108. popup->exec(pos);
  5109. }
  5110. void OBSBasic::on_actionAddSource_triggered()
  5111. {
  5112. AddSourcePopupMenu(QCursor::pos());
  5113. }
  5114. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5115. {
  5116. vector<OBSSceneItem> &items =
  5117. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  5118. if (obs_sceneitem_selected(item)) {
  5119. items.emplace_back(item);
  5120. } else if (obs_sceneitem_is_group(item)) {
  5121. obs_sceneitem_group_enum_items(item, remove_items, &items);
  5122. }
  5123. return true;
  5124. };
  5125. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  5126. std::vector<obs_source_t *> *sources)
  5127. {
  5128. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  5129. if (!sources) {
  5130. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  5131. } else {
  5132. for (obs_source_t *source : *sources) {
  5133. obs_data_t *source_data = obs_save_source(source);
  5134. obs_data_array_push_back(undo_array, source_data);
  5135. obs_data_release(source_data);
  5136. }
  5137. }
  5138. OBSDataAutoRelease scene_data =
  5139. obs_save_source(obs_scene_get_source(scene));
  5140. obs_data_array_push_back(undo_array, scene_data);
  5141. OBSDataAutoRelease data = obs_data_create();
  5142. obs_data_set_array(data, "array", undo_array);
  5143. obs_data_get_json(data);
  5144. return data.Get();
  5145. }
  5146. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  5147. {
  5148. auto sources = static_cast<std::vector<OBSSource> *>(p);
  5149. sources->push_back(obs_sceneitem_get_source(item));
  5150. return true;
  5151. }
  5152. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  5153. OBSData undo_data, OBSData redo_data)
  5154. {
  5155. auto undo_redo = [this](const std::string &json) {
  5156. OBSDataAutoRelease base =
  5157. obs_data_create_from_json(json.c_str());
  5158. OBSDataArrayAutoRelease array =
  5159. obs_data_get_array(base, "array");
  5160. std::vector<OBSSource> sources;
  5161. std::vector<OBSSource> old_sources;
  5162. /* create missing sources */
  5163. const size_t count = obs_data_array_count(array);
  5164. sources.reserve(count);
  5165. for (size_t i = 0; i < count; i++) {
  5166. OBSDataAutoRelease data = obs_data_array_item(array, i);
  5167. const char *name = obs_data_get_string(data, "name");
  5168. OBSSourceAutoRelease source =
  5169. obs_get_source_by_name(name);
  5170. if (!source)
  5171. source = obs_load_source(data);
  5172. sources.push_back(source.Get());
  5173. /* update scene/group settings to restore their
  5174. * contents to their saved settings */
  5175. obs_scene_t *scene =
  5176. obs_group_or_scene_from_source(source);
  5177. if (scene) {
  5178. obs_scene_enum_items(scene, add_source_enum,
  5179. &old_sources);
  5180. OBSDataAutoRelease scene_settings =
  5181. obs_data_get_obj(data, "settings");
  5182. obs_source_update(source, scene_settings);
  5183. }
  5184. }
  5185. /* actually load sources now */
  5186. for (obs_source_t *source : sources)
  5187. obs_source_load2(source);
  5188. ui->sources->RefreshItems();
  5189. };
  5190. const char *undo_json = obs_data_get_last_json(undo_data);
  5191. const char *redo_json = obs_data_get_last_json(redo_data);
  5192. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  5193. redo_json);
  5194. }
  5195. void OBSBasic::on_actionRemoveSource_triggered()
  5196. {
  5197. vector<OBSSceneItem> items;
  5198. OBSScene scene = GetCurrentScene();
  5199. obs_source_t *scene_source = obs_scene_get_source(scene);
  5200. obs_scene_enum_items(scene, remove_items, &items);
  5201. if (!items.size())
  5202. return;
  5203. /* ------------------------------------- */
  5204. /* confirm action with user */
  5205. bool confirmed = false;
  5206. if (items.size() > 1) {
  5207. QString text = QTStr("ConfirmRemove.TextMultiple")
  5208. .arg(QString::number(items.size()));
  5209. QMessageBox remove_items(this);
  5210. remove_items.setText(text);
  5211. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  5212. QMessageBox::YesRole);
  5213. remove_items.setDefaultButton(Yes);
  5214. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  5215. remove_items.setIcon(QMessageBox::Question);
  5216. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  5217. remove_items.exec();
  5218. confirmed = Yes == remove_items.clickedButton();
  5219. } else {
  5220. OBSSceneItem &item = items[0];
  5221. obs_source_t *source = obs_sceneitem_get_source(item);
  5222. if (source && QueryRemoveSource(source))
  5223. confirmed = true;
  5224. }
  5225. if (!confirmed)
  5226. return;
  5227. /* ----------------------------------------------- */
  5228. /* save undo data */
  5229. OBSData undo_data = BackupScene(scene_source);
  5230. /* ----------------------------------------------- */
  5231. /* remove items */
  5232. for (auto &item : items)
  5233. obs_sceneitem_remove(item);
  5234. /* ----------------------------------------------- */
  5235. /* save redo data */
  5236. OBSData redo_data = BackupScene(scene_source);
  5237. /* ----------------------------------------------- */
  5238. /* add undo/redo action */
  5239. QString action_name;
  5240. if (items.size() > 1) {
  5241. action_name = QTStr("Undo.Sources.Multi")
  5242. .arg(QString::number(items.size()));
  5243. } else {
  5244. QString str = QTStr("Undo.Delete");
  5245. action_name = str.arg(obs_source_get_name(
  5246. obs_sceneitem_get_source(items[0])));
  5247. }
  5248. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  5249. }
  5250. void OBSBasic::on_actionInteract_triggered()
  5251. {
  5252. OBSSceneItem item = GetCurrentSceneItem();
  5253. OBSSource source = obs_sceneitem_get_source(item);
  5254. if (source)
  5255. CreateInteractionWindow(source);
  5256. }
  5257. void OBSBasic::on_actionSourceProperties_triggered()
  5258. {
  5259. OBSSceneItem item = GetCurrentSceneItem();
  5260. OBSSource source = obs_sceneitem_get_source(item);
  5261. if (source)
  5262. CreatePropertiesWindow(source);
  5263. }
  5264. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  5265. const QString &action_name)
  5266. {
  5267. OBSSceneItem item = GetCurrentSceneItem();
  5268. obs_source_t *source = obs_sceneitem_get_source(item);
  5269. if (!source)
  5270. return;
  5271. OBSScene scene = GetCurrentScene();
  5272. std::vector<obs_source_t *> sources;
  5273. if (scene != obs_sceneitem_get_scene(item))
  5274. sources.push_back(
  5275. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  5276. OBSData undo_data = BackupScene(scene, &sources);
  5277. obs_sceneitem_set_order(item, movement);
  5278. const char *source_name = obs_source_get_name(source);
  5279. const char *scene_name =
  5280. obs_source_get_name(obs_scene_get_source(scene));
  5281. OBSData redo_data = BackupScene(scene, &sources);
  5282. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  5283. undo_data, redo_data);
  5284. }
  5285. void OBSBasic::on_actionSourceUp_triggered()
  5286. {
  5287. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5288. }
  5289. void OBSBasic::on_actionSourceDown_triggered()
  5290. {
  5291. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5292. }
  5293. void OBSBasic::on_actionMoveUp_triggered()
  5294. {
  5295. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5296. }
  5297. void OBSBasic::on_actionMoveDown_triggered()
  5298. {
  5299. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5300. }
  5301. void OBSBasic::on_actionMoveToTop_triggered()
  5302. {
  5303. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  5304. }
  5305. void OBSBasic::on_actionMoveToBottom_triggered()
  5306. {
  5307. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  5308. }
  5309. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  5310. {
  5311. char logDir[512];
  5312. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  5313. return nullptr;
  5314. string path = logDir;
  5315. path += "/";
  5316. path += log;
  5317. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  5318. if (!file)
  5319. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  5320. return file;
  5321. }
  5322. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  5323. {
  5324. BPtr<char> fileString{ReadLogFile(subdir, file)};
  5325. if (!fileString)
  5326. return;
  5327. if (!*fileString)
  5328. return;
  5329. ui->menuLogFiles->setEnabled(false);
  5330. #if defined(_WIN32)
  5331. ui->menuCrashLogs->setEnabled(false);
  5332. #endif
  5333. stringstream ss;
  5334. ss << "OBS " << App()->GetVersionString(false)
  5335. << " log file uploaded at " << CurrentDateTimeString() << "\n\n"
  5336. << fileString;
  5337. if (logUploadThread) {
  5338. logUploadThread->wait();
  5339. }
  5340. RemoteTextThread *thread = new RemoteTextThread(
  5341. "https://obsproject.com/logs/upload", "text/plain", ss.str());
  5342. logUploadThread.reset(thread);
  5343. if (crash) {
  5344. connect(thread, &RemoteTextThread::Result, this,
  5345. &OBSBasic::crashUploadFinished);
  5346. } else {
  5347. connect(thread, &RemoteTextThread::Result, this,
  5348. &OBSBasic::logUploadFinished);
  5349. }
  5350. logUploadThread->start();
  5351. }
  5352. void OBSBasic::on_actionShowLogs_triggered()
  5353. {
  5354. char logDir[512];
  5355. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5356. return;
  5357. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5358. QDesktopServices::openUrl(url);
  5359. }
  5360. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5361. {
  5362. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5363. }
  5364. void OBSBasic::on_actionUploadLastLog_triggered()
  5365. {
  5366. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5367. }
  5368. void OBSBasic::on_actionViewCurrentLog_triggered()
  5369. {
  5370. if (!logView)
  5371. logView = new OBSLogViewer();
  5372. logView->show();
  5373. logView->setWindowState(
  5374. (logView->windowState() & ~Qt::WindowMinimized) |
  5375. Qt::WindowActive);
  5376. logView->activateWindow();
  5377. logView->raise();
  5378. }
  5379. void OBSBasic::on_actionShowCrashLogs_triggered()
  5380. {
  5381. char logDir[512];
  5382. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5383. return;
  5384. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5385. QDesktopServices::openUrl(url);
  5386. }
  5387. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5388. {
  5389. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5390. }
  5391. void OBSBasic::on_actionCheckForUpdates_triggered()
  5392. {
  5393. CheckForUpdates(true);
  5394. }
  5395. void OBSBasic::on_actionRepair_triggered()
  5396. {
  5397. #if defined(_WIN32)
  5398. ui->actionCheckForUpdates->setEnabled(false);
  5399. ui->actionRepair->setEnabled(false);
  5400. if (updateCheckThread && updateCheckThread->isRunning())
  5401. return;
  5402. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5403. updateCheckThread->start();
  5404. #endif
  5405. }
  5406. void OBSBasic::on_actionRestartSafe_triggered()
  5407. {
  5408. QMessageBox::StandardButton button = OBSMessageBox::question(
  5409. this, QTStr("Restart"),
  5410. safe_mode ? QTStr("SafeMode.RestartNormal")
  5411. : QTStr("SafeMode.Restart"));
  5412. if (button == QMessageBox::Yes) {
  5413. restart = safe_mode;
  5414. restart_safe = !safe_mode;
  5415. close();
  5416. }
  5417. }
  5418. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5419. {
  5420. ui->menuLogFiles->setEnabled(true);
  5421. #if defined(_WIN32)
  5422. ui->menuCrashLogs->setEnabled(true);
  5423. #endif
  5424. if (text.isEmpty()) {
  5425. OBSMessageBox::critical(
  5426. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5427. error);
  5428. return;
  5429. }
  5430. openLogDialog(text, false);
  5431. }
  5432. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5433. {
  5434. ui->menuLogFiles->setEnabled(true);
  5435. #if defined(_WIN32)
  5436. ui->menuCrashLogs->setEnabled(true);
  5437. #endif
  5438. if (text.isEmpty()) {
  5439. OBSMessageBox::critical(
  5440. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5441. error);
  5442. return;
  5443. }
  5444. openLogDialog(text, true);
  5445. }
  5446. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5447. {
  5448. OBSDataAutoRelease returnData =
  5449. obs_data_create_from_json(QT_TO_UTF8(text));
  5450. string resURL = obs_data_get_string(returnData, "url");
  5451. QString logURL = resURL.c_str();
  5452. OBSLogReply logDialog(this, logURL, crash);
  5453. logDialog.exec();
  5454. }
  5455. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5456. obs_source_t *source, const string &name)
  5457. {
  5458. const char *prevName = obs_source_get_name(source);
  5459. if (name == prevName)
  5460. return;
  5461. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5462. QListWidgetItem *listItem = listWidget->currentItem();
  5463. if (foundSource || name.empty()) {
  5464. listItem->setText(QT_UTF8(prevName));
  5465. if (foundSource) {
  5466. OBSMessageBox::warning(parent,
  5467. QTStr("NameExists.Title"),
  5468. QTStr("NameExists.Text"));
  5469. } else if (name.empty()) {
  5470. OBSMessageBox::warning(parent,
  5471. QTStr("NoNameEntered.Title"),
  5472. QTStr("NoNameEntered.Text"));
  5473. }
  5474. } else {
  5475. auto undo = [prev = std::string(prevName)](
  5476. const std::string &data) {
  5477. OBSSourceAutoRelease source =
  5478. obs_get_source_by_uuid(data.c_str());
  5479. obs_source_set_name(source, prev.c_str());
  5480. };
  5481. auto redo = [name](const std::string &data) {
  5482. OBSSourceAutoRelease source =
  5483. obs_get_source_by_uuid(data.c_str());
  5484. obs_source_set_name(source, name.c_str());
  5485. };
  5486. std::string source_uuid(obs_source_get_uuid(source));
  5487. parent->undo_s.add_action(
  5488. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5489. source_uuid, source_uuid);
  5490. listItem->setText(QT_UTF8(name.c_str()));
  5491. obs_source_set_name(source, name.c_str());
  5492. }
  5493. }
  5494. void OBSBasic::SceneNameEdited(QWidget *editor)
  5495. {
  5496. OBSScene scene = GetCurrentScene();
  5497. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5498. string text = QT_TO_UTF8(edit->text().trimmed());
  5499. if (!scene)
  5500. return;
  5501. obs_source_t *source = obs_scene_get_source(scene);
  5502. RenameListItem(this, ui->scenes, source, text);
  5503. ui->scenesDock->addAction(renameScene);
  5504. if (api)
  5505. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5506. }
  5507. void OBSBasic::OpenFilters(OBSSource source)
  5508. {
  5509. if (source == nullptr) {
  5510. OBSSceneItem item = GetCurrentSceneItem();
  5511. source = obs_sceneitem_get_source(item);
  5512. }
  5513. CreateFiltersWindow(source);
  5514. }
  5515. void OBSBasic::OpenProperties(OBSSource source)
  5516. {
  5517. if (source == nullptr) {
  5518. OBSSceneItem item = GetCurrentSceneItem();
  5519. source = obs_sceneitem_get_source(item);
  5520. }
  5521. CreatePropertiesWindow(source);
  5522. }
  5523. void OBSBasic::OpenInteraction(OBSSource source)
  5524. {
  5525. if (source == nullptr) {
  5526. OBSSceneItem item = GetCurrentSceneItem();
  5527. source = obs_sceneitem_get_source(item);
  5528. }
  5529. CreateInteractionWindow(source);
  5530. }
  5531. void OBSBasic::OpenEditTransform(OBSSceneItem item)
  5532. {
  5533. if (!item)
  5534. item = GetCurrentSceneItem();
  5535. if (!item)
  5536. return;
  5537. CreateEditTransformWindow(item);
  5538. }
  5539. void OBSBasic::OpenSceneFilters()
  5540. {
  5541. OBSScene scene = GetCurrentScene();
  5542. OBSSource source = obs_scene_get_source(scene);
  5543. CreateFiltersWindow(source);
  5544. }
  5545. #define RECORDING_START \
  5546. "==== Recording Start ==============================================="
  5547. #define RECORDING_STOP \
  5548. "==== Recording Stop ================================================"
  5549. #define REPLAY_BUFFER_START \
  5550. "==== Replay Buffer Start ==========================================="
  5551. #define REPLAY_BUFFER_STOP \
  5552. "==== Replay Buffer Stop ============================================"
  5553. #define STREAMING_START \
  5554. "==== Streaming Start ==============================================="
  5555. #define STREAMING_STOP \
  5556. "==== Streaming Stop ================================================"
  5557. #define VIRTUAL_CAM_START \
  5558. "==== Virtual Camera Start =========================================="
  5559. #define VIRTUAL_CAM_STOP \
  5560. "==== Virtual Camera Stop ==========================================="
  5561. void OBSBasic::DisplayStreamStartError()
  5562. {
  5563. QString message = !outputHandler->lastError.empty()
  5564. ? QTStr(outputHandler->lastError.c_str())
  5565. : QTStr("Output.StartFailedGeneric");
  5566. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5567. ui->streamButton->setEnabled(true);
  5568. ui->streamButton->setChecked(false);
  5569. if (sysTrayStream) {
  5570. sysTrayStream->setText(ui->streamButton->text());
  5571. sysTrayStream->setEnabled(true);
  5572. }
  5573. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5574. }
  5575. #ifdef YOUTUBE_ENABLED
  5576. void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id,
  5577. const QString &stream_id,
  5578. const QString &key, bool autostart,
  5579. bool autostop, bool start_now)
  5580. {
  5581. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5582. obs_service_t *service_obj = GetService();
  5583. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5584. const std::string a_key = QT_TO_UTF8(key);
  5585. obs_data_set_string(settings, "key", a_key.c_str());
  5586. const std::string b_id = QT_TO_UTF8(broadcast_id);
  5587. obs_data_set_string(settings, "broadcast_id", b_id.c_str());
  5588. const std::string s_id = QT_TO_UTF8(stream_id);
  5589. obs_data_set_string(settings, "stream_id", s_id.c_str());
  5590. obs_service_update(service_obj, settings);
  5591. autoStartBroadcast = autostart;
  5592. autoStopBroadcast = autostop;
  5593. broadcastReady = true;
  5594. if (start_now)
  5595. QMetaObject::invokeMethod(this, "StartStreaming");
  5596. }
  5597. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5598. {
  5599. YoutubeApiWrappers *apiYouTube(
  5600. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5601. if (!apiYouTube) {
  5602. /* technically we should never get here -Lain */
  5603. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5604. Qt::QueuedConnection);
  5605. youtubeStreamCheckThread->deleteLater();
  5606. blog(LOG_ERROR, "==========================================");
  5607. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5608. blog(LOG_ERROR, "==========================================");
  5609. return;
  5610. }
  5611. int timeout = 0;
  5612. json11::Json json;
  5613. QString id = key.c_str();
  5614. while (StreamingActive()) {
  5615. if (timeout == 14) {
  5616. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5617. Qt::QueuedConnection);
  5618. break;
  5619. }
  5620. if (!apiYouTube->FindStream(id, json)) {
  5621. QMetaObject::invokeMethod(this,
  5622. "DisplayStreamStartError",
  5623. Qt::QueuedConnection);
  5624. QMetaObject::invokeMethod(this, "StopStreaming",
  5625. Qt::QueuedConnection);
  5626. break;
  5627. }
  5628. auto item = json["items"][0];
  5629. auto status = item["status"]["streamStatus"].string_value();
  5630. if (status == "active") {
  5631. QMetaObject::invokeMethod(ui->broadcastButton,
  5632. "setEnabled",
  5633. Q_ARG(bool, true));
  5634. break;
  5635. } else {
  5636. QThread::sleep(1);
  5637. timeout++;
  5638. }
  5639. }
  5640. youtubeStreamCheckThread->deleteLater();
  5641. }
  5642. void OBSBasic::ShowYouTubeAutoStartWarning()
  5643. {
  5644. auto msgBox = []() {
  5645. QMessageBox msgbox(App()->GetMainWindow());
  5646. msgbox.setWindowTitle(QTStr(
  5647. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5648. msgbox.setText(
  5649. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5650. msgbox.setIcon(QMessageBox::Icon::Information);
  5651. msgbox.addButton(QMessageBox::Ok);
  5652. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5653. msgbox.setCheckBox(cb);
  5654. msgbox.exec();
  5655. if (cb->isChecked()) {
  5656. config_set_bool(App()->GlobalConfig(), "General",
  5657. "WarnedAboutYouTubeAutoStart", true);
  5658. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5659. }
  5660. };
  5661. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5662. "WarnedAboutYouTubeAutoStart");
  5663. if (!warned) {
  5664. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5665. Q_ARG(VoidFunc, msgBox));
  5666. }
  5667. }
  5668. #endif
  5669. void OBSBasic::StartStreaming()
  5670. {
  5671. if (outputHandler->StreamingActive())
  5672. return;
  5673. if (disableOutputsRef)
  5674. return;
  5675. if (auth && auth->broadcastFlow()) {
  5676. if (!broadcastActive && !broadcastReady) {
  5677. ui->streamButton->setChecked(false);
  5678. QMessageBox no_broadcast(this);
  5679. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5680. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5681. QTStr("Basic.Main.SetupBroadcast"),
  5682. QMessageBox::YesRole);
  5683. no_broadcast.setDefaultButton(SetupBroadcast);
  5684. no_broadcast.addButton(QTStr("Close"),
  5685. QMessageBox::NoRole);
  5686. no_broadcast.setIcon(QMessageBox::Information);
  5687. no_broadcast.setWindowTitle(
  5688. QTStr("Output.NoBroadcast.Title"));
  5689. no_broadcast.exec();
  5690. if (no_broadcast.clickedButton() == SetupBroadcast)
  5691. QMetaObject::invokeMethod(this,
  5692. "SetupBroadcast");
  5693. return;
  5694. }
  5695. }
  5696. if (!outputHandler->SetupStreaming(service)) {
  5697. DisplayStreamStartError();
  5698. return;
  5699. }
  5700. if (api)
  5701. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5702. SaveProject();
  5703. ui->streamButton->setEnabled(false);
  5704. ui->streamButton->setChecked(false);
  5705. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5706. ui->broadcastButton->setChecked(false);
  5707. if (sysTrayStream) {
  5708. sysTrayStream->setEnabled(false);
  5709. sysTrayStream->setText(ui->streamButton->text());
  5710. }
  5711. if (!outputHandler->StartStreaming(service)) {
  5712. DisplayStreamStartError();
  5713. return;
  5714. }
  5715. if (!autoStartBroadcast) {
  5716. ui->broadcastButton->setText(
  5717. QTStr("Basic.Main.StartBroadcast"));
  5718. ui->broadcastButton->setProperty("broadcastState", "ready");
  5719. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5720. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5721. // well, we need to disable button while stream is not active
  5722. ui->broadcastButton->setEnabled(false);
  5723. } else {
  5724. if (!autoStopBroadcast) {
  5725. ui->broadcastButton->setText(
  5726. QTStr("Basic.Main.StopBroadcast"));
  5727. } else {
  5728. ui->broadcastButton->setText(
  5729. QTStr("Basic.Main.AutoStopEnabled"));
  5730. ui->broadcastButton->setEnabled(false);
  5731. }
  5732. ui->broadcastButton->setProperty("broadcastState", "active");
  5733. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5734. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5735. broadcastActive = true;
  5736. }
  5737. bool recordWhenStreaming = config_get_bool(
  5738. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5739. if (recordWhenStreaming)
  5740. StartRecording();
  5741. bool replayBufferWhileStreaming = config_get_bool(
  5742. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5743. if (replayBufferWhileStreaming)
  5744. StartReplayBuffer();
  5745. #ifdef YOUTUBE_ENABLED
  5746. if (!autoStartBroadcast)
  5747. OBSBasic::ShowYouTubeAutoStartWarning();
  5748. #endif
  5749. }
  5750. void OBSBasic::BroadcastButtonClicked()
  5751. {
  5752. if (!broadcastReady ||
  5753. (!broadcastActive && !outputHandler->StreamingActive())) {
  5754. SetupBroadcast();
  5755. if (broadcastReady)
  5756. ui->broadcastButton->setChecked(true);
  5757. return;
  5758. }
  5759. if (!autoStartBroadcast) {
  5760. #ifdef YOUTUBE_ENABLED
  5761. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5762. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5763. if (ytAuth.get()) {
  5764. if (!ytAuth->StartLatestBroadcast()) {
  5765. auto last_error = ytAuth->GetLastError();
  5766. if (last_error.isEmpty())
  5767. last_error = QTStr(
  5768. "YouTube.Actions.Error.YouTubeApi");
  5769. if (!ytAuth->GetTranslatedError(last_error))
  5770. last_error =
  5771. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5772. .arg(last_error,
  5773. ytAuth->GetBroadcastId());
  5774. OBSMessageBox::warning(
  5775. this,
  5776. QTStr("Output.BroadcastStartFailed"),
  5777. last_error, true);
  5778. ui->broadcastButton->setChecked(false);
  5779. return;
  5780. }
  5781. }
  5782. #endif
  5783. broadcastActive = true;
  5784. autoStartBroadcast = true; // and clear the flag
  5785. if (!autoStopBroadcast) {
  5786. ui->broadcastButton->setText(
  5787. QTStr("Basic.Main.StopBroadcast"));
  5788. } else {
  5789. ui->broadcastButton->setText(
  5790. QTStr("Basic.Main.AutoStopEnabled"));
  5791. ui->broadcastButton->setEnabled(false);
  5792. }
  5793. ui->broadcastButton->setProperty("broadcastState", "active");
  5794. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5795. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5796. } else if (!autoStopBroadcast) {
  5797. #ifdef YOUTUBE_ENABLED
  5798. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5799. "WarnBeforeStoppingStream");
  5800. if (confirm && isVisible()) {
  5801. QMessageBox::StandardButton button = OBSMessageBox::question(
  5802. this, QTStr("ConfirmStop.Title"),
  5803. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5804. QMessageBox::Yes | QMessageBox::No,
  5805. QMessageBox::No);
  5806. if (button == QMessageBox::No) {
  5807. ui->broadcastButton->setChecked(true);
  5808. return;
  5809. }
  5810. }
  5811. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5812. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5813. if (ytAuth.get()) {
  5814. if (!ytAuth->StopLatestBroadcast()) {
  5815. auto last_error = ytAuth->GetLastError();
  5816. if (last_error.isEmpty())
  5817. last_error = QTStr(
  5818. "YouTube.Actions.Error.YouTubeApi");
  5819. if (!ytAuth->GetTranslatedError(last_error))
  5820. last_error =
  5821. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5822. .arg(last_error,
  5823. ytAuth->GetBroadcastId());
  5824. OBSMessageBox::warning(
  5825. this,
  5826. QTStr("Output.BroadcastStopFailed"),
  5827. last_error, true);
  5828. }
  5829. }
  5830. #endif
  5831. broadcastActive = false;
  5832. broadcastReady = false;
  5833. autoStopBroadcast = true;
  5834. QMetaObject::invokeMethod(this, "StopStreaming");
  5835. SetBroadcastFlowEnabled(true);
  5836. }
  5837. }
  5838. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5839. {
  5840. ui->broadcastButton->setEnabled(enabled);
  5841. ui->broadcastButton->setVisible(enabled);
  5842. ui->broadcastButton->setChecked(broadcastReady);
  5843. ui->broadcastButton->setProperty("broadcastState", "idle");
  5844. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5845. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5846. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5847. }
  5848. void OBSBasic::SetupBroadcast()
  5849. {
  5850. #ifdef YOUTUBE_ENABLED
  5851. Auth *const auth = GetAuth();
  5852. if (IsYouTubeService(auth->service())) {
  5853. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5854. connect(&dialog, &OBSYoutubeActions::ok, this,
  5855. &OBSBasic::YouTubeActionDialogOk);
  5856. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5857. if (result != QDialog::Accepted) {
  5858. if (!broadcastReady)
  5859. ui->broadcastButton->setChecked(false);
  5860. }
  5861. }
  5862. #endif
  5863. }
  5864. #ifdef _WIN32
  5865. static inline void UpdateProcessPriority()
  5866. {
  5867. const char *priority = config_get_string(App()->GlobalConfig(),
  5868. "General", "ProcessPriority");
  5869. if (priority && strcmp(priority, "Normal") != 0)
  5870. SetProcessPriority(priority);
  5871. }
  5872. static inline void ClearProcessPriority()
  5873. {
  5874. const char *priority = config_get_string(App()->GlobalConfig(),
  5875. "General", "ProcessPriority");
  5876. if (priority && strcmp(priority, "Normal") != 0)
  5877. SetProcessPriority("Normal");
  5878. }
  5879. #else
  5880. #define UpdateProcessPriority() \
  5881. do { \
  5882. } while (false)
  5883. #define ClearProcessPriority() \
  5884. do { \
  5885. } while (false)
  5886. #endif
  5887. inline void OBSBasic::OnActivate(bool force)
  5888. {
  5889. if (ui->profileMenu->isEnabled() || force) {
  5890. ui->profileMenu->setEnabled(false);
  5891. ui->autoConfigure->setEnabled(false);
  5892. App()->IncrementSleepInhibition();
  5893. UpdateProcessPriority();
  5894. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5895. if (trayIcon && trayIcon->isVisible()) {
  5896. #ifdef __APPLE__
  5897. QIcon trayMask =
  5898. QIcon(":/res/images/tray_active_macos.svg");
  5899. trayMask.setIsMask(true);
  5900. trayIcon->setIcon(
  5901. QIcon::fromTheme("obs-tray", trayMask));
  5902. #else
  5903. trayIcon->setIcon(QIcon::fromTheme(
  5904. "obs-tray-active",
  5905. QIcon(":/res/images/tray_active.png")));
  5906. #endif
  5907. }
  5908. }
  5909. }
  5910. extern volatile bool recording_paused;
  5911. extern volatile bool replaybuf_active;
  5912. inline void OBSBasic::OnDeactivate()
  5913. {
  5914. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5915. ui->profileMenu->setEnabled(true);
  5916. ui->autoConfigure->setEnabled(true);
  5917. App()->DecrementSleepInhibition();
  5918. ClearProcessPriority();
  5919. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5920. if (trayIcon && trayIcon->isVisible()) {
  5921. #ifdef __APPLE__
  5922. QIcon trayIconFile =
  5923. QIcon(":/res/images/obs_macos.svg");
  5924. trayIconFile.setIsMask(true);
  5925. #else
  5926. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5927. #endif
  5928. trayIcon->setIcon(
  5929. QIcon::fromTheme("obs-tray", trayIconFile));
  5930. }
  5931. } else if (outputHandler->Active() && trayIcon &&
  5932. trayIcon->isVisible()) {
  5933. if (os_atomic_load_bool(&recording_paused)) {
  5934. #ifdef __APPLE__
  5935. QIcon trayIconFile =
  5936. QIcon(":/res/images/obs_paused_macos.svg");
  5937. trayIconFile.setIsMask(true);
  5938. #else
  5939. QIcon trayIconFile =
  5940. QIcon(":/res/images/obs_paused.png");
  5941. #endif
  5942. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5943. trayIconFile));
  5944. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5945. } else {
  5946. #ifdef __APPLE__
  5947. QIcon trayIconFile =
  5948. QIcon(":/res/images/tray_active_macos.svg");
  5949. trayIconFile.setIsMask(true);
  5950. #else
  5951. QIcon trayIconFile =
  5952. QIcon(":/res/images/tray_active.png");
  5953. #endif
  5954. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5955. trayIconFile));
  5956. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5957. }
  5958. }
  5959. }
  5960. void OBSBasic::StopStreaming()
  5961. {
  5962. SaveProject();
  5963. if (outputHandler->StreamingActive())
  5964. outputHandler->StopStreaming(streamingStopping);
  5965. // special case: force reset broadcast state if
  5966. // no autostart and no autostop selected
  5967. if (!autoStartBroadcast && !broadcastActive) {
  5968. broadcastActive = false;
  5969. autoStartBroadcast = true;
  5970. autoStopBroadcast = true;
  5971. broadcastReady = false;
  5972. }
  5973. if (autoStopBroadcast) {
  5974. broadcastActive = false;
  5975. broadcastReady = false;
  5976. }
  5977. OnDeactivate();
  5978. bool recordWhenStreaming = config_get_bool(
  5979. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5980. bool keepRecordingWhenStreamStops =
  5981. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5982. "KeepRecordingWhenStreamStops");
  5983. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5984. StopRecording();
  5985. bool replayBufferWhileStreaming = config_get_bool(
  5986. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5987. bool keepReplayBufferStreamStops =
  5988. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5989. "KeepReplayBufferStreamStops");
  5990. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5991. StopReplayBuffer();
  5992. }
  5993. void OBSBasic::ForceStopStreaming()
  5994. {
  5995. SaveProject();
  5996. if (outputHandler->StreamingActive())
  5997. outputHandler->StopStreaming(true);
  5998. // special case: force reset broadcast state if
  5999. // no autostart and no autostop selected
  6000. if (!autoStartBroadcast && !broadcastActive) {
  6001. broadcastActive = false;
  6002. autoStartBroadcast = true;
  6003. autoStopBroadcast = true;
  6004. broadcastReady = false;
  6005. }
  6006. if (autoStopBroadcast) {
  6007. broadcastActive = false;
  6008. broadcastReady = false;
  6009. }
  6010. OnDeactivate();
  6011. bool recordWhenStreaming = config_get_bool(
  6012. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6013. bool keepRecordingWhenStreamStops =
  6014. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6015. "KeepRecordingWhenStreamStops");
  6016. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6017. StopRecording();
  6018. bool replayBufferWhileStreaming = config_get_bool(
  6019. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6020. bool keepReplayBufferStreamStops =
  6021. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6022. "KeepReplayBufferStreamStops");
  6023. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6024. StopReplayBuffer();
  6025. }
  6026. void OBSBasic::StreamDelayStarting(int sec)
  6027. {
  6028. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6029. ui->streamButton->setEnabled(true);
  6030. ui->streamButton->setChecked(true);
  6031. if (sysTrayStream) {
  6032. sysTrayStream->setText(ui->streamButton->text());
  6033. sysTrayStream->setEnabled(true);
  6034. }
  6035. if (!startStreamMenu.isNull())
  6036. startStreamMenu->deleteLater();
  6037. startStreamMenu = new QMenu();
  6038. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  6039. &OBSBasic::StopStreaming);
  6040. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6041. &OBSBasic::ForceStopStreaming);
  6042. ui->streamButton->setMenu(startStreamMenu);
  6043. ui->statusbar->StreamDelayStarting(sec);
  6044. OnActivate();
  6045. }
  6046. void OBSBasic::StreamDelayStopping(int sec)
  6047. {
  6048. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6049. ui->streamButton->setEnabled(true);
  6050. ui->streamButton->setChecked(false);
  6051. if (sysTrayStream) {
  6052. sysTrayStream->setText(ui->streamButton->text());
  6053. sysTrayStream->setEnabled(true);
  6054. }
  6055. if (!startStreamMenu.isNull())
  6056. startStreamMenu->deleteLater();
  6057. startStreamMenu = new QMenu();
  6058. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  6059. &OBSBasic::StartStreaming);
  6060. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6061. &OBSBasic::ForceStopStreaming);
  6062. ui->streamButton->setMenu(startStreamMenu);
  6063. ui->statusbar->StreamDelayStopping(sec);
  6064. if (api)
  6065. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6066. }
  6067. void OBSBasic::StreamingStart()
  6068. {
  6069. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6070. ui->streamButton->setEnabled(true);
  6071. ui->streamButton->setChecked(true);
  6072. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  6073. if (sysTrayStream) {
  6074. sysTrayStream->setText(ui->streamButton->text());
  6075. sysTrayStream->setEnabled(true);
  6076. }
  6077. #ifdef YOUTUBE_ENABLED
  6078. if (!autoStartBroadcast) {
  6079. // get a current stream key
  6080. obs_service_t *service_obj = GetService();
  6081. OBSDataAutoRelease settings =
  6082. obs_service_get_settings(service_obj);
  6083. std::string key = obs_data_get_string(settings, "stream_id");
  6084. if (!key.empty() && !youtubeStreamCheckThread) {
  6085. youtubeStreamCheckThread = CreateQThread(
  6086. [this, key] { YoutubeStreamCheck(key); });
  6087. youtubeStreamCheckThread->setObjectName(
  6088. "YouTubeStreamCheckThread");
  6089. youtubeStreamCheckThread->start();
  6090. }
  6091. }
  6092. #endif
  6093. if (api)
  6094. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  6095. OnActivate();
  6096. #ifdef YOUTUBE_ENABLED
  6097. if (YouTubeAppDock::IsYTServiceSelected())
  6098. youtubeAppDock->IngestionStarted();
  6099. #endif
  6100. blog(LOG_INFO, STREAMING_START);
  6101. }
  6102. void OBSBasic::StreamStopping()
  6103. {
  6104. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  6105. if (sysTrayStream)
  6106. sysTrayStream->setText(ui->streamButton->text());
  6107. streamingStopping = true;
  6108. if (api)
  6109. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6110. }
  6111. void OBSBasic::StreamingStop(int code, QString last_error)
  6112. {
  6113. const char *errorDescription = "";
  6114. DStr errorMessage;
  6115. bool use_last_error = false;
  6116. bool encode_error = false;
  6117. switch (code) {
  6118. case OBS_OUTPUT_BAD_PATH:
  6119. errorDescription = Str("Output.ConnectFail.BadPath");
  6120. break;
  6121. case OBS_OUTPUT_CONNECT_FAILED:
  6122. use_last_error = true;
  6123. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  6124. break;
  6125. case OBS_OUTPUT_INVALID_STREAM:
  6126. errorDescription = Str("Output.ConnectFail.InvalidStream");
  6127. break;
  6128. case OBS_OUTPUT_ENCODE_ERROR:
  6129. encode_error = true;
  6130. break;
  6131. case OBS_OUTPUT_HDR_DISABLED:
  6132. errorDescription = Str("Output.ConnectFail.HdrDisabled");
  6133. break;
  6134. default:
  6135. case OBS_OUTPUT_ERROR:
  6136. use_last_error = true;
  6137. errorDescription = Str("Output.ConnectFail.Error");
  6138. break;
  6139. case OBS_OUTPUT_DISCONNECTED:
  6140. /* doesn't happen if output is set to reconnect. note that
  6141. * reconnects are handled in the output, not in the UI */
  6142. use_last_error = true;
  6143. errorDescription = Str("Output.ConnectFail.Disconnected");
  6144. }
  6145. if (use_last_error && !last_error.isEmpty())
  6146. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6147. QT_TO_UTF8(last_error));
  6148. else
  6149. dstr_copy(errorMessage, errorDescription);
  6150. ui->statusbar->StreamStopped();
  6151. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6152. ui->streamButton->setEnabled(true);
  6153. ui->streamButton->setChecked(false);
  6154. if (sysTrayStream) {
  6155. sysTrayStream->setText(ui->streamButton->text());
  6156. sysTrayStream->setEnabled(true);
  6157. }
  6158. streamingStopping = false;
  6159. if (api)
  6160. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  6161. OnDeactivate();
  6162. #ifdef YOUTUBE_ENABLED
  6163. if (YouTubeAppDock::IsYTServiceSelected())
  6164. youtubeAppDock->IngestionStopped();
  6165. #endif
  6166. blog(LOG_INFO, STREAMING_STOP);
  6167. if (encode_error) {
  6168. QString msg =
  6169. last_error.isEmpty()
  6170. ? QTStr("Output.StreamEncodeError.Msg")
  6171. : QTStr("Output.StreamEncodeError.Msg.LastError")
  6172. .arg(last_error);
  6173. OBSMessageBox::information(
  6174. this, QTStr("Output.StreamEncodeError.Title"), msg);
  6175. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6176. OBSMessageBox::information(this,
  6177. QTStr("Output.ConnectFail.Title"),
  6178. QT_UTF8(errorMessage));
  6179. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6180. SysTrayNotify(QT_UTF8(errorDescription),
  6181. QSystemTrayIcon::Warning);
  6182. }
  6183. if (!startStreamMenu.isNull()) {
  6184. ui->streamButton->setMenu(nullptr);
  6185. startStreamMenu->deleteLater();
  6186. startStreamMenu = nullptr;
  6187. }
  6188. // Reset broadcast button state/text
  6189. if (!broadcastActive)
  6190. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  6191. }
  6192. void OBSBasic::AutoRemux(QString input, bool no_show)
  6193. {
  6194. auto config = Config();
  6195. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  6196. if (!autoRemux)
  6197. return;
  6198. bool isSimpleMode = false;
  6199. const char *mode = config_get_string(config, "Output", "Mode");
  6200. if (!mode) {
  6201. isSimpleMode = true;
  6202. } else {
  6203. isSimpleMode = strcmp(mode, "Simple") == 0;
  6204. }
  6205. if (!isSimpleMode) {
  6206. const char *recType =
  6207. config_get_string(config, "AdvOut", "RecType");
  6208. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  6209. if (ffmpegOutput)
  6210. return;
  6211. }
  6212. if (input.isEmpty())
  6213. return;
  6214. QFileInfo fi(input);
  6215. QString suffix = fi.suffix();
  6216. /* do not remux if lossless */
  6217. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  6218. return;
  6219. }
  6220. QString path = fi.path();
  6221. QString output = input;
  6222. output.resize(output.size() - suffix.size());
  6223. const obs_encoder_t *videoEncoder =
  6224. obs_output_get_video_encoder(outputHandler->fileOutput);
  6225. const obs_encoder_t *audioEncoder =
  6226. obs_output_get_audio_encoder(outputHandler->fileOutput, 0);
  6227. const char *vCodecName = obs_encoder_get_codec(videoEncoder);
  6228. const char *aCodecName = obs_encoder_get_codec(audioEncoder);
  6229. const char *format = config_get_string(
  6230. config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2");
  6231. bool audio_is_pcm = strncmp(aCodecName, "pcm", 3) == 0;
  6232. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6233. /* FFmpeg <= 6.0 cannot remux AV1+PCM into any supported format. */
  6234. if (audio_is_pcm && strcmp(vCodecName, "av1") == 0)
  6235. return;
  6236. #endif
  6237. /* Retain original container for fMP4/fMOV */
  6238. if (strncmp(format, "fragmented", 10) == 0) {
  6239. output += "remuxed." + suffix;
  6240. } else if (strcmp(vCodecName, "prores") == 0) {
  6241. output += "mov";
  6242. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6243. } else if (audio_is_pcm) {
  6244. output += "mov";
  6245. #endif
  6246. } else {
  6247. output += "mp4";
  6248. }
  6249. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  6250. if (!no_show)
  6251. remux->show();
  6252. remux->AutoRemux(input, output);
  6253. }
  6254. void OBSBasic::StartRecording()
  6255. {
  6256. if (outputHandler->RecordingActive())
  6257. return;
  6258. if (disableOutputsRef)
  6259. return;
  6260. if (!OutputPathValid()) {
  6261. OutputPathInvalidMessage();
  6262. ui->recordButton->setChecked(false);
  6263. return;
  6264. }
  6265. if (LowDiskSpace()) {
  6266. DiskSpaceMessage();
  6267. ui->recordButton->setChecked(false);
  6268. return;
  6269. }
  6270. if (api)
  6271. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  6272. SaveProject();
  6273. if (!outputHandler->StartRecording())
  6274. ui->recordButton->setChecked(false);
  6275. }
  6276. void OBSBasic::RecordStopping()
  6277. {
  6278. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  6279. if (sysTrayRecord)
  6280. sysTrayRecord->setText(ui->recordButton->text());
  6281. recordingStopping = true;
  6282. if (api)
  6283. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  6284. }
  6285. void OBSBasic::StopRecording()
  6286. {
  6287. SaveProject();
  6288. if (outputHandler->RecordingActive())
  6289. outputHandler->StopRecording(recordingStopping);
  6290. OnDeactivate();
  6291. }
  6292. void OBSBasic::RecordingStart()
  6293. {
  6294. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  6295. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  6296. ui->recordButton->setChecked(true);
  6297. if (sysTrayRecord)
  6298. sysTrayRecord->setText(ui->recordButton->text());
  6299. recordingStopping = false;
  6300. if (api)
  6301. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  6302. if (!diskFullTimer->isActive())
  6303. diskFullTimer->start(1000);
  6304. OnActivate();
  6305. UpdatePause();
  6306. blog(LOG_INFO, RECORDING_START);
  6307. }
  6308. void OBSBasic::RecordingStop(int code, QString last_error)
  6309. {
  6310. ui->statusbar->RecordingStopped();
  6311. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  6312. ui->recordButton->setChecked(false);
  6313. if (sysTrayRecord)
  6314. sysTrayRecord->setText(ui->recordButton->text());
  6315. blog(LOG_INFO, RECORDING_STOP);
  6316. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6317. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6318. QTStr("Output.RecordFail.Unsupported"));
  6319. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  6320. QString msg =
  6321. last_error.isEmpty()
  6322. ? QTStr("Output.RecordError.EncodeErrorMsg")
  6323. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  6324. .arg(last_error);
  6325. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  6326. msg);
  6327. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6328. OBSMessageBox::warning(this,
  6329. QTStr("Output.RecordNoSpace.Title"),
  6330. QTStr("Output.RecordNoSpace.Msg"));
  6331. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6332. const char *errorDescription;
  6333. DStr errorMessage;
  6334. bool use_last_error = true;
  6335. errorDescription = Str("Output.RecordError.Msg");
  6336. if (use_last_error && !last_error.isEmpty())
  6337. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6338. QT_TO_UTF8(last_error));
  6339. else
  6340. dstr_copy(errorMessage, errorDescription);
  6341. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6342. QT_UTF8(errorMessage));
  6343. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6344. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6345. QSystemTrayIcon::Warning);
  6346. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6347. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6348. QSystemTrayIcon::Warning);
  6349. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6350. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6351. QSystemTrayIcon::Warning);
  6352. } else if (code == OBS_OUTPUT_SUCCESS) {
  6353. if (outputHandler) {
  6354. std::string path = outputHandler->lastRecordingPath;
  6355. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6356. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  6357. }
  6358. }
  6359. if (api)
  6360. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  6361. if (diskFullTimer->isActive())
  6362. diskFullTimer->stop();
  6363. AutoRemux(outputHandler->lastRecordingPath.c_str());
  6364. OnDeactivate();
  6365. UpdatePause(false);
  6366. }
  6367. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  6368. {
  6369. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6370. ShowStatusBarMessage(str.arg(lastRecordingPath));
  6371. AutoRemux(lastRecordingPath, true);
  6372. }
  6373. void OBSBasic::ShowReplayBufferPauseWarning()
  6374. {
  6375. auto msgBox = []() {
  6376. QMessageBox msgbox(App()->GetMainWindow());
  6377. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  6378. "PauseWarning.Title"));
  6379. msgbox.setText(QTStr("Output.ReplayBuffer."
  6380. "PauseWarning.Text"));
  6381. msgbox.setIcon(QMessageBox::Icon::Information);
  6382. msgbox.addButton(QMessageBox::Ok);
  6383. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  6384. msgbox.setCheckBox(cb);
  6385. msgbox.exec();
  6386. if (cb->isChecked()) {
  6387. config_set_bool(App()->GlobalConfig(), "General",
  6388. "WarnedAboutReplayBufferPausing", true);
  6389. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  6390. }
  6391. };
  6392. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  6393. "WarnedAboutReplayBufferPausing");
  6394. if (!warned) {
  6395. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  6396. Q_ARG(VoidFunc, msgBox));
  6397. }
  6398. }
  6399. void OBSBasic::StartReplayBuffer()
  6400. {
  6401. if (!outputHandler || !outputHandler->replayBuffer)
  6402. return;
  6403. if (outputHandler->ReplayBufferActive())
  6404. return;
  6405. if (disableOutputsRef)
  6406. return;
  6407. if (!UIValidation::NoSourcesConfirmation(this)) {
  6408. replayBufferButton->first()->setChecked(false);
  6409. return;
  6410. }
  6411. if (!OutputPathValid()) {
  6412. OutputPathInvalidMessage();
  6413. replayBufferButton->first()->setChecked(false);
  6414. return;
  6415. }
  6416. if (LowDiskSpace()) {
  6417. DiskSpaceMessage();
  6418. replayBufferButton->first()->setChecked(false);
  6419. return;
  6420. }
  6421. if (api)
  6422. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6423. SaveProject();
  6424. if (!outputHandler->StartReplayBuffer()) {
  6425. replayBufferButton->first()->setChecked(false);
  6426. } else if (os_atomic_load_bool(&recording_paused)) {
  6427. ShowReplayBufferPauseWarning();
  6428. }
  6429. }
  6430. void OBSBasic::ReplayBufferStopping()
  6431. {
  6432. if (!outputHandler || !outputHandler->replayBuffer)
  6433. return;
  6434. replayBufferButton->first()->setText(
  6435. QTStr("Basic.Main.StoppingReplayBuffer"));
  6436. if (sysTrayReplayBuffer)
  6437. sysTrayReplayBuffer->setText(
  6438. replayBufferButton->first()->text());
  6439. replayBufferStopping = true;
  6440. if (api)
  6441. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6442. }
  6443. void OBSBasic::StopReplayBuffer()
  6444. {
  6445. if (!outputHandler || !outputHandler->replayBuffer)
  6446. return;
  6447. SaveProject();
  6448. if (outputHandler->ReplayBufferActive())
  6449. outputHandler->StopReplayBuffer(replayBufferStopping);
  6450. OnDeactivate();
  6451. }
  6452. void OBSBasic::ReplayBufferStart()
  6453. {
  6454. if (!outputHandler || !outputHandler->replayBuffer)
  6455. return;
  6456. replayBufferButton->first()->setText(
  6457. QTStr("Basic.Main.StopReplayBuffer"));
  6458. replayBufferButton->first()->setChecked(true);
  6459. if (sysTrayReplayBuffer)
  6460. sysTrayReplayBuffer->setText(
  6461. replayBufferButton->first()->text());
  6462. replayBufferStopping = false;
  6463. if (api)
  6464. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6465. OnActivate();
  6466. UpdateReplayBuffer();
  6467. blog(LOG_INFO, REPLAY_BUFFER_START);
  6468. }
  6469. void OBSBasic::ReplayBufferSave()
  6470. {
  6471. if (!outputHandler || !outputHandler->replayBuffer)
  6472. return;
  6473. if (!outputHandler->ReplayBufferActive())
  6474. return;
  6475. calldata_t cd = {0};
  6476. proc_handler_t *ph =
  6477. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6478. proc_handler_call(ph, "save", &cd);
  6479. calldata_free(&cd);
  6480. }
  6481. void OBSBasic::ReplayBufferSaved()
  6482. {
  6483. if (!outputHandler || !outputHandler->replayBuffer)
  6484. return;
  6485. if (!outputHandler->ReplayBufferActive())
  6486. return;
  6487. calldata_t cd = {0};
  6488. proc_handler_t *ph =
  6489. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6490. proc_handler_call(ph, "get_last_replay", &cd);
  6491. std::string path = calldata_string(&cd, "path");
  6492. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo")
  6493. .arg(QT_UTF8(path.c_str()));
  6494. ShowStatusBarMessage(msg);
  6495. lastReplay = path;
  6496. calldata_free(&cd);
  6497. if (api)
  6498. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6499. AutoRemux(QT_UTF8(path.c_str()));
  6500. }
  6501. void OBSBasic::ReplayBufferStop(int code)
  6502. {
  6503. if (!outputHandler || !outputHandler->replayBuffer)
  6504. return;
  6505. replayBufferButton->first()->setText(
  6506. QTStr("Basic.Main.StartReplayBuffer"));
  6507. replayBufferButton->first()->setChecked(false);
  6508. if (sysTrayReplayBuffer)
  6509. sysTrayReplayBuffer->setText(
  6510. replayBufferButton->first()->text());
  6511. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6512. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6513. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6514. QTStr("Output.RecordFail.Unsupported"));
  6515. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6516. OBSMessageBox::warning(this,
  6517. QTStr("Output.RecordNoSpace.Title"),
  6518. QTStr("Output.RecordNoSpace.Msg"));
  6519. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6520. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6521. QTStr("Output.RecordError.Msg"));
  6522. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6523. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6524. QSystemTrayIcon::Warning);
  6525. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6526. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6527. QSystemTrayIcon::Warning);
  6528. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6529. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6530. QSystemTrayIcon::Warning);
  6531. }
  6532. if (api)
  6533. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6534. OnDeactivate();
  6535. UpdateReplayBuffer(false);
  6536. }
  6537. void OBSBasic::StartVirtualCam()
  6538. {
  6539. if (!outputHandler || !outputHandler->virtualCam)
  6540. return;
  6541. if (outputHandler->VirtualCamActive())
  6542. return;
  6543. if (disableOutputsRef)
  6544. return;
  6545. SaveProject();
  6546. if (!outputHandler->StartVirtualCam()) {
  6547. vcamButton->first()->setChecked(false);
  6548. }
  6549. }
  6550. void OBSBasic::StopVirtualCam()
  6551. {
  6552. if (!outputHandler || !outputHandler->virtualCam)
  6553. return;
  6554. SaveProject();
  6555. if (outputHandler->VirtualCamActive())
  6556. outputHandler->StopVirtualCam();
  6557. OnDeactivate();
  6558. }
  6559. void OBSBasic::OnVirtualCamStart()
  6560. {
  6561. if (!outputHandler || !outputHandler->virtualCam)
  6562. return;
  6563. vcamButton->first()->setText(QTStr("Basic.Main.StopVirtualCam"));
  6564. if (sysTrayVirtualCam)
  6565. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6566. vcamButton->first()->setChecked(true);
  6567. if (api)
  6568. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6569. OnActivate();
  6570. blog(LOG_INFO, VIRTUAL_CAM_START);
  6571. }
  6572. void OBSBasic::OnVirtualCamStop(int)
  6573. {
  6574. if (!outputHandler || !outputHandler->virtualCam)
  6575. return;
  6576. vcamButton->first()->setText(QTStr("Basic.Main.StartVirtualCam"));
  6577. if (sysTrayVirtualCam)
  6578. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6579. vcamButton->first()->setChecked(false);
  6580. if (api)
  6581. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6582. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6583. OnDeactivate();
  6584. if (!restartingVCam)
  6585. return;
  6586. /* Restarting needs to be delayed to make sure that the virtual camera
  6587. * implementation is stopped and avoid race condition. */
  6588. QTimer::singleShot(100, this, &OBSBasic::RestartingVirtualCam);
  6589. }
  6590. void OBSBasic::on_streamButton_clicked()
  6591. {
  6592. if (outputHandler->StreamingActive()) {
  6593. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6594. "WarnBeforeStoppingStream");
  6595. #ifdef YOUTUBE_ENABLED
  6596. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6597. autoStopBroadcast) {
  6598. QMessageBox::StandardButton button = OBSMessageBox::question(
  6599. this, QTStr("ConfirmStop.Title"),
  6600. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6601. QMessageBox::Yes | QMessageBox::No,
  6602. QMessageBox::No);
  6603. if (button == QMessageBox::No) {
  6604. ui->streamButton->setChecked(true);
  6605. return;
  6606. }
  6607. confirm = false;
  6608. }
  6609. #endif
  6610. if (confirm && isVisible()) {
  6611. QMessageBox::StandardButton button =
  6612. OBSMessageBox::question(
  6613. this, QTStr("ConfirmStop.Title"),
  6614. QTStr("ConfirmStop.Text"),
  6615. QMessageBox::Yes | QMessageBox::No,
  6616. QMessageBox::No);
  6617. if (button == QMessageBox::No) {
  6618. ui->streamButton->setChecked(true);
  6619. return;
  6620. }
  6621. }
  6622. StopStreaming();
  6623. } else {
  6624. if (!UIValidation::NoSourcesConfirmation(this)) {
  6625. ui->streamButton->setChecked(false);
  6626. return;
  6627. }
  6628. Auth *auth = GetAuth();
  6629. auto action =
  6630. (auth && auth->external())
  6631. ? StreamSettingsAction::ContinueStream
  6632. : UIValidation::StreamSettingsConfirmation(
  6633. this, service);
  6634. switch (action) {
  6635. case StreamSettingsAction::ContinueStream:
  6636. break;
  6637. case StreamSettingsAction::OpenSettings:
  6638. on_action_Settings_triggered();
  6639. ui->streamButton->setChecked(false);
  6640. return;
  6641. case StreamSettingsAction::Cancel:
  6642. ui->streamButton->setChecked(false);
  6643. return;
  6644. }
  6645. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6646. "WarnBeforeStartingStream");
  6647. bool bwtest = false;
  6648. if (this->auth) {
  6649. OBSDataAutoRelease settings =
  6650. obs_service_get_settings(service);
  6651. bwtest = obs_data_get_bool(settings, "bwtest");
  6652. // Disable confirmation if this is going to open broadcast setup
  6653. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6654. !broadcastActive)
  6655. confirm = false;
  6656. }
  6657. if (bwtest && isVisible()) {
  6658. QMessageBox::StandardButton button =
  6659. OBSMessageBox::question(
  6660. this, QTStr("ConfirmBWTest.Title"),
  6661. QTStr("ConfirmBWTest.Text"));
  6662. if (button == QMessageBox::No) {
  6663. ui->streamButton->setChecked(false);
  6664. return;
  6665. }
  6666. } else if (confirm && isVisible()) {
  6667. QMessageBox::StandardButton button =
  6668. OBSMessageBox::question(
  6669. this, QTStr("ConfirmStart.Title"),
  6670. QTStr("ConfirmStart.Text"),
  6671. QMessageBox::Yes | QMessageBox::No,
  6672. QMessageBox::No);
  6673. if (button == QMessageBox::No) {
  6674. ui->streamButton->setChecked(false);
  6675. return;
  6676. }
  6677. }
  6678. StartStreaming();
  6679. }
  6680. }
  6681. void OBSBasic::on_recordButton_clicked()
  6682. {
  6683. if (outputHandler->RecordingActive()) {
  6684. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6685. "WarnBeforeStoppingRecord");
  6686. if (confirm && isVisible()) {
  6687. QMessageBox::StandardButton button =
  6688. OBSMessageBox::question(
  6689. this, QTStr("ConfirmStopRecord.Title"),
  6690. QTStr("ConfirmStopRecord.Text"),
  6691. QMessageBox::Yes | QMessageBox::No,
  6692. QMessageBox::No);
  6693. if (button == QMessageBox::No) {
  6694. ui->recordButton->setChecked(true);
  6695. return;
  6696. }
  6697. }
  6698. StopRecording();
  6699. } else {
  6700. if (!UIValidation::NoSourcesConfirmation(this)) {
  6701. ui->recordButton->setChecked(false);
  6702. return;
  6703. }
  6704. StartRecording();
  6705. }
  6706. }
  6707. void OBSBasic::VCamButtonClicked()
  6708. {
  6709. if (outputHandler->VirtualCamActive()) {
  6710. StopVirtualCam();
  6711. } else {
  6712. if (!UIValidation::NoSourcesConfirmation(this)) {
  6713. vcamButton->first()->setChecked(false);
  6714. return;
  6715. }
  6716. StartVirtualCam();
  6717. }
  6718. }
  6719. void OBSBasic::VCamConfigButtonClicked()
  6720. {
  6721. OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(),
  6722. this);
  6723. connect(&dialog, &OBSBasicVCamConfig::Accepted, this,
  6724. &OBSBasic::UpdateVirtualCamConfig);
  6725. connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this,
  6726. &OBSBasic::RestartVirtualCam);
  6727. dialog.exec();
  6728. }
  6729. void OBSBasic::UpdateVirtualCamConfig(const VCamConfig &config)
  6730. {
  6731. vcamConfig = config;
  6732. outputHandler->UpdateVirtualCamOutputSource();
  6733. }
  6734. void OBSBasic::RestartVirtualCam(const VCamConfig &config)
  6735. {
  6736. restartingVCam = true;
  6737. StopVirtualCam();
  6738. vcamConfig = config;
  6739. }
  6740. void OBSBasic::RestartingVirtualCam()
  6741. {
  6742. if (!restartingVCam)
  6743. return;
  6744. outputHandler->UpdateVirtualCamOutputSource();
  6745. StartVirtualCam();
  6746. restartingVCam = false;
  6747. }
  6748. void OBSBasic::on_settingsButton_clicked()
  6749. {
  6750. on_action_Settings_triggered();
  6751. }
  6752. void OBSBasic::on_actionHelpPortal_triggered()
  6753. {
  6754. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6755. QDesktopServices::openUrl(url);
  6756. }
  6757. void OBSBasic::on_actionWebsite_triggered()
  6758. {
  6759. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6760. QDesktopServices::openUrl(url);
  6761. }
  6762. void OBSBasic::on_actionDiscord_triggered()
  6763. {
  6764. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6765. QDesktopServices::openUrl(url);
  6766. }
  6767. void OBSBasic::on_actionShowWhatsNew_triggered()
  6768. {
  6769. #ifdef WHATSNEW_ENABLED
  6770. if (introCheckThread && introCheckThread->isRunning())
  6771. return;
  6772. if (!cef)
  6773. return;
  6774. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement", -1);
  6775. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  6776. connect(wnit, &WhatsNewInfoThread::Result, this,
  6777. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  6778. introCheckThread.reset(wnit);
  6779. introCheckThread->start();
  6780. #endif
  6781. }
  6782. void OBSBasic::on_actionReleaseNotes_triggered()
  6783. {
  6784. QString addr("https://github.com/obsproject/obs-studio/releases");
  6785. QUrl url(QString("%1/%2").arg(addr, obs_get_version_string()),
  6786. QUrl::TolerantMode);
  6787. QDesktopServices::openUrl(url);
  6788. }
  6789. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6790. {
  6791. char path[512];
  6792. int ret = GetConfigPath(path, 512, "obs-studio");
  6793. if (ret <= 0)
  6794. return;
  6795. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6796. }
  6797. void OBSBasic::on_actionShowProfileFolder_triggered()
  6798. {
  6799. char path[512];
  6800. int ret = GetProfilePath(path, 512, "");
  6801. if (ret <= 0)
  6802. return;
  6803. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6804. }
  6805. int OBSBasic::GetTopSelectedSourceItem()
  6806. {
  6807. QModelIndexList selectedItems =
  6808. ui->sources->selectionModel()->selectedIndexes();
  6809. return selectedItems.count() ? selectedItems[0].row() : -1;
  6810. }
  6811. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6812. {
  6813. return ui->sources->selectionModel()->selectedIndexes();
  6814. }
  6815. void OBSBasic::on_preview_customContextMenuRequested()
  6816. {
  6817. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6818. }
  6819. void OBSBasic::ProgramViewContextMenuRequested()
  6820. {
  6821. QMenu popup(this);
  6822. QPointer<QMenu> studioProgramProjector;
  6823. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6824. AddProjectorMenuMonitors(studioProgramProjector, this,
  6825. &OBSBasic::OpenStudioProgramProjector);
  6826. popup.addMenu(studioProgramProjector);
  6827. QAction *studioProgramWindow =
  6828. popup.addAction(QTStr("StudioProgramWindow"), this,
  6829. &OBSBasic::OpenStudioProgramWindow);
  6830. popup.addAction(studioProgramWindow);
  6831. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6832. &OBSBasic::ScreenshotProgram);
  6833. popup.exec(QCursor::pos());
  6834. }
  6835. void OBSBasic::on_previewDisabledWidget_customContextMenuRequested()
  6836. {
  6837. QMenu popup(this);
  6838. delete previewProjectorMain;
  6839. QAction *action =
  6840. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6841. this, &OBSBasic::TogglePreview);
  6842. action->setCheckable(true);
  6843. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6844. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6845. AddProjectorMenuMonitors(previewProjectorMain, this,
  6846. &OBSBasic::OpenPreviewProjector);
  6847. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6848. &OBSBasic::OpenPreviewWindow);
  6849. popup.addMenu(previewProjectorMain);
  6850. popup.addAction(previewWindow);
  6851. popup.exec(QCursor::pos());
  6852. }
  6853. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6854. {
  6855. #ifndef _WIN32
  6856. /* Make sure all dialogs are safely and successfully closed before
  6857. * switching the always on top mode due to the fact that windows all
  6858. * have to be recreated, so queue the actual toggle to happen after
  6859. * all events related to closing the dialogs have finished */
  6860. CloseDialogs();
  6861. #endif
  6862. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6863. Qt::QueuedConnection);
  6864. }
  6865. void OBSBasic::ToggleAlwaysOnTop()
  6866. {
  6867. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6868. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6869. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6870. show();
  6871. }
  6872. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6873. {
  6874. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6875. if (strcmp(val, "10") == 0) {
  6876. num = 10;
  6877. den = 1;
  6878. } else if (strcmp(val, "20") == 0) {
  6879. num = 20;
  6880. den = 1;
  6881. } else if (strcmp(val, "24 NTSC") == 0) {
  6882. num = 24000;
  6883. den = 1001;
  6884. } else if (strcmp(val, "25 PAL") == 0) {
  6885. num = 25;
  6886. den = 1;
  6887. } else if (strcmp(val, "29.97") == 0) {
  6888. num = 30000;
  6889. den = 1001;
  6890. } else if (strcmp(val, "48") == 0) {
  6891. num = 48;
  6892. den = 1;
  6893. } else if (strcmp(val, "50 PAL") == 0) {
  6894. num = 50;
  6895. den = 1;
  6896. } else if (strcmp(val, "59.94") == 0) {
  6897. num = 60000;
  6898. den = 1001;
  6899. } else if (strcmp(val, "60") == 0) {
  6900. num = 60;
  6901. den = 1;
  6902. } else {
  6903. num = 30;
  6904. den = 1;
  6905. }
  6906. }
  6907. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6908. {
  6909. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6910. den = 1;
  6911. }
  6912. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6913. {
  6914. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6915. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6916. }
  6917. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6918. {
  6919. num = 1000000000;
  6920. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6921. }
  6922. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6923. {
  6924. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6925. if (type == 1) //"Integer"
  6926. GetFPSInteger(num, den);
  6927. else if (type == 2) //"Fraction"
  6928. GetFPSFraction(num, den);
  6929. /*
  6930. * else if (false) //"Nanoseconds", currently not implemented
  6931. * GetFPSNanoseconds(num, den);
  6932. */
  6933. else
  6934. GetFPSCommon(num, den);
  6935. }
  6936. config_t *OBSBasic::Config() const
  6937. {
  6938. return basicConfig;
  6939. }
  6940. #ifdef YOUTUBE_ENABLED
  6941. YouTubeAppDock *OBSBasic::GetYouTubeAppDock()
  6942. {
  6943. return youtubeAppDock;
  6944. }
  6945. void OBSBasic::NewYouTubeAppDock()
  6946. {
  6947. if (!cef_js_avail)
  6948. return;
  6949. if (youtubeAppDock)
  6950. RemoveDockWidget(youtubeAppDock->objectName());
  6951. youtubeAppDock = new YouTubeAppDock("YouTube Live Control Panel");
  6952. }
  6953. void OBSBasic::DeleteYouTubeAppDock()
  6954. {
  6955. if (!cef_js_avail)
  6956. return;
  6957. if (youtubeAppDock)
  6958. RemoveDockWidget(youtubeAppDock->objectName());
  6959. youtubeAppDock = nullptr;
  6960. }
  6961. #endif
  6962. void OBSBasic::UpdateEditMenu()
  6963. {
  6964. QModelIndexList items = GetAllSelectedSourceItems();
  6965. int totalCount = items.count();
  6966. size_t filter_count = 0;
  6967. if (totalCount == 1) {
  6968. OBSSceneItem sceneItem =
  6969. ui->sources->Get(GetTopSelectedSourceItem());
  6970. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6971. filter_count = obs_source_filter_count(source);
  6972. }
  6973. bool allowPastingDuplicate = !!clipboard.size();
  6974. for (size_t i = clipboard.size(); i > 0; i--) {
  6975. const size_t idx = i - 1;
  6976. OBSWeakSource &weak = clipboard[idx].weak_source;
  6977. if (obs_weak_source_expired(weak)) {
  6978. clipboard.erase(clipboard.begin() + idx);
  6979. continue;
  6980. }
  6981. OBSSourceAutoRelease strong =
  6982. obs_weak_source_get_source(weak.Get());
  6983. if (allowPastingDuplicate &&
  6984. obs_source_get_output_flags(strong) &
  6985. OBS_SOURCE_DO_NOT_DUPLICATE)
  6986. allowPastingDuplicate = false;
  6987. }
  6988. int videoCount = 0;
  6989. bool canTransformMultiple = false;
  6990. for (int i = 0; i < totalCount; i++) {
  6991. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6992. OBSSource source = obs_sceneitem_get_source(item);
  6993. const uint32_t flags = obs_source_get_output_flags(source);
  6994. const bool hasVideo = (flags & OBS_SOURCE_VIDEO) != 0;
  6995. if (hasVideo && !obs_sceneitem_locked(item))
  6996. canTransformMultiple = true;
  6997. if (hasVideo)
  6998. videoCount++;
  6999. }
  7000. const bool canTransformSingle = videoCount == 1 && totalCount == 1;
  7001. ui->actionCopySource->setEnabled(totalCount > 0);
  7002. ui->actionEditTransform->setEnabled(canTransformSingle);
  7003. ui->actionCopyTransform->setEnabled(canTransformSingle);
  7004. ui->actionPasteTransform->setEnabled(hasCopiedTransform &&
  7005. videoCount > 0);
  7006. ui->actionCopyFilters->setEnabled(filter_count > 0);
  7007. ui->actionPasteFilters->setEnabled(
  7008. !obs_weak_source_expired(copyFiltersSource) && totalCount > 0);
  7009. ui->actionPasteRef->setEnabled(!!clipboard.size());
  7010. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  7011. ui->actionMoveUp->setEnabled(totalCount > 0);
  7012. ui->actionMoveDown->setEnabled(totalCount > 0);
  7013. ui->actionMoveToTop->setEnabled(totalCount > 0);
  7014. ui->actionMoveToBottom->setEnabled(totalCount > 0);
  7015. ui->actionResetTransform->setEnabled(canTransformMultiple);
  7016. ui->actionRotate90CW->setEnabled(canTransformMultiple);
  7017. ui->actionRotate90CCW->setEnabled(canTransformMultiple);
  7018. ui->actionRotate180->setEnabled(canTransformMultiple);
  7019. ui->actionFlipHorizontal->setEnabled(canTransformMultiple);
  7020. ui->actionFlipVertical->setEnabled(canTransformMultiple);
  7021. ui->actionFitToScreen->setEnabled(canTransformMultiple);
  7022. ui->actionStretchToScreen->setEnabled(canTransformMultiple);
  7023. ui->actionCenterToScreen->setEnabled(canTransformMultiple);
  7024. ui->actionVerticalCenter->setEnabled(canTransformMultiple);
  7025. ui->actionHorizontalCenter->setEnabled(canTransformMultiple);
  7026. }
  7027. void OBSBasic::on_actionEditTransform_triggered()
  7028. {
  7029. const auto item = GetCurrentSceneItem();
  7030. if (!item)
  7031. return;
  7032. CreateEditTransformWindow(item);
  7033. }
  7034. void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item)
  7035. {
  7036. if (transformWindow)
  7037. transformWindow->close();
  7038. transformWindow = new OBSBasicTransform(item, this);
  7039. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  7040. &OBSBasicTransform::OnSceneChanged);
  7041. transformWindow->show();
  7042. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  7043. }
  7044. void OBSBasic::on_actionCopyTransform_triggered()
  7045. {
  7046. OBSSceneItem item = GetCurrentSceneItem();
  7047. obs_sceneitem_get_info(item, &copiedTransformInfo);
  7048. obs_sceneitem_get_crop(item, &copiedCropInfo);
  7049. ui->actionPasteTransform->setEnabled(true);
  7050. hasCopiedTransform = true;
  7051. }
  7052. void undo_redo(const std::string &data)
  7053. {
  7054. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  7055. OBSSourceAutoRelease source =
  7056. obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid"));
  7057. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  7058. ->SetCurrentScene(source.Get(), true);
  7059. obs_scene_load_transform_states(data.c_str());
  7060. }
  7061. void OBSBasic::on_actionPasteTransform_triggered()
  7062. {
  7063. OBSDataAutoRelease wrapper =
  7064. obs_scene_save_transform_states(GetCurrentScene(), false);
  7065. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  7066. if (!obs_sceneitem_selected(item))
  7067. return true;
  7068. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  7069. obs_sceneitem_defer_update_begin(item);
  7070. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  7071. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  7072. obs_sceneitem_defer_update_end(item);
  7073. return true;
  7074. };
  7075. obs_scene_enum_items(GetCurrentScene(), func, this);
  7076. OBSDataAutoRelease rwrapper =
  7077. obs_scene_save_transform_states(GetCurrentScene(), false);
  7078. std::string undo_data(obs_data_get_json(wrapper));
  7079. std::string redo_data(obs_data_get_json(rwrapper));
  7080. undo_s.add_action(
  7081. QTStr("Undo.Transform.Paste")
  7082. .arg(obs_source_get_name(GetCurrentSceneSource())),
  7083. undo_redo, undo_redo, undo_data, redo_data);
  7084. }
  7085. static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *)
  7086. {
  7087. if (obs_sceneitem_is_group(item))
  7088. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  7089. if (!obs_sceneitem_selected(item))
  7090. return true;
  7091. if (obs_sceneitem_locked(item))
  7092. return true;
  7093. obs_sceneitem_defer_update_begin(item);
  7094. obs_transform_info info;
  7095. vec2_set(&info.pos, 0.0f, 0.0f);
  7096. vec2_set(&info.scale, 1.0f, 1.0f);
  7097. info.rot = 0.0f;
  7098. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  7099. info.bounds_type = OBS_BOUNDS_NONE;
  7100. info.bounds_alignment = OBS_ALIGN_CENTER;
  7101. vec2_set(&info.bounds, 0.0f, 0.0f);
  7102. obs_sceneitem_set_info(item, &info);
  7103. obs_sceneitem_crop crop = {};
  7104. obs_sceneitem_set_crop(item, &crop);
  7105. obs_sceneitem_defer_update_end(item);
  7106. return true;
  7107. }
  7108. void OBSBasic::on_actionResetTransform_triggered()
  7109. {
  7110. OBSScene scene = GetCurrentScene();
  7111. OBSDataAutoRelease wrapper =
  7112. obs_scene_save_transform_states(scene, false);
  7113. obs_scene_enum_items(scene, reset_tr, nullptr);
  7114. OBSDataAutoRelease rwrapper =
  7115. obs_scene_save_transform_states(scene, false);
  7116. std::string undo_data(obs_data_get_json(wrapper));
  7117. std::string redo_data(obs_data_get_json(rwrapper));
  7118. undo_s.add_action(
  7119. QTStr("Undo.Transform.Reset")
  7120. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  7121. undo_redo, undo_redo, undo_data, redo_data);
  7122. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  7123. }
  7124. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  7125. {
  7126. matrix4 boxTransform;
  7127. obs_sceneitem_get_box_transform(item, &boxTransform);
  7128. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  7129. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  7130. auto GetMinPos = [&](float x, float y) {
  7131. vec3 pos;
  7132. vec3_set(&pos, x, y, 0.0f);
  7133. vec3_transform(&pos, &pos, &boxTransform);
  7134. vec3_min(&tl, &tl, &pos);
  7135. vec3_max(&br, &br, &pos);
  7136. };
  7137. GetMinPos(0.0f, 0.0f);
  7138. GetMinPos(1.0f, 0.0f);
  7139. GetMinPos(0.0f, 1.0f);
  7140. GetMinPos(1.0f, 1.0f);
  7141. }
  7142. static vec3 GetItemTL(obs_sceneitem_t *item)
  7143. {
  7144. vec3 tl, br;
  7145. GetItemBox(item, tl, br);
  7146. return tl;
  7147. }
  7148. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  7149. {
  7150. vec3 newTL;
  7151. vec2 pos;
  7152. obs_sceneitem_get_pos(item, &pos);
  7153. newTL = GetItemTL(item);
  7154. pos.x += tl.x - newTL.x;
  7155. pos.y += tl.y - newTL.y;
  7156. obs_sceneitem_set_pos(item, &pos);
  7157. }
  7158. static bool RotateSelectedSources(obs_scene_t * /* scene */,
  7159. obs_sceneitem_t *item, void *param)
  7160. {
  7161. if (obs_sceneitem_is_group(item))
  7162. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  7163. param);
  7164. if (!obs_sceneitem_selected(item))
  7165. return true;
  7166. if (obs_sceneitem_locked(item))
  7167. return true;
  7168. float rot = *reinterpret_cast<float *>(param);
  7169. vec3 tl = GetItemTL(item);
  7170. rot += obs_sceneitem_get_rot(item);
  7171. if (rot >= 360.0f)
  7172. rot -= 360.0f;
  7173. else if (rot <= -360.0f)
  7174. rot += 360.0f;
  7175. obs_sceneitem_set_rot(item, rot);
  7176. obs_sceneitem_force_update_transform(item);
  7177. SetItemTL(item, tl);
  7178. return true;
  7179. };
  7180. void OBSBasic::on_actionRotate90CW_triggered()
  7181. {
  7182. float f90CW = 90.0f;
  7183. OBSDataAutoRelease wrapper =
  7184. obs_scene_save_transform_states(GetCurrentScene(), false);
  7185. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  7186. OBSDataAutoRelease rwrapper =
  7187. obs_scene_save_transform_states(GetCurrentScene(), false);
  7188. std::string undo_data(obs_data_get_json(wrapper));
  7189. std::string redo_data(obs_data_get_json(rwrapper));
  7190. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7191. .arg(obs_source_get_name(obs_scene_get_source(
  7192. GetCurrentScene()))),
  7193. undo_redo, undo_redo, undo_data, redo_data);
  7194. }
  7195. void OBSBasic::on_actionRotate90CCW_triggered()
  7196. {
  7197. float f90CCW = -90.0f;
  7198. OBSDataAutoRelease wrapper =
  7199. obs_scene_save_transform_states(GetCurrentScene(), false);
  7200. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  7201. OBSDataAutoRelease rwrapper =
  7202. obs_scene_save_transform_states(GetCurrentScene(), false);
  7203. std::string undo_data(obs_data_get_json(wrapper));
  7204. std::string redo_data(obs_data_get_json(rwrapper));
  7205. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7206. .arg(obs_source_get_name(obs_scene_get_source(
  7207. GetCurrentScene()))),
  7208. undo_redo, undo_redo, undo_data, redo_data);
  7209. }
  7210. void OBSBasic::on_actionRotate180_triggered()
  7211. {
  7212. float f180 = 180.0f;
  7213. OBSDataAutoRelease wrapper =
  7214. obs_scene_save_transform_states(GetCurrentScene(), false);
  7215. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  7216. OBSDataAutoRelease rwrapper =
  7217. obs_scene_save_transform_states(GetCurrentScene(), false);
  7218. std::string undo_data(obs_data_get_json(wrapper));
  7219. std::string redo_data(obs_data_get_json(rwrapper));
  7220. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7221. .arg(obs_source_get_name(obs_scene_get_source(
  7222. GetCurrentScene()))),
  7223. undo_redo, undo_redo, undo_data, redo_data);
  7224. }
  7225. static bool MultiplySelectedItemScale(obs_scene_t * /* scene */,
  7226. obs_sceneitem_t *item, void *param)
  7227. {
  7228. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  7229. if (obs_sceneitem_is_group(item))
  7230. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  7231. param);
  7232. if (!obs_sceneitem_selected(item))
  7233. return true;
  7234. if (obs_sceneitem_locked(item))
  7235. return true;
  7236. vec3 tl = GetItemTL(item);
  7237. vec2 scale;
  7238. obs_sceneitem_get_scale(item, &scale);
  7239. vec2_mul(&scale, &scale, &mul);
  7240. obs_sceneitem_set_scale(item, &scale);
  7241. obs_sceneitem_force_update_transform(item);
  7242. SetItemTL(item, tl);
  7243. return true;
  7244. }
  7245. void OBSBasic::on_actionFlipHorizontal_triggered()
  7246. {
  7247. vec2 scale;
  7248. vec2_set(&scale, -1.0f, 1.0f);
  7249. OBSDataAutoRelease wrapper =
  7250. obs_scene_save_transform_states(GetCurrentScene(), false);
  7251. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7252. &scale);
  7253. OBSDataAutoRelease rwrapper =
  7254. obs_scene_save_transform_states(GetCurrentScene(), false);
  7255. std::string undo_data(obs_data_get_json(wrapper));
  7256. std::string redo_data(obs_data_get_json(rwrapper));
  7257. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  7258. .arg(obs_source_get_name(obs_scene_get_source(
  7259. GetCurrentScene()))),
  7260. undo_redo, undo_redo, undo_data, redo_data);
  7261. }
  7262. void OBSBasic::on_actionFlipVertical_triggered()
  7263. {
  7264. vec2 scale;
  7265. vec2_set(&scale, 1.0f, -1.0f);
  7266. OBSDataAutoRelease wrapper =
  7267. obs_scene_save_transform_states(GetCurrentScene(), false);
  7268. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7269. &scale);
  7270. OBSDataAutoRelease rwrapper =
  7271. obs_scene_save_transform_states(GetCurrentScene(), false);
  7272. std::string undo_data(obs_data_get_json(wrapper));
  7273. std::string redo_data(obs_data_get_json(rwrapper));
  7274. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  7275. .arg(obs_source_get_name(obs_scene_get_source(
  7276. GetCurrentScene()))),
  7277. undo_redo, undo_redo, undo_data, redo_data);
  7278. }
  7279. static bool CenterAlignSelectedItems(obs_scene_t * /* scene */,
  7280. obs_sceneitem_t *item, void *param)
  7281. {
  7282. obs_bounds_type boundsType =
  7283. *reinterpret_cast<obs_bounds_type *>(param);
  7284. if (obs_sceneitem_is_group(item))
  7285. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  7286. param);
  7287. if (!obs_sceneitem_selected(item))
  7288. return true;
  7289. if (obs_sceneitem_locked(item))
  7290. return true;
  7291. obs_video_info ovi;
  7292. obs_get_video_info(&ovi);
  7293. obs_transform_info itemInfo;
  7294. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  7295. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  7296. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  7297. itemInfo.rot = 0.0f;
  7298. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  7299. float(ovi.base_height));
  7300. itemInfo.bounds_type = boundsType;
  7301. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  7302. obs_sceneitem_set_info(item, &itemInfo);
  7303. return true;
  7304. }
  7305. void OBSBasic::on_actionFitToScreen_triggered()
  7306. {
  7307. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  7308. OBSDataAutoRelease wrapper =
  7309. obs_scene_save_transform_states(GetCurrentScene(), false);
  7310. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7311. &boundsType);
  7312. OBSDataAutoRelease rwrapper =
  7313. obs_scene_save_transform_states(GetCurrentScene(), false);
  7314. std::string undo_data(obs_data_get_json(wrapper));
  7315. std::string redo_data(obs_data_get_json(rwrapper));
  7316. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  7317. .arg(obs_source_get_name(obs_scene_get_source(
  7318. GetCurrentScene()))),
  7319. undo_redo, undo_redo, undo_data, redo_data);
  7320. }
  7321. void OBSBasic::on_actionStretchToScreen_triggered()
  7322. {
  7323. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  7324. OBSDataAutoRelease wrapper =
  7325. obs_scene_save_transform_states(GetCurrentScene(), false);
  7326. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7327. &boundsType);
  7328. OBSDataAutoRelease rwrapper =
  7329. obs_scene_save_transform_states(GetCurrentScene(), false);
  7330. std::string undo_data(obs_data_get_json(wrapper));
  7331. std::string redo_data(obs_data_get_json(rwrapper));
  7332. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  7333. .arg(obs_source_get_name(obs_scene_get_source(
  7334. GetCurrentScene()))),
  7335. undo_redo, undo_redo, undo_data, redo_data);
  7336. }
  7337. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  7338. {
  7339. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  7340. if (!selectedItems.count())
  7341. return;
  7342. vector<OBSSceneItem> items;
  7343. // Filter out items that have no size
  7344. for (int x = 0; x < selectedItems.count(); x++) {
  7345. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  7346. obs_transform_info oti;
  7347. obs_sceneitem_get_info(item, &oti);
  7348. obs_source_t *source = obs_sceneitem_get_source(item);
  7349. float width = float(obs_source_get_width(source)) * oti.scale.x;
  7350. float height =
  7351. float(obs_source_get_height(source)) * oti.scale.y;
  7352. if (width == 0.0f || height == 0.0f)
  7353. continue;
  7354. items.emplace_back(item);
  7355. }
  7356. if (!items.size())
  7357. return;
  7358. // Get center x, y coordinates of items
  7359. vec3 center;
  7360. float top = M_INFINITE;
  7361. float left = M_INFINITE;
  7362. float right = 0.0f;
  7363. float bottom = 0.0f;
  7364. for (auto &item : items) {
  7365. vec3 tl, br;
  7366. GetItemBox(item, tl, br);
  7367. left = (std::min)(tl.x, left);
  7368. top = (std::min)(tl.y, top);
  7369. right = (std::max)(br.x, right);
  7370. bottom = (std::max)(br.y, bottom);
  7371. }
  7372. center.x = (right + left) / 2.0f;
  7373. center.y = (top + bottom) / 2.0f;
  7374. center.z = 0.0f;
  7375. // Get coordinates of screen center
  7376. obs_video_info ovi;
  7377. obs_get_video_info(&ovi);
  7378. vec3 screenCenter;
  7379. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  7380. 0.0f);
  7381. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  7382. // Calculate difference between screen center and item center
  7383. vec3 offset;
  7384. vec3_sub(&offset, &screenCenter, &center);
  7385. // Shift items by offset
  7386. for (auto &item : items) {
  7387. vec3 tl, br;
  7388. GetItemBox(item, tl, br);
  7389. vec3_add(&tl, &tl, &offset);
  7390. vec3 itemTL = GetItemTL(item);
  7391. if (centerType == CenterType::Vertical)
  7392. tl.x = itemTL.x;
  7393. else if (centerType == CenterType::Horizontal)
  7394. tl.y = itemTL.y;
  7395. SetItemTL(item, tl);
  7396. }
  7397. }
  7398. void OBSBasic::on_actionCenterToScreen_triggered()
  7399. {
  7400. CenterType centerType = CenterType::Scene;
  7401. OBSDataAutoRelease wrapper =
  7402. obs_scene_save_transform_states(GetCurrentScene(), false);
  7403. CenterSelectedSceneItems(centerType);
  7404. OBSDataAutoRelease rwrapper =
  7405. obs_scene_save_transform_states(GetCurrentScene(), false);
  7406. std::string undo_data(obs_data_get_json(wrapper));
  7407. std::string redo_data(obs_data_get_json(rwrapper));
  7408. undo_s.add_action(QTStr("Undo.Transform.Center")
  7409. .arg(obs_source_get_name(obs_scene_get_source(
  7410. GetCurrentScene()))),
  7411. undo_redo, undo_redo, undo_data, redo_data);
  7412. }
  7413. void OBSBasic::on_actionVerticalCenter_triggered()
  7414. {
  7415. CenterType centerType = CenterType::Vertical;
  7416. OBSDataAutoRelease wrapper =
  7417. obs_scene_save_transform_states(GetCurrentScene(), false);
  7418. CenterSelectedSceneItems(centerType);
  7419. OBSDataAutoRelease rwrapper =
  7420. obs_scene_save_transform_states(GetCurrentScene(), false);
  7421. std::string undo_data(obs_data_get_json(wrapper));
  7422. std::string redo_data(obs_data_get_json(rwrapper));
  7423. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  7424. .arg(obs_source_get_name(obs_scene_get_source(
  7425. GetCurrentScene()))),
  7426. undo_redo, undo_redo, undo_data, redo_data);
  7427. }
  7428. void OBSBasic::on_actionHorizontalCenter_triggered()
  7429. {
  7430. CenterType centerType = CenterType::Horizontal;
  7431. OBSDataAutoRelease wrapper =
  7432. obs_scene_save_transform_states(GetCurrentScene(), false);
  7433. CenterSelectedSceneItems(centerType);
  7434. OBSDataAutoRelease rwrapper =
  7435. obs_scene_save_transform_states(GetCurrentScene(), false);
  7436. std::string undo_data(obs_data_get_json(wrapper));
  7437. std::string redo_data(obs_data_get_json(rwrapper));
  7438. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  7439. .arg(obs_source_get_name(obs_scene_get_source(
  7440. GetCurrentScene()))),
  7441. undo_redo, undo_redo, undo_data, redo_data);
  7442. }
  7443. void OBSBasic::EnablePreviewDisplay(bool enable)
  7444. {
  7445. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  7446. ui->preview->setVisible(enable);
  7447. ui->previewDisabledWidget->setVisible(!enable);
  7448. }
  7449. void OBSBasic::TogglePreview()
  7450. {
  7451. previewEnabled = !previewEnabled;
  7452. EnablePreviewDisplay(previewEnabled);
  7453. }
  7454. void OBSBasic::EnablePreview()
  7455. {
  7456. if (previewProgramMode)
  7457. return;
  7458. previewEnabled = true;
  7459. EnablePreviewDisplay(true);
  7460. }
  7461. void OBSBasic::DisablePreview()
  7462. {
  7463. if (previewProgramMode)
  7464. return;
  7465. previewEnabled = false;
  7466. EnablePreviewDisplay(false);
  7467. }
  7468. void OBSBasic::EnablePreviewProgram()
  7469. {
  7470. SetPreviewProgramMode(true);
  7471. }
  7472. void OBSBasic::DisablePreviewProgram()
  7473. {
  7474. SetPreviewProgramMode(false);
  7475. }
  7476. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  7477. {
  7478. if (obs_sceneitem_locked(item))
  7479. return true;
  7480. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  7481. struct vec2 pos;
  7482. if (!obs_sceneitem_selected(item)) {
  7483. if (obs_sceneitem_is_group(item)) {
  7484. struct vec3 offset3;
  7485. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  7486. struct matrix4 matrix;
  7487. obs_sceneitem_get_draw_transform(item, &matrix);
  7488. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  7489. matrix4_inv(&matrix, &matrix);
  7490. vec3_transform(&offset3, &offset3, &matrix);
  7491. struct vec2 new_offset;
  7492. vec2_set(&new_offset, offset3.x, offset3.y);
  7493. obs_sceneitem_group_enum_items(item, nudge_callback,
  7494. &new_offset);
  7495. }
  7496. return true;
  7497. }
  7498. obs_sceneitem_get_pos(item, &pos);
  7499. vec2_add(&pos, &pos, &offset);
  7500. obs_sceneitem_set_pos(item, &pos);
  7501. return true;
  7502. }
  7503. void OBSBasic::Nudge(int dist, MoveDir dir)
  7504. {
  7505. if (ui->preview->Locked())
  7506. return;
  7507. struct vec2 offset;
  7508. vec2_set(&offset, 0.0f, 0.0f);
  7509. switch (dir) {
  7510. case MoveDir::Up:
  7511. offset.y = (float)-dist;
  7512. break;
  7513. case MoveDir::Down:
  7514. offset.y = (float)dist;
  7515. break;
  7516. case MoveDir::Left:
  7517. offset.x = (float)-dist;
  7518. break;
  7519. case MoveDir::Right:
  7520. offset.x = (float)dist;
  7521. break;
  7522. }
  7523. if (!recent_nudge) {
  7524. recent_nudge = true;
  7525. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7526. GetCurrentScene(), true);
  7527. std::string undo_data(obs_data_get_json(wrapper));
  7528. nudge_timer = new QTimer;
  7529. QObject::connect(
  7530. nudge_timer, &QTimer::timeout,
  7531. [this, &recent_nudge = recent_nudge, undo_data]() {
  7532. OBSDataAutoRelease rwrapper =
  7533. obs_scene_save_transform_states(
  7534. GetCurrentScene(), true);
  7535. std::string redo_data(
  7536. obs_data_get_json(rwrapper));
  7537. undo_s.add_action(
  7538. QTStr("Undo.Transform")
  7539. .arg(obs_source_get_name(
  7540. GetCurrentSceneSource())),
  7541. undo_redo, undo_redo, undo_data,
  7542. redo_data);
  7543. recent_nudge = false;
  7544. });
  7545. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7546. &QTimer::deleteLater);
  7547. nudge_timer->setSingleShot(true);
  7548. }
  7549. if (nudge_timer) {
  7550. nudge_timer->stop();
  7551. nudge_timer->start(1000);
  7552. } else {
  7553. blog(LOG_ERROR, "No nudge timer!");
  7554. }
  7555. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7556. }
  7557. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7558. {
  7559. for (size_t i = 0; i < projectors.size(); i++) {
  7560. if (projectors[i] == projector) {
  7561. projectors[i]->deleteLater();
  7562. projectors.erase(projectors.begin() + i);
  7563. break;
  7564. }
  7565. }
  7566. }
  7567. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7568. ProjectorType type)
  7569. {
  7570. /* seriously? 10 monitors? */
  7571. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7572. return nullptr;
  7573. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7574. "CloseExistingProjectors");
  7575. if (closeProjectors && monitor > -1) {
  7576. for (size_t i = projectors.size(); i > 0; i--) {
  7577. size_t idx = i - 1;
  7578. if (projectors[idx]->GetMonitor() == monitor)
  7579. DeleteProjector(projectors[idx]);
  7580. }
  7581. }
  7582. OBSProjector *projector =
  7583. new OBSProjector(nullptr, source, monitor, type);
  7584. projectors.emplace_back(projector);
  7585. return projector;
  7586. }
  7587. void OBSBasic::OpenStudioProgramProjector()
  7588. {
  7589. int monitor = sender()->property("monitor").toInt();
  7590. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7591. }
  7592. void OBSBasic::OpenPreviewProjector()
  7593. {
  7594. int monitor = sender()->property("monitor").toInt();
  7595. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7596. }
  7597. void OBSBasic::OpenSourceProjector()
  7598. {
  7599. int monitor = sender()->property("monitor").toInt();
  7600. OBSSceneItem item = GetCurrentSceneItem();
  7601. if (!item)
  7602. return;
  7603. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7604. ProjectorType::Source);
  7605. }
  7606. void OBSBasic::OpenMultiviewProjector()
  7607. {
  7608. int monitor = sender()->property("monitor").toInt();
  7609. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7610. }
  7611. void OBSBasic::OpenSceneProjector()
  7612. {
  7613. int monitor = sender()->property("monitor").toInt();
  7614. OBSScene scene = GetCurrentScene();
  7615. if (!scene)
  7616. return;
  7617. OpenProjector(obs_scene_get_source(scene), monitor,
  7618. ProjectorType::Scene);
  7619. }
  7620. void OBSBasic::OpenStudioProgramWindow()
  7621. {
  7622. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7623. }
  7624. void OBSBasic::OpenPreviewWindow()
  7625. {
  7626. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7627. }
  7628. void OBSBasic::OpenSourceWindow()
  7629. {
  7630. OBSSceneItem item = GetCurrentSceneItem();
  7631. if (!item)
  7632. return;
  7633. OBSSource source = obs_sceneitem_get_source(item);
  7634. OpenProjector(obs_sceneitem_get_source(item), -1,
  7635. ProjectorType::Source);
  7636. }
  7637. void OBSBasic::OpenSceneWindow()
  7638. {
  7639. OBSScene scene = GetCurrentScene();
  7640. if (!scene)
  7641. return;
  7642. OBSSource source = obs_scene_get_source(scene);
  7643. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7644. }
  7645. void OBSBasic::OpenSavedProjectors()
  7646. {
  7647. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7648. OpenSavedProjector(info);
  7649. }
  7650. }
  7651. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7652. {
  7653. if (info) {
  7654. OBSProjector *projector = nullptr;
  7655. switch (info->type) {
  7656. case ProjectorType::Source:
  7657. case ProjectorType::Scene: {
  7658. OBSSourceAutoRelease source =
  7659. obs_get_source_by_name(info->name.c_str());
  7660. if (!source)
  7661. return;
  7662. projector = OpenProjector(source, info->monitor,
  7663. info->type);
  7664. break;
  7665. }
  7666. default: {
  7667. projector = OpenProjector(nullptr, info->monitor,
  7668. info->type);
  7669. break;
  7670. }
  7671. }
  7672. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7673. QByteArray byteArray = QByteArray::fromBase64(
  7674. QByteArray(info->geometry.c_str()));
  7675. projector->restoreGeometry(byteArray);
  7676. if (!WindowPositionValid(projector->normalGeometry())) {
  7677. QRect rect = QGuiApplication::primaryScreen()
  7678. ->geometry();
  7679. projector->setGeometry(QStyle::alignedRect(
  7680. Qt::LeftToRight, Qt::AlignCenter,
  7681. size(), rect));
  7682. }
  7683. if (info->alwaysOnTopOverridden)
  7684. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7685. true);
  7686. }
  7687. }
  7688. }
  7689. void OBSBasic::on_actionFullscreenInterface_triggered()
  7690. {
  7691. if (!isFullScreen())
  7692. showFullScreen();
  7693. else
  7694. showNormal();
  7695. }
  7696. void OBSBasic::UpdateTitleBar()
  7697. {
  7698. stringstream name;
  7699. const char *profile =
  7700. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7701. const char *sceneCollection = config_get_string(
  7702. App()->GlobalConfig(), "Basic", "SceneCollection");
  7703. name << "OBS ";
  7704. if (previewProgramMode)
  7705. name << "Studio ";
  7706. name << App()->GetVersionString(false);
  7707. if (safe_mode)
  7708. name << " (" << Str("TitleBar.SafeMode") << ")";
  7709. if (App()->IsPortableMode())
  7710. name << " - " << Str("TitleBar.PortableMode");
  7711. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7712. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7713. setWindowTitle(QT_UTF8(name.str().c_str()));
  7714. }
  7715. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7716. {
  7717. char profiles_path[512];
  7718. const char *profile =
  7719. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7720. int ret;
  7721. if (!profile)
  7722. return -1;
  7723. if (!path)
  7724. return -1;
  7725. if (!file)
  7726. file = "";
  7727. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7728. if (ret <= 0)
  7729. return ret;
  7730. if (!*file)
  7731. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7732. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7733. }
  7734. void OBSBasic::on_resetDocks_triggered(bool force)
  7735. {
  7736. /* prune deleted extra docks */
  7737. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7738. if (!oldExtraDocks[i]) {
  7739. oldExtraDocks.removeAt(i);
  7740. oldExtraDockNames.removeAt(i);
  7741. }
  7742. }
  7743. #ifdef BROWSER_AVAILABLE
  7744. if ((oldExtraDocks.size() || extraDocks.size() ||
  7745. extraCustomDocks.size() || extraBrowserDocks.size()) &&
  7746. !force) {
  7747. #else
  7748. if ((oldExtraDocks.size() || extraDocks.size() ||
  7749. extraCustomDocks.size()) &&
  7750. !force) {
  7751. #endif
  7752. QMessageBox::StandardButton button = QMessageBox::question(
  7753. this, QTStr("ResetUIWarning.Title"),
  7754. QTStr("ResetUIWarning.Text"));
  7755. if (button == QMessageBox::No)
  7756. return;
  7757. }
  7758. /* undock/hide/center extra docks */
  7759. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7760. if (oldExtraDocks[i]) {
  7761. oldExtraDocks[i]->setVisible(true);
  7762. oldExtraDocks[i]->setFloating(true);
  7763. oldExtraDocks[i]->move(
  7764. frameGeometry().topLeft() + rect().center() -
  7765. oldExtraDocks[i]->rect().center());
  7766. oldExtraDocks[i]->setVisible(false);
  7767. }
  7768. }
  7769. #define RESET_DOCKLIST(dockList) \
  7770. for (int i = dockList.size() - 1; i >= 0; i--) { \
  7771. dockList[i]->setVisible(true); \
  7772. dockList[i]->setFloating(true); \
  7773. dockList[i]->move(frameGeometry().topLeft() + \
  7774. rect().center() - \
  7775. dockList[i]->rect().center()); \
  7776. dockList[i]->setVisible(false); \
  7777. }
  7778. RESET_DOCKLIST(extraDocks)
  7779. RESET_DOCKLIST(extraCustomDocks)
  7780. #ifdef BROWSER_AVAILABLE
  7781. RESET_DOCKLIST(extraBrowserDocks)
  7782. #endif
  7783. #undef RESET_DOCKLIST
  7784. restoreState(startingDockLayout);
  7785. int cx = width();
  7786. int cy = height();
  7787. int cx22_5 = cx * 225 / 1000;
  7788. int cx5 = cx * 5 / 100;
  7789. int cx21 = cx * 21 / 100;
  7790. cy = cy * 225 / 1000;
  7791. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7792. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7793. ui->mixerDock, ui->transitionsDock,
  7794. ui->controlsDock};
  7795. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7796. ui->scenesDock->setVisible(true);
  7797. ui->sourcesDock->setVisible(true);
  7798. ui->mixerDock->setVisible(true);
  7799. ui->transitionsDock->setVisible(true);
  7800. ui->controlsDock->setVisible(true);
  7801. statsDock->setVisible(false);
  7802. statsDock->setFloating(true);
  7803. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7804. resizeDocks(docks, sizes, Qt::Horizontal);
  7805. activateWindow();
  7806. }
  7807. void OBSBasic::on_lockDocks_toggled(bool lock)
  7808. {
  7809. QDockWidget::DockWidgetFeatures features =
  7810. lock ? QDockWidget::NoDockWidgetFeatures
  7811. : (QDockWidget::DockWidgetClosable |
  7812. QDockWidget::DockWidgetMovable |
  7813. QDockWidget::DockWidgetFloatable);
  7814. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7815. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7816. ui->scenesDock->setFeatures(mainFeatures);
  7817. ui->sourcesDock->setFeatures(mainFeatures);
  7818. ui->mixerDock->setFeatures(mainFeatures);
  7819. ui->transitionsDock->setFeatures(mainFeatures);
  7820. ui->controlsDock->setFeatures(mainFeatures);
  7821. statsDock->setFeatures(features);
  7822. for (int i = extraDocks.size() - 1; i >= 0; i--)
  7823. extraDocks[i]->setFeatures(features);
  7824. for (int i = extraCustomDocks.size() - 1; i >= 0; i--)
  7825. extraCustomDocks[i]->setFeatures(features);
  7826. #ifdef BROWSER_AVAILABLE
  7827. for (int i = extraBrowserDocks.size() - 1; i >= 0; i--)
  7828. extraBrowserDocks[i]->setFeatures(features);
  7829. #endif
  7830. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7831. if (!oldExtraDocks[i]) {
  7832. oldExtraDocks.removeAt(i);
  7833. oldExtraDockNames.removeAt(i);
  7834. } else {
  7835. oldExtraDocks[i]->setFeatures(features);
  7836. }
  7837. }
  7838. }
  7839. void OBSBasic::on_sideDocks_toggled(bool side)
  7840. {
  7841. if (side) {
  7842. setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
  7843. setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
  7844. setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
  7845. setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
  7846. } else {
  7847. setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
  7848. setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
  7849. setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
  7850. setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
  7851. }
  7852. }
  7853. void OBSBasic::on_resetUI_triggered()
  7854. {
  7855. on_resetDocks_triggered();
  7856. ui->toggleListboxToolbars->setChecked(true);
  7857. ui->toggleContextBar->setChecked(true);
  7858. ui->toggleSourceIcons->setChecked(true);
  7859. ui->toggleStatusBar->setChecked(true);
  7860. ui->scenes->SetGridMode(false);
  7861. ui->actionSceneListMode->setChecked(true);
  7862. }
  7863. void OBSBasic::on_multiviewProjectorWindowed_triggered()
  7864. {
  7865. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7866. }
  7867. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7868. {
  7869. ui->sourcesToolbar->setVisible(visible);
  7870. ui->scenesToolbar->setVisible(visible);
  7871. ui->mixerToolbar->setVisible(visible);
  7872. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7873. "ShowListboxToolbars", visible);
  7874. }
  7875. void OBSBasic::ShowContextBar()
  7876. {
  7877. on_toggleContextBar_toggled(true);
  7878. ui->toggleContextBar->setChecked(true);
  7879. }
  7880. void OBSBasic::HideContextBar()
  7881. {
  7882. on_toggleContextBar_toggled(false);
  7883. ui->toggleContextBar->setChecked(false);
  7884. }
  7885. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7886. {
  7887. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7888. "ShowContextToolbars", visible);
  7889. this->ui->contextContainer->setVisible(visible);
  7890. UpdateContextBar(true);
  7891. }
  7892. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7893. {
  7894. ui->statusbar->setVisible(visible);
  7895. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7896. visible);
  7897. }
  7898. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7899. {
  7900. ui->sources->SetIconsVisible(visible);
  7901. if (advAudioWindow != nullptr)
  7902. advAudioWindow->SetIconsVisible(visible);
  7903. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7904. visible);
  7905. }
  7906. void OBSBasic::on_actionLockPreview_triggered()
  7907. {
  7908. ui->preview->ToggleLocked();
  7909. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7910. }
  7911. void OBSBasic::on_scalingMenu_aboutToShow()
  7912. {
  7913. obs_video_info ovi;
  7914. obs_get_video_info(&ovi);
  7915. QAction *action = ui->actionScaleCanvas;
  7916. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7917. text = text.arg(QString::number(ovi.base_width),
  7918. QString::number(ovi.base_height));
  7919. action->setText(text);
  7920. action = ui->actionScaleOutput;
  7921. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7922. text = text.arg(QString::number(ovi.output_width),
  7923. QString::number(ovi.output_height));
  7924. action->setText(text);
  7925. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7926. ovi.output_height == ovi.base_height));
  7927. UpdatePreviewScalingMenu();
  7928. }
  7929. void OBSBasic::on_actionScaleWindow_triggered()
  7930. {
  7931. ui->preview->SetFixedScaling(false);
  7932. ui->preview->ResetScrollingOffset();
  7933. emit ui->preview->DisplayResized();
  7934. }
  7935. void OBSBasic::on_actionScaleCanvas_triggered()
  7936. {
  7937. ui->preview->SetFixedScaling(true);
  7938. ui->preview->SetScalingLevel(0);
  7939. emit ui->preview->DisplayResized();
  7940. }
  7941. void OBSBasic::on_actionScaleOutput_triggered()
  7942. {
  7943. obs_video_info ovi;
  7944. obs_get_video_info(&ovi);
  7945. ui->preview->SetFixedScaling(true);
  7946. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7947. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7948. int32_t approxScalingLevel =
  7949. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7950. ui->preview->SetScalingLevel(approxScalingLevel);
  7951. ui->preview->SetScalingAmount(scalingAmount);
  7952. emit ui->preview->DisplayResized();
  7953. }
  7954. void OBSBasic::SetShowing(bool showing)
  7955. {
  7956. if (!showing && isVisible()) {
  7957. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7958. "geometry",
  7959. saveGeometry().toBase64().constData());
  7960. /* hide all visible child dialogs */
  7961. visDlgPositions.clear();
  7962. if (!visDialogs.isEmpty()) {
  7963. for (QDialog *dlg : visDialogs) {
  7964. visDlgPositions.append(dlg->pos());
  7965. dlg->hide();
  7966. }
  7967. }
  7968. if (showHide)
  7969. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7970. QTimer::singleShot(0, this, &OBSBasic::hide);
  7971. if (previewEnabled)
  7972. EnablePreviewDisplay(false);
  7973. #ifdef __APPLE__
  7974. EnableOSXDockIcon(false);
  7975. #endif
  7976. } else if (showing && !isVisible()) {
  7977. if (showHide)
  7978. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7979. QTimer::singleShot(0, this, &OBSBasic::show);
  7980. if (previewEnabled)
  7981. EnablePreviewDisplay(true);
  7982. #ifdef __APPLE__
  7983. EnableOSXDockIcon(true);
  7984. #endif
  7985. /* raise and activate window to ensure it is on top */
  7986. raise();
  7987. activateWindow();
  7988. /* show all child dialogs that was visible earlier */
  7989. if (!visDialogs.isEmpty()) {
  7990. for (int i = 0; i < visDialogs.size(); ++i) {
  7991. QDialog *dlg = visDialogs[i];
  7992. dlg->move(visDlgPositions[i]);
  7993. dlg->show();
  7994. }
  7995. }
  7996. /* Unminimize window if it was hidden to tray instead of task
  7997. * bar. */
  7998. if (sysTrayMinimizeToTray()) {
  7999. Qt::WindowStates state;
  8000. state = windowState() & ~Qt::WindowMinimized;
  8001. state |= Qt::WindowActive;
  8002. setWindowState(state);
  8003. }
  8004. }
  8005. }
  8006. void OBSBasic::ToggleShowHide()
  8007. {
  8008. bool showing = isVisible();
  8009. if (showing) {
  8010. /* check for modal dialogs */
  8011. EnumDialogs();
  8012. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  8013. return;
  8014. }
  8015. SetShowing(!showing);
  8016. }
  8017. void OBSBasic::SystemTrayInit()
  8018. {
  8019. #ifdef __APPLE__
  8020. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  8021. trayIconFile.setIsMask(true);
  8022. #else
  8023. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  8024. #endif
  8025. trayIcon.reset(new QSystemTrayIcon(
  8026. QIcon::fromTheme("obs-tray", trayIconFile), this));
  8027. trayIcon->setToolTip("OBS Studio");
  8028. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  8029. sysTrayStream = new QAction(
  8030. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  8031. : QTStr("Basic.Main.StartStreaming"),
  8032. trayIcon.data());
  8033. sysTrayRecord = new QAction(
  8034. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  8035. : QTStr("Basic.Main.StartRecording"),
  8036. trayIcon.data());
  8037. sysTrayReplayBuffer = new QAction(
  8038. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  8039. : QTStr("Basic.Main.StartReplayBuffer"),
  8040. trayIcon.data());
  8041. sysTrayVirtualCam = new QAction(
  8042. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  8043. : QTStr("Basic.Main.StartVirtualCam"),
  8044. trayIcon.data());
  8045. exit = new QAction(QTStr("Exit"), trayIcon.data());
  8046. trayMenu = new QMenu;
  8047. previewProjector = new QMenu(QTStr("PreviewProjector"));
  8048. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  8049. AddProjectorMenuMonitors(previewProjector, this,
  8050. &OBSBasic::OpenPreviewProjector);
  8051. AddProjectorMenuMonitors(studioProgramProjector, this,
  8052. &OBSBasic::OpenStudioProgramProjector);
  8053. trayMenu->addAction(showHide);
  8054. trayMenu->addSeparator();
  8055. trayMenu->addMenu(previewProjector);
  8056. trayMenu->addMenu(studioProgramProjector);
  8057. trayMenu->addSeparator();
  8058. trayMenu->addAction(sysTrayStream);
  8059. trayMenu->addAction(sysTrayRecord);
  8060. trayMenu->addAction(sysTrayReplayBuffer);
  8061. trayMenu->addAction(sysTrayVirtualCam);
  8062. trayMenu->addSeparator();
  8063. trayMenu->addAction(exit);
  8064. trayIcon->setContextMenu(trayMenu);
  8065. trayIcon->show();
  8066. if (outputHandler && !outputHandler->replayBuffer)
  8067. sysTrayReplayBuffer->setEnabled(false);
  8068. sysTrayVirtualCam->setEnabled(vcamEnabled);
  8069. if (Active())
  8070. OnActivate(true);
  8071. connect(trayIcon.data(), &QSystemTrayIcon::activated, this,
  8072. &OBSBasic::IconActivated);
  8073. connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide);
  8074. connect(sysTrayStream, &QAction::triggered, this,
  8075. &OBSBasic::on_streamButton_clicked);
  8076. connect(sysTrayRecord, &QAction::triggered, this,
  8077. &OBSBasic::on_recordButton_clicked);
  8078. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  8079. &OBSBasic::ReplayBufferClicked);
  8080. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  8081. &OBSBasic::VCamButtonClicked);
  8082. connect(exit, &QAction::triggered, this, &OBSBasic::close);
  8083. }
  8084. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  8085. {
  8086. // Refresh projector list
  8087. previewProjector->clear();
  8088. studioProgramProjector->clear();
  8089. AddProjectorMenuMonitors(previewProjector, this,
  8090. &OBSBasic::OpenPreviewProjector);
  8091. AddProjectorMenuMonitors(studioProgramProjector, this,
  8092. &OBSBasic::OpenStudioProgramProjector);
  8093. #ifdef __APPLE__
  8094. UNUSED_PARAMETER(reason);
  8095. #else
  8096. if (reason == QSystemTrayIcon::Trigger) {
  8097. EnablePreviewDisplay(previewEnabled && !isVisible());
  8098. ToggleShowHide();
  8099. }
  8100. #endif
  8101. }
  8102. void OBSBasic::SysTrayNotify(const QString &text,
  8103. QSystemTrayIcon::MessageIcon n)
  8104. {
  8105. if (trayIcon && trayIcon->isVisible() &&
  8106. QSystemTrayIcon::supportsMessages()) {
  8107. QSystemTrayIcon::MessageIcon icon =
  8108. QSystemTrayIcon::MessageIcon(n);
  8109. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  8110. }
  8111. }
  8112. void OBSBasic::SystemTray(bool firstStarted)
  8113. {
  8114. if (!QSystemTrayIcon::isSystemTrayAvailable())
  8115. return;
  8116. if (!trayIcon && !firstStarted)
  8117. return;
  8118. bool sysTrayWhenStarted = config_get_bool(
  8119. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  8120. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  8121. "SysTrayEnabled");
  8122. if (firstStarted)
  8123. SystemTrayInit();
  8124. if (!sysTrayEnabled) {
  8125. trayIcon->hide();
  8126. } else {
  8127. trayIcon->show();
  8128. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  8129. EnablePreviewDisplay(false);
  8130. #ifdef __APPLE__
  8131. EnableOSXDockIcon(false);
  8132. #endif
  8133. opt_minimize_tray = false;
  8134. }
  8135. }
  8136. if (isVisible())
  8137. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8138. else
  8139. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8140. }
  8141. bool OBSBasic::sysTrayMinimizeToTray()
  8142. {
  8143. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  8144. "SysTrayMinimizeToTray");
  8145. }
  8146. void OBSBasic::on_actionMainUndo_triggered()
  8147. {
  8148. undo_s.undo();
  8149. }
  8150. void OBSBasic::on_actionMainRedo_triggered()
  8151. {
  8152. undo_s.redo();
  8153. }
  8154. void OBSBasic::on_actionCopySource_triggered()
  8155. {
  8156. clipboard.clear();
  8157. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  8158. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  8159. if (!item)
  8160. continue;
  8161. OBSSource source = obs_sceneitem_get_source(item);
  8162. SourceCopyInfo copyInfo;
  8163. copyInfo.weak_source = OBSGetWeakRef(source);
  8164. obs_sceneitem_get_info(item, &copyInfo.transform);
  8165. obs_sceneitem_get_crop(item, &copyInfo.crop);
  8166. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  8167. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  8168. copyInfo.visible = obs_sceneitem_visible(item);
  8169. clipboard.push_back(copyInfo);
  8170. }
  8171. UpdateEditMenu();
  8172. }
  8173. void OBSBasic::on_actionPasteRef_triggered()
  8174. {
  8175. OBSSource scene_source = GetCurrentSceneSource();
  8176. OBSData undo_data = BackupScene(scene_source);
  8177. OBSScene scene = GetCurrentScene();
  8178. undo_s.push_disabled();
  8179. for (size_t i = clipboard.size(); i > 0; i--) {
  8180. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8181. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  8182. if (!source)
  8183. continue;
  8184. const char *name = obs_source_get_name(source);
  8185. /* do not allow duplicate refs of the same group in the same
  8186. * scene */
  8187. if (!!obs_scene_get_group(scene, name)) {
  8188. continue;
  8189. }
  8190. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  8191. }
  8192. undo_s.pop_disabled();
  8193. QString action_name = QTStr("Undo.PasteSourceRef");
  8194. const char *scene_name = obs_source_get_name(scene_source);
  8195. OBSData redo_data = BackupScene(scene_source);
  8196. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8197. redo_data);
  8198. }
  8199. void OBSBasic::on_actionPasteDup_triggered()
  8200. {
  8201. OBSSource scene_source = GetCurrentSceneSource();
  8202. OBSData undo_data = BackupScene(scene_source);
  8203. undo_s.push_disabled();
  8204. for (size_t i = clipboard.size(); i > 0; i--) {
  8205. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8206. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  8207. }
  8208. undo_s.pop_disabled();
  8209. QString action_name = QTStr("Undo.PasteSource");
  8210. const char *scene_name = obs_source_get_name(scene_source);
  8211. OBSData redo_data = BackupScene(scene_source);
  8212. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8213. redo_data);
  8214. }
  8215. void OBSBasic::AudioMixerCopyFilters()
  8216. {
  8217. QAction *action = reinterpret_cast<QAction *>(sender());
  8218. VolControl *vol = action->property("volControl").value<VolControl *>();
  8219. obs_source_t *source = vol->GetSource();
  8220. copyFiltersSource = obs_source_get_weak_source(source);
  8221. }
  8222. void OBSBasic::AudioMixerPasteFilters()
  8223. {
  8224. QAction *action = reinterpret_cast<QAction *>(sender());
  8225. VolControl *vol = action->property("volControl").value<VolControl *>();
  8226. obs_source_t *dstSource = vol->GetSource();
  8227. OBSSourceAutoRelease source =
  8228. obs_weak_source_get_source(copyFiltersSource);
  8229. if (source == dstSource)
  8230. return;
  8231. obs_source_copy_filters(dstSource, source);
  8232. }
  8233. void OBSBasic::SceneCopyFilters()
  8234. {
  8235. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  8236. }
  8237. void OBSBasic::ScenePasteFilters()
  8238. {
  8239. OBSSourceAutoRelease source =
  8240. obs_weak_source_get_source(copyFiltersSource);
  8241. OBSSource dstSource = GetCurrentSceneSource();
  8242. if (source == dstSource)
  8243. return;
  8244. obs_source_copy_filters(dstSource, source);
  8245. }
  8246. void OBSBasic::on_actionCopyFilters_triggered()
  8247. {
  8248. OBSSceneItem item = GetCurrentSceneItem();
  8249. if (!item)
  8250. return;
  8251. OBSSource source = obs_sceneitem_get_source(item);
  8252. copyFiltersSource = obs_source_get_weak_source(source);
  8253. ui->actionPasteFilters->setEnabled(true);
  8254. }
  8255. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  8256. obs_source_t *source,
  8257. obs_data_array_t *undo_array,
  8258. obs_data_array_t *redo_array)
  8259. {
  8260. auto undo_redo = [this](const std::string &json) {
  8261. OBSDataAutoRelease data =
  8262. obs_data_create_from_json(json.c_str());
  8263. OBSDataArrayAutoRelease array =
  8264. obs_data_get_array(data, "array");
  8265. OBSSourceAutoRelease source = obs_get_source_by_uuid(
  8266. obs_data_get_string(data, "uuid"));
  8267. obs_source_restore_filters(source, array);
  8268. if (filters)
  8269. filters->UpdateSource(source);
  8270. };
  8271. const char *uuid = obs_source_get_uuid(source);
  8272. OBSDataAutoRelease undo_data = obs_data_create();
  8273. OBSDataAutoRelease redo_data = obs_data_create();
  8274. obs_data_set_array(undo_data, "array", undo_array);
  8275. obs_data_set_array(redo_data, "array", redo_array);
  8276. obs_data_set_string(undo_data, "uuid", uuid);
  8277. obs_data_set_string(redo_data, "uuid", uuid);
  8278. undo_s.add_action(text, undo_redo, undo_redo,
  8279. obs_data_get_json(undo_data),
  8280. obs_data_get_json(redo_data));
  8281. }
  8282. void OBSBasic::on_actionPasteFilters_triggered()
  8283. {
  8284. OBSSourceAutoRelease source =
  8285. obs_weak_source_get_source(copyFiltersSource);
  8286. OBSSceneItem sceneItem = GetCurrentSceneItem();
  8287. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  8288. if (source == dstSource)
  8289. return;
  8290. OBSDataArrayAutoRelease undo_array =
  8291. obs_source_backup_filters(dstSource);
  8292. obs_source_copy_filters(dstSource, source);
  8293. OBSDataArrayAutoRelease redo_array =
  8294. obs_source_backup_filters(dstSource);
  8295. const char *srcName = obs_source_get_name(source);
  8296. const char *dstName = obs_source_get_name(dstSource);
  8297. QString text =
  8298. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  8299. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  8300. redo_array);
  8301. }
  8302. static void ConfirmColor(SourceTree *sources, const QColor &color,
  8303. QModelIndexList selectedItems)
  8304. {
  8305. for (int x = 0; x < selectedItems.count(); x++) {
  8306. SourceTreeItem *treeItem =
  8307. sources->GetItemWidget(selectedItems[x].row());
  8308. treeItem->setStyleSheet("background: " +
  8309. color.name(QColor::HexArgb));
  8310. treeItem->style()->unpolish(treeItem);
  8311. treeItem->style()->polish(treeItem);
  8312. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  8313. OBSDataAutoRelease privData =
  8314. obs_sceneitem_get_private_settings(sceneItem);
  8315. obs_data_set_int(privData, "color-preset", 1);
  8316. obs_data_set_string(privData, "color",
  8317. QT_TO_UTF8(color.name(QColor::HexArgb)));
  8318. }
  8319. }
  8320. void OBSBasic::ColorChange()
  8321. {
  8322. QModelIndexList selectedItems =
  8323. ui->sources->selectionModel()->selectedIndexes();
  8324. QAction *action = qobject_cast<QAction *>(sender());
  8325. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  8326. if (selectedItems.count() == 0)
  8327. return;
  8328. if (colorButton) {
  8329. int preset = colorButton->property("bgColor").value<int>();
  8330. for (int x = 0; x < selectedItems.count(); x++) {
  8331. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  8332. selectedItems[x].row());
  8333. treeItem->setStyleSheet("");
  8334. treeItem->setProperty("bgColor", preset);
  8335. treeItem->style()->unpolish(treeItem);
  8336. treeItem->style()->polish(treeItem);
  8337. OBSSceneItem sceneItem =
  8338. ui->sources->Get(selectedItems[x].row());
  8339. OBSDataAutoRelease privData =
  8340. obs_sceneitem_get_private_settings(sceneItem);
  8341. obs_data_set_int(privData, "color-preset", preset + 1);
  8342. obs_data_set_string(privData, "color", "");
  8343. }
  8344. for (int i = 1; i < 9; i++) {
  8345. stringstream button;
  8346. button << "preset" << i;
  8347. QPushButton *cButton =
  8348. colorButton->parentWidget()
  8349. ->findChild<QPushButton *>(
  8350. button.str().c_str());
  8351. cButton->setStyleSheet("border: 1px solid black");
  8352. }
  8353. colorButton->setStyleSheet("border: 2px solid black");
  8354. } else if (action) {
  8355. int preset = action->property("bgColor").value<int>();
  8356. if (preset == 1) {
  8357. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  8358. SourceTreeItem *curTreeItem =
  8359. GetItemWidgetFromSceneItem(curSceneItem);
  8360. OBSDataAutoRelease curPrivData =
  8361. obs_sceneitem_get_private_settings(
  8362. curSceneItem);
  8363. int oldPreset =
  8364. obs_data_get_int(curPrivData, "color-preset");
  8365. const QString oldSheet = curTreeItem->styleSheet();
  8366. auto liveChangeColor = [=](const QColor &color) {
  8367. if (color.isValid()) {
  8368. curTreeItem->setStyleSheet(
  8369. "background: " +
  8370. color.name(QColor::HexArgb));
  8371. }
  8372. };
  8373. auto changedColor = [=](const QColor &color) {
  8374. if (color.isValid()) {
  8375. ConfirmColor(ui->sources, color,
  8376. selectedItems);
  8377. }
  8378. };
  8379. auto rejected = [=]() {
  8380. if (oldPreset == 1) {
  8381. curTreeItem->setStyleSheet(oldSheet);
  8382. curTreeItem->setProperty("bgColor", 0);
  8383. } else if (oldPreset == 0) {
  8384. curTreeItem->setStyleSheet(
  8385. "background: none");
  8386. curTreeItem->setProperty("bgColor", 0);
  8387. } else {
  8388. curTreeItem->setStyleSheet("");
  8389. curTreeItem->setProperty("bgColor",
  8390. oldPreset - 1);
  8391. }
  8392. curTreeItem->style()->unpolish(curTreeItem);
  8393. curTreeItem->style()->polish(curTreeItem);
  8394. };
  8395. QColorDialog::ColorDialogOptions options =
  8396. QColorDialog::ShowAlphaChannel;
  8397. const char *oldColor =
  8398. obs_data_get_string(curPrivData, "color");
  8399. const char *customColor = *oldColor != 0 ? oldColor
  8400. : "#55FF0000";
  8401. #ifdef __linux__
  8402. // TODO: Revisit hang on Ubuntu with native dialog
  8403. options |= QColorDialog::DontUseNativeDialog;
  8404. #endif
  8405. QColorDialog *colorDialog = new QColorDialog(this);
  8406. colorDialog->setOptions(options);
  8407. colorDialog->setCurrentColor(QColor(customColor));
  8408. connect(colorDialog, &QColorDialog::currentColorChanged,
  8409. liveChangeColor);
  8410. connect(colorDialog, &QColorDialog::colorSelected,
  8411. changedColor);
  8412. connect(colorDialog, &QColorDialog::rejected, rejected);
  8413. colorDialog->open();
  8414. } else {
  8415. for (int x = 0; x < selectedItems.count(); x++) {
  8416. SourceTreeItem *treeItem =
  8417. ui->sources->GetItemWidget(
  8418. selectedItems[x].row());
  8419. treeItem->setStyleSheet("background: none");
  8420. treeItem->setProperty("bgColor", preset);
  8421. treeItem->style()->unpolish(treeItem);
  8422. treeItem->style()->polish(treeItem);
  8423. OBSSceneItem sceneItem = ui->sources->Get(
  8424. selectedItems[x].row());
  8425. OBSDataAutoRelease privData =
  8426. obs_sceneitem_get_private_settings(
  8427. sceneItem);
  8428. obs_data_set_int(privData, "color-preset",
  8429. preset);
  8430. obs_data_set_string(privData, "color", "");
  8431. }
  8432. }
  8433. }
  8434. }
  8435. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  8436. {
  8437. int i = 0;
  8438. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  8439. OBSSceneItem item = ui->sources->Get(i);
  8440. int64_t id = obs_sceneitem_get_id(sceneItem);
  8441. while (treeItem && obs_sceneitem_get_id(item) != id) {
  8442. i++;
  8443. treeItem = ui->sources->GetItemWidget(i);
  8444. item = ui->sources->Get(i);
  8445. }
  8446. if (treeItem)
  8447. return treeItem;
  8448. return nullptr;
  8449. }
  8450. void OBSBasic::on_autoConfigure_triggered()
  8451. {
  8452. AutoConfig test(this);
  8453. test.setModal(true);
  8454. test.show();
  8455. test.exec();
  8456. }
  8457. void OBSBasic::on_stats_triggered()
  8458. {
  8459. if (!stats.isNull()) {
  8460. stats->show();
  8461. stats->raise();
  8462. return;
  8463. }
  8464. OBSBasicStats *statsDlg;
  8465. statsDlg = new OBSBasicStats(nullptr);
  8466. statsDlg->show();
  8467. stats = statsDlg;
  8468. }
  8469. void OBSBasic::on_actionShowAbout_triggered()
  8470. {
  8471. if (about)
  8472. about->close();
  8473. about = new OBSAbout(this);
  8474. about->show();
  8475. about->setAttribute(Qt::WA_DeleteOnClose, true);
  8476. }
  8477. void OBSBasic::ResizeOutputSizeOfSource()
  8478. {
  8479. if (obs_video_active())
  8480. return;
  8481. QMessageBox resize_output(this);
  8482. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  8483. QTStr("ResizeOutputSizeOfSource.Continue"));
  8484. QAbstractButton *Yes =
  8485. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  8486. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  8487. resize_output.setIcon(QMessageBox::Warning);
  8488. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  8489. resize_output.exec();
  8490. if (resize_output.clickedButton() != Yes)
  8491. return;
  8492. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  8493. int width = obs_source_get_width(source);
  8494. int height = obs_source_get_height(source);
  8495. config_set_uint(basicConfig, "Video", "BaseCX", width);
  8496. config_set_uint(basicConfig, "Video", "BaseCY", height);
  8497. config_set_uint(basicConfig, "Video", "OutputCX", width);
  8498. config_set_uint(basicConfig, "Video", "OutputCY", height);
  8499. ResetVideo();
  8500. ResetOutputs();
  8501. config_save_safe(basicConfig, "tmp", nullptr);
  8502. on_actionFitToScreen_triggered();
  8503. }
  8504. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  8505. {
  8506. // Prevent the object name from being changed
  8507. connect(dock, &QObject::objectNameChanged, this,
  8508. &OBSBasic::RepairOldExtraDockName);
  8509. #ifdef BROWSER_AVAILABLE
  8510. QAction *action = new QAction(dock->windowTitle(), ui->menuDocks);
  8511. if (!extraBrowserMenuDocksSeparator.isNull())
  8512. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8513. action);
  8514. else
  8515. ui->menuDocks->addAction(action);
  8516. #else
  8517. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  8518. #endif
  8519. action->setCheckable(true);
  8520. assignDockToggle(dock, action);
  8521. oldExtraDocks.push_back(dock);
  8522. oldExtraDockNames.push_back(dock->objectName());
  8523. bool lock = ui->lockDocks->isChecked();
  8524. QDockWidget::DockWidgetFeatures features =
  8525. lock ? QDockWidget::NoDockWidgetFeatures
  8526. : (QDockWidget::DockWidgetClosable |
  8527. QDockWidget::DockWidgetMovable |
  8528. QDockWidget::DockWidgetFloatable);
  8529. dock->setFeatures(features);
  8530. /* prune deleted docks */
  8531. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  8532. if (!oldExtraDocks[i]) {
  8533. oldExtraDocks.removeAt(i);
  8534. oldExtraDockNames.removeAt(i);
  8535. }
  8536. }
  8537. return action;
  8538. }
  8539. void OBSBasic::RepairOldExtraDockName()
  8540. {
  8541. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8542. int idx = oldExtraDocks.indexOf(dock);
  8543. QSignalBlocker block(dock);
  8544. if (idx == -1) {
  8545. blog(LOG_WARNING, "A dock got its object name changed");
  8546. return;
  8547. }
  8548. blog(LOG_WARNING, "The dock '%s' got its object name restored",
  8549. QT_TO_UTF8(oldExtraDockNames[idx]));
  8550. dock->setObjectName(oldExtraDockNames[idx]);
  8551. }
  8552. void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area,
  8553. bool extraBrowser)
  8554. {
  8555. if (dock->objectName().isEmpty())
  8556. return;
  8557. bool lock = ui->lockDocks->isChecked();
  8558. QDockWidget::DockWidgetFeatures features =
  8559. lock ? QDockWidget::NoDockWidgetFeatures
  8560. : (QDockWidget::DockWidgetClosable |
  8561. QDockWidget::DockWidgetMovable |
  8562. QDockWidget::DockWidgetFloatable);
  8563. setupDockAction(dock);
  8564. dock->setFeatures(features);
  8565. addDockWidget(area, dock);
  8566. #ifdef BROWSER_AVAILABLE
  8567. if (extraBrowser && extraBrowserMenuDocksSeparator.isNull())
  8568. extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator();
  8569. if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull())
  8570. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8571. dock->toggleViewAction());
  8572. else
  8573. ui->menuDocks->addAction(dock->toggleViewAction());
  8574. if (extraBrowser)
  8575. return;
  8576. #else
  8577. UNUSED_PARAMETER(extraBrowser);
  8578. ui->menuDocks->addAction(dock->toggleViewAction());
  8579. #endif
  8580. extraDockNames.push_back(dock->objectName());
  8581. extraDocks.push_back(QSharedPointer<QDockWidget>(dock));
  8582. }
  8583. void OBSBasic::RemoveDockWidget(const QString &name)
  8584. {
  8585. if (extraDockNames.contains(name)) {
  8586. int idx = extraDockNames.indexOf(name);
  8587. extraDockNames.removeAt(idx);
  8588. extraDocks[idx].clear();
  8589. extraDocks.removeAt(idx);
  8590. } else if (extraCustomDockNames.contains(name)) {
  8591. int idx = extraCustomDockNames.indexOf(name);
  8592. extraCustomDockNames.removeAt(idx);
  8593. removeDockWidget(extraCustomDocks[idx]);
  8594. extraCustomDocks.removeAt(idx);
  8595. }
  8596. }
  8597. bool OBSBasic::IsDockObjectNameUsed(const QString &name)
  8598. {
  8599. QStringList list;
  8600. list << "scenesDock"
  8601. << "sourcesDock"
  8602. << "mixerDock"
  8603. << "transitionsDock"
  8604. << "controlsDock"
  8605. << "statsDock";
  8606. list << oldExtraDockNames;
  8607. list << extraDockNames;
  8608. list << extraCustomDockNames;
  8609. return list.contains(name);
  8610. }
  8611. void OBSBasic::AddCustomDockWidget(QDockWidget *dock)
  8612. {
  8613. // Prevent the object name from being changed
  8614. connect(dock, &QObject::objectNameChanged, this,
  8615. &OBSBasic::RepairCustomExtraDockName);
  8616. bool lock = ui->lockDocks->isChecked();
  8617. QDockWidget::DockWidgetFeatures features =
  8618. lock ? QDockWidget::NoDockWidgetFeatures
  8619. : (QDockWidget::DockWidgetClosable |
  8620. QDockWidget::DockWidgetMovable |
  8621. QDockWidget::DockWidgetFloatable);
  8622. dock->setFeatures(features);
  8623. addDockWidget(Qt::RightDockWidgetArea, dock);
  8624. extraCustomDockNames.push_back(dock->objectName());
  8625. extraCustomDocks.push_back(dock);
  8626. }
  8627. void OBSBasic::RepairCustomExtraDockName()
  8628. {
  8629. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8630. int idx = extraCustomDocks.indexOf(dock);
  8631. QSignalBlocker block(dock);
  8632. if (idx == -1) {
  8633. blog(LOG_WARNING, "A custom dock got its object name changed");
  8634. return;
  8635. }
  8636. blog(LOG_WARNING, "The custom dock '%s' got its object name restored",
  8637. QT_TO_UTF8(extraCustomDockNames[idx]));
  8638. dock->setObjectName(extraCustomDockNames[idx]);
  8639. }
  8640. OBSBasic *OBSBasic::Get()
  8641. {
  8642. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8643. }
  8644. bool OBSBasic::StreamingActive()
  8645. {
  8646. if (!outputHandler)
  8647. return false;
  8648. return outputHandler->StreamingActive();
  8649. }
  8650. bool OBSBasic::RecordingActive()
  8651. {
  8652. if (!outputHandler)
  8653. return false;
  8654. return outputHandler->RecordingActive();
  8655. }
  8656. bool OBSBasic::ReplayBufferActive()
  8657. {
  8658. if (!outputHandler)
  8659. return false;
  8660. return outputHandler->ReplayBufferActive();
  8661. }
  8662. bool OBSBasic::VirtualCamActive()
  8663. {
  8664. if (!outputHandler)
  8665. return false;
  8666. return outputHandler->VirtualCamActive();
  8667. }
  8668. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8669. : QStyledItemDelegate(parent)
  8670. {
  8671. }
  8672. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8673. const QModelIndex &index) const
  8674. {
  8675. QStyledItemDelegate::setEditorData(editor, index);
  8676. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8677. if (lineEdit)
  8678. lineEdit->selectAll();
  8679. }
  8680. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8681. {
  8682. if (event->type() == QEvent::KeyPress) {
  8683. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8684. if (keyEvent->key() == Qt::Key_Escape) {
  8685. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8686. if (lineEdit)
  8687. lineEdit->undo();
  8688. }
  8689. }
  8690. return QStyledItemDelegate::eventFilter(editor, event);
  8691. }
  8692. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8693. {
  8694. if (!error.isEmpty())
  8695. return;
  8696. patronJson = QT_TO_UTF8(text);
  8697. }
  8698. void OBSBasic::PauseRecording()
  8699. {
  8700. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8701. os_atomic_load_bool(&recording_paused))
  8702. return;
  8703. obs_output_t *output = outputHandler->fileOutput;
  8704. if (obs_output_pause(output, true)) {
  8705. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  8706. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  8707. pause->blockSignals(true);
  8708. pause->setChecked(true);
  8709. pause->blockSignals(false);
  8710. ui->statusbar->RecordingPaused();
  8711. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8712. if (trayIcon && trayIcon->isVisible()) {
  8713. #ifdef __APPLE__
  8714. QIcon trayIconFile =
  8715. QIcon(":/res/images/obs_paused_macos.svg");
  8716. trayIconFile.setIsMask(true);
  8717. #else
  8718. QIcon trayIconFile =
  8719. QIcon(":/res/images/obs_paused.png");
  8720. #endif
  8721. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8722. trayIconFile));
  8723. }
  8724. os_atomic_set_bool(&recording_paused, true);
  8725. auto replay = replayBufferButton ? replayBufferButton->second()
  8726. : nullptr;
  8727. if (replay)
  8728. replay->setEnabled(false);
  8729. if (api)
  8730. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8731. if (os_atomic_load_bool(&replaybuf_active))
  8732. ShowReplayBufferPauseWarning();
  8733. }
  8734. }
  8735. void OBSBasic::UnpauseRecording()
  8736. {
  8737. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8738. !os_atomic_load_bool(&recording_paused))
  8739. return;
  8740. obs_output_t *output = outputHandler->fileOutput;
  8741. if (obs_output_pause(output, false)) {
  8742. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8743. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8744. pause->blockSignals(true);
  8745. pause->setChecked(false);
  8746. pause->blockSignals(false);
  8747. ui->statusbar->RecordingUnpaused();
  8748. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8749. if (trayIcon && trayIcon->isVisible()) {
  8750. #ifdef __APPLE__
  8751. QIcon trayIconFile =
  8752. QIcon(":/res/images/tray_active_macos.svg");
  8753. trayIconFile.setIsMask(true);
  8754. #else
  8755. QIcon trayIconFile =
  8756. QIcon(":/res/images/tray_active.png");
  8757. #endif
  8758. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8759. trayIconFile));
  8760. }
  8761. os_atomic_set_bool(&recording_paused, false);
  8762. auto replay = replayBufferButton ? replayBufferButton->second()
  8763. : nullptr;
  8764. if (replay)
  8765. replay->setEnabled(true);
  8766. if (api)
  8767. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8768. }
  8769. }
  8770. void OBSBasic::PauseToggled()
  8771. {
  8772. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8773. return;
  8774. obs_output_t *output = outputHandler->fileOutput;
  8775. bool enable = !obs_output_paused(output);
  8776. if (enable)
  8777. PauseRecording();
  8778. else
  8779. UnpauseRecording();
  8780. }
  8781. void OBSBasic::UpdatePause(bool activate)
  8782. {
  8783. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8784. pause.reset();
  8785. return;
  8786. }
  8787. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8788. bool adv = astrcmpi(mode, "Advanced") == 0;
  8789. bool shared;
  8790. if (adv) {
  8791. const char *recType =
  8792. config_get_string(basicConfig, "AdvOut", "RecType");
  8793. if (astrcmpi(recType, "FFmpeg") == 0) {
  8794. shared = config_get_bool(basicConfig, "AdvOut",
  8795. "FFOutputToFile");
  8796. } else {
  8797. const char *recordEncoder = config_get_string(
  8798. basicConfig, "AdvOut", "RecEncoder");
  8799. shared = astrcmpi(recordEncoder, "none") == 0;
  8800. }
  8801. } else {
  8802. const char *quality = config_get_string(
  8803. basicConfig, "SimpleOutput", "RecQuality");
  8804. shared = strcmp(quality, "Stream") == 0;
  8805. }
  8806. if (!shared) {
  8807. pause.reset(new QPushButton());
  8808. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8809. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8810. pause->setCheckable(true);
  8811. pause->setChecked(false);
  8812. pause->setProperty("themeID",
  8813. QVariant(QStringLiteral("pauseIconSmall")));
  8814. QSizePolicy sp;
  8815. sp.setHeightForWidth(true);
  8816. pause->setSizePolicy(sp);
  8817. connect(pause.data(), &QAbstractButton::clicked, this,
  8818. &OBSBasic::PauseToggled);
  8819. ui->recordingLayout->addWidget(pause.data());
  8820. } else {
  8821. pause.reset();
  8822. }
  8823. }
  8824. void OBSBasic::UpdateReplayBuffer(bool activate)
  8825. {
  8826. if (!activate || !outputHandler ||
  8827. !outputHandler->ReplayBufferActive()) {
  8828. replayBufferButton->removeIcon();
  8829. return;
  8830. }
  8831. replayBufferButton->addIcon(QTStr("Basic.Main.SaveReplay"),
  8832. QStringLiteral("replayIconSmall"),
  8833. &OBSBasic::ReplayBufferSave);
  8834. }
  8835. #define MBYTE (1024ULL * 1024ULL)
  8836. #define MBYTES_LEFT_STOP_REC 50ULL
  8837. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8838. const char *OBSBasic::GetCurrentOutputPath()
  8839. {
  8840. const char *path = nullptr;
  8841. const char *mode = config_get_string(Config(), "Output", "Mode");
  8842. if (strcmp(mode, "Advanced") == 0) {
  8843. const char *advanced_mode =
  8844. config_get_string(Config(), "AdvOut", "RecType");
  8845. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8846. path = config_get_string(Config(), "AdvOut",
  8847. "FFFilePath");
  8848. } else {
  8849. path = config_get_string(Config(), "AdvOut",
  8850. "RecFilePath");
  8851. }
  8852. } else {
  8853. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8854. }
  8855. return path;
  8856. }
  8857. void OBSBasic::OutputPathInvalidMessage()
  8858. {
  8859. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8860. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8861. QTStr("Output.BadPath.Text"));
  8862. }
  8863. bool OBSBasic::OutputPathValid()
  8864. {
  8865. const char *mode = config_get_string(Config(), "Output", "Mode");
  8866. if (strcmp(mode, "Advanced") == 0) {
  8867. const char *advanced_mode =
  8868. config_get_string(Config(), "AdvOut", "RecType");
  8869. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8870. bool is_local = config_get_bool(Config(), "AdvOut",
  8871. "FFOutputToFile");
  8872. if (!is_local)
  8873. return true;
  8874. }
  8875. }
  8876. const char *path = GetCurrentOutputPath();
  8877. return path && *path && QDir(path).exists();
  8878. }
  8879. void OBSBasic::DiskSpaceMessage()
  8880. {
  8881. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8882. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8883. QTStr("Output.RecordNoSpace.Msg"));
  8884. }
  8885. bool OBSBasic::LowDiskSpace()
  8886. {
  8887. const char *path;
  8888. path = GetCurrentOutputPath();
  8889. if (!path)
  8890. return false;
  8891. uint64_t num_bytes = os_get_free_disk_space(path);
  8892. if (num_bytes < (MAX_BYTES_LEFT))
  8893. return true;
  8894. else
  8895. return false;
  8896. }
  8897. void OBSBasic::CheckDiskSpaceRemaining()
  8898. {
  8899. if (LowDiskSpace()) {
  8900. StopRecording();
  8901. StopReplayBuffer();
  8902. DiskSpaceMessage();
  8903. }
  8904. }
  8905. void OBSBasic::ResetStatsHotkey()
  8906. {
  8907. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8908. foreach(OBSBasicStats * s, list) s->Reset();
  8909. }
  8910. void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos)
  8911. {
  8912. QWidget *widget = childAt(pos);
  8913. const char *className = nullptr;
  8914. QString objName;
  8915. if (widget != nullptr) {
  8916. className = widget->metaObject()->className();
  8917. objName = widget->objectName();
  8918. }
  8919. QPoint globalPos = mapToGlobal(pos);
  8920. if (className && strstr(className, "Dock") != nullptr &&
  8921. !objName.isEmpty()) {
  8922. if (objName.compare("scenesDock") == 0) {
  8923. ui->scenes->customContextMenuRequested(globalPos);
  8924. } else if (objName.compare("sourcesDock") == 0) {
  8925. ui->sources->customContextMenuRequested(globalPos);
  8926. } else if (objName.compare("mixerDock") == 0) {
  8927. StackedMixerAreaContextMenuRequested();
  8928. }
  8929. } else if (!className) {
  8930. ui->menuDocks->exec(globalPos);
  8931. }
  8932. }
  8933. void OBSBasic::UpdateProjectorHideCursor()
  8934. {
  8935. for (size_t i = 0; i < projectors.size(); i++)
  8936. projectors[i]->SetHideCursor();
  8937. }
  8938. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8939. {
  8940. for (size_t i = 0; i < projectors.size(); i++)
  8941. SetAlwaysOnTop(projectors[i], top);
  8942. }
  8943. void OBSBasic::ResetProjectors()
  8944. {
  8945. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8946. ClearProjectors();
  8947. LoadSavedProjectors(savedProjectorList);
  8948. OpenSavedProjectors();
  8949. }
  8950. void OBSBasic::on_sourcePropertiesButton_clicked()
  8951. {
  8952. on_actionSourceProperties_triggered();
  8953. }
  8954. void OBSBasic::on_sourceFiltersButton_clicked()
  8955. {
  8956. OpenFilters();
  8957. }
  8958. void OBSBasic::on_actionSceneFilters_triggered()
  8959. {
  8960. OBSSource sceneSource = GetCurrentSceneSource();
  8961. if (sceneSource)
  8962. OpenFilters(sceneSource);
  8963. }
  8964. void OBSBasic::on_sourceInteractButton_clicked()
  8965. {
  8966. on_actionInteract_triggered();
  8967. }
  8968. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8969. {
  8970. ui->statusbar->clearMessage();
  8971. ui->statusbar->showMessage(message, 10000);
  8972. }
  8973. void OBSBasic::UpdatePreviewSafeAreas()
  8974. {
  8975. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8976. "ShowSafeAreas");
  8977. }
  8978. void OBSBasic::UpdatePreviewOverflowSettings()
  8979. {
  8980. bool hidden = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8981. "OverflowHidden");
  8982. bool select = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8983. "OverflowSelectionHidden");
  8984. bool always = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8985. "OverflowAlwaysVisible");
  8986. ui->preview->SetOverflowHidden(hidden);
  8987. ui->preview->SetOverflowSelectionHidden(select);
  8988. ui->preview->SetOverflowAlwaysVisible(always);
  8989. }
  8990. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8991. {
  8992. if (!SetDisplayAffinitySupported())
  8993. return;
  8994. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8995. "BasicWindow",
  8996. "HideOBSWindowsFromCapture");
  8997. // Don't hide projectors, those are designed to be visible / captured
  8998. if (window->property("isOBSProjectorWindow") == true)
  8999. return;
  9000. #ifdef _WIN32
  9001. HWND hwnd = (HWND)window->winId();
  9002. DWORD curAffinity;
  9003. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  9004. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  9005. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  9006. else if (!hideFromCapture && curAffinity != WDA_NONE)
  9007. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  9008. }
  9009. #else
  9010. // TODO: Implement for other platforms if possible. Don't forget to
  9011. // implement SetDisplayAffinitySupported too!
  9012. UNUSED_PARAMETER(hideFromCapture);
  9013. #endif
  9014. }
  9015. static inline QColor color_from_int(long long val)
  9016. {
  9017. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  9018. (val >> 24) & 0xff);
  9019. }
  9020. QColor OBSBasic::GetSelectionColor() const
  9021. {
  9022. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9023. "OverrideColors")) {
  9024. return color_from_int(config_get_int(
  9025. GetGlobalConfig(), "Accessibility", "SelectRed"));
  9026. } else {
  9027. return QColor::fromRgb(255, 0, 0);
  9028. }
  9029. }
  9030. QColor OBSBasic::GetCropColor() const
  9031. {
  9032. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9033. "OverrideColors")) {
  9034. return color_from_int(config_get_int(
  9035. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  9036. } else {
  9037. return QColor::fromRgb(0, 255, 0);
  9038. }
  9039. }
  9040. QColor OBSBasic::GetHoverColor() const
  9041. {
  9042. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9043. "OverrideColors")) {
  9044. return color_from_int(config_get_int(
  9045. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  9046. } else {
  9047. return QColor::fromRgb(0, 127, 255);
  9048. }
  9049. }
  9050. void OBSBasic::UpdatePreviewSpacingHelpers()
  9051. {
  9052. drawSpacingHelpers = config_get_bool(
  9053. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  9054. }
  9055. float OBSBasic::GetDevicePixelRatio()
  9056. {
  9057. return dpi;
  9058. }
  9059. void OBSBasic::ThemeChanged()
  9060. {
  9061. /* Since volume/media sliders are using QProxyStyle, they are not
  9062. * updated when themes are changed, so re-initialize them. */
  9063. vector<OBSSource> sources;
  9064. for (size_t i = 0; i != volumes.size(); i++)
  9065. sources.emplace_back(volumes[i]->GetSource());
  9066. ClearVolumeControls();
  9067. for (const auto &source : sources)
  9068. ActivateAudioSource(source);
  9069. UpdateContextBar(true);
  9070. if (api)
  9071. api->on_event(OBS_FRONTEND_EVENT_THEME_CHANGED);
  9072. }