1
0

window-basic-main.cpp 274 KB

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