window-basic-main.cpp 304 KB

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