window-basic-main.cpp 272 KB

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