window-basic-main.cpp 303 KB

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