window-basic-main.cpp 297 KB

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