window-basic-main.cpp 296 KB

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