window-basic-main.cpp 274 KB

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