window-basic-main.cpp 282 KB

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