window-basic-main.cpp 301 KB

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