window-basic-main.cpp 278 KB

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