window-basic-main.cpp 287 KB

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