window-basic-main.cpp 280 KB

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