window-basic-main.cpp 292 KB

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