window-basic-main.cpp 280 KB

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