window-basic-main.cpp 275 KB

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