window-basic-main.cpp 288 KB

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