window-basic-main.cpp 304 KB

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