window-basic-main.cpp 288 KB

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