window-basic-main.cpp 279 KB

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