window-basic-main.cpp 306 KB

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