window-basic-main.cpp 299 KB

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