window-basic-main.cpp 290 KB

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