1
0

window-basic-main.cpp 278 KB

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