window-basic-main.cpp 274 KB

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