window-basic-main.cpp 279 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318
  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", "RecRB", false);
  1158. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1159. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1160. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1161. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1162. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1163. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1164. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1165. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1166. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1167. config_save_safe(basicConfig, "tmp", nullptr);
  1168. }
  1169. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1170. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1171. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1172. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1173. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1174. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1175. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1176. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1177. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1178. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1179. false);
  1180. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1181. false);
  1182. int i = 0;
  1183. uint32_t scale_cx = cx;
  1184. uint32_t scale_cy = cy;
  1185. /* use a default scaled resolution that has a pixel count no higher
  1186. * than 1280x720 */
  1187. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1188. double scale = scaled_vals[i++];
  1189. scale_cx = uint32_t(double(cx) / scale);
  1190. scale_cy = uint32_t(double(cy) / scale);
  1191. }
  1192. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1193. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1194. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1195. * changing */
  1196. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1197. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1198. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1199. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1200. config_save_safe(basicConfig, "tmp", nullptr);
  1201. }
  1202. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1203. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1204. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1205. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1206. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1207. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1208. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1209. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1210. config_set_default_string(basicConfig, "Video", "ColorRange",
  1211. "Partial");
  1212. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1213. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1214. 1000);
  1215. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1216. "default");
  1217. config_set_default_string(
  1218. basicConfig, "Audio", "MonitoringDeviceName",
  1219. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1220. ".Default"));
  1221. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1222. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1223. "Stereo");
  1224. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1225. VOLUME_METER_DECAY_FAST);
  1226. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1227. CheckExistingCookieId();
  1228. return true;
  1229. }
  1230. extern bool EncoderAvailable(const char *encoder);
  1231. void OBSBasic::InitBasicConfigDefaults2()
  1232. {
  1233. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1234. "Pre23Defaults");
  1235. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1236. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1237. useNV ? SIMPLE_ENCODER_NVENC
  1238. : SIMPLE_ENCODER_X264);
  1239. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1240. useNV ? SIMPLE_ENCODER_NVENC
  1241. : SIMPLE_ENCODER_X264);
  1242. }
  1243. bool OBSBasic::InitBasicConfig()
  1244. {
  1245. ProfileScope("OBSBasic::InitBasicConfig");
  1246. char configPath[512];
  1247. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1248. if (ret <= 0) {
  1249. OBSErrorBox(nullptr, "Failed to get profile path");
  1250. return false;
  1251. }
  1252. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1253. OBSErrorBox(nullptr, "Failed to create profile path");
  1254. return false;
  1255. }
  1256. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1257. if (ret <= 0) {
  1258. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1259. return false;
  1260. }
  1261. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1262. if (code != CONFIG_SUCCESS) {
  1263. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1264. return false;
  1265. }
  1266. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1267. const char *curName = config_get_string(App()->GlobalConfig(),
  1268. "Basic", "Profile");
  1269. config_set_string(basicConfig, "General", "Name", curName);
  1270. basicConfig.SaveSafe("tmp");
  1271. }
  1272. return InitBasicConfigDefaults();
  1273. }
  1274. void OBSBasic::InitOBSCallbacks()
  1275. {
  1276. ProfileScope("OBSBasic::InitOBSCallbacks");
  1277. signalHandlers.reserve(signalHandlers.size() + 7);
  1278. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1279. OBSBasic::SourceCreated, this);
  1280. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1281. OBSBasic::SourceRemoved, this);
  1282. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1283. OBSBasic::SourceActivated, this);
  1284. signalHandlers.emplace_back(obs_get_signal_handler(),
  1285. "source_deactivate",
  1286. OBSBasic::SourceDeactivated, this);
  1287. signalHandlers.emplace_back(obs_get_signal_handler(),
  1288. "source_audio_activate",
  1289. OBSBasic::SourceAudioActivated, this);
  1290. signalHandlers.emplace_back(obs_get_signal_handler(),
  1291. "source_audio_deactivate",
  1292. OBSBasic::SourceAudioDeactivated, this);
  1293. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1294. OBSBasic::SourceRenamed, this);
  1295. }
  1296. void OBSBasic::InitPrimitives()
  1297. {
  1298. ProfileScope("OBSBasic::InitPrimitives");
  1299. obs_enter_graphics();
  1300. gs_render_start(true);
  1301. gs_vertex2f(0.0f, 0.0f);
  1302. gs_vertex2f(0.0f, 1.0f);
  1303. gs_vertex2f(1.0f, 0.0f);
  1304. gs_vertex2f(1.0f, 1.0f);
  1305. box = gs_render_save();
  1306. gs_render_start(true);
  1307. gs_vertex2f(0.0f, 0.0f);
  1308. gs_vertex2f(0.0f, 1.0f);
  1309. boxLeft = gs_render_save();
  1310. gs_render_start(true);
  1311. gs_vertex2f(0.0f, 0.0f);
  1312. gs_vertex2f(1.0f, 0.0f);
  1313. boxTop = gs_render_save();
  1314. gs_render_start(true);
  1315. gs_vertex2f(1.0f, 0.0f);
  1316. gs_vertex2f(1.0f, 1.0f);
  1317. boxRight = gs_render_save();
  1318. gs_render_start(true);
  1319. gs_vertex2f(0.0f, 1.0f);
  1320. gs_vertex2f(1.0f, 1.0f);
  1321. boxBottom = gs_render_save();
  1322. gs_render_start(true);
  1323. for (int i = 0; i <= 360; i += (360 / 20)) {
  1324. float pos = RAD(float(i));
  1325. gs_vertex2f(cosf(pos), sinf(pos));
  1326. }
  1327. circle = gs_render_save();
  1328. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1329. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1330. obs_leave_graphics();
  1331. }
  1332. void OBSBasic::ReplayBufferClicked()
  1333. {
  1334. if (outputHandler->ReplayBufferActive())
  1335. StopReplayBuffer();
  1336. else
  1337. StartReplayBuffer();
  1338. };
  1339. void OBSBasic::AddVCamButton()
  1340. {
  1341. OBSBasicVCamConfig::Init();
  1342. vcamButton = new ControlsSplitButton(
  1343. QTStr("Basic.Main.StartVirtualCam"), "vcamButton",
  1344. &OBSBasic::VCamButtonClicked);
  1345. vcamButton->addIcon(QTStr("Basic.Main.VirtualCamConfig"),
  1346. QStringLiteral("configIconSmall"),
  1347. &OBSBasic::VCamConfigButtonClicked);
  1348. vcamButton->insert(2);
  1349. }
  1350. void OBSBasic::ResetOutputs()
  1351. {
  1352. ProfileScope("OBSBasic::ResetOutputs");
  1353. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1354. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1355. if (!outputHandler || !outputHandler->Active()) {
  1356. outputHandler.reset();
  1357. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1358. : CreateSimpleOutputHandler(this));
  1359. delete replayBufferButton;
  1360. if (outputHandler->replayBuffer) {
  1361. replayBufferButton = new ControlsSplitButton(
  1362. QTStr("Basic.Main.StartReplayBuffer"),
  1363. "replayBufferButton",
  1364. &OBSBasic::ReplayBufferClicked);
  1365. replayBufferButton->insert(2);
  1366. }
  1367. if (sysTrayReplayBuffer)
  1368. sysTrayReplayBuffer->setEnabled(
  1369. !!outputHandler->replayBuffer);
  1370. } else {
  1371. outputHandler->Update();
  1372. }
  1373. }
  1374. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1375. const char *slot);
  1376. #define STARTUP_SEPARATOR \
  1377. "==== Startup complete ==============================================="
  1378. #define SHUTDOWN_SEPARATOR \
  1379. "==== Shutting down =================================================="
  1380. #define UNSUPPORTED_ERROR \
  1381. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1382. "not found. Your GPU may not be supported."
  1383. #define UNKNOWN_ERROR \
  1384. "Failed to initialize video. Your GPU may not be supported, " \
  1385. "or your graphics drivers may need to be updated."
  1386. void OBSBasic::OBSInit()
  1387. {
  1388. ProfileScope("OBSBasic::OBSInit");
  1389. const char *sceneCollection = config_get_string(
  1390. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1391. char savePath[1024];
  1392. char fileName[1024];
  1393. int ret;
  1394. if (!sceneCollection)
  1395. throw "Failed to get scene collection name";
  1396. ret = snprintf(fileName, sizeof(fileName),
  1397. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1398. if (ret <= 0)
  1399. throw "Failed to create scene collection file name";
  1400. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1401. if (ret <= 0)
  1402. throw "Failed to get scene collection json file path";
  1403. if (!InitBasicConfig())
  1404. throw "Failed to load basic.ini";
  1405. if (!ResetAudio())
  1406. throw "Failed to initialize audio";
  1407. ret = ResetVideo();
  1408. switch (ret) {
  1409. case OBS_VIDEO_MODULE_NOT_FOUND:
  1410. throw "Failed to initialize video: Graphics module not found";
  1411. case OBS_VIDEO_NOT_SUPPORTED:
  1412. throw UNSUPPORTED_ERROR;
  1413. case OBS_VIDEO_INVALID_PARAM:
  1414. throw "Failed to initialize video: Invalid parameters";
  1415. default:
  1416. if (ret != OBS_VIDEO_SUCCESS)
  1417. throw UNKNOWN_ERROR;
  1418. }
  1419. /* load audio monitoring */
  1420. if (obs_audio_monitoring_available()) {
  1421. const char *device_name = config_get_string(
  1422. basicConfig, "Audio", "MonitoringDeviceName");
  1423. const char *device_id = config_get_string(basicConfig, "Audio",
  1424. "MonitoringDeviceId");
  1425. obs_set_audio_monitoring_device(device_name, device_id);
  1426. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1427. device_name, device_id);
  1428. }
  1429. InitOBSCallbacks();
  1430. InitHotkeys();
  1431. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1432. * to ship with */
  1433. #if defined(_WIN32) && !defined(_DEBUG)
  1434. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1435. LoadLibraryW(L"Qt5Network");
  1436. #else
  1437. LoadLibraryW(L"Qt6Network");
  1438. #endif
  1439. #endif
  1440. struct obs_module_failure_info mfi;
  1441. AddExtraModulePaths();
  1442. blog(LOG_INFO, "---------------------------------");
  1443. obs_load_all_modules2(&mfi);
  1444. blog(LOG_INFO, "---------------------------------");
  1445. obs_log_loaded_modules();
  1446. blog(LOG_INFO, "---------------------------------");
  1447. obs_post_load_modules();
  1448. BPtr<char *> failed_modules = mfi.failed_modules;
  1449. #ifdef BROWSER_AVAILABLE
  1450. cef = obs_browser_init_panel();
  1451. #endif
  1452. OBSDataAutoRelease obsData = obs_get_private_data();
  1453. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1454. if (vcamEnabled) {
  1455. AddVCamButton();
  1456. }
  1457. InitBasicConfigDefaults2();
  1458. CheckForSimpleModeX264Fallback();
  1459. blog(LOG_INFO, STARTUP_SEPARATOR);
  1460. ResetOutputs();
  1461. CreateHotkeys();
  1462. if (!InitService())
  1463. throw "Failed to initialize service";
  1464. InitPrimitives();
  1465. sceneDuplicationMode = config_get_bool(
  1466. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1467. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1468. "SwapScenesMode");
  1469. editPropertiesMode = config_get_bool(
  1470. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1471. if (!opt_studio_mode) {
  1472. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1473. "BasicWindow",
  1474. "PreviewProgramMode"));
  1475. } else {
  1476. SetPreviewProgramMode(true);
  1477. opt_studio_mode = false;
  1478. }
  1479. #define SET_VISIBILITY(name, control) \
  1480. do { \
  1481. if (config_has_user_value(App()->GlobalConfig(), \
  1482. "BasicWindow", name)) { \
  1483. bool visible = config_get_bool(App()->GlobalConfig(), \
  1484. "BasicWindow", name); \
  1485. ui->control->setChecked(visible); \
  1486. } \
  1487. } while (false)
  1488. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1489. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1490. #undef SET_VISIBILITY
  1491. bool sourceIconsVisible = config_get_bool(
  1492. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1493. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1494. bool contextVisible = config_get_bool(
  1495. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1496. ui->toggleContextBar->setChecked(contextVisible);
  1497. ui->contextContainer->setVisible(contextVisible);
  1498. if (contextVisible)
  1499. UpdateContextBar(true);
  1500. UpdateEditMenu();
  1501. {
  1502. ProfileScope("OBSBasic::Load");
  1503. disableSaving--;
  1504. Load(savePath);
  1505. disableSaving++;
  1506. }
  1507. TimedCheckForUpdates();
  1508. loaded = true;
  1509. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1510. "PreviewEnabled");
  1511. if (!previewEnabled && !IsPreviewProgramMode())
  1512. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1513. Qt::QueuedConnection,
  1514. Q_ARG(bool, previewEnabled));
  1515. #ifdef _WIN32
  1516. uint32_t winVer = GetWindowsVersion();
  1517. if (winVer > 0 && winVer < 0x602) {
  1518. bool disableAero =
  1519. config_get_bool(basicConfig, "Video", "DisableAero");
  1520. SetAeroEnabled(!disableAero);
  1521. }
  1522. #endif
  1523. RefreshSceneCollections();
  1524. RefreshProfiles();
  1525. disableSaving--;
  1526. auto addDisplay = [this](OBSQTDisplay *window) {
  1527. obs_display_add_draw_callback(window->GetDisplay(),
  1528. OBSBasic::RenderMain, this);
  1529. struct obs_video_info ovi;
  1530. if (obs_get_video_info(&ovi))
  1531. ResizePreview(ovi.base_width, ovi.base_height);
  1532. };
  1533. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1534. /* Show the main window, unless the tray icon isn't available
  1535. * or neither the setting nor flag for starting minimized is set. */
  1536. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1537. "BasicWindow", "sysTrayEnabled");
  1538. bool sysTrayWhenStarted = config_get_bool(
  1539. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1540. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1541. sysTrayEnabled &&
  1542. (opt_minimize_tray || sysTrayWhenStarted);
  1543. #ifdef _WIN32
  1544. SetWin32DropStyle(this);
  1545. if (!hideWindowOnStart)
  1546. show();
  1547. #endif
  1548. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1549. "AlwaysOnTop");
  1550. #ifdef ENABLE_WAYLAND
  1551. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1552. #else
  1553. bool isWayland = false;
  1554. #endif
  1555. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1556. SetAlwaysOnTop(this, true);
  1557. ui->actionAlwaysOnTop->setChecked(true);
  1558. } else if (isWayland) {
  1559. if (opt_always_on_top)
  1560. blog(LOG_INFO,
  1561. "Always On Top not available on Wayland, ignoring.");
  1562. ui->actionAlwaysOnTop->setEnabled(false);
  1563. ui->actionAlwaysOnTop->setVisible(false);
  1564. }
  1565. #ifndef _WIN32
  1566. if (!hideWindowOnStart)
  1567. show();
  1568. #endif
  1569. /* setup stats dock */
  1570. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1571. statsDock->setWidget(statsDlg);
  1572. /* ----------------------------- */
  1573. /* add custom browser docks */
  1574. #ifdef BROWSER_AVAILABLE
  1575. if (cef) {
  1576. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1577. "CustomBrowserDocks"),
  1578. this);
  1579. ui->menuDocks->insertAction(ui->toggleScenes, action);
  1580. connect(action, &QAction::triggered, this,
  1581. &OBSBasic::ManageExtraBrowserDocks);
  1582. ui->menuDocks->insertSeparator(ui->toggleScenes);
  1583. LoadExtraBrowserDocks();
  1584. }
  1585. #endif
  1586. const char *dockStateStr = config_get_string(
  1587. App()->GlobalConfig(), "BasicWindow", "DockState");
  1588. if (!dockStateStr) {
  1589. on_resetDocks_triggered(true);
  1590. } else {
  1591. QByteArray dockState =
  1592. QByteArray::fromBase64(QByteArray(dockStateStr));
  1593. if (!restoreState(dockState))
  1594. on_resetDocks_triggered(true);
  1595. }
  1596. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1597. "Pre23Defaults");
  1598. if (pre23Defaults) {
  1599. bool resetDockLock23 = config_get_bool(
  1600. App()->GlobalConfig(), "General", "ResetDockLock23");
  1601. if (!resetDockLock23) {
  1602. config_set_bool(App()->GlobalConfig(), "General",
  1603. "ResetDockLock23", true);
  1604. config_remove_value(App()->GlobalConfig(),
  1605. "BasicWindow", "DocksLocked");
  1606. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1607. }
  1608. }
  1609. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1610. "DocksLocked");
  1611. on_lockDocks_toggled(docksLocked);
  1612. ui->lockDocks->blockSignals(true);
  1613. ui->lockDocks->setChecked(docksLocked);
  1614. ui->lockDocks->blockSignals(false);
  1615. SystemTray(true);
  1616. TaskbarOverlayInit();
  1617. #ifdef __APPLE__
  1618. disableColorSpaceConversion(this);
  1619. #endif
  1620. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1621. "General", "LastVersion");
  1622. bool first_run =
  1623. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1624. if (!first_run) {
  1625. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1626. true);
  1627. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1628. }
  1629. if (!first_run && !has_last_version && !Active())
  1630. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1631. Qt::QueuedConnection);
  1632. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1633. "VerticalVolControl"));
  1634. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1635. on_stats_triggered();
  1636. OBSBasicStats::InitializeValues();
  1637. /* ----------------------- */
  1638. /* Add multiview menu */
  1639. ui->viewMenu->addSeparator();
  1640. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1641. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1642. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1643. SLOT(OpenMultiviewProjector()));
  1644. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1645. &OBSBasic::UpdateMultiviewProjectorMenu);
  1646. ui->viewMenu->addAction(QTStr("MultiviewWindowed"), this,
  1647. SLOT(OpenMultiviewWindow()));
  1648. ui->sources->UpdateIcons();
  1649. #if !defined(_WIN32)
  1650. delete ui->actionShowCrashLogs;
  1651. delete ui->actionUploadLastCrashLog;
  1652. delete ui->menuCrashLogs;
  1653. delete ui->actionRepair;
  1654. ui->actionShowCrashLogs = nullptr;
  1655. ui->actionUploadLastCrashLog = nullptr;
  1656. ui->menuCrashLogs = nullptr;
  1657. ui->actionRepair = nullptr;
  1658. #if !defined(__APPLE__)
  1659. delete ui->actionCheckForUpdates;
  1660. ui->actionCheckForUpdates = nullptr;
  1661. #endif
  1662. #endif
  1663. #ifdef __APPLE__
  1664. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1665. delete ui->actionFullscreenInterface;
  1666. ui->actionFullscreenInterface = nullptr;
  1667. #else
  1668. /* Don't show menu to raise macOS-only permissions dialog */
  1669. delete ui->actionShowMacPermissions;
  1670. ui->actionShowMacPermissions = nullptr;
  1671. #endif
  1672. #if defined(_WIN32) || defined(__APPLE__)
  1673. if (App()->IsUpdaterDisabled()) {
  1674. ui->actionCheckForUpdates->setEnabled(false);
  1675. #if defined(_WIN32)
  1676. ui->actionRepair->setEnabled(false);
  1677. #endif
  1678. }
  1679. #endif
  1680. UpdatePreviewProgramIndicators();
  1681. OnFirstLoad();
  1682. activateWindow();
  1683. /* ------------------------------------------- */
  1684. /* display warning message for failed modules */
  1685. if (mfi.count) {
  1686. QString failed_plugins;
  1687. char **plugin = mfi.failed_modules;
  1688. while (*plugin) {
  1689. failed_plugins += *plugin;
  1690. failed_plugins += "\n";
  1691. plugin++;
  1692. }
  1693. QString failed_msg =
  1694. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  1695. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  1696. failed_msg);
  1697. }
  1698. }
  1699. void OBSBasic::OnFirstLoad()
  1700. {
  1701. if (api)
  1702. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1703. #ifdef WHATSNEW_ENABLED
  1704. /* Attempt to load init screen if available */
  1705. if (cef) {
  1706. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1707. connect(wnit, &WhatsNewInfoThread::Result, this,
  1708. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  1709. introCheckThread.reset(wnit);
  1710. introCheckThread->start();
  1711. }
  1712. #endif
  1713. Auth::Load();
  1714. bool showLogViewerOnStartup = config_get_bool(
  1715. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1716. if (showLogViewerOnStartup)
  1717. on_actionViewCurrentLog_triggered();
  1718. }
  1719. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1720. #define CUR_VER \
  1721. ((uint64_t)OBS_RELEASE_CANDIDATE_VER << 16ULL | OBS_RELEASE_CANDIDATE)
  1722. #define LAST_INFO_VERSION_STRING "InfoLastRCVersion"
  1723. #elif OBS_BETA > 0
  1724. #define CUR_VER ((uint64_t)OBS_BETA_VER << 16ULL | OBS_BETA)
  1725. #define LAST_INFO_VERSION_STRING "InfoLastBetaVersion"
  1726. #else
  1727. #define CUR_VER ((uint64_t)LIBOBS_API_VER << 16ULL)
  1728. #define LAST_INFO_VERSION_STRING "InfoLastVersion"
  1729. #endif
  1730. /* shows a "what's new" page on startup of new versions using CEF */
  1731. void OBSBasic::ReceivedIntroJson(const QString &text)
  1732. {
  1733. #ifdef WHATSNEW_ENABLED
  1734. if (closing)
  1735. return;
  1736. std::string err;
  1737. Json json = Json::parse(QT_TO_UTF8(text), err);
  1738. if (!err.empty())
  1739. return;
  1740. std::string info_url;
  1741. int info_increment = -1;
  1742. /* check to see if there's an info page for this version */
  1743. const Json::array &items = json.array_items();
  1744. for (const Json &item : items) {
  1745. const std::string &version = item["version"].string_value();
  1746. const std::string &url = item["url"].string_value();
  1747. int increment = item["increment"].int_value();
  1748. int beta = item["Beta"].int_value();
  1749. int rc = item["RC"].int_value();
  1750. int major = 0;
  1751. int minor = 0;
  1752. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1753. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1754. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1755. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1756. rc == OBS_RELEASE_CANDIDATE) {
  1757. #elif OBS_BETA > 0
  1758. if (major == OBS_BETA_MAJOR && minor == OBS_BETA_MINOR &&
  1759. beta == OBS_BETA) {
  1760. #else
  1761. if (major == LIBOBS_API_MAJOR_VER &&
  1762. minor == LIBOBS_API_MINOR_VER && rc == 0 && beta == 0) {
  1763. #endif
  1764. info_url = url;
  1765. info_increment = increment;
  1766. }
  1767. }
  1768. /* this version was not found, or no info for this version */
  1769. if (info_increment == -1) {
  1770. return;
  1771. }
  1772. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  1773. LAST_INFO_VERSION_STRING);
  1774. int current_version_increment = -1;
  1775. if ((lastVersion & ~0xFFFF0000ULL) < (CUR_VER & ~0xFFFF0000ULL)) {
  1776. config_set_int(App()->GlobalConfig(), "General",
  1777. "InfoIncrement", -1);
  1778. config_set_uint(App()->GlobalConfig(), "General",
  1779. LAST_INFO_VERSION_STRING, CUR_VER);
  1780. } else {
  1781. current_version_increment = config_get_int(
  1782. App()->GlobalConfig(), "General", "InfoIncrement");
  1783. }
  1784. if (info_increment <= current_version_increment) {
  1785. return;
  1786. }
  1787. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  1788. info_increment);
  1789. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1790. cef->init_browser();
  1791. WhatsNewBrowserInitThread *wnbit =
  1792. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  1793. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  1794. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  1795. whatsNewInitThread.reset(wnbit);
  1796. whatsNewInitThread->start();
  1797. #else
  1798. UNUSED_PARAMETER(text);
  1799. #endif
  1800. }
  1801. #undef CUR_VER
  1802. #undef LAST_INFO_VERSION_STRING
  1803. void OBSBasic::ShowWhatsNew(const QString &url)
  1804. {
  1805. #ifdef BROWSER_AVAILABLE
  1806. if (closing)
  1807. return;
  1808. std::string info_url = QT_TO_UTF8(url);
  1809. QDialog *dlg = new QDialog(this);
  1810. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1811. dlg->setWindowTitle("What's New");
  1812. dlg->resize(700, 600);
  1813. Qt::WindowFlags flags = dlg->windowFlags();
  1814. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1815. dlg->setWindowFlags(flags & (~helpFlag));
  1816. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1817. if (!cefWidget) {
  1818. return;
  1819. }
  1820. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  1821. SLOT(setWindowTitle(const QString &)));
  1822. QPushButton *close = new QPushButton(QTStr("Close"));
  1823. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  1824. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1825. bottomLayout->addStretch();
  1826. bottomLayout->addWidget(close);
  1827. bottomLayout->addStretch();
  1828. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1829. topLayout->addWidget(cefWidget);
  1830. topLayout->addLayout(bottomLayout);
  1831. dlg->show();
  1832. #else
  1833. UNUSED_PARAMETER(url);
  1834. #endif
  1835. }
  1836. void OBSBasic::UpdateMultiviewProjectorMenu()
  1837. {
  1838. multiviewProjectorMenu->clear();
  1839. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1840. SLOT(OpenMultiviewProjector()));
  1841. }
  1842. void OBSBasic::InitHotkeys()
  1843. {
  1844. ProfileScope("OBSBasic::InitHotkeys");
  1845. struct obs_hotkeys_translations t = {};
  1846. t.insert = Str("Hotkeys.Insert");
  1847. t.del = Str("Hotkeys.Delete");
  1848. t.home = Str("Hotkeys.Home");
  1849. t.end = Str("Hotkeys.End");
  1850. t.page_up = Str("Hotkeys.PageUp");
  1851. t.page_down = Str("Hotkeys.PageDown");
  1852. t.num_lock = Str("Hotkeys.NumLock");
  1853. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1854. t.caps_lock = Str("Hotkeys.CapsLock");
  1855. t.backspace = Str("Hotkeys.Backspace");
  1856. t.tab = Str("Hotkeys.Tab");
  1857. t.print = Str("Hotkeys.Print");
  1858. t.pause = Str("Hotkeys.Pause");
  1859. t.left = Str("Hotkeys.Left");
  1860. t.right = Str("Hotkeys.Right");
  1861. t.up = Str("Hotkeys.Up");
  1862. t.down = Str("Hotkeys.Down");
  1863. #ifdef _WIN32
  1864. t.meta = Str("Hotkeys.Windows");
  1865. #else
  1866. t.meta = Str("Hotkeys.Super");
  1867. #endif
  1868. t.menu = Str("Hotkeys.Menu");
  1869. t.space = Str("Hotkeys.Space");
  1870. t.numpad_num = Str("Hotkeys.NumpadNum");
  1871. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1872. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1873. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1874. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1875. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1876. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1877. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1878. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1879. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1880. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1881. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1882. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1883. t.mouse_num = Str("Hotkeys.MouseButton");
  1884. t.escape = Str("Hotkeys.Escape");
  1885. obs_hotkeys_set_translations(&t);
  1886. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1887. Str("Push-to-mute"),
  1888. Str("Push-to-talk"));
  1889. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  1890. Str("SceneItemHide"));
  1891. obs_hotkey_enable_callback_rerouting(true);
  1892. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1893. }
  1894. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1895. {
  1896. obs_hotkey_trigger_routed_callback(id, pressed);
  1897. }
  1898. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1899. {
  1900. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1901. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1902. Q_ARG(obs_hotkey_id, id),
  1903. Q_ARG(bool, pressed));
  1904. }
  1905. void OBSBasic::CreateHotkeys()
  1906. {
  1907. ProfileScope("OBSBasic::CreateHotkeys");
  1908. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  1909. const char *info =
  1910. config_get_string(basicConfig, "Hotkeys", name);
  1911. if (!info)
  1912. return {};
  1913. OBSDataAutoRelease data = obs_data_create_from_json(info);
  1914. if (!data)
  1915. return {};
  1916. return data.Get();
  1917. };
  1918. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  1919. OBSDataArrayAutoRelease array =
  1920. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1921. obs_hotkey_load(id, array);
  1922. };
  1923. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1924. const char *name1) {
  1925. OBSDataArrayAutoRelease array0 =
  1926. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1927. OBSDataArrayAutoRelease array1 =
  1928. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1929. obs_hotkey_pair_load(id, array0, array1);
  1930. };
  1931. #define MAKE_CALLBACK(pred, method, log_action) \
  1932. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  1933. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  1934. if ((pred) && pressed) { \
  1935. blog(LOG_INFO, log_action " due to hotkey"); \
  1936. method(); \
  1937. return true; \
  1938. } \
  1939. return false; \
  1940. }
  1941. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1942. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  1943. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  1944. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1945. basic.ui->streamButton->isEnabled(),
  1946. basic.StartStreaming, "Starting stream"),
  1947. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1948. basic.ui->streamButton->isEnabled(),
  1949. basic.StopStreaming, "Stopping stream"),
  1950. this, this);
  1951. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  1952. "OBSBasic.StopStreaming");
  1953. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1954. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1955. if (basic.outputHandler->StreamingActive() && pressed) {
  1956. basic.ForceStopStreaming();
  1957. }
  1958. };
  1959. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1960. "OBSBasic.ForceStopStreaming",
  1961. Str("Basic.Main.ForceStopStreaming"), cb, this);
  1962. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  1963. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1964. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  1965. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  1966. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1967. !basic.ui->recordButton->isChecked(),
  1968. basic.StartRecording, "Starting recording"),
  1969. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1970. basic.ui->recordButton->isChecked(),
  1971. basic.StopRecording, "Stopping recording"),
  1972. this, this);
  1973. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  1974. "OBSBasic.StopRecording");
  1975. pauseHotkeys = obs_hotkey_pair_register_frontend(
  1976. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  1977. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  1978. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  1979. basic.PauseRecording, "Pausing recording"),
  1980. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  1981. basic.UnpauseRecording, "Unpausing recording"),
  1982. this, this);
  1983. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  1984. "OBSBasic.UnpauseRecording");
  1985. splitFileHotkey = obs_hotkey_register_frontend(
  1986. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  1987. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1988. if (pressed)
  1989. obs_frontend_recording_split_file();
  1990. },
  1991. this);
  1992. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  1993. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1994. "OBSBasic.StartReplayBuffer",
  1995. Str("Basic.Main.StartReplayBuffer"),
  1996. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  1997. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1998. basic.StartReplayBuffer,
  1999. "Starting replay buffer"),
  2000. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2001. basic.StopReplayBuffer, "Stopping replay buffer"),
  2002. this, this);
  2003. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2004. "OBSBasic.StopReplayBuffer");
  2005. if (vcamEnabled) {
  2006. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2007. "OBSBasic.StartVirtualCam",
  2008. Str("Basic.Main.StartVirtualCam"),
  2009. "OBSBasic.StopVirtualCam",
  2010. Str("Basic.Main.StopVirtualCam"),
  2011. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2012. basic.StartVirtualCam,
  2013. "Starting virtual camera"),
  2014. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2015. basic.StopVirtualCam,
  2016. "Stopping virtual camera"),
  2017. this, this);
  2018. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2019. "OBSBasic.StopVirtualCam");
  2020. }
  2021. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2022. "OBSBasic.EnablePreview",
  2023. Str("Basic.Main.PreviewConextMenu.Enable"),
  2024. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2025. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2026. "Enabling preview"),
  2027. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2028. "Disabling preview"),
  2029. this, this);
  2030. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2031. "OBSBasic.DisablePreview");
  2032. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2033. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2034. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2035. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2036. basic.ShowContextBar, "Showing Context Bar"),
  2037. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2038. basic.HideContextBar, "Hiding Context Bar"),
  2039. this, this);
  2040. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2041. "OBSBasic.HideContextBar");
  2042. #undef MAKE_CALLBACK
  2043. auto togglePreviewProgram = [](void *data, obs_hotkey_id,
  2044. obs_hotkey_t *, bool pressed) {
  2045. if (pressed)
  2046. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2047. "on_modeSwitch_clicked",
  2048. Qt::QueuedConnection);
  2049. };
  2050. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  2051. "OBSBasic.TogglePreviewProgram",
  2052. Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
  2053. this);
  2054. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  2055. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2056. bool pressed) {
  2057. if (pressed)
  2058. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2059. "TransitionClicked",
  2060. Qt::QueuedConnection);
  2061. };
  2062. transitionHotkey = obs_hotkey_register_frontend(
  2063. "OBSBasic.Transition", Str("Transition"), transition, this);
  2064. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2065. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2066. bool pressed) {
  2067. if (pressed)
  2068. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2069. "ResetStatsHotkey",
  2070. Qt::QueuedConnection);
  2071. };
  2072. statsHotkey = obs_hotkey_register_frontend(
  2073. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2074. resetStats, this);
  2075. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2076. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2077. bool pressed) {
  2078. if (pressed)
  2079. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2080. "Screenshot",
  2081. Qt::QueuedConnection);
  2082. };
  2083. screenshotHotkey = obs_hotkey_register_frontend(
  2084. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2085. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2086. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2087. bool pressed) {
  2088. if (pressed)
  2089. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2090. "ScreenshotSelectedSource",
  2091. Qt::QueuedConnection);
  2092. };
  2093. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2094. "OBSBasic.SelectedSourceScreenshot",
  2095. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2096. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2097. }
  2098. void OBSBasic::ClearHotkeys()
  2099. {
  2100. obs_hotkey_pair_unregister(streamingHotkeys);
  2101. obs_hotkey_pair_unregister(recordingHotkeys);
  2102. obs_hotkey_pair_unregister(pauseHotkeys);
  2103. obs_hotkey_unregister(splitFileHotkey);
  2104. obs_hotkey_pair_unregister(replayBufHotkeys);
  2105. obs_hotkey_pair_unregister(vcamHotkeys);
  2106. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2107. obs_hotkey_pair_unregister(contextBarHotkeys);
  2108. obs_hotkey_unregister(forceStreamingStopHotkey);
  2109. obs_hotkey_unregister(togglePreviewProgramHotkey);
  2110. obs_hotkey_unregister(transitionHotkey);
  2111. obs_hotkey_unregister(statsHotkey);
  2112. obs_hotkey_unregister(screenshotHotkey);
  2113. obs_hotkey_unregister(sourceScreenshotHotkey);
  2114. }
  2115. OBSBasic::~OBSBasic()
  2116. {
  2117. /* clear out UI event queue */
  2118. QApplication::sendPostedEvents(nullptr);
  2119. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2120. if (updateCheckThread && updateCheckThread->isRunning())
  2121. updateCheckThread->wait();
  2122. delete screenshotData;
  2123. delete multiviewProjectorMenu;
  2124. delete previewProjector;
  2125. delete studioProgramProjector;
  2126. delete previewProjectorSource;
  2127. delete previewProjectorMain;
  2128. delete sourceProjector;
  2129. delete sceneProjectorMenu;
  2130. delete scaleFilteringMenu;
  2131. delete blendingModeMenu;
  2132. delete colorMenu;
  2133. delete colorWidgetAction;
  2134. delete colorSelect;
  2135. delete deinterlaceMenu;
  2136. delete perSceneTransitionMenu;
  2137. delete shortcutFilter;
  2138. delete trayMenu;
  2139. delete programOptions;
  2140. delete program;
  2141. /* XXX: any obs data must be released before calling obs_shutdown.
  2142. * currently, we can't automate this with C++ RAII because of the
  2143. * delicate nature of obs_shutdown needing to be freed before the UI
  2144. * can be freed, and we have no control over the destruction order of
  2145. * the Qt UI stuff, so we have to manually clear any references to
  2146. * libobs. */
  2147. delete cpuUsageTimer;
  2148. os_cpu_usage_info_destroy(cpuUsageInfo);
  2149. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2150. ClearHotkeys();
  2151. service = nullptr;
  2152. outputHandler.reset();
  2153. if (interaction)
  2154. delete interaction;
  2155. if (properties)
  2156. delete properties;
  2157. if (filters)
  2158. delete filters;
  2159. if (transformWindow)
  2160. delete transformWindow;
  2161. if (advAudioWindow)
  2162. delete advAudioWindow;
  2163. if (about)
  2164. delete about;
  2165. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2166. OBSBasic::RenderMain, this);
  2167. obs_enter_graphics();
  2168. gs_vertexbuffer_destroy(box);
  2169. gs_vertexbuffer_destroy(boxLeft);
  2170. gs_vertexbuffer_destroy(boxTop);
  2171. gs_vertexbuffer_destroy(boxRight);
  2172. gs_vertexbuffer_destroy(boxBottom);
  2173. gs_vertexbuffer_destroy(circle);
  2174. gs_vertexbuffer_destroy(actionSafeMargin);
  2175. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2176. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2177. gs_vertexbuffer_destroy(leftLine);
  2178. gs_vertexbuffer_destroy(topLine);
  2179. gs_vertexbuffer_destroy(rightLine);
  2180. obs_leave_graphics();
  2181. /* When shutting down, sometimes source references can get in to the
  2182. * event queue, and if we don't forcibly process those events they
  2183. * won't get processed until after obs_shutdown has been called. I
  2184. * really wish there were a more elegant way to deal with this via C++,
  2185. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2186. * normal C++ behavior for your data to be freed in the order that you
  2187. * expect or want it to. */
  2188. QApplication::sendPostedEvents(nullptr);
  2189. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2190. LIBOBS_API_VER);
  2191. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  2192. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2193. OBS_RELEASE_CANDIDATE_VER);
  2194. #elif OBS_BETA > 0
  2195. config_set_int(App()->GlobalConfig(), "General", "LastBetaVersion",
  2196. OBS_BETA_VER);
  2197. #endif
  2198. bool alwaysOnTop = IsAlwaysOnTop(this);
  2199. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2200. previewEnabled);
  2201. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2202. alwaysOnTop);
  2203. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2204. "SceneDuplicationMode", sceneDuplicationMode);
  2205. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2206. swapScenesMode);
  2207. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2208. "EditPropertiesMode", editPropertiesMode);
  2209. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2210. "PreviewProgramMode", IsPreviewProgramMode());
  2211. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2212. ui->lockDocks->isChecked());
  2213. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2214. #ifdef _WIN32
  2215. uint32_t winVer = GetWindowsVersion();
  2216. if (winVer > 0 && winVer < 0x602) {
  2217. bool disableAero =
  2218. config_get_bool(basicConfig, "Video", "DisableAero");
  2219. if (disableAero) {
  2220. SetAeroEnabled(true);
  2221. }
  2222. }
  2223. #endif
  2224. #ifdef BROWSER_AVAILABLE
  2225. DestroyPanelCookieManager();
  2226. delete cef;
  2227. cef = nullptr;
  2228. #endif
  2229. OBSBasicVCamConfig::DestroyView();
  2230. }
  2231. void OBSBasic::SaveProjectNow()
  2232. {
  2233. if (disableSaving)
  2234. return;
  2235. projectChanged = true;
  2236. SaveProjectDeferred();
  2237. }
  2238. void OBSBasic::SaveProject()
  2239. {
  2240. if (disableSaving)
  2241. return;
  2242. projectChanged = true;
  2243. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2244. Qt::QueuedConnection);
  2245. }
  2246. void OBSBasic::SaveProjectDeferred()
  2247. {
  2248. if (disableSaving)
  2249. return;
  2250. if (!projectChanged)
  2251. return;
  2252. projectChanged = false;
  2253. const char *sceneCollection = config_get_string(
  2254. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2255. char savePath[1024];
  2256. char fileName[1024];
  2257. int ret;
  2258. if (!sceneCollection)
  2259. return;
  2260. ret = snprintf(fileName, sizeof(fileName),
  2261. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2262. if (ret <= 0)
  2263. return;
  2264. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2265. if (ret <= 0)
  2266. return;
  2267. Save(savePath);
  2268. }
  2269. OBSSource OBSBasic::GetProgramSource()
  2270. {
  2271. return OBSGetStrongRef(programScene);
  2272. }
  2273. OBSScene OBSBasic::GetCurrentScene()
  2274. {
  2275. return currentScene.load();
  2276. }
  2277. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2278. {
  2279. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2280. }
  2281. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2282. {
  2283. return ui->sources->Get(GetTopSelectedSourceItem());
  2284. }
  2285. void OBSBasic::UpdatePreviewScalingMenu()
  2286. {
  2287. bool fixedScaling = ui->preview->IsFixedScaling();
  2288. float scalingAmount = ui->preview->GetScalingAmount();
  2289. if (!fixedScaling) {
  2290. ui->actionScaleWindow->setChecked(true);
  2291. ui->actionScaleCanvas->setChecked(false);
  2292. ui->actionScaleOutput->setChecked(false);
  2293. return;
  2294. }
  2295. obs_video_info ovi;
  2296. obs_get_video_info(&ovi);
  2297. ui->actionScaleWindow->setChecked(false);
  2298. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2299. ui->actionScaleOutput->setChecked(scalingAmount ==
  2300. float(ovi.output_width) /
  2301. float(ovi.base_width));
  2302. }
  2303. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2304. {
  2305. bool closed = true;
  2306. if (interaction)
  2307. closed = interaction->close();
  2308. if (!closed)
  2309. return;
  2310. interaction = new OBSBasicInteraction(this, source);
  2311. interaction->Init();
  2312. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2313. }
  2314. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2315. {
  2316. bool closed = true;
  2317. if (properties)
  2318. closed = properties->close();
  2319. if (!closed)
  2320. return;
  2321. properties = new OBSBasicProperties(this, source);
  2322. properties->Init();
  2323. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2324. }
  2325. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2326. {
  2327. bool closed = true;
  2328. if (filters)
  2329. closed = filters->close();
  2330. if (!closed)
  2331. return;
  2332. filters = new OBSBasicFilters(this, source);
  2333. filters->Init();
  2334. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2335. }
  2336. /* Qt callbacks for invokeMethod */
  2337. void OBSBasic::AddScene(OBSSource source)
  2338. {
  2339. const char *name = obs_source_get_name(source);
  2340. obs_scene_t *scene = obs_scene_from_source(source);
  2341. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2342. SetOBSRef(item, OBSScene(scene));
  2343. ui->scenes->addItem(item);
  2344. obs_hotkey_register_source(
  2345. source, "OBSBasic.SelectScene",
  2346. Str("Basic.Hotkeys.SelectScene"),
  2347. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2348. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2349. App()->GetMainWindow());
  2350. auto potential_source =
  2351. static_cast<obs_source_t *>(data);
  2352. OBSSourceAutoRelease source =
  2353. obs_source_get_ref(potential_source);
  2354. if (source && pressed)
  2355. main->SetCurrentScene(source.Get());
  2356. },
  2357. static_cast<obs_source_t *>(source));
  2358. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2359. SignalContainer<OBSScene> container;
  2360. container.ref = scene;
  2361. container.handlers.assign({
  2362. std::make_shared<OBSSignal>(handler, "item_add",
  2363. OBSBasic::SceneItemAdded, this),
  2364. std::make_shared<OBSSignal>(handler, "reorder",
  2365. OBSBasic::SceneReordered, this),
  2366. std::make_shared<OBSSignal>(handler, "refresh",
  2367. OBSBasic::SceneRefreshed, this),
  2368. });
  2369. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2370. QVariant::fromValue(container));
  2371. /* if the scene already has items (a duplicated scene) add them */
  2372. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2373. AddSceneItem(item);
  2374. };
  2375. using addSceneItem_t = decltype(addSceneItem);
  2376. obs_scene_enum_items(
  2377. scene,
  2378. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2379. addSceneItem_t *func;
  2380. func = reinterpret_cast<addSceneItem_t *>(param);
  2381. (*func)(item);
  2382. return true;
  2383. },
  2384. &addSceneItem);
  2385. SaveProject();
  2386. if (!disableSaving) {
  2387. obs_source_t *source = obs_scene_get_source(scene);
  2388. blog(LOG_INFO, "User added scene '%s'",
  2389. obs_source_get_name(source));
  2390. OBSProjector::UpdateMultiviewProjectors();
  2391. }
  2392. if (api)
  2393. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2394. }
  2395. void OBSBasic::RemoveScene(OBSSource source)
  2396. {
  2397. obs_scene_t *scene = obs_scene_from_source(source);
  2398. QListWidgetItem *sel = nullptr;
  2399. int count = ui->scenes->count();
  2400. for (int i = 0; i < count; i++) {
  2401. auto item = ui->scenes->item(i);
  2402. auto cur_scene = GetOBSRef<OBSScene>(item);
  2403. if (cur_scene != scene)
  2404. continue;
  2405. sel = item;
  2406. break;
  2407. }
  2408. if (sel != nullptr) {
  2409. if (sel == ui->scenes->currentItem())
  2410. ui->sources->Clear();
  2411. delete sel;
  2412. }
  2413. SaveProject();
  2414. if (!disableSaving) {
  2415. blog(LOG_INFO, "User Removed scene '%s'",
  2416. obs_source_get_name(source));
  2417. OBSProjector::UpdateMultiviewProjectors();
  2418. }
  2419. if (api)
  2420. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2421. }
  2422. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2423. {
  2424. obs_sceneitem_t *selectedItem =
  2425. reinterpret_cast<obs_sceneitem_t *>(param);
  2426. if (obs_sceneitem_is_group(item))
  2427. obs_sceneitem_group_enum_items(item, select_one, param);
  2428. obs_sceneitem_select(item, (selectedItem == item));
  2429. UNUSED_PARAMETER(scene);
  2430. return true;
  2431. }
  2432. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2433. {
  2434. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2435. if (GetCurrentScene() == scene)
  2436. ui->sources->Add(item);
  2437. SaveProject();
  2438. if (!disableSaving) {
  2439. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2440. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2441. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2442. obs_source_get_name(itemSource),
  2443. obs_source_get_id(itemSource),
  2444. obs_source_get_name(sceneSource));
  2445. obs_scene_enum_items(scene, select_one,
  2446. (obs_sceneitem_t *)item);
  2447. }
  2448. }
  2449. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2450. const QString &prevName)
  2451. {
  2452. QList<QListWidgetItem *> items =
  2453. listWidget->findItems(prevName, Qt::MatchExactly);
  2454. for (int i = 0; i < items.count(); i++)
  2455. items[i]->setText(newName);
  2456. }
  2457. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2458. QString prevName)
  2459. {
  2460. RenameListValues(ui->scenes, newName, prevName);
  2461. for (size_t i = 0; i < volumes.size(); i++) {
  2462. if (volumes[i]->GetName().compare(prevName) == 0)
  2463. volumes[i]->SetName(newName);
  2464. }
  2465. for (size_t i = 0; i < projectors.size(); i++) {
  2466. if (projectors[i]->GetSource() == source)
  2467. projectors[i]->RenameProjector(prevName, newName);
  2468. }
  2469. SaveProject();
  2470. obs_scene_t *scene = obs_scene_from_source(source);
  2471. if (scene)
  2472. OBSProjector::UpdateMultiviewProjectors();
  2473. UpdateContextBar();
  2474. UpdatePreviewProgramIndicators();
  2475. }
  2476. void OBSBasic::ClearContextBar()
  2477. {
  2478. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2479. if (la) {
  2480. delete la->widget();
  2481. ui->emptySpace->layout()->removeItem(la);
  2482. }
  2483. }
  2484. void OBSBasic::UpdateContextBarVisibility()
  2485. {
  2486. int width = ui->centralwidget->size().width();
  2487. ContextBarSize contextBarSizeNew;
  2488. if (width >= 740) {
  2489. contextBarSizeNew = ContextBarSize_Normal;
  2490. } else if (width >= 600) {
  2491. contextBarSizeNew = ContextBarSize_Reduced;
  2492. } else {
  2493. contextBarSizeNew = ContextBarSize_Minimized;
  2494. }
  2495. if (contextBarSize == contextBarSizeNew)
  2496. return;
  2497. contextBarSize = contextBarSizeNew;
  2498. UpdateContextBarDeferred();
  2499. }
  2500. static bool is_network_media_source(obs_source_t *source, const char *id)
  2501. {
  2502. if (strcmp(id, "ffmpeg_source") != 0)
  2503. return false;
  2504. OBSDataAutoRelease s = obs_source_get_settings(source);
  2505. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2506. return !is_local_file;
  2507. }
  2508. void OBSBasic::UpdateContextBarDeferred(bool force)
  2509. {
  2510. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2511. Qt::QueuedConnection, Q_ARG(bool, force));
  2512. }
  2513. void OBSBasic::UpdateContextBar(bool force)
  2514. {
  2515. if (!ui->contextContainer->isVisible() && !force)
  2516. return;
  2517. OBSSceneItem item = GetCurrentSceneItem();
  2518. if (item) {
  2519. obs_source_t *source = obs_sceneitem_get_source(item);
  2520. bool updateNeeded = true;
  2521. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2522. if (la) {
  2523. if (SourceToolbar *toolbar =
  2524. dynamic_cast<SourceToolbar *>(
  2525. la->widget())) {
  2526. if (toolbar->GetSource() == source)
  2527. updateNeeded = false;
  2528. } else if (MediaControls *toolbar =
  2529. dynamic_cast<MediaControls *>(
  2530. la->widget())) {
  2531. if (toolbar->GetSource() == source)
  2532. updateNeeded = false;
  2533. }
  2534. }
  2535. const char *id = obs_source_get_unversioned_id(source);
  2536. uint32_t flags = obs_source_get_output_flags(source);
  2537. ui->sourceInteractButton->setVisible(flags &
  2538. OBS_SOURCE_INTERACTION);
  2539. if (contextBarSize >= ContextBarSize_Reduced &&
  2540. (updateNeeded || force)) {
  2541. ClearContextBar();
  2542. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2543. if (!is_network_media_source(source, id)) {
  2544. MediaControls *mediaControls =
  2545. new MediaControls(
  2546. ui->emptySpace);
  2547. mediaControls->SetSource(source);
  2548. ui->emptySpace->layout()->addWidget(
  2549. mediaControls);
  2550. }
  2551. } else if (strcmp(id, "browser_source") == 0) {
  2552. BrowserToolbar *c = new BrowserToolbar(
  2553. ui->emptySpace, source);
  2554. ui->emptySpace->layout()->addWidget(c);
  2555. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2556. strcmp(id, "wasapi_output_capture") == 0 ||
  2557. strcmp(id, "coreaudio_input_capture") == 0 ||
  2558. strcmp(id, "coreaudio_output_capture") ==
  2559. 0 ||
  2560. strcmp(id, "pulse_input_capture") == 0 ||
  2561. strcmp(id, "pulse_output_capture") == 0 ||
  2562. strcmp(id, "alsa_input_capture") == 0) {
  2563. AudioCaptureToolbar *c =
  2564. new AudioCaptureToolbar(ui->emptySpace,
  2565. source);
  2566. c->Init();
  2567. ui->emptySpace->layout()->addWidget(c);
  2568. } else if (strcmp(id,
  2569. "wasapi_process_output_capture") ==
  2570. 0) {
  2571. ApplicationAudioCaptureToolbar *c =
  2572. new ApplicationAudioCaptureToolbar(
  2573. ui->emptySpace, source);
  2574. c->Init();
  2575. ui->emptySpace->layout()->addWidget(c);
  2576. } else if (strcmp(id, "window_capture") == 0 ||
  2577. strcmp(id, "xcomposite_input") == 0) {
  2578. WindowCaptureToolbar *c =
  2579. new WindowCaptureToolbar(ui->emptySpace,
  2580. source);
  2581. c->Init();
  2582. ui->emptySpace->layout()->addWidget(c);
  2583. } else if (strcmp(id, "monitor_capture") == 0 ||
  2584. strcmp(id, "display_capture") == 0 ||
  2585. strcmp(id, "xshm_input") == 0) {
  2586. DisplayCaptureToolbar *c =
  2587. new DisplayCaptureToolbar(
  2588. ui->emptySpace, source);
  2589. c->Init();
  2590. ui->emptySpace->layout()->addWidget(c);
  2591. } else if (strcmp(id, "dshow_input") == 0) {
  2592. DeviceCaptureToolbar *c =
  2593. new DeviceCaptureToolbar(ui->emptySpace,
  2594. source);
  2595. ui->emptySpace->layout()->addWidget(c);
  2596. } else if (strcmp(id, "game_capture") == 0) {
  2597. GameCaptureToolbar *c = new GameCaptureToolbar(
  2598. ui->emptySpace, source);
  2599. ui->emptySpace->layout()->addWidget(c);
  2600. } else if (strcmp(id, "image_source") == 0) {
  2601. ImageSourceToolbar *c = new ImageSourceToolbar(
  2602. ui->emptySpace, source);
  2603. ui->emptySpace->layout()->addWidget(c);
  2604. } else if (strcmp(id, "color_source") == 0) {
  2605. ColorSourceToolbar *c = new ColorSourceToolbar(
  2606. ui->emptySpace, source);
  2607. ui->emptySpace->layout()->addWidget(c);
  2608. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2609. strcmp(id, "text_gdiplus") == 0) {
  2610. TextSourceToolbar *c = new TextSourceToolbar(
  2611. ui->emptySpace, source);
  2612. ui->emptySpace->layout()->addWidget(c);
  2613. }
  2614. } else if (contextBarSize == ContextBarSize_Minimized) {
  2615. ClearContextBar();
  2616. }
  2617. QIcon icon;
  2618. if (strcmp(id, "scene") == 0)
  2619. icon = GetSceneIcon();
  2620. else if (strcmp(id, "group") == 0)
  2621. icon = GetGroupIcon();
  2622. else
  2623. icon = GetSourceIcon(id);
  2624. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2625. ui->contextSourceIcon->setPixmap(pixmap);
  2626. ui->contextSourceIconSpacer->hide();
  2627. ui->contextSourceIcon->show();
  2628. const char *name = obs_source_get_name(source);
  2629. ui->contextSourceLabel->setText(name);
  2630. ui->sourceFiltersButton->setEnabled(true);
  2631. ui->sourcePropertiesButton->setEnabled(
  2632. obs_source_configurable(source));
  2633. } else {
  2634. ClearContextBar();
  2635. ui->contextSourceIcon->hide();
  2636. ui->contextSourceIconSpacer->show();
  2637. ui->contextSourceLabel->setText(
  2638. QTStr("ContextBar.NoSelectedSource"));
  2639. ui->sourceFiltersButton->setEnabled(false);
  2640. ui->sourcePropertiesButton->setEnabled(false);
  2641. ui->sourceInteractButton->setVisible(false);
  2642. }
  2643. if (contextBarSize == ContextBarSize_Normal) {
  2644. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2645. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2646. ui->sourceInteractButton->setText(QTStr("Interact"));
  2647. } else {
  2648. ui->sourcePropertiesButton->setText("");
  2649. ui->sourceFiltersButton->setText("");
  2650. ui->sourceInteractButton->setText("");
  2651. }
  2652. }
  2653. static inline bool SourceMixerHidden(obs_source_t *source)
  2654. {
  2655. OBSDataAutoRelease priv_settings =
  2656. obs_source_get_private_settings(source);
  2657. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2658. return hidden;
  2659. }
  2660. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2661. {
  2662. OBSDataAutoRelease priv_settings =
  2663. obs_source_get_private_settings(source);
  2664. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2665. }
  2666. void OBSBasic::GetAudioSourceFilters()
  2667. {
  2668. QAction *action = reinterpret_cast<QAction *>(sender());
  2669. VolControl *vol = action->property("volControl").value<VolControl *>();
  2670. obs_source_t *source = vol->GetSource();
  2671. CreateFiltersWindow(source);
  2672. }
  2673. void OBSBasic::GetAudioSourceProperties()
  2674. {
  2675. QAction *action = reinterpret_cast<QAction *>(sender());
  2676. VolControl *vol = action->property("volControl").value<VolControl *>();
  2677. obs_source_t *source = vol->GetSource();
  2678. CreatePropertiesWindow(source);
  2679. }
  2680. void OBSBasic::HideAudioControl()
  2681. {
  2682. QAction *action = reinterpret_cast<QAction *>(sender());
  2683. VolControl *vol = action->property("volControl").value<VolControl *>();
  2684. obs_source_t *source = vol->GetSource();
  2685. if (!SourceMixerHidden(source)) {
  2686. SetSourceMixerHidden(source, true);
  2687. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  2688. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  2689. * the next event loop to hide it. Doesn't seem to be a problem
  2690. * with newer versions of QT. */
  2691. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  2692. Qt::QueuedConnection,
  2693. Q_ARG(OBSSource, OBSSource(source)));
  2694. }
  2695. }
  2696. void OBSBasic::UnhideAllAudioControls()
  2697. {
  2698. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2699. {
  2700. if (!obs_source_active(source))
  2701. return true;
  2702. if (!SourceMixerHidden(source))
  2703. return true;
  2704. SetSourceMixerHidden(source, false);
  2705. ActivateAudioSource(source);
  2706. return true;
  2707. };
  2708. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2709. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2710. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2711. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2712. }
  2713. void OBSBasic::ToggleHideMixer()
  2714. {
  2715. OBSSceneItem item = GetCurrentSceneItem();
  2716. OBSSource source = obs_sceneitem_get_source(item);
  2717. if (!SourceMixerHidden(source)) {
  2718. SetSourceMixerHidden(source, true);
  2719. DeactivateAudioSource(source);
  2720. } else {
  2721. SetSourceMixerHidden(source, false);
  2722. ActivateAudioSource(source);
  2723. }
  2724. }
  2725. void OBSBasic::MixerRenameSource()
  2726. {
  2727. QAction *action = reinterpret_cast<QAction *>(sender());
  2728. VolControl *vol = action->property("volControl").value<VolControl *>();
  2729. OBSSource source = vol->GetSource();
  2730. const char *prevName = obs_source_get_name(source);
  2731. for (;;) {
  2732. string name;
  2733. bool accepted = NameDialog::AskForName(
  2734. this, QTStr("Basic.Main.MixerRename.Title"),
  2735. QTStr("Basic.Main.MixerRename.Text"), name,
  2736. QT_UTF8(prevName));
  2737. if (!accepted)
  2738. return;
  2739. if (name.empty()) {
  2740. OBSMessageBox::warning(this,
  2741. QTStr("NoNameEntered.Title"),
  2742. QTStr("NoNameEntered.Text"));
  2743. continue;
  2744. }
  2745. OBSSourceAutoRelease sourceTest =
  2746. obs_get_source_by_name(name.c_str());
  2747. if (sourceTest) {
  2748. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2749. QTStr("NameExists.Text"));
  2750. continue;
  2751. }
  2752. obs_source_set_name(source, name.c_str());
  2753. break;
  2754. }
  2755. }
  2756. static inline bool SourceVolumeLocked(obs_source_t *source)
  2757. {
  2758. OBSDataAutoRelease priv_settings =
  2759. obs_source_get_private_settings(source);
  2760. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2761. return lock;
  2762. }
  2763. void OBSBasic::LockVolumeControl(bool lock)
  2764. {
  2765. QAction *action = reinterpret_cast<QAction *>(sender());
  2766. VolControl *vol = action->property("volControl").value<VolControl *>();
  2767. obs_source_t *source = vol->GetSource();
  2768. OBSDataAutoRelease priv_settings =
  2769. obs_source_get_private_settings(source);
  2770. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2771. vol->EnableSlider(!lock);
  2772. }
  2773. void OBSBasic::VolControlContextMenu()
  2774. {
  2775. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2776. /* ------------------- */
  2777. QAction lockAction(QTStr("LockVolume"), this);
  2778. lockAction.setCheckable(true);
  2779. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2780. QAction hideAction(QTStr("Hide"), this);
  2781. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2782. QAction mixerRenameAction(QTStr("Rename"), this);
  2783. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2784. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2785. QAction filtersAction(QTStr("Filters"), this);
  2786. QAction propertiesAction(QTStr("Properties"), this);
  2787. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2788. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2789. toggleControlLayoutAction.setCheckable(true);
  2790. toggleControlLayoutAction.setChecked(config_get_bool(
  2791. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2792. /* ------------------- */
  2793. connect(&hideAction, &QAction::triggered, this,
  2794. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2795. connect(&unhideAllAction, &QAction::triggered, this,
  2796. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2797. connect(&lockAction, &QAction::toggled, this,
  2798. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2799. connect(&mixerRenameAction, &QAction::triggered, this,
  2800. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2801. connect(&copyFiltersAction, &QAction::triggered, this,
  2802. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2803. connect(&pasteFiltersAction, &QAction::triggered, this,
  2804. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2805. connect(&filtersAction, &QAction::triggered, this,
  2806. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2807. connect(&propertiesAction, &QAction::triggered, this,
  2808. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2809. connect(&advPropAction, &QAction::triggered, this,
  2810. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2811. Qt::DirectConnection);
  2812. /* ------------------- */
  2813. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2814. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2815. /* ------------------- */
  2816. hideAction.setProperty("volControl",
  2817. QVariant::fromValue<VolControl *>(vol));
  2818. lockAction.setProperty("volControl",
  2819. QVariant::fromValue<VolControl *>(vol));
  2820. mixerRenameAction.setProperty("volControl",
  2821. QVariant::fromValue<VolControl *>(vol));
  2822. copyFiltersAction.setProperty("volControl",
  2823. QVariant::fromValue<VolControl *>(vol));
  2824. pasteFiltersAction.setProperty("volControl",
  2825. QVariant::fromValue<VolControl *>(vol));
  2826. filtersAction.setProperty("volControl",
  2827. QVariant::fromValue<VolControl *>(vol));
  2828. propertiesAction.setProperty("volControl",
  2829. QVariant::fromValue<VolControl *>(vol));
  2830. /* ------------------- */
  2831. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  2832. 0);
  2833. OBSSourceAutoRelease source =
  2834. obs_weak_source_get_source(copyFiltersSource);
  2835. if (source) {
  2836. pasteFiltersAction.setEnabled(true);
  2837. } else {
  2838. pasteFiltersAction.setEnabled(false);
  2839. }
  2840. QMenu popup;
  2841. vol->SetContextMenu(&popup);
  2842. popup.addAction(&lockAction);
  2843. popup.addSeparator();
  2844. popup.addAction(&unhideAllAction);
  2845. popup.addAction(&hideAction);
  2846. popup.addAction(&mixerRenameAction);
  2847. popup.addSeparator();
  2848. popup.addAction(&copyFiltersAction);
  2849. popup.addAction(&pasteFiltersAction);
  2850. popup.addSeparator();
  2851. popup.addAction(&toggleControlLayoutAction);
  2852. popup.addSeparator();
  2853. popup.addAction(&filtersAction);
  2854. popup.addAction(&propertiesAction);
  2855. popup.addAction(&advPropAction);
  2856. // toggleControlLayoutAction deletes and re-creates the volume controls
  2857. // meaning that "vol" would be pointing to freed memory.
  2858. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  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. if (cef)
  3874. SaveExtraBrowserDocks();
  3875. ClearExtraBrowserDocks();
  3876. #endif
  3877. if (api)
  3878. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  3879. disableSaving++;
  3880. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3881. * sources, etc) so that all references are released before shutdown */
  3882. ClearSceneData();
  3883. if (api)
  3884. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3885. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  3886. }
  3887. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  3888. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  3889. #else
  3890. bool OBSBasic::nativeEvent(const QByteArray &, void *message, long *)
  3891. #endif
  3892. {
  3893. #ifdef _WIN32
  3894. const MSG &msg = *static_cast<MSG *>(message);
  3895. switch (msg.message) {
  3896. case WM_MOVE:
  3897. for (OBSQTDisplay *const display :
  3898. findChildren<OBSQTDisplay *>()) {
  3899. display->OnMove();
  3900. }
  3901. break;
  3902. case WM_DISPLAYCHANGE:
  3903. for (OBSQTDisplay *const display :
  3904. findChildren<OBSQTDisplay *>()) {
  3905. display->OnDisplayChange();
  3906. }
  3907. }
  3908. #else
  3909. UNUSED_PARAMETER(message);
  3910. #endif
  3911. return false;
  3912. }
  3913. void OBSBasic::changeEvent(QEvent *event)
  3914. {
  3915. if (event->type() == QEvent::WindowStateChange) {
  3916. QWindowStateChangeEvent *stateEvent =
  3917. (QWindowStateChangeEvent *)event;
  3918. if (isMinimized()) {
  3919. if (trayIcon && trayIcon->isVisible() &&
  3920. sysTrayMinimizeToTray()) {
  3921. ToggleShowHide();
  3922. return;
  3923. }
  3924. if (previewEnabled)
  3925. EnablePreviewDisplay(false);
  3926. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3927. isVisible()) {
  3928. if (previewEnabled)
  3929. EnablePreviewDisplay(true);
  3930. }
  3931. }
  3932. }
  3933. void OBSBasic::on_actionShow_Recordings_triggered()
  3934. {
  3935. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3936. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3937. const char *adv_path =
  3938. strcmp(type, "Standard")
  3939. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3940. : config_get_string(basicConfig, "AdvOut",
  3941. "RecFilePath");
  3942. const char *path = strcmp(mode, "Advanced")
  3943. ? config_get_string(basicConfig,
  3944. "SimpleOutput",
  3945. "FilePath")
  3946. : adv_path;
  3947. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3948. }
  3949. void OBSBasic::on_actionRemux_triggered()
  3950. {
  3951. if (!remux.isNull()) {
  3952. remux->show();
  3953. remux->raise();
  3954. return;
  3955. }
  3956. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3957. const char *path = strcmp(mode, "Advanced")
  3958. ? config_get_string(basicConfig,
  3959. "SimpleOutput",
  3960. "FilePath")
  3961. : config_get_string(basicConfig, "AdvOut",
  3962. "RecFilePath");
  3963. OBSRemux *remuxDlg;
  3964. remuxDlg = new OBSRemux(path, this);
  3965. remuxDlg->show();
  3966. remux = remuxDlg;
  3967. }
  3968. void OBSBasic::on_action_Settings_triggered()
  3969. {
  3970. static bool settings_already_executing = false;
  3971. /* Do not load settings window if inside of a temporary event loop
  3972. * because we could be inside of an Auth::LoadUI call. Keep trying
  3973. * once per second until we've exit any known sub-loops. */
  3974. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3975. QTimer::singleShot(1000, this,
  3976. SLOT(on_action_Settings_triggered()));
  3977. return;
  3978. }
  3979. if (settings_already_executing) {
  3980. return;
  3981. }
  3982. settings_already_executing = true;
  3983. {
  3984. OBSBasicSettings settings(this);
  3985. settings.exec();
  3986. }
  3987. settings_already_executing = false;
  3988. if (restart) {
  3989. QMessageBox::StandardButton button = OBSMessageBox::question(
  3990. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3991. if (button == QMessageBox::Yes)
  3992. close();
  3993. else
  3994. restart = false;
  3995. }
  3996. }
  3997. void OBSBasic::on_actionShowMacPermissions_triggered()
  3998. {
  3999. #ifdef __APPLE__
  4000. OBSPermissions *check =
  4001. new OBSPermissions(this, CheckPermission(kScreenCapture),
  4002. CheckPermission(kVideoDeviceAccess),
  4003. CheckPermission(kAudioDeviceAccess),
  4004. CheckPermission(kAccessibility));
  4005. check->exec();
  4006. #endif
  4007. }
  4008. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4009. {
  4010. if (obs_missing_files_count(files) > 0) {
  4011. /* When loading the missing files dialog on launch, the
  4012. * window hasn't fully initialized by this point on macOS,
  4013. * so put this at the end of the current task queue. Fixes
  4014. * a bug where the window is behind OBS on startup. */
  4015. QTimer::singleShot(0, [this, files] {
  4016. missDialog = new OBSMissingFiles(files, this);
  4017. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4018. missDialog->show();
  4019. missDialog->raise();
  4020. });
  4021. } else {
  4022. obs_missing_files_destroy(files);
  4023. /* Only raise dialog if triggered manually */
  4024. if (!disableSaving)
  4025. OBSMessageBox::information(
  4026. this, QTStr("MissingFiles.NoMissing.Title"),
  4027. QTStr("MissingFiles.NoMissing.Text"));
  4028. }
  4029. }
  4030. void OBSBasic::on_actionShowMissingFiles_triggered()
  4031. {
  4032. obs_missing_files_t *files = obs_missing_files_create();
  4033. auto cb_sources = [](void *data, obs_source_t *source) {
  4034. AddMissingFiles(data, source);
  4035. return true;
  4036. };
  4037. obs_enum_all_sources(cb_sources, files);
  4038. ShowMissingFilesDialog(files);
  4039. }
  4040. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4041. {
  4042. if (advAudioWindow != nullptr) {
  4043. advAudioWindow->raise();
  4044. return;
  4045. }
  4046. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4047. "BasicWindow", "ShowSourceIcons");
  4048. advAudioWindow = new OBSBasicAdvAudio(this);
  4049. advAudioWindow->show();
  4050. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4051. advAudioWindow->SetIconsVisible(iconsVisible);
  4052. }
  4053. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4054. {
  4055. on_actionAdvAudioProperties_triggered();
  4056. }
  4057. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4058. {
  4059. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4060. connect(&unhideAllAction, &QAction::triggered, this,
  4061. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4062. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4063. toggleControlLayoutAction.setCheckable(true);
  4064. toggleControlLayoutAction.setChecked(config_get_bool(
  4065. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4066. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4067. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4068. QMenu popup;
  4069. popup.addAction(&unhideAllAction);
  4070. popup.addSeparator();
  4071. popup.addAction(&toggleControlLayoutAction);
  4072. popup.exec(QCursor::pos());
  4073. }
  4074. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4075. QListWidgetItem *prev)
  4076. {
  4077. obs_source_t *source = NULL;
  4078. if (current) {
  4079. obs_scene_t *scene;
  4080. scene = GetOBSRef<OBSScene>(current);
  4081. source = obs_scene_get_source(scene);
  4082. currentScene = scene;
  4083. } else {
  4084. currentScene = NULL;
  4085. }
  4086. SetCurrentScene(source);
  4087. if (api)
  4088. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4089. UpdateContextBar();
  4090. UNUSED_PARAMETER(prev);
  4091. }
  4092. void OBSBasic::EditSceneName()
  4093. {
  4094. ui->scenesDock->removeAction(renameScene);
  4095. QListWidgetItem *item = ui->scenes->currentItem();
  4096. Qt::ItemFlags flags = item->flags();
  4097. item->setFlags(flags | Qt::ItemIsEditable);
  4098. ui->scenes->editItem(item);
  4099. item->setFlags(flags);
  4100. }
  4101. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  4102. const char *slot)
  4103. {
  4104. QAction *action;
  4105. QList<QScreen *> screens = QGuiApplication::screens();
  4106. for (int i = 0; i < screens.size(); i++) {
  4107. QScreen *screen = screens[i];
  4108. QRect screenGeometry = screen->geometry();
  4109. qreal ratio = screen->devicePixelRatio();
  4110. QString name = "";
  4111. #ifdef _WIN32
  4112. QTextStream fullname(&name);
  4113. fullname << GetMonitorName(screen->name());
  4114. fullname << " (";
  4115. fullname << (i + 1);
  4116. fullname << ")";
  4117. #elif defined(__APPLE__)
  4118. name = screen->name();
  4119. #else
  4120. name = screen->model().simplified();
  4121. if (name.length() > 1 && name.endsWith("-"))
  4122. name.chop(1);
  4123. #endif
  4124. name = name.simplified();
  4125. if (name.length() == 0) {
  4126. name = QString("%1 %2")
  4127. .arg(QTStr("Display"))
  4128. .arg(QString::number(i + 1));
  4129. }
  4130. QString str =
  4131. QString("%1: %2x%3 @ %4,%5")
  4132. .arg(name,
  4133. QString::number(screenGeometry.width() *
  4134. ratio),
  4135. QString::number(screenGeometry.height() *
  4136. ratio),
  4137. QString::number(screenGeometry.x()),
  4138. QString::number(screenGeometry.y()));
  4139. action = parent->addAction(str, target, slot);
  4140. action->setProperty("monitor", i);
  4141. }
  4142. }
  4143. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4144. {
  4145. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4146. QMenu popup(this);
  4147. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4148. popup.addAction(QTStr("Add"), this,
  4149. SLOT(on_actionAddScene_triggered()));
  4150. if (item) {
  4151. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4152. copyFilters->setEnabled(false);
  4153. connect(copyFilters, SIGNAL(triggered()), this,
  4154. SLOT(SceneCopyFilters()));
  4155. QAction *pasteFilters =
  4156. new QAction(QTStr("Paste.Filters"), this);
  4157. pasteFilters->setEnabled(
  4158. !obs_weak_source_expired(copyFiltersSource));
  4159. connect(pasteFilters, SIGNAL(triggered()), this,
  4160. SLOT(ScenePasteFilters()));
  4161. popup.addSeparator();
  4162. popup.addAction(QTStr("Duplicate"), this,
  4163. SLOT(DuplicateSelectedScene()));
  4164. popup.addAction(copyFilters);
  4165. popup.addAction(pasteFilters);
  4166. popup.addSeparator();
  4167. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  4168. popup.addAction(QTStr("Remove"), this,
  4169. SLOT(RemoveSelectedScene()));
  4170. popup.addSeparator();
  4171. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4172. SLOT(on_actionSceneUp_triggered()));
  4173. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4174. this, SLOT(on_actionSceneDown_triggered()));
  4175. order.addSeparator();
  4176. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4177. this, SLOT(MoveSceneToTop()));
  4178. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4179. this, SLOT(MoveSceneToBottom()));
  4180. popup.addMenu(&order);
  4181. popup.addSeparator();
  4182. delete sceneProjectorMenu;
  4183. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4184. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4185. SLOT(OpenSceneProjector()));
  4186. popup.addMenu(sceneProjectorMenu);
  4187. QAction *sceneWindow = popup.addAction(
  4188. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  4189. popup.addAction(sceneWindow);
  4190. popup.addAction(QTStr("Screenshot.Scene"), this,
  4191. SLOT(ScreenshotScene()));
  4192. popup.addSeparator();
  4193. popup.addAction(QTStr("Filters"), this,
  4194. SLOT(OpenSceneFilters()));
  4195. popup.addSeparator();
  4196. delete perSceneTransitionMenu;
  4197. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4198. popup.addMenu(perSceneTransitionMenu);
  4199. /* ---------------------- */
  4200. QAction *multiviewAction =
  4201. popup.addAction(QTStr("ShowInMultiview"));
  4202. OBSSource source = GetCurrentSceneSource();
  4203. OBSDataAutoRelease data =
  4204. obs_source_get_private_settings(source);
  4205. obs_data_set_default_bool(data, "show_in_multiview", true);
  4206. bool show = obs_data_get_bool(data, "show_in_multiview");
  4207. multiviewAction->setCheckable(true);
  4208. multiviewAction->setChecked(show);
  4209. auto showInMultiview = [](OBSData data) {
  4210. bool show =
  4211. obs_data_get_bool(data, "show_in_multiview");
  4212. obs_data_set_bool(data, "show_in_multiview", !show);
  4213. OBSProjector::UpdateMultiviewProjectors();
  4214. };
  4215. connect(multiviewAction, &QAction::triggered,
  4216. std::bind(showInMultiview, data.Get()));
  4217. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4218. }
  4219. popup.addSeparator();
  4220. bool grid = ui->scenes->GetGridMode();
  4221. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4222. : QTStr("Basic.Main.GridMode"),
  4223. this);
  4224. connect(gridAction, SIGNAL(triggered()), this,
  4225. SLOT(GridActionClicked()));
  4226. popup.addAction(gridAction);
  4227. popup.exec(QCursor::pos());
  4228. }
  4229. void OBSBasic::GridActionClicked()
  4230. {
  4231. bool gridMode = !ui->scenes->GetGridMode();
  4232. ui->scenes->SetGridMode(gridMode);
  4233. }
  4234. void OBSBasic::on_actionAddScene_triggered()
  4235. {
  4236. string name;
  4237. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4238. int i = 2;
  4239. QString placeHolderText = format.arg(i);
  4240. OBSSourceAutoRelease source = nullptr;
  4241. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4242. placeHolderText = format.arg(++i);
  4243. }
  4244. bool accepted = NameDialog::AskForName(
  4245. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4246. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4247. if (accepted) {
  4248. if (name.empty()) {
  4249. OBSMessageBox::warning(this,
  4250. QTStr("NoNameEntered.Title"),
  4251. QTStr("NoNameEntered.Text"));
  4252. on_actionAddScene_triggered();
  4253. return;
  4254. }
  4255. OBSSourceAutoRelease source =
  4256. obs_get_source_by_name(name.c_str());
  4257. if (source) {
  4258. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4259. QTStr("NameExists.Text"));
  4260. on_actionAddScene_triggered();
  4261. return;
  4262. }
  4263. auto undo_fn = [](const std::string &data) {
  4264. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4265. if (t) {
  4266. obs_source_release(t);
  4267. obs_source_remove(t);
  4268. }
  4269. };
  4270. auto redo_fn = [this](const std::string &data) {
  4271. OBSSceneAutoRelease scene =
  4272. obs_scene_create(data.c_str());
  4273. obs_source_t *source = obs_scene_get_source(scene);
  4274. SetCurrentScene(source, true);
  4275. };
  4276. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4277. undo_fn, redo_fn, name, name);
  4278. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4279. obs_source_t *scene_source = obs_scene_get_source(scene);
  4280. SetCurrentScene(scene_source);
  4281. }
  4282. }
  4283. void OBSBasic::on_actionRemoveScene_triggered()
  4284. {
  4285. RemoveSelectedScene();
  4286. }
  4287. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4288. {
  4289. int idx = ui->scenes->currentRow();
  4290. if (idx == -1 || idx == invalidIdx)
  4291. return;
  4292. ui->scenes->blockSignals(true);
  4293. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4294. if (!relative)
  4295. idx = 0;
  4296. ui->scenes->insertItem(idx + offset, item);
  4297. ui->scenes->setCurrentRow(idx + offset);
  4298. item->setSelected(true);
  4299. currentScene = GetOBSRef<OBSScene>(item).Get();
  4300. ui->scenes->blockSignals(false);
  4301. OBSProjector::UpdateMultiviewProjectors();
  4302. }
  4303. void OBSBasic::on_actionSceneUp_triggered()
  4304. {
  4305. ChangeSceneIndex(true, -1, 0);
  4306. }
  4307. void OBSBasic::on_actionSceneDown_triggered()
  4308. {
  4309. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4310. }
  4311. void OBSBasic::MoveSceneToTop()
  4312. {
  4313. ChangeSceneIndex(false, 0, 0);
  4314. }
  4315. void OBSBasic::MoveSceneToBottom()
  4316. {
  4317. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4318. ui->scenes->count() - 1);
  4319. }
  4320. void OBSBasic::EditSceneItemName()
  4321. {
  4322. int idx = GetTopSelectedSourceItem();
  4323. ui->sources->Edit(idx);
  4324. }
  4325. void OBSBasic::SetDeinterlacingMode()
  4326. {
  4327. QAction *action = reinterpret_cast<QAction *>(sender());
  4328. obs_deinterlace_mode mode =
  4329. (obs_deinterlace_mode)action->property("mode").toInt();
  4330. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4331. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4332. obs_source_set_deinterlace_mode(source, mode);
  4333. }
  4334. void OBSBasic::SetDeinterlacingOrder()
  4335. {
  4336. QAction *action = reinterpret_cast<QAction *>(sender());
  4337. obs_deinterlace_field_order order =
  4338. (obs_deinterlace_field_order)action->property("order").toInt();
  4339. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4340. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4341. obs_source_set_deinterlace_field_order(source, order);
  4342. }
  4343. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4344. {
  4345. obs_deinterlace_mode deinterlaceMode =
  4346. obs_source_get_deinterlace_mode(source);
  4347. obs_deinterlace_field_order deinterlaceOrder =
  4348. obs_source_get_deinterlace_field_order(source);
  4349. QAction *action;
  4350. #define ADD_MODE(name, mode) \
  4351. action = menu->addAction(QTStr("" name), this, \
  4352. SLOT(SetDeinterlacingMode())); \
  4353. action->setProperty("mode", (int)mode); \
  4354. action->setCheckable(true); \
  4355. action->setChecked(deinterlaceMode == mode);
  4356. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4357. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4358. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4359. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4360. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4361. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4362. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4363. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4364. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4365. #undef ADD_MODE
  4366. menu->addSeparator();
  4367. #define ADD_ORDER(name, order) \
  4368. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4369. SLOT(SetDeinterlacingOrder())); \
  4370. action->setProperty("order", (int)order); \
  4371. action->setCheckable(true); \
  4372. action->setChecked(deinterlaceOrder == order);
  4373. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4374. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4375. #undef ADD_ORDER
  4376. return menu;
  4377. }
  4378. void OBSBasic::SetScaleFilter()
  4379. {
  4380. QAction *action = reinterpret_cast<QAction *>(sender());
  4381. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4382. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4383. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4384. }
  4385. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4386. {
  4387. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4388. QAction *action;
  4389. #define ADD_MODE(name, mode) \
  4390. action = \
  4391. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4392. action->setProperty("mode", (int)mode); \
  4393. action->setCheckable(true); \
  4394. action->setChecked(scaleFilter == mode);
  4395. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4396. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4397. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4398. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4399. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4400. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4401. #undef ADD_MODE
  4402. return menu;
  4403. }
  4404. void OBSBasic::SetBlendingMethod()
  4405. {
  4406. QAction *action = reinterpret_cast<QAction *>(sender());
  4407. obs_blending_method method =
  4408. (obs_blending_method)action->property("method").toInt();
  4409. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4410. obs_sceneitem_set_blending_method(sceneItem, method);
  4411. }
  4412. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4413. {
  4414. obs_blending_method blendingMethod =
  4415. obs_sceneitem_get_blending_method(item);
  4416. QAction *action;
  4417. #define ADD_MODE(name, method) \
  4418. action = menu->addAction(QTStr("" name), this, \
  4419. SLOT(SetBlendingMethod())); \
  4420. action->setProperty("method", (int)method); \
  4421. action->setCheckable(true); \
  4422. action->setChecked(blendingMethod == method);
  4423. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4424. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4425. #undef ADD_MODE
  4426. return menu;
  4427. }
  4428. void OBSBasic::SetBlendingMode()
  4429. {
  4430. QAction *action = reinterpret_cast<QAction *>(sender());
  4431. obs_blending_type mode =
  4432. (obs_blending_type)action->property("mode").toInt();
  4433. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4434. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4435. }
  4436. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4437. {
  4438. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4439. QAction *action;
  4440. #define ADD_MODE(name, mode) \
  4441. action = menu->addAction(QTStr("" name), this, \
  4442. SLOT(SetBlendingMode())); \
  4443. action->setProperty("mode", (int)mode); \
  4444. action->setCheckable(true); \
  4445. action->setChecked(blendingMode == mode);
  4446. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4447. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4448. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4449. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4450. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4451. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4452. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4453. #undef ADD_MODE
  4454. return menu;
  4455. }
  4456. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4457. QWidgetAction *widgetAction,
  4458. ColorSelect *select,
  4459. obs_sceneitem_t *item)
  4460. {
  4461. QAction *action;
  4462. menu->setStyleSheet(QString(
  4463. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4464. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4465. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4466. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4467. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4468. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4469. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4470. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4471. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4472. obs_data_release(privData);
  4473. obs_data_set_default_int(privData, "color-preset", 0);
  4474. int preset = obs_data_get_int(privData, "color-preset");
  4475. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4476. action->setCheckable(true);
  4477. action->setProperty("bgColor", 0);
  4478. action->setChecked(preset == 0);
  4479. action = menu->addAction(QTStr("CustomColor"), this,
  4480. +SLOT(ColorChange()));
  4481. action->setCheckable(true);
  4482. action->setProperty("bgColor", 1);
  4483. action->setChecked(preset == 1);
  4484. menu->addSeparator();
  4485. widgetAction->setDefaultWidget(select);
  4486. for (int i = 1; i < 9; i++) {
  4487. stringstream button;
  4488. button << "preset" << i;
  4489. QPushButton *colorButton =
  4490. select->findChild<QPushButton *>(button.str().c_str());
  4491. if (preset == i + 1)
  4492. colorButton->setStyleSheet("border: 2px solid black");
  4493. colorButton->setProperty("bgColor", i);
  4494. select->connect(colorButton, SIGNAL(released()), this,
  4495. SLOT(ColorChange()));
  4496. }
  4497. menu->addAction(widgetAction);
  4498. return menu;
  4499. }
  4500. ColorSelect::ColorSelect(QWidget *parent)
  4501. : QWidget(parent), ui(new Ui::ColorSelect)
  4502. {
  4503. ui->setupUi(this);
  4504. }
  4505. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4506. {
  4507. QMenu popup(this);
  4508. delete previewProjectorSource;
  4509. delete sourceProjector;
  4510. delete scaleFilteringMenu;
  4511. delete blendingMethodMenu;
  4512. delete blendingModeMenu;
  4513. delete colorMenu;
  4514. delete colorWidgetAction;
  4515. delete colorSelect;
  4516. delete deinterlaceMenu;
  4517. if (preview) {
  4518. QAction *action = popup.addAction(
  4519. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4520. SLOT(TogglePreview()));
  4521. action->setCheckable(true);
  4522. action->setChecked(
  4523. obs_display_enabled(ui->preview->GetDisplay()));
  4524. if (IsPreviewProgramMode())
  4525. action->setEnabled(false);
  4526. popup.addAction(ui->actionLockPreview);
  4527. popup.addMenu(ui->scalingMenu);
  4528. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4529. AddProjectorMenuMonitors(previewProjectorSource, this,
  4530. SLOT(OpenPreviewProjector()));
  4531. popup.addMenu(previewProjectorSource);
  4532. QAction *previewWindow =
  4533. popup.addAction(QTStr("PreviewWindow"), this,
  4534. SLOT(OpenPreviewWindow()));
  4535. popup.addAction(previewWindow);
  4536. popup.addAction(QTStr("Screenshot.Preview"), this,
  4537. SLOT(ScreenshotScene()));
  4538. popup.addSeparator();
  4539. }
  4540. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4541. if (addSourceMenu)
  4542. popup.addMenu(addSourceMenu);
  4543. if (ui->sources->MultipleBaseSelected()) {
  4544. popup.addSeparator();
  4545. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4546. SLOT(GroupSelectedItems()));
  4547. } else if (ui->sources->GroupsSelected()) {
  4548. popup.addSeparator();
  4549. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4550. SLOT(UngroupSelectedGroups()));
  4551. }
  4552. popup.addSeparator();
  4553. popup.addAction(ui->actionCopySource);
  4554. popup.addAction(ui->actionPasteRef);
  4555. popup.addAction(ui->actionPasteDup);
  4556. popup.addSeparator();
  4557. popup.addSeparator();
  4558. popup.addAction(ui->actionCopyFilters);
  4559. popup.addAction(ui->actionPasteFilters);
  4560. popup.addSeparator();
  4561. if (idx != -1) {
  4562. if (addSourceMenu)
  4563. popup.addSeparator();
  4564. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4565. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4566. uint32_t flags = obs_source_get_output_flags(source);
  4567. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4568. OBS_SOURCE_ASYNC_VIDEO;
  4569. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4570. colorMenu = new QMenu(QTStr("ChangeBG"));
  4571. colorWidgetAction = new QWidgetAction(colorMenu);
  4572. colorSelect = new ColorSelect(colorMenu);
  4573. popup.addMenu(AddBackgroundColorMenu(
  4574. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4575. popup.addAction(QTStr("Rename"), this,
  4576. SLOT(EditSceneItemName()));
  4577. popup.addAction(QTStr("Remove"), this,
  4578. SLOT(on_actionRemoveSource_triggered()));
  4579. popup.addSeparator();
  4580. popup.addMenu(ui->orderMenu);
  4581. popup.addMenu(ui->transformMenu);
  4582. popup.addSeparator();
  4583. if (hasAudio) {
  4584. QAction *actionHideMixer =
  4585. popup.addAction(QTStr("HideMixer"), this,
  4586. SLOT(ToggleHideMixer()));
  4587. actionHideMixer->setCheckable(true);
  4588. actionHideMixer->setChecked(SourceMixerHidden(source));
  4589. popup.addSeparator();
  4590. }
  4591. QAction *resizeOutput =
  4592. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  4593. SLOT(ResizeOutputSizeOfSource()));
  4594. int width = obs_source_get_width(source);
  4595. int height = obs_source_get_height(source);
  4596. resizeOutput->setEnabled(!obs_video_active());
  4597. if (width < 8 || height < 8)
  4598. resizeOutput->setEnabled(false);
  4599. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4600. popup.addMenu(
  4601. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4602. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4603. popup.addMenu(AddBlendingModeMenu(blendingModeMenu, sceneItem));
  4604. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4605. popup.addMenu(
  4606. AddBlendingMethodMenu(blendingMethodMenu, sceneItem));
  4607. if (isAsyncVideo) {
  4608. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4609. popup.addMenu(
  4610. AddDeinterlacingMenu(deinterlaceMenu, source));
  4611. }
  4612. popup.addSeparator();
  4613. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4614. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4615. popup.addSeparator();
  4616. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4617. AddProjectorMenuMonitors(sourceProjector, this,
  4618. SLOT(OpenSourceProjector()));
  4619. popup.addMenu(sourceProjector);
  4620. popup.addAction(QTStr("SourceWindow"), this,
  4621. SLOT(OpenSourceWindow()));
  4622. popup.addAction(QTStr("Screenshot.Source"), this,
  4623. SLOT(ScreenshotSelectedSource()));
  4624. popup.addSeparator();
  4625. if (flags & OBS_SOURCE_INTERACTION)
  4626. popup.addAction(QTStr("Interact"), this,
  4627. SLOT(on_actionInteract_triggered()));
  4628. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4629. QAction *action = popup.addAction(
  4630. QTStr("Properties"), this,
  4631. SLOT(on_actionSourceProperties_triggered()));
  4632. action->setEnabled(obs_source_configurable(source));
  4633. }
  4634. popup.exec(QCursor::pos());
  4635. }
  4636. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4637. {
  4638. if (ui->scenes->count()) {
  4639. QModelIndex idx = ui->sources->indexAt(pos);
  4640. CreateSourcePopupMenu(idx.row(), false);
  4641. }
  4642. }
  4643. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4644. {
  4645. if (!witem)
  4646. return;
  4647. if (IsPreviewProgramMode()) {
  4648. bool doubleClickSwitch =
  4649. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4650. "TransitionOnDoubleClick");
  4651. if (doubleClickSwitch)
  4652. TransitionClicked();
  4653. }
  4654. }
  4655. static inline bool should_show_properties(obs_source_t *source, const char *id)
  4656. {
  4657. if (!source)
  4658. return false;
  4659. if (strcmp(id, "group") == 0)
  4660. return false;
  4661. if (!obs_source_configurable(source))
  4662. return false;
  4663. uint32_t caps = obs_source_get_output_flags(source);
  4664. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  4665. return false;
  4666. return true;
  4667. }
  4668. void OBSBasic::AddSource(const char *id)
  4669. {
  4670. if (id && *id) {
  4671. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4672. sourceSelect.exec();
  4673. if (should_show_properties(sourceSelect.newSource, id)) {
  4674. CreatePropertiesWindow(sourceSelect.newSource);
  4675. }
  4676. }
  4677. }
  4678. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4679. {
  4680. const char *unversioned_type;
  4681. const char *type;
  4682. bool foundValues = false;
  4683. bool foundDeprecated = false;
  4684. size_t idx = 0;
  4685. QMenu *popup = new QMenu(QTStr("Add"), this);
  4686. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4687. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4688. QList<QAction *> actions = menu->actions();
  4689. for (QAction *menuAction : actions) {
  4690. if (menuAction->text().compare(name) >= 0)
  4691. return menuAction;
  4692. }
  4693. return (QAction *)nullptr;
  4694. };
  4695. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4696. const char *name) {
  4697. QString qname = QT_UTF8(name);
  4698. QAction *popupItem = new QAction(qname, this);
  4699. popupItem->setData(QT_UTF8(type));
  4700. connect(popupItem, SIGNAL(triggered(bool)), this,
  4701. SLOT(AddSourceFromAction()));
  4702. QIcon icon;
  4703. if (strcmp(type, "scene") == 0)
  4704. icon = GetSceneIcon();
  4705. else
  4706. icon = GetSourceIcon(type);
  4707. popupItem->setIcon(icon);
  4708. QAction *after = getActionAfter(popup, qname);
  4709. popup->insertAction(after, popupItem);
  4710. };
  4711. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4712. const char *name = obs_source_get_display_name(type);
  4713. uint32_t caps = obs_get_source_output_flags(type);
  4714. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4715. continue;
  4716. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4717. addSource(popup, unversioned_type, name);
  4718. } else {
  4719. addSource(deprecated, unversioned_type, name);
  4720. foundDeprecated = true;
  4721. }
  4722. foundValues = true;
  4723. }
  4724. addSource(popup, "scene", Str("Basic.Scene"));
  4725. popup->addSeparator();
  4726. QAction *addGroup = new QAction(QTStr("Group"), this);
  4727. addGroup->setData(QT_UTF8("group"));
  4728. addGroup->setIcon(GetGroupIcon());
  4729. connect(addGroup, SIGNAL(triggered(bool)), this,
  4730. SLOT(AddSourceFromAction()));
  4731. popup->addAction(addGroup);
  4732. if (!foundDeprecated) {
  4733. delete deprecated;
  4734. deprecated = nullptr;
  4735. }
  4736. if (!foundValues) {
  4737. delete popup;
  4738. popup = nullptr;
  4739. } else if (foundDeprecated) {
  4740. popup->addSeparator();
  4741. popup->addMenu(deprecated);
  4742. }
  4743. return popup;
  4744. }
  4745. void OBSBasic::AddSourceFromAction()
  4746. {
  4747. QAction *action = qobject_cast<QAction *>(sender());
  4748. if (!action)
  4749. return;
  4750. AddSource(QT_TO_UTF8(action->data().toString()));
  4751. }
  4752. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4753. {
  4754. if (!GetCurrentScene()) {
  4755. // Tell the user he needs a scene first (help beginners).
  4756. OBSMessageBox::information(
  4757. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4758. QTStr("Basic.Main.AddSourceHelp.Text"));
  4759. return;
  4760. }
  4761. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4762. if (popup)
  4763. popup->exec(pos);
  4764. }
  4765. void OBSBasic::on_actionAddSource_triggered()
  4766. {
  4767. AddSourcePopupMenu(QCursor::pos());
  4768. }
  4769. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4770. {
  4771. vector<OBSSceneItem> &items =
  4772. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4773. if (obs_sceneitem_selected(item)) {
  4774. items.emplace_back(item);
  4775. } else if (obs_sceneitem_is_group(item)) {
  4776. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4777. }
  4778. return true;
  4779. };
  4780. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4781. std::vector<obs_source_t *> *sources)
  4782. {
  4783. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  4784. if (!sources) {
  4785. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4786. } else {
  4787. for (obs_source_t *source : *sources) {
  4788. obs_data_t *source_data = obs_save_source(source);
  4789. obs_data_array_push_back(undo_array, source_data);
  4790. obs_data_release(source_data);
  4791. }
  4792. }
  4793. OBSDataAutoRelease scene_data =
  4794. obs_save_source(obs_scene_get_source(scene));
  4795. obs_data_array_push_back(undo_array, scene_data);
  4796. OBSDataAutoRelease data = obs_data_create();
  4797. obs_data_set_array(data, "array", undo_array);
  4798. obs_data_get_json(data);
  4799. return data.Get();
  4800. }
  4801. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4802. {
  4803. auto sources = static_cast<std::vector<OBSSource> *>(p);
  4804. sources->push_back(obs_sceneitem_get_source(item));
  4805. return true;
  4806. }
  4807. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4808. OBSData undo_data, OBSData redo_data)
  4809. {
  4810. auto undo_redo = [this](const std::string &json) {
  4811. OBSDataAutoRelease base =
  4812. obs_data_create_from_json(json.c_str());
  4813. OBSDataArrayAutoRelease array =
  4814. obs_data_get_array(base, "array");
  4815. std::vector<OBSSource> sources;
  4816. std::vector<OBSSource> old_sources;
  4817. /* create missing sources */
  4818. const size_t count = obs_data_array_count(array);
  4819. sources.reserve(count);
  4820. for (size_t i = 0; i < count; i++) {
  4821. OBSDataAutoRelease data = obs_data_array_item(array, i);
  4822. const char *name = obs_data_get_string(data, "name");
  4823. OBSSourceAutoRelease source =
  4824. obs_get_source_by_name(name);
  4825. if (!source)
  4826. source = obs_load_source(data);
  4827. sources.push_back(source.Get());
  4828. /* update scene/group settings to restore their
  4829. * contents to their saved settings */
  4830. obs_scene_t *scene =
  4831. obs_group_or_scene_from_source(source);
  4832. if (scene) {
  4833. obs_scene_enum_items(scene, add_source_enum,
  4834. &old_sources);
  4835. OBSDataAutoRelease scene_settings =
  4836. obs_data_get_obj(data, "settings");
  4837. obs_source_update(source, scene_settings);
  4838. }
  4839. }
  4840. /* actually load sources now */
  4841. for (obs_source_t *source : sources)
  4842. obs_source_load2(source);
  4843. ui->sources->RefreshItems();
  4844. };
  4845. const char *undo_json = obs_data_get_last_json(undo_data);
  4846. const char *redo_json = obs_data_get_last_json(redo_data);
  4847. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4848. redo_json);
  4849. }
  4850. void OBSBasic::on_actionRemoveSource_triggered()
  4851. {
  4852. vector<OBSSceneItem> items;
  4853. OBSScene scene = GetCurrentScene();
  4854. obs_source_t *scene_source = obs_scene_get_source(scene);
  4855. obs_scene_enum_items(scene, remove_items, &items);
  4856. if (!items.size())
  4857. return;
  4858. /* ------------------------------------- */
  4859. /* confirm action with user */
  4860. bool confirmed = false;
  4861. if (items.size() > 1) {
  4862. QString text = QTStr("ConfirmRemove.TextMultiple")
  4863. .arg(QString::number(items.size()));
  4864. QMessageBox remove_items(this);
  4865. remove_items.setText(text);
  4866. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4867. QMessageBox::YesRole);
  4868. remove_items.setDefaultButton(Yes);
  4869. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4870. remove_items.setIcon(QMessageBox::Question);
  4871. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4872. remove_items.exec();
  4873. confirmed = Yes == remove_items.clickedButton();
  4874. } else {
  4875. OBSSceneItem &item = items[0];
  4876. obs_source_t *source = obs_sceneitem_get_source(item);
  4877. if (source && QueryRemoveSource(source))
  4878. confirmed = true;
  4879. }
  4880. if (!confirmed)
  4881. return;
  4882. /* ----------------------------------------------- */
  4883. /* save undo data */
  4884. OBSData undo_data = BackupScene(scene_source);
  4885. /* ----------------------------------------------- */
  4886. /* remove items */
  4887. for (auto &item : items)
  4888. obs_sceneitem_remove(item);
  4889. /* ----------------------------------------------- */
  4890. /* save redo data */
  4891. OBSData redo_data = BackupScene(scene_source);
  4892. /* ----------------------------------------------- */
  4893. /* add undo/redo action */
  4894. QString action_name;
  4895. if (items.size() > 1) {
  4896. action_name = QTStr("Undo.Sources.Multi")
  4897. .arg(QString::number(items.size()));
  4898. } else {
  4899. QString str = QTStr("Undo.Delete");
  4900. action_name = str.arg(obs_source_get_name(
  4901. obs_sceneitem_get_source(items[0])));
  4902. }
  4903. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4904. }
  4905. void OBSBasic::on_actionInteract_triggered()
  4906. {
  4907. OBSSceneItem item = GetCurrentSceneItem();
  4908. OBSSource source = obs_sceneitem_get_source(item);
  4909. if (source)
  4910. CreateInteractionWindow(source);
  4911. }
  4912. void OBSBasic::on_actionSourceProperties_triggered()
  4913. {
  4914. OBSSceneItem item = GetCurrentSceneItem();
  4915. OBSSource source = obs_sceneitem_get_source(item);
  4916. if (source)
  4917. CreatePropertiesWindow(source);
  4918. }
  4919. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4920. const QString &action_name)
  4921. {
  4922. OBSSceneItem item = GetCurrentSceneItem();
  4923. obs_source_t *source = obs_sceneitem_get_source(item);
  4924. if (!source)
  4925. return;
  4926. OBSScene scene = GetCurrentScene();
  4927. std::vector<obs_source_t *> sources;
  4928. if (scene != obs_sceneitem_get_scene(item))
  4929. sources.push_back(
  4930. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4931. OBSData undo_data = BackupScene(scene, &sources);
  4932. obs_sceneitem_set_order(item, movement);
  4933. const char *source_name = obs_source_get_name(source);
  4934. const char *scene_name =
  4935. obs_source_get_name(obs_scene_get_source(scene));
  4936. OBSData redo_data = BackupScene(scene, &sources);
  4937. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4938. undo_data, redo_data);
  4939. }
  4940. void OBSBasic::on_actionSourceUp_triggered()
  4941. {
  4942. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4943. }
  4944. void OBSBasic::on_actionSourceDown_triggered()
  4945. {
  4946. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4947. }
  4948. void OBSBasic::on_actionMoveUp_triggered()
  4949. {
  4950. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4951. }
  4952. void OBSBasic::on_actionMoveDown_triggered()
  4953. {
  4954. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4955. }
  4956. void OBSBasic::on_actionMoveToTop_triggered()
  4957. {
  4958. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4959. }
  4960. void OBSBasic::on_actionMoveToBottom_triggered()
  4961. {
  4962. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4963. }
  4964. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4965. {
  4966. char logDir[512];
  4967. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4968. return nullptr;
  4969. string path = logDir;
  4970. path += "/";
  4971. path += log;
  4972. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4973. if (!file)
  4974. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4975. return file;
  4976. }
  4977. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4978. {
  4979. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4980. if (!fileString)
  4981. return;
  4982. if (!*fileString)
  4983. return;
  4984. ui->menuLogFiles->setEnabled(false);
  4985. #if defined(_WIN32)
  4986. ui->menuCrashLogs->setEnabled(false);
  4987. #endif
  4988. stringstream ss;
  4989. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4990. << CurrentDateTimeString() << "\n\n"
  4991. << fileString;
  4992. if (logUploadThread) {
  4993. logUploadThread->wait();
  4994. }
  4995. RemoteTextThread *thread =
  4996. new RemoteTextThread("https://obsproject.com/logs/upload",
  4997. "text/plain", ss.str().c_str());
  4998. logUploadThread.reset(thread);
  4999. if (crash) {
  5000. connect(thread, &RemoteTextThread::Result, this,
  5001. &OBSBasic::crashUploadFinished);
  5002. } else {
  5003. connect(thread, &RemoteTextThread::Result, this,
  5004. &OBSBasic::logUploadFinished);
  5005. }
  5006. logUploadThread->start();
  5007. }
  5008. void OBSBasic::on_actionShowLogs_triggered()
  5009. {
  5010. char logDir[512];
  5011. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5012. return;
  5013. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5014. QDesktopServices::openUrl(url);
  5015. }
  5016. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5017. {
  5018. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5019. }
  5020. void OBSBasic::on_actionUploadLastLog_triggered()
  5021. {
  5022. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5023. }
  5024. void OBSBasic::on_actionViewCurrentLog_triggered()
  5025. {
  5026. if (!logView)
  5027. logView = new OBSLogViewer();
  5028. logView->show();
  5029. logView->setWindowState(
  5030. (logView->windowState() & ~Qt::WindowMinimized) |
  5031. Qt::WindowActive);
  5032. logView->activateWindow();
  5033. logView->raise();
  5034. }
  5035. void OBSBasic::on_actionShowCrashLogs_triggered()
  5036. {
  5037. char logDir[512];
  5038. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5039. return;
  5040. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5041. QDesktopServices::openUrl(url);
  5042. }
  5043. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5044. {
  5045. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5046. }
  5047. void OBSBasic::on_actionCheckForUpdates_triggered()
  5048. {
  5049. CheckForUpdates(true);
  5050. }
  5051. void OBSBasic::on_actionRepair_triggered()
  5052. {
  5053. #if defined(_WIN32)
  5054. ui->actionCheckForUpdates->setEnabled(false);
  5055. ui->actionRepair->setEnabled(false);
  5056. if (updateCheckThread && updateCheckThread->isRunning())
  5057. return;
  5058. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5059. updateCheckThread->start();
  5060. #endif
  5061. }
  5062. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5063. {
  5064. ui->menuLogFiles->setEnabled(true);
  5065. #if defined(_WIN32)
  5066. ui->menuCrashLogs->setEnabled(true);
  5067. #endif
  5068. if (text.isEmpty()) {
  5069. OBSMessageBox::critical(
  5070. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5071. error);
  5072. return;
  5073. }
  5074. openLogDialog(text, false);
  5075. }
  5076. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5077. {
  5078. ui->menuLogFiles->setEnabled(true);
  5079. #if defined(_WIN32)
  5080. ui->menuCrashLogs->setEnabled(true);
  5081. #endif
  5082. if (text.isEmpty()) {
  5083. OBSMessageBox::critical(
  5084. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5085. error);
  5086. return;
  5087. }
  5088. openLogDialog(text, true);
  5089. }
  5090. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5091. {
  5092. OBSDataAutoRelease returnData =
  5093. obs_data_create_from_json(QT_TO_UTF8(text));
  5094. string resURL = obs_data_get_string(returnData, "url");
  5095. QString logURL = resURL.c_str();
  5096. OBSLogReply logDialog(this, logURL, crash);
  5097. logDialog.exec();
  5098. }
  5099. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5100. obs_source_t *source, const string &name)
  5101. {
  5102. const char *prevName = obs_source_get_name(source);
  5103. if (name == prevName)
  5104. return;
  5105. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5106. QListWidgetItem *listItem = listWidget->currentItem();
  5107. if (foundSource || name.empty()) {
  5108. listItem->setText(QT_UTF8(prevName));
  5109. if (foundSource) {
  5110. OBSMessageBox::warning(parent,
  5111. QTStr("NameExists.Title"),
  5112. QTStr("NameExists.Text"));
  5113. } else if (name.empty()) {
  5114. OBSMessageBox::warning(parent,
  5115. QTStr("NoNameEntered.Title"),
  5116. QTStr("NoNameEntered.Text"));
  5117. }
  5118. } else {
  5119. auto undo = [prev = std::string(prevName)](
  5120. const std::string &data) {
  5121. OBSSourceAutoRelease source =
  5122. obs_get_source_by_name(data.c_str());
  5123. obs_source_set_name(source, prev.c_str());
  5124. };
  5125. auto redo = [name](const std::string &data) {
  5126. OBSSourceAutoRelease source =
  5127. obs_get_source_by_name(data.c_str());
  5128. obs_source_set_name(source, name.c_str());
  5129. };
  5130. std::string undo_data(name);
  5131. std::string redo_data(prevName);
  5132. parent->undo_s.add_action(
  5133. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5134. undo_data, redo_data);
  5135. listItem->setText(QT_UTF8(name.c_str()));
  5136. obs_source_set_name(source, name.c_str());
  5137. }
  5138. }
  5139. void OBSBasic::SceneNameEdited(QWidget *editor,
  5140. QAbstractItemDelegate::EndEditHint endHint)
  5141. {
  5142. OBSScene scene = GetCurrentScene();
  5143. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5144. string text = QT_TO_UTF8(edit->text().trimmed());
  5145. if (!scene)
  5146. return;
  5147. obs_source_t *source = obs_scene_get_source(scene);
  5148. RenameListItem(this, ui->scenes, source, text);
  5149. ui->scenesDock->addAction(renameScene);
  5150. if (api)
  5151. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5152. UNUSED_PARAMETER(endHint);
  5153. }
  5154. void OBSBasic::OpenFilters(OBSSource source)
  5155. {
  5156. if (source == nullptr) {
  5157. OBSSceneItem item = GetCurrentSceneItem();
  5158. source = obs_sceneitem_get_source(item);
  5159. }
  5160. CreateFiltersWindow(source);
  5161. }
  5162. void OBSBasic::OpenProperties(OBSSource source)
  5163. {
  5164. if (source == nullptr) {
  5165. OBSSceneItem item = GetCurrentSceneItem();
  5166. source = obs_sceneitem_get_source(item);
  5167. }
  5168. CreatePropertiesWindow(source);
  5169. }
  5170. void OBSBasic::OpenInteraction(OBSSource source)
  5171. {
  5172. if (source == nullptr) {
  5173. OBSSceneItem item = GetCurrentSceneItem();
  5174. source = obs_sceneitem_get_source(item);
  5175. }
  5176. CreateInteractionWindow(source);
  5177. }
  5178. void OBSBasic::OpenSceneFilters()
  5179. {
  5180. OBSScene scene = GetCurrentScene();
  5181. OBSSource source = obs_scene_get_source(scene);
  5182. CreateFiltersWindow(source);
  5183. }
  5184. #define RECORDING_START \
  5185. "==== Recording Start ==============================================="
  5186. #define RECORDING_STOP \
  5187. "==== Recording Stop ================================================"
  5188. #define REPLAY_BUFFER_START \
  5189. "==== Replay Buffer Start ==========================================="
  5190. #define REPLAY_BUFFER_STOP \
  5191. "==== Replay Buffer Stop ============================================"
  5192. #define STREAMING_START \
  5193. "==== Streaming Start ==============================================="
  5194. #define STREAMING_STOP \
  5195. "==== Streaming Stop ================================================"
  5196. #define VIRTUAL_CAM_START \
  5197. "==== Virtual Camera Start =========================================="
  5198. #define VIRTUAL_CAM_STOP \
  5199. "==== Virtual Camera Stop ==========================================="
  5200. void OBSBasic::DisplayStreamStartError()
  5201. {
  5202. QString message = !outputHandler->lastError.empty()
  5203. ? QTStr(outputHandler->lastError.c_str())
  5204. : QTStr("Output.StartFailedGeneric");
  5205. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5206. ui->streamButton->setEnabled(true);
  5207. ui->streamButton->setChecked(false);
  5208. if (sysTrayStream) {
  5209. sysTrayStream->setText(ui->streamButton->text());
  5210. sysTrayStream->setEnabled(true);
  5211. }
  5212. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5213. }
  5214. #if YOUTUBE_ENABLED
  5215. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  5216. bool autostart, bool autostop,
  5217. bool start_now)
  5218. {
  5219. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5220. obs_service_t *service_obj = GetService();
  5221. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5222. const std::string a_key = QT_TO_UTF8(key);
  5223. obs_data_set_string(settings, "key", a_key.c_str());
  5224. const std::string an_id = QT_TO_UTF8(id);
  5225. obs_data_set_string(settings, "stream_id", an_id.c_str());
  5226. obs_service_update(service_obj, settings);
  5227. autoStartBroadcast = autostart;
  5228. autoStopBroadcast = autostop;
  5229. broadcastReady = true;
  5230. if (start_now)
  5231. QMetaObject::invokeMethod(this, "StartStreaming");
  5232. }
  5233. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5234. {
  5235. YoutubeApiWrappers *apiYouTube(
  5236. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5237. if (!apiYouTube) {
  5238. /* technically we should never get here -Jim */
  5239. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5240. Qt::QueuedConnection);
  5241. youtubeStreamCheckThread->deleteLater();
  5242. blog(LOG_ERROR, "==========================================");
  5243. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5244. blog(LOG_ERROR, "==========================================");
  5245. return;
  5246. }
  5247. int timeout = 0;
  5248. json11::Json json;
  5249. QString id = key.c_str();
  5250. while (StreamingActive()) {
  5251. if (timeout == 14) {
  5252. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5253. Qt::QueuedConnection);
  5254. break;
  5255. }
  5256. if (!apiYouTube->FindStream(id, json)) {
  5257. QMetaObject::invokeMethod(this,
  5258. "DisplayStreamStartError",
  5259. Qt::QueuedConnection);
  5260. QMetaObject::invokeMethod(this, "StopStreaming",
  5261. Qt::QueuedConnection);
  5262. break;
  5263. }
  5264. auto item = json["items"][0];
  5265. auto status = item["status"]["streamStatus"].string_value();
  5266. if (status == "active") {
  5267. QMetaObject::invokeMethod(ui->broadcastButton,
  5268. "setEnabled",
  5269. Q_ARG(bool, true));
  5270. break;
  5271. } else {
  5272. QThread::sleep(1);
  5273. timeout++;
  5274. }
  5275. }
  5276. youtubeStreamCheckThread->deleteLater();
  5277. }
  5278. void OBSBasic::ShowYouTubeAutoStartWarning()
  5279. {
  5280. auto msgBox = []() {
  5281. QMessageBox msgbox(App()->GetMainWindow());
  5282. msgbox.setWindowTitle(QTStr(
  5283. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5284. msgbox.setText(
  5285. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5286. msgbox.setIcon(QMessageBox::Icon::Information);
  5287. msgbox.addButton(QMessageBox::Ok);
  5288. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5289. msgbox.setCheckBox(cb);
  5290. msgbox.exec();
  5291. if (cb->isChecked()) {
  5292. config_set_bool(App()->GlobalConfig(), "General",
  5293. "WarnedAboutYouTubeAutoStart", true);
  5294. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5295. }
  5296. };
  5297. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5298. "WarnedAboutYouTubeAutoStart");
  5299. if (!warned) {
  5300. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5301. Q_ARG(VoidFunc, msgBox));
  5302. }
  5303. }
  5304. #endif
  5305. void OBSBasic::StartStreaming()
  5306. {
  5307. if (outputHandler->StreamingActive())
  5308. return;
  5309. if (disableOutputsRef)
  5310. return;
  5311. if (auth && auth->broadcastFlow()) {
  5312. if (!broadcastActive && !broadcastReady) {
  5313. ui->streamButton->setChecked(false);
  5314. QMessageBox no_broadcast(this);
  5315. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5316. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5317. QTStr("Basic.Main.SetupBroadcast"),
  5318. QMessageBox::YesRole);
  5319. no_broadcast.setDefaultButton(SetupBroadcast);
  5320. no_broadcast.addButton(QTStr("Close"),
  5321. QMessageBox::NoRole);
  5322. no_broadcast.setIcon(QMessageBox::Information);
  5323. no_broadcast.setWindowTitle(
  5324. QTStr("Output.NoBroadcast.Title"));
  5325. no_broadcast.exec();
  5326. if (no_broadcast.clickedButton() == SetupBroadcast)
  5327. QMetaObject::invokeMethod(this,
  5328. "SetupBroadcast");
  5329. return;
  5330. }
  5331. }
  5332. if (!outputHandler->SetupStreaming(service)) {
  5333. DisplayStreamStartError();
  5334. return;
  5335. }
  5336. if (api)
  5337. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5338. SaveProject();
  5339. ui->streamButton->setEnabled(false);
  5340. ui->streamButton->setChecked(false);
  5341. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5342. ui->broadcastButton->setChecked(false);
  5343. if (sysTrayStream) {
  5344. sysTrayStream->setEnabled(false);
  5345. sysTrayStream->setText(ui->streamButton->text());
  5346. }
  5347. if (!outputHandler->StartStreaming(service)) {
  5348. DisplayStreamStartError();
  5349. return;
  5350. }
  5351. if (!autoStartBroadcast) {
  5352. ui->broadcastButton->setText(
  5353. QTStr("Basic.Main.StartBroadcast"));
  5354. ui->broadcastButton->setProperty("broadcastState", "ready");
  5355. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5356. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5357. // well, we need to disable button while stream is not active
  5358. ui->broadcastButton->setEnabled(false);
  5359. } else {
  5360. if (!autoStopBroadcast) {
  5361. ui->broadcastButton->setText(
  5362. QTStr("Basic.Main.StopBroadcast"));
  5363. } else {
  5364. ui->broadcastButton->setText(
  5365. QTStr("Basic.Main.AutoStopEnabled"));
  5366. ui->broadcastButton->setEnabled(false);
  5367. }
  5368. ui->broadcastButton->setProperty("broadcastState", "active");
  5369. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5370. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5371. broadcastActive = true;
  5372. }
  5373. bool recordWhenStreaming = config_get_bool(
  5374. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5375. if (recordWhenStreaming)
  5376. StartRecording();
  5377. bool replayBufferWhileStreaming = config_get_bool(
  5378. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5379. if (replayBufferWhileStreaming)
  5380. StartReplayBuffer();
  5381. #if YOUTUBE_ENABLED
  5382. if (!autoStartBroadcast)
  5383. OBSBasic::ShowYouTubeAutoStartWarning();
  5384. #endif
  5385. }
  5386. void OBSBasic::BroadcastButtonClicked()
  5387. {
  5388. if (!broadcastReady ||
  5389. (!broadcastActive && !outputHandler->StreamingActive())) {
  5390. SetupBroadcast();
  5391. if (broadcastReady)
  5392. ui->broadcastButton->setChecked(true);
  5393. return;
  5394. }
  5395. if (!autoStartBroadcast) {
  5396. #if YOUTUBE_ENABLED
  5397. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5398. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5399. if (ytAuth.get()) {
  5400. if (!ytAuth->StartLatestBroadcast()) {
  5401. auto last_error = ytAuth->GetLastError();
  5402. if (last_error.isEmpty())
  5403. last_error = QTStr(
  5404. "YouTube.Actions.Error.YouTubeApi");
  5405. if (!ytAuth->GetTranslatedError(last_error))
  5406. last_error =
  5407. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5408. .arg(last_error,
  5409. ytAuth->GetBroadcastId());
  5410. OBSMessageBox::warning(
  5411. this,
  5412. QTStr("Output.BroadcastStartFailed"),
  5413. last_error, true);
  5414. ui->broadcastButton->setChecked(false);
  5415. return;
  5416. }
  5417. }
  5418. #endif
  5419. broadcastActive = true;
  5420. autoStartBroadcast = true; // and clear the flag
  5421. if (!autoStopBroadcast) {
  5422. ui->broadcastButton->setText(
  5423. QTStr("Basic.Main.StopBroadcast"));
  5424. } else {
  5425. ui->broadcastButton->setText(
  5426. QTStr("Basic.Main.AutoStopEnabled"));
  5427. ui->broadcastButton->setEnabled(false);
  5428. }
  5429. ui->broadcastButton->setProperty("broadcastState", "active");
  5430. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5431. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5432. } else if (!autoStopBroadcast) {
  5433. #if YOUTUBE_ENABLED
  5434. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5435. "WarnBeforeStoppingStream");
  5436. if (confirm && isVisible()) {
  5437. QMessageBox::StandardButton button = OBSMessageBox::question(
  5438. this, QTStr("ConfirmStop.Title"),
  5439. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5440. QMessageBox::Yes | QMessageBox::No,
  5441. QMessageBox::No);
  5442. if (button == QMessageBox::No) {
  5443. ui->broadcastButton->setChecked(true);
  5444. return;
  5445. }
  5446. }
  5447. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5448. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5449. if (ytAuth.get()) {
  5450. if (!ytAuth->StopLatestBroadcast()) {
  5451. auto last_error = ytAuth->GetLastError();
  5452. if (last_error.isEmpty())
  5453. last_error = QTStr(
  5454. "YouTube.Actions.Error.YouTubeApi");
  5455. if (!ytAuth->GetTranslatedError(last_error))
  5456. last_error =
  5457. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5458. .arg(last_error,
  5459. ytAuth->GetBroadcastId());
  5460. OBSMessageBox::warning(
  5461. this,
  5462. QTStr("Output.BroadcastStopFailed"),
  5463. last_error, true);
  5464. }
  5465. }
  5466. #endif
  5467. broadcastActive = false;
  5468. broadcastReady = false;
  5469. autoStopBroadcast = true;
  5470. QMetaObject::invokeMethod(this, "StopStreaming");
  5471. SetBroadcastFlowEnabled(true);
  5472. }
  5473. }
  5474. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5475. {
  5476. ui->broadcastButton->setEnabled(enabled);
  5477. ui->broadcastButton->setVisible(enabled);
  5478. ui->broadcastButton->setChecked(broadcastReady);
  5479. ui->broadcastButton->setProperty("broadcastState", "idle");
  5480. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5481. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5482. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5483. }
  5484. void OBSBasic::SetupBroadcast()
  5485. {
  5486. #if YOUTUBE_ENABLED
  5487. Auth *const auth = GetAuth();
  5488. if (IsYouTubeService(auth->service())) {
  5489. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5490. connect(&dialog, &OBSYoutubeActions::ok, this,
  5491. &OBSBasic::YouTubeActionDialogOk);
  5492. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5493. if (result != QDialog::Accepted) {
  5494. if (!broadcastReady)
  5495. ui->broadcastButton->setChecked(false);
  5496. }
  5497. }
  5498. #endif
  5499. }
  5500. #ifdef _WIN32
  5501. static inline void UpdateProcessPriority()
  5502. {
  5503. const char *priority = config_get_string(App()->GlobalConfig(),
  5504. "General", "ProcessPriority");
  5505. if (priority && strcmp(priority, "Normal") != 0)
  5506. SetProcessPriority(priority);
  5507. }
  5508. static inline void ClearProcessPriority()
  5509. {
  5510. const char *priority = config_get_string(App()->GlobalConfig(),
  5511. "General", "ProcessPriority");
  5512. if (priority && strcmp(priority, "Normal") != 0)
  5513. SetProcessPriority("Normal");
  5514. }
  5515. #else
  5516. #define UpdateProcessPriority() \
  5517. do { \
  5518. } while (false)
  5519. #define ClearProcessPriority() \
  5520. do { \
  5521. } while (false)
  5522. #endif
  5523. inline void OBSBasic::OnActivate(bool force)
  5524. {
  5525. if (ui->profileMenu->isEnabled() || force) {
  5526. ui->profileMenu->setEnabled(false);
  5527. ui->autoConfigure->setEnabled(false);
  5528. App()->IncrementSleepInhibition();
  5529. UpdateProcessPriority();
  5530. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5531. if (trayIcon && trayIcon->isVisible()) {
  5532. #ifdef __APPLE__
  5533. QIcon trayMask =
  5534. QIcon(":/res/images/tray_active_macos.svg");
  5535. trayMask.setIsMask(true);
  5536. trayIcon->setIcon(
  5537. QIcon::fromTheme("obs-tray", trayMask));
  5538. #else
  5539. trayIcon->setIcon(QIcon::fromTheme(
  5540. "obs-tray-active",
  5541. QIcon(":/res/images/tray_active.png")));
  5542. #endif
  5543. }
  5544. }
  5545. }
  5546. extern volatile bool recording_paused;
  5547. extern volatile bool replaybuf_active;
  5548. inline void OBSBasic::OnDeactivate()
  5549. {
  5550. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5551. ui->profileMenu->setEnabled(true);
  5552. ui->autoConfigure->setEnabled(true);
  5553. App()->DecrementSleepInhibition();
  5554. ClearProcessPriority();
  5555. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5556. if (trayIcon && trayIcon->isVisible()) {
  5557. #ifdef __APPLE__
  5558. QIcon trayIconFile =
  5559. QIcon(":/res/images/obs_macos.svg");
  5560. trayIconFile.setIsMask(true);
  5561. #else
  5562. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5563. #endif
  5564. trayIcon->setIcon(
  5565. QIcon::fromTheme("obs-tray", trayIconFile));
  5566. }
  5567. } else if (outputHandler->Active() && trayIcon &&
  5568. trayIcon->isVisible()) {
  5569. if (os_atomic_load_bool(&recording_paused)) {
  5570. #ifdef __APPLE__
  5571. QIcon trayIconFile =
  5572. QIcon(":/res/images/obs_paused_macos.svg");
  5573. trayIconFile.setIsMask(true);
  5574. #else
  5575. QIcon trayIconFile =
  5576. QIcon(":/res/images/obs_paused.png");
  5577. #endif
  5578. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5579. trayIconFile));
  5580. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5581. } else {
  5582. #ifdef __APPLE__
  5583. QIcon trayIconFile =
  5584. QIcon(":/res/images/tray_active_macos.svg");
  5585. trayIconFile.setIsMask(true);
  5586. #else
  5587. QIcon trayIconFile =
  5588. QIcon(":/res/images/tray_active.png");
  5589. #endif
  5590. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5591. trayIconFile));
  5592. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5593. }
  5594. }
  5595. }
  5596. void OBSBasic::StopStreaming()
  5597. {
  5598. SaveProject();
  5599. if (outputHandler->StreamingActive())
  5600. outputHandler->StopStreaming(streamingStopping);
  5601. // special case: force reset broadcast state if
  5602. // no autostart and no autostop selected
  5603. if (!autoStartBroadcast && !broadcastActive) {
  5604. broadcastActive = false;
  5605. autoStartBroadcast = true;
  5606. autoStopBroadcast = true;
  5607. broadcastReady = false;
  5608. }
  5609. if (autoStopBroadcast) {
  5610. broadcastActive = false;
  5611. broadcastReady = false;
  5612. }
  5613. OnDeactivate();
  5614. bool recordWhenStreaming = config_get_bool(
  5615. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5616. bool keepRecordingWhenStreamStops =
  5617. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5618. "KeepRecordingWhenStreamStops");
  5619. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5620. StopRecording();
  5621. bool replayBufferWhileStreaming = config_get_bool(
  5622. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5623. bool keepReplayBufferStreamStops =
  5624. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5625. "KeepReplayBufferStreamStops");
  5626. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5627. StopReplayBuffer();
  5628. }
  5629. void OBSBasic::ForceStopStreaming()
  5630. {
  5631. SaveProject();
  5632. if (outputHandler->StreamingActive())
  5633. outputHandler->StopStreaming(true);
  5634. // special case: force reset broadcast state if
  5635. // no autostart and no autostop selected
  5636. if (!autoStartBroadcast && !broadcastActive) {
  5637. broadcastActive = false;
  5638. autoStartBroadcast = true;
  5639. autoStopBroadcast = true;
  5640. broadcastReady = false;
  5641. }
  5642. if (autoStopBroadcast) {
  5643. broadcastActive = false;
  5644. broadcastReady = false;
  5645. }
  5646. OnDeactivate();
  5647. bool recordWhenStreaming = config_get_bool(
  5648. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5649. bool keepRecordingWhenStreamStops =
  5650. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5651. "KeepRecordingWhenStreamStops");
  5652. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5653. StopRecording();
  5654. bool replayBufferWhileStreaming = config_get_bool(
  5655. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5656. bool keepReplayBufferStreamStops =
  5657. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5658. "KeepReplayBufferStreamStops");
  5659. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5660. StopReplayBuffer();
  5661. }
  5662. void OBSBasic::StreamDelayStarting(int sec)
  5663. {
  5664. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5665. ui->streamButton->setEnabled(true);
  5666. ui->streamButton->setChecked(true);
  5667. if (sysTrayStream) {
  5668. sysTrayStream->setText(ui->streamButton->text());
  5669. sysTrayStream->setEnabled(true);
  5670. }
  5671. if (!startStreamMenu.isNull())
  5672. startStreamMenu->deleteLater();
  5673. startStreamMenu = new QMenu();
  5674. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5675. SLOT(StopStreaming()));
  5676. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5677. SLOT(ForceStopStreaming()));
  5678. ui->streamButton->setMenu(startStreamMenu);
  5679. ui->statusbar->StreamDelayStarting(sec);
  5680. OnActivate();
  5681. }
  5682. void OBSBasic::StreamDelayStopping(int sec)
  5683. {
  5684. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5685. ui->streamButton->setEnabled(true);
  5686. ui->streamButton->setChecked(false);
  5687. if (sysTrayStream) {
  5688. sysTrayStream->setText(ui->streamButton->text());
  5689. sysTrayStream->setEnabled(true);
  5690. }
  5691. if (!startStreamMenu.isNull())
  5692. startStreamMenu->deleteLater();
  5693. startStreamMenu = new QMenu();
  5694. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5695. SLOT(StartStreaming()));
  5696. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5697. SLOT(ForceStopStreaming()));
  5698. ui->streamButton->setMenu(startStreamMenu);
  5699. ui->statusbar->StreamDelayStopping(sec);
  5700. if (api)
  5701. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5702. }
  5703. void OBSBasic::StreamingStart()
  5704. {
  5705. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5706. ui->streamButton->setEnabled(true);
  5707. ui->streamButton->setChecked(true);
  5708. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5709. if (sysTrayStream) {
  5710. sysTrayStream->setText(ui->streamButton->text());
  5711. sysTrayStream->setEnabled(true);
  5712. }
  5713. #if YOUTUBE_ENABLED
  5714. if (!autoStartBroadcast) {
  5715. // get a current stream key
  5716. obs_service_t *service_obj = GetService();
  5717. OBSDataAutoRelease settings =
  5718. obs_service_get_settings(service_obj);
  5719. std::string key = obs_data_get_string(settings, "stream_id");
  5720. if (!key.empty() && !youtubeStreamCheckThread) {
  5721. youtubeStreamCheckThread = CreateQThread(
  5722. [this, key] { YoutubeStreamCheck(key); });
  5723. youtubeStreamCheckThread->setObjectName(
  5724. "YouTubeStreamCheckThread");
  5725. youtubeStreamCheckThread->start();
  5726. }
  5727. }
  5728. #endif
  5729. if (api)
  5730. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5731. OnActivate();
  5732. blog(LOG_INFO, STREAMING_START);
  5733. }
  5734. void OBSBasic::StreamStopping()
  5735. {
  5736. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5737. if (sysTrayStream)
  5738. sysTrayStream->setText(ui->streamButton->text());
  5739. streamingStopping = true;
  5740. if (api)
  5741. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5742. }
  5743. void OBSBasic::StreamingStop(int code, QString last_error)
  5744. {
  5745. const char *errorDescription = "";
  5746. DStr errorMessage;
  5747. bool use_last_error = false;
  5748. bool encode_error = false;
  5749. switch (code) {
  5750. case OBS_OUTPUT_BAD_PATH:
  5751. errorDescription = Str("Output.ConnectFail.BadPath");
  5752. break;
  5753. case OBS_OUTPUT_CONNECT_FAILED:
  5754. use_last_error = true;
  5755. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5756. break;
  5757. case OBS_OUTPUT_INVALID_STREAM:
  5758. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5759. break;
  5760. case OBS_OUTPUT_ENCODE_ERROR:
  5761. encode_error = true;
  5762. break;
  5763. default:
  5764. case OBS_OUTPUT_ERROR:
  5765. use_last_error = true;
  5766. errorDescription = Str("Output.ConnectFail.Error");
  5767. break;
  5768. case OBS_OUTPUT_DISCONNECTED:
  5769. /* doesn't happen if output is set to reconnect. note that
  5770. * reconnects are handled in the output, not in the UI */
  5771. use_last_error = true;
  5772. errorDescription = Str("Output.ConnectFail.Disconnected");
  5773. }
  5774. if (use_last_error && !last_error.isEmpty())
  5775. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5776. QT_TO_UTF8(last_error));
  5777. else
  5778. dstr_copy(errorMessage, errorDescription);
  5779. ui->statusbar->StreamStopped();
  5780. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5781. ui->streamButton->setEnabled(true);
  5782. ui->streamButton->setChecked(false);
  5783. if (sysTrayStream) {
  5784. sysTrayStream->setText(ui->streamButton->text());
  5785. sysTrayStream->setEnabled(true);
  5786. }
  5787. streamingStopping = false;
  5788. if (api)
  5789. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5790. OnDeactivate();
  5791. blog(LOG_INFO, STREAMING_STOP);
  5792. if (encode_error) {
  5793. QString msg =
  5794. last_error.isEmpty()
  5795. ? QTStr("Output.StreamEncodeError.Msg")
  5796. : QTStr("Output.StreamEncodeError.Msg.LastError")
  5797. .arg(last_error);
  5798. OBSMessageBox::information(
  5799. this, QTStr("Output.StreamEncodeError.Title"), msg);
  5800. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5801. OBSMessageBox::information(this,
  5802. QTStr("Output.ConnectFail.Title"),
  5803. QT_UTF8(errorMessage));
  5804. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5805. SysTrayNotify(QT_UTF8(errorDescription),
  5806. QSystemTrayIcon::Warning);
  5807. }
  5808. if (!startStreamMenu.isNull()) {
  5809. ui->streamButton->setMenu(nullptr);
  5810. startStreamMenu->deleteLater();
  5811. startStreamMenu = nullptr;
  5812. }
  5813. // Reset broadcast button state/text
  5814. if (!broadcastActive)
  5815. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  5816. }
  5817. void OBSBasic::AutoRemux(QString input, bool no_show)
  5818. {
  5819. auto config = Config();
  5820. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  5821. if (!autoRemux)
  5822. return;
  5823. bool isSimpleMode = false;
  5824. const char *mode = config_get_string(config, "Output", "Mode");
  5825. if (!mode) {
  5826. isSimpleMode = true;
  5827. } else {
  5828. isSimpleMode = strcmp(mode, "Simple") == 0;
  5829. }
  5830. if (!isSimpleMode) {
  5831. const char *recType =
  5832. config_get_string(config, "AdvOut", "RecType");
  5833. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5834. if (ffmpegOutput)
  5835. return;
  5836. }
  5837. if (input.isEmpty())
  5838. return;
  5839. QFileInfo fi(input);
  5840. QString suffix = fi.suffix();
  5841. /* do not remux if lossless */
  5842. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5843. return;
  5844. }
  5845. QString path = fi.path();
  5846. QString output = input;
  5847. output.resize(output.size() - suffix.size());
  5848. output += "mp4";
  5849. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5850. if (!no_show)
  5851. remux->show();
  5852. remux->AutoRemux(input, output);
  5853. }
  5854. void OBSBasic::StartRecording()
  5855. {
  5856. if (outputHandler->RecordingActive())
  5857. return;
  5858. if (disableOutputsRef)
  5859. return;
  5860. if (!OutputPathValid()) {
  5861. OutputPathInvalidMessage();
  5862. ui->recordButton->setChecked(false);
  5863. return;
  5864. }
  5865. if (LowDiskSpace()) {
  5866. DiskSpaceMessage();
  5867. ui->recordButton->setChecked(false);
  5868. return;
  5869. }
  5870. if (api)
  5871. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5872. SaveProject();
  5873. if (!outputHandler->StartRecording())
  5874. ui->recordButton->setChecked(false);
  5875. }
  5876. void OBSBasic::RecordStopping()
  5877. {
  5878. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5879. if (sysTrayRecord)
  5880. sysTrayRecord->setText(ui->recordButton->text());
  5881. recordingStopping = true;
  5882. if (api)
  5883. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5884. }
  5885. void OBSBasic::StopRecording()
  5886. {
  5887. SaveProject();
  5888. if (outputHandler->RecordingActive())
  5889. outputHandler->StopRecording(recordingStopping);
  5890. OnDeactivate();
  5891. }
  5892. void OBSBasic::RecordingStart()
  5893. {
  5894. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5895. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5896. ui->recordButton->setChecked(true);
  5897. if (sysTrayRecord)
  5898. sysTrayRecord->setText(ui->recordButton->text());
  5899. recordingStopping = false;
  5900. if (api)
  5901. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5902. if (!diskFullTimer->isActive())
  5903. diskFullTimer->start(1000);
  5904. OnActivate();
  5905. UpdatePause();
  5906. blog(LOG_INFO, RECORDING_START);
  5907. }
  5908. void OBSBasic::RecordingStop(int code, QString last_error)
  5909. {
  5910. ui->statusbar->RecordingStopped();
  5911. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5912. ui->recordButton->setChecked(false);
  5913. if (sysTrayRecord)
  5914. sysTrayRecord->setText(ui->recordButton->text());
  5915. blog(LOG_INFO, RECORDING_STOP);
  5916. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5917. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5918. QTStr("Output.RecordFail.Unsupported"));
  5919. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5920. QString msg =
  5921. last_error.isEmpty()
  5922. ? QTStr("Output.RecordError.EncodeErrorMsg")
  5923. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  5924. .arg(last_error);
  5925. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  5926. msg);
  5927. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5928. OBSMessageBox::warning(this,
  5929. QTStr("Output.RecordNoSpace.Title"),
  5930. QTStr("Output.RecordNoSpace.Msg"));
  5931. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5932. const char *errorDescription;
  5933. DStr errorMessage;
  5934. bool use_last_error = true;
  5935. errorDescription = Str("Output.RecordError.Msg");
  5936. if (use_last_error && !last_error.isEmpty())
  5937. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5938. QT_TO_UTF8(last_error));
  5939. else
  5940. dstr_copy(errorMessage, errorDescription);
  5941. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5942. QT_UTF8(errorMessage));
  5943. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5944. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5945. QSystemTrayIcon::Warning);
  5946. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5947. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5948. QSystemTrayIcon::Warning);
  5949. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5950. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5951. QSystemTrayIcon::Warning);
  5952. } else if (code == OBS_OUTPUT_SUCCESS) {
  5953. if (outputHandler) {
  5954. std::string path = outputHandler->lastRecordingPath;
  5955. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5956. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5957. }
  5958. }
  5959. if (api)
  5960. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5961. if (diskFullTimer->isActive())
  5962. diskFullTimer->stop();
  5963. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5964. OnDeactivate();
  5965. UpdatePause(false);
  5966. }
  5967. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  5968. {
  5969. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5970. ShowStatusBarMessage(str.arg(lastRecordingPath));
  5971. AutoRemux(lastRecordingPath, true);
  5972. }
  5973. void OBSBasic::ShowReplayBufferPauseWarning()
  5974. {
  5975. auto msgBox = []() {
  5976. QMessageBox msgbox(App()->GetMainWindow());
  5977. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5978. "PauseWarning.Title"));
  5979. msgbox.setText(QTStr("Output.ReplayBuffer."
  5980. "PauseWarning.Text"));
  5981. msgbox.setIcon(QMessageBox::Icon::Information);
  5982. msgbox.addButton(QMessageBox::Ok);
  5983. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5984. msgbox.setCheckBox(cb);
  5985. msgbox.exec();
  5986. if (cb->isChecked()) {
  5987. config_set_bool(App()->GlobalConfig(), "General",
  5988. "WarnedAboutReplayBufferPausing", true);
  5989. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5990. }
  5991. };
  5992. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5993. "WarnedAboutReplayBufferPausing");
  5994. if (!warned) {
  5995. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5996. Q_ARG(VoidFunc, msgBox));
  5997. }
  5998. }
  5999. void OBSBasic::StartReplayBuffer()
  6000. {
  6001. if (!outputHandler || !outputHandler->replayBuffer)
  6002. return;
  6003. if (outputHandler->ReplayBufferActive())
  6004. return;
  6005. if (disableOutputsRef)
  6006. return;
  6007. if (!UIValidation::NoSourcesConfirmation(this)) {
  6008. replayBufferButton->first()->setChecked(false);
  6009. return;
  6010. }
  6011. if (!OutputPathValid()) {
  6012. OutputPathInvalidMessage();
  6013. replayBufferButton->first()->setChecked(false);
  6014. return;
  6015. }
  6016. if (LowDiskSpace()) {
  6017. DiskSpaceMessage();
  6018. replayBufferButton->first()->setChecked(false);
  6019. return;
  6020. }
  6021. if (api)
  6022. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6023. SaveProject();
  6024. if (!outputHandler->StartReplayBuffer()) {
  6025. replayBufferButton->first()->setChecked(false);
  6026. } else if (os_atomic_load_bool(&recording_paused)) {
  6027. ShowReplayBufferPauseWarning();
  6028. }
  6029. }
  6030. void OBSBasic::ReplayBufferStopping()
  6031. {
  6032. if (!outputHandler || !outputHandler->replayBuffer)
  6033. return;
  6034. replayBufferButton->first()->setText(
  6035. QTStr("Basic.Main.StoppingReplayBuffer"));
  6036. if (sysTrayReplayBuffer)
  6037. sysTrayReplayBuffer->setText(
  6038. replayBufferButton->first()->text());
  6039. replayBufferStopping = true;
  6040. if (api)
  6041. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6042. }
  6043. void OBSBasic::StopReplayBuffer()
  6044. {
  6045. if (!outputHandler || !outputHandler->replayBuffer)
  6046. return;
  6047. SaveProject();
  6048. if (outputHandler->ReplayBufferActive())
  6049. outputHandler->StopReplayBuffer(replayBufferStopping);
  6050. OnDeactivate();
  6051. }
  6052. void OBSBasic::ReplayBufferStart()
  6053. {
  6054. if (!outputHandler || !outputHandler->replayBuffer)
  6055. return;
  6056. replayBufferButton->first()->setText(
  6057. QTStr("Basic.Main.StopReplayBuffer"));
  6058. replayBufferButton->first()->setChecked(true);
  6059. if (sysTrayReplayBuffer)
  6060. sysTrayReplayBuffer->setText(
  6061. replayBufferButton->first()->text());
  6062. replayBufferStopping = false;
  6063. if (api)
  6064. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6065. OnActivate();
  6066. UpdateReplayBuffer();
  6067. blog(LOG_INFO, REPLAY_BUFFER_START);
  6068. }
  6069. void OBSBasic::ReplayBufferSave()
  6070. {
  6071. if (!outputHandler || !outputHandler->replayBuffer)
  6072. return;
  6073. if (!outputHandler->ReplayBufferActive())
  6074. return;
  6075. calldata_t cd = {0};
  6076. proc_handler_t *ph =
  6077. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6078. proc_handler_call(ph, "save", &cd);
  6079. calldata_free(&cd);
  6080. }
  6081. void OBSBasic::ReplayBufferSaved()
  6082. {
  6083. if (!outputHandler || !outputHandler->replayBuffer)
  6084. return;
  6085. if (!outputHandler->ReplayBufferActive())
  6086. return;
  6087. calldata_t cd = {0};
  6088. proc_handler_t *ph =
  6089. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6090. proc_handler_call(ph, "get_last_replay", &cd);
  6091. QString path = QT_UTF8(calldata_string(&cd, "path"));
  6092. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  6093. ShowStatusBarMessage(msg);
  6094. calldata_free(&cd);
  6095. if (api)
  6096. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6097. AutoRemux(path);
  6098. }
  6099. void OBSBasic::ReplayBufferStop(int code)
  6100. {
  6101. if (!outputHandler || !outputHandler->replayBuffer)
  6102. return;
  6103. replayBufferButton->first()->setText(
  6104. QTStr("Basic.Main.StartReplayBuffer"));
  6105. replayBufferButton->first()->setChecked(false);
  6106. if (sysTrayReplayBuffer)
  6107. sysTrayReplayBuffer->setText(
  6108. replayBufferButton->first()->text());
  6109. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6110. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6111. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6112. QTStr("Output.RecordFail.Unsupported"));
  6113. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6114. OBSMessageBox::warning(this,
  6115. QTStr("Output.RecordNoSpace.Title"),
  6116. QTStr("Output.RecordNoSpace.Msg"));
  6117. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6118. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6119. QTStr("Output.RecordError.Msg"));
  6120. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6121. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6122. QSystemTrayIcon::Warning);
  6123. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6124. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6125. QSystemTrayIcon::Warning);
  6126. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6127. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6128. QSystemTrayIcon::Warning);
  6129. }
  6130. if (api)
  6131. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6132. OnDeactivate();
  6133. UpdateReplayBuffer(false);
  6134. }
  6135. void OBSBasic::StartVirtualCam()
  6136. {
  6137. if (!outputHandler || !outputHandler->virtualCam)
  6138. return;
  6139. if (outputHandler->VirtualCamActive())
  6140. return;
  6141. if (disableOutputsRef)
  6142. return;
  6143. SaveProject();
  6144. if (!outputHandler->StartVirtualCam()) {
  6145. vcamButton->first()->setChecked(false);
  6146. }
  6147. }
  6148. void OBSBasic::StopVirtualCam()
  6149. {
  6150. if (!outputHandler || !outputHandler->virtualCam)
  6151. return;
  6152. SaveProject();
  6153. if (outputHandler->VirtualCamActive())
  6154. outputHandler->StopVirtualCam();
  6155. OnDeactivate();
  6156. }
  6157. void OBSBasic::OnVirtualCamStart()
  6158. {
  6159. if (!outputHandler || !outputHandler->virtualCam)
  6160. return;
  6161. vcamButton->first()->setText(QTStr("Basic.Main.StopVirtualCam"));
  6162. if (sysTrayVirtualCam)
  6163. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6164. vcamButton->first()->setChecked(true);
  6165. if (api)
  6166. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6167. OnActivate();
  6168. blog(LOG_INFO, VIRTUAL_CAM_START);
  6169. }
  6170. void OBSBasic::OnVirtualCamStop(int)
  6171. {
  6172. if (!outputHandler || !outputHandler->virtualCam)
  6173. return;
  6174. vcamButton->first()->setText(QTStr("Basic.Main.StartVirtualCam"));
  6175. if (sysTrayVirtualCam)
  6176. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6177. vcamButton->first()->setChecked(false);
  6178. if (api)
  6179. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6180. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6181. OnDeactivate();
  6182. }
  6183. void OBSBasic::on_streamButton_clicked()
  6184. {
  6185. if (outputHandler->StreamingActive()) {
  6186. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6187. "WarnBeforeStoppingStream");
  6188. #if YOUTUBE_ENABLED
  6189. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6190. autoStopBroadcast) {
  6191. QMessageBox::StandardButton button = OBSMessageBox::question(
  6192. this, QTStr("ConfirmStop.Title"),
  6193. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6194. QMessageBox::Yes | QMessageBox::No,
  6195. QMessageBox::No);
  6196. if (button == QMessageBox::No) {
  6197. ui->streamButton->setChecked(true);
  6198. return;
  6199. }
  6200. confirm = false;
  6201. }
  6202. #endif
  6203. if (confirm && isVisible()) {
  6204. QMessageBox::StandardButton button =
  6205. OBSMessageBox::question(
  6206. this, QTStr("ConfirmStop.Title"),
  6207. QTStr("ConfirmStop.Text"),
  6208. QMessageBox::Yes | QMessageBox::No,
  6209. QMessageBox::No);
  6210. if (button == QMessageBox::No) {
  6211. ui->streamButton->setChecked(true);
  6212. return;
  6213. }
  6214. }
  6215. StopStreaming();
  6216. } else {
  6217. if (!UIValidation::NoSourcesConfirmation(this)) {
  6218. ui->streamButton->setChecked(false);
  6219. return;
  6220. }
  6221. Auth *auth = GetAuth();
  6222. auto action =
  6223. (auth && auth->external())
  6224. ? StreamSettingsAction::ContinueStream
  6225. : UIValidation::StreamSettingsConfirmation(
  6226. this, service);
  6227. switch (action) {
  6228. case StreamSettingsAction::ContinueStream:
  6229. break;
  6230. case StreamSettingsAction::OpenSettings:
  6231. on_action_Settings_triggered();
  6232. ui->streamButton->setChecked(false);
  6233. return;
  6234. case StreamSettingsAction::Cancel:
  6235. ui->streamButton->setChecked(false);
  6236. return;
  6237. }
  6238. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6239. "WarnBeforeStartingStream");
  6240. bool bwtest = false;
  6241. if (this->auth) {
  6242. OBSDataAutoRelease settings =
  6243. obs_service_get_settings(service);
  6244. bwtest = obs_data_get_bool(settings, "bwtest");
  6245. // Disable confirmation if this is going to open broadcast setup
  6246. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6247. !broadcastActive)
  6248. confirm = false;
  6249. }
  6250. if (bwtest && isVisible()) {
  6251. QMessageBox::StandardButton button =
  6252. OBSMessageBox::question(
  6253. this, QTStr("ConfirmBWTest.Title"),
  6254. QTStr("ConfirmBWTest.Text"));
  6255. if (button == QMessageBox::No) {
  6256. ui->streamButton->setChecked(false);
  6257. return;
  6258. }
  6259. } else if (confirm && isVisible()) {
  6260. QMessageBox::StandardButton button =
  6261. OBSMessageBox::question(
  6262. this, QTStr("ConfirmStart.Title"),
  6263. QTStr("ConfirmStart.Text"),
  6264. QMessageBox::Yes | QMessageBox::No,
  6265. QMessageBox::No);
  6266. if (button == QMessageBox::No) {
  6267. ui->streamButton->setChecked(false);
  6268. return;
  6269. }
  6270. }
  6271. StartStreaming();
  6272. }
  6273. }
  6274. void OBSBasic::on_recordButton_clicked()
  6275. {
  6276. if (outputHandler->RecordingActive()) {
  6277. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6278. "WarnBeforeStoppingRecord");
  6279. if (confirm && isVisible()) {
  6280. QMessageBox::StandardButton button =
  6281. OBSMessageBox::question(
  6282. this, QTStr("ConfirmStopRecord.Title"),
  6283. QTStr("ConfirmStopRecord.Text"),
  6284. QMessageBox::Yes | QMessageBox::No,
  6285. QMessageBox::No);
  6286. if (button == QMessageBox::No) {
  6287. ui->recordButton->setChecked(true);
  6288. return;
  6289. }
  6290. }
  6291. StopRecording();
  6292. } else {
  6293. if (!UIValidation::NoSourcesConfirmation(this)) {
  6294. ui->recordButton->setChecked(false);
  6295. return;
  6296. }
  6297. StartRecording();
  6298. }
  6299. }
  6300. void OBSBasic::VCamButtonClicked()
  6301. {
  6302. if (outputHandler->VirtualCamActive()) {
  6303. StopVirtualCam();
  6304. } else {
  6305. if (!UIValidation::NoSourcesConfirmation(this)) {
  6306. vcamButton->first()->setChecked(false);
  6307. return;
  6308. }
  6309. StartVirtualCam();
  6310. }
  6311. }
  6312. void OBSBasic::VCamConfigButtonClicked()
  6313. {
  6314. OBSBasicVCamConfig config(this);
  6315. config.exec();
  6316. }
  6317. void OBSBasic::on_settingsButton_clicked()
  6318. {
  6319. on_action_Settings_triggered();
  6320. }
  6321. void OBSBasic::on_actionHelpPortal_triggered()
  6322. {
  6323. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6324. QDesktopServices::openUrl(url);
  6325. }
  6326. void OBSBasic::on_actionWebsite_triggered()
  6327. {
  6328. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6329. QDesktopServices::openUrl(url);
  6330. }
  6331. void OBSBasic::on_actionDiscord_triggered()
  6332. {
  6333. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6334. QDesktopServices::openUrl(url);
  6335. }
  6336. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6337. {
  6338. char path[512];
  6339. int ret = GetConfigPath(path, 512, "obs-studio");
  6340. if (ret <= 0)
  6341. return;
  6342. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6343. }
  6344. void OBSBasic::on_actionShowProfileFolder_triggered()
  6345. {
  6346. char path[512];
  6347. int ret = GetProfilePath(path, 512, "");
  6348. if (ret <= 0)
  6349. return;
  6350. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6351. }
  6352. int OBSBasic::GetTopSelectedSourceItem()
  6353. {
  6354. QModelIndexList selectedItems =
  6355. ui->sources->selectionModel()->selectedIndexes();
  6356. return selectedItems.count() ? selectedItems[0].row() : -1;
  6357. }
  6358. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6359. {
  6360. return ui->sources->selectionModel()->selectedIndexes();
  6361. }
  6362. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  6363. {
  6364. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6365. UNUSED_PARAMETER(pos);
  6366. }
  6367. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  6368. {
  6369. QMenu popup(this);
  6370. QPointer<QMenu> studioProgramProjector;
  6371. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6372. AddProjectorMenuMonitors(studioProgramProjector, this,
  6373. SLOT(OpenStudioProgramProjector()));
  6374. popup.addMenu(studioProgramProjector);
  6375. QAction *studioProgramWindow =
  6376. popup.addAction(QTStr("StudioProgramWindow"), this,
  6377. SLOT(OpenStudioProgramWindow()));
  6378. popup.addAction(studioProgramWindow);
  6379. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6380. SLOT(ScreenshotProgram()));
  6381. popup.exec(QCursor::pos());
  6382. }
  6383. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  6384. {
  6385. QMenu popup(this);
  6386. delete previewProjectorMain;
  6387. QAction *action =
  6388. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6389. this, SLOT(TogglePreview()));
  6390. action->setCheckable(true);
  6391. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6392. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6393. AddProjectorMenuMonitors(previewProjectorMain, this,
  6394. SLOT(OpenPreviewProjector()));
  6395. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6396. SLOT(OpenPreviewWindow()));
  6397. popup.addMenu(previewProjectorMain);
  6398. popup.addAction(previewWindow);
  6399. popup.exec(QCursor::pos());
  6400. UNUSED_PARAMETER(pos);
  6401. }
  6402. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6403. {
  6404. #ifndef _WIN32
  6405. /* Make sure all dialogs are safely and successfully closed before
  6406. * switching the always on top mode due to the fact that windows all
  6407. * have to be recreated, so queue the actual toggle to happen after
  6408. * all events related to closing the dialogs have finished */
  6409. CloseDialogs();
  6410. #endif
  6411. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6412. Qt::QueuedConnection);
  6413. }
  6414. void OBSBasic::ToggleAlwaysOnTop()
  6415. {
  6416. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6417. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6418. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6419. show();
  6420. }
  6421. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6422. {
  6423. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6424. if (strcmp(val, "10") == 0) {
  6425. num = 10;
  6426. den = 1;
  6427. } else if (strcmp(val, "20") == 0) {
  6428. num = 20;
  6429. den = 1;
  6430. } else if (strcmp(val, "24 NTSC") == 0) {
  6431. num = 24000;
  6432. den = 1001;
  6433. } else if (strcmp(val, "25 PAL") == 0) {
  6434. num = 25;
  6435. den = 1;
  6436. } else if (strcmp(val, "29.97") == 0) {
  6437. num = 30000;
  6438. den = 1001;
  6439. } else if (strcmp(val, "48") == 0) {
  6440. num = 48;
  6441. den = 1;
  6442. } else if (strcmp(val, "50 PAL") == 0) {
  6443. num = 50;
  6444. den = 1;
  6445. } else if (strcmp(val, "59.94") == 0) {
  6446. num = 60000;
  6447. den = 1001;
  6448. } else if (strcmp(val, "60") == 0) {
  6449. num = 60;
  6450. den = 1;
  6451. } else {
  6452. num = 30;
  6453. den = 1;
  6454. }
  6455. }
  6456. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6457. {
  6458. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6459. den = 1;
  6460. }
  6461. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6462. {
  6463. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6464. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6465. }
  6466. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6467. {
  6468. num = 1000000000;
  6469. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6470. }
  6471. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6472. {
  6473. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6474. if (type == 1) //"Integer"
  6475. GetFPSInteger(num, den);
  6476. else if (type == 2) //"Fraction"
  6477. GetFPSFraction(num, den);
  6478. else if (false) //"Nanoseconds", currently not implemented
  6479. GetFPSNanoseconds(num, den);
  6480. else
  6481. GetFPSCommon(num, den);
  6482. }
  6483. config_t *OBSBasic::Config() const
  6484. {
  6485. return basicConfig;
  6486. }
  6487. void OBSBasic::UpdateEditMenu()
  6488. {
  6489. QModelIndexList items = GetAllSelectedSourceItems();
  6490. int count = items.count();
  6491. size_t filter_count = 0;
  6492. if (count == 1) {
  6493. OBSSceneItem sceneItem =
  6494. ui->sources->Get(GetTopSelectedSourceItem());
  6495. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6496. filter_count = obs_source_filter_count(source);
  6497. }
  6498. bool allowPastingDuplicate = !!clipboard.size();
  6499. for (size_t i = clipboard.size(); i > 0; i--) {
  6500. const size_t idx = i - 1;
  6501. OBSWeakSource &weak = clipboard[idx].weak_source;
  6502. if (obs_weak_source_expired(weak)) {
  6503. clipboard.erase(clipboard.begin() + idx);
  6504. continue;
  6505. }
  6506. OBSSourceAutoRelease strong =
  6507. obs_weak_source_get_source(weak.Get());
  6508. if (allowPastingDuplicate &&
  6509. obs_source_get_output_flags(strong) &
  6510. OBS_SOURCE_DO_NOT_DUPLICATE)
  6511. allowPastingDuplicate = false;
  6512. }
  6513. ui->actionCopySource->setEnabled(count > 0);
  6514. ui->actionEditTransform->setEnabled(count == 1);
  6515. ui->actionCopyTransform->setEnabled(count == 1);
  6516. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6517. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6518. ui->actionPasteFilters->setEnabled(
  6519. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6520. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6521. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6522. ui->actionMoveUp->setEnabled(count > 0);
  6523. ui->actionMoveDown->setEnabled(count > 0);
  6524. ui->actionMoveToTop->setEnabled(count > 0);
  6525. ui->actionMoveToBottom->setEnabled(count > 0);
  6526. bool canTransform = false;
  6527. for (int i = 0; i < count; i++) {
  6528. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6529. if (!obs_sceneitem_locked(item))
  6530. canTransform = true;
  6531. }
  6532. ui->actionResetTransform->setEnabled(canTransform);
  6533. ui->actionRotate90CW->setEnabled(canTransform);
  6534. ui->actionRotate90CCW->setEnabled(canTransform);
  6535. ui->actionRotate180->setEnabled(canTransform);
  6536. ui->actionFlipHorizontal->setEnabled(canTransform);
  6537. ui->actionFlipVertical->setEnabled(canTransform);
  6538. ui->actionFitToScreen->setEnabled(canTransform);
  6539. ui->actionStretchToScreen->setEnabled(canTransform);
  6540. ui->actionCenterToScreen->setEnabled(canTransform);
  6541. ui->actionVerticalCenter->setEnabled(canTransform);
  6542. ui->actionHorizontalCenter->setEnabled(canTransform);
  6543. }
  6544. void OBSBasic::on_actionEditTransform_triggered()
  6545. {
  6546. if (transformWindow)
  6547. transformWindow->close();
  6548. if (!GetCurrentSceneItem())
  6549. return;
  6550. transformWindow = new OBSBasicTransform(this);
  6551. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  6552. &OBSBasicTransform::OnSceneChanged);
  6553. transformWindow->show();
  6554. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6555. }
  6556. void OBSBasic::on_actionCopyTransform_triggered()
  6557. {
  6558. OBSSceneItem item = GetCurrentSceneItem();
  6559. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6560. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6561. ui->actionPasteTransform->setEnabled(true);
  6562. hasCopiedTransform = true;
  6563. }
  6564. void undo_redo(const std::string &data)
  6565. {
  6566. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  6567. OBSSourceAutoRelease source =
  6568. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6569. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6570. ->SetCurrentScene(source.Get(), true);
  6571. obs_scene_load_transform_states(data.c_str());
  6572. }
  6573. void OBSBasic::on_actionPasteTransform_triggered()
  6574. {
  6575. OBSDataAutoRelease wrapper =
  6576. obs_scene_save_transform_states(GetCurrentScene(), false);
  6577. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  6578. if (!obs_sceneitem_selected(item))
  6579. return true;
  6580. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  6581. obs_sceneitem_defer_update_begin(item);
  6582. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  6583. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  6584. obs_sceneitem_defer_update_end(item);
  6585. return true;
  6586. };
  6587. obs_scene_enum_items(GetCurrentScene(), func, this);
  6588. OBSDataAutoRelease rwrapper =
  6589. obs_scene_save_transform_states(GetCurrentScene(), false);
  6590. std::string undo_data(obs_data_get_json(wrapper));
  6591. std::string redo_data(obs_data_get_json(rwrapper));
  6592. undo_s.add_action(
  6593. QTStr("Undo.Transform.Paste")
  6594. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6595. undo_redo, undo_redo, undo_data, redo_data);
  6596. }
  6597. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6598. {
  6599. if (obs_sceneitem_is_group(item))
  6600. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6601. if (!obs_sceneitem_selected(item))
  6602. return true;
  6603. if (obs_sceneitem_locked(item))
  6604. return true;
  6605. obs_sceneitem_defer_update_begin(item);
  6606. obs_transform_info info;
  6607. vec2_set(&info.pos, 0.0f, 0.0f);
  6608. vec2_set(&info.scale, 1.0f, 1.0f);
  6609. info.rot = 0.0f;
  6610. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6611. info.bounds_type = OBS_BOUNDS_NONE;
  6612. info.bounds_alignment = OBS_ALIGN_CENTER;
  6613. vec2_set(&info.bounds, 0.0f, 0.0f);
  6614. obs_sceneitem_set_info(item, &info);
  6615. obs_sceneitem_crop crop = {};
  6616. obs_sceneitem_set_crop(item, &crop);
  6617. obs_sceneitem_defer_update_end(item);
  6618. UNUSED_PARAMETER(scene);
  6619. UNUSED_PARAMETER(param);
  6620. return true;
  6621. }
  6622. void OBSBasic::on_actionResetTransform_triggered()
  6623. {
  6624. obs_scene_t *scene = GetCurrentScene();
  6625. OBSDataAutoRelease wrapper =
  6626. obs_scene_save_transform_states(scene, false);
  6627. obs_scene_enum_items(scene, reset_tr, nullptr);
  6628. OBSDataAutoRelease rwrapper =
  6629. obs_scene_save_transform_states(scene, false);
  6630. std::string undo_data(obs_data_get_json(wrapper));
  6631. std::string redo_data(obs_data_get_json(rwrapper));
  6632. undo_s.add_action(
  6633. QTStr("Undo.Transform.Reset")
  6634. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6635. undo_redo, undo_redo, undo_data, redo_data);
  6636. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6637. }
  6638. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6639. {
  6640. matrix4 boxTransform;
  6641. obs_sceneitem_get_box_transform(item, &boxTransform);
  6642. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6643. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6644. auto GetMinPos = [&](float x, float y) {
  6645. vec3 pos;
  6646. vec3_set(&pos, x, y, 0.0f);
  6647. vec3_transform(&pos, &pos, &boxTransform);
  6648. vec3_min(&tl, &tl, &pos);
  6649. vec3_max(&br, &br, &pos);
  6650. };
  6651. GetMinPos(0.0f, 0.0f);
  6652. GetMinPos(1.0f, 0.0f);
  6653. GetMinPos(0.0f, 1.0f);
  6654. GetMinPos(1.0f, 1.0f);
  6655. }
  6656. static vec3 GetItemTL(obs_sceneitem_t *item)
  6657. {
  6658. vec3 tl, br;
  6659. GetItemBox(item, tl, br);
  6660. return tl;
  6661. }
  6662. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6663. {
  6664. vec3 newTL;
  6665. vec2 pos;
  6666. obs_sceneitem_get_pos(item, &pos);
  6667. newTL = GetItemTL(item);
  6668. pos.x += tl.x - newTL.x;
  6669. pos.y += tl.y - newTL.y;
  6670. obs_sceneitem_set_pos(item, &pos);
  6671. }
  6672. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6673. void *param)
  6674. {
  6675. if (obs_sceneitem_is_group(item))
  6676. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6677. param);
  6678. if (!obs_sceneitem_selected(item))
  6679. return true;
  6680. if (obs_sceneitem_locked(item))
  6681. return true;
  6682. float rot = *reinterpret_cast<float *>(param);
  6683. vec3 tl = GetItemTL(item);
  6684. rot += obs_sceneitem_get_rot(item);
  6685. if (rot >= 360.0f)
  6686. rot -= 360.0f;
  6687. else if (rot <= -360.0f)
  6688. rot += 360.0f;
  6689. obs_sceneitem_set_rot(item, rot);
  6690. obs_sceneitem_force_update_transform(item);
  6691. SetItemTL(item, tl);
  6692. UNUSED_PARAMETER(scene);
  6693. return true;
  6694. };
  6695. void OBSBasic::on_actionRotate90CW_triggered()
  6696. {
  6697. float f90CW = 90.0f;
  6698. OBSDataAutoRelease wrapper =
  6699. obs_scene_save_transform_states(GetCurrentScene(), false);
  6700. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6701. OBSDataAutoRelease rwrapper =
  6702. obs_scene_save_transform_states(GetCurrentScene(), false);
  6703. std::string undo_data(obs_data_get_json(wrapper));
  6704. std::string redo_data(obs_data_get_json(rwrapper));
  6705. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6706. .arg(obs_source_get_name(obs_scene_get_source(
  6707. GetCurrentScene()))),
  6708. undo_redo, undo_redo, undo_data, redo_data);
  6709. }
  6710. void OBSBasic::on_actionRotate90CCW_triggered()
  6711. {
  6712. float f90CCW = -90.0f;
  6713. OBSDataAutoRelease wrapper =
  6714. obs_scene_save_transform_states(GetCurrentScene(), false);
  6715. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6716. OBSDataAutoRelease rwrapper =
  6717. obs_scene_save_transform_states(GetCurrentScene(), false);
  6718. std::string undo_data(obs_data_get_json(wrapper));
  6719. std::string redo_data(obs_data_get_json(rwrapper));
  6720. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6721. .arg(obs_source_get_name(obs_scene_get_source(
  6722. GetCurrentScene()))),
  6723. undo_redo, undo_redo, undo_data, redo_data);
  6724. }
  6725. void OBSBasic::on_actionRotate180_triggered()
  6726. {
  6727. float f180 = 180.0f;
  6728. OBSDataAutoRelease wrapper =
  6729. obs_scene_save_transform_states(GetCurrentScene(), false);
  6730. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6731. OBSDataAutoRelease rwrapper =
  6732. obs_scene_save_transform_states(GetCurrentScene(), false);
  6733. std::string undo_data(obs_data_get_json(wrapper));
  6734. std::string redo_data(obs_data_get_json(rwrapper));
  6735. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6736. .arg(obs_source_get_name(obs_scene_get_source(
  6737. GetCurrentScene()))),
  6738. undo_redo, undo_redo, undo_data, redo_data);
  6739. }
  6740. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6741. void *param)
  6742. {
  6743. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6744. if (obs_sceneitem_is_group(item))
  6745. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6746. param);
  6747. if (!obs_sceneitem_selected(item))
  6748. return true;
  6749. if (obs_sceneitem_locked(item))
  6750. return true;
  6751. vec3 tl = GetItemTL(item);
  6752. vec2 scale;
  6753. obs_sceneitem_get_scale(item, &scale);
  6754. vec2_mul(&scale, &scale, &mul);
  6755. obs_sceneitem_set_scale(item, &scale);
  6756. obs_sceneitem_force_update_transform(item);
  6757. SetItemTL(item, tl);
  6758. UNUSED_PARAMETER(scene);
  6759. return true;
  6760. }
  6761. void OBSBasic::on_actionFlipHorizontal_triggered()
  6762. {
  6763. vec2 scale;
  6764. vec2_set(&scale, -1.0f, 1.0f);
  6765. OBSDataAutoRelease wrapper =
  6766. obs_scene_save_transform_states(GetCurrentScene(), false);
  6767. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6768. &scale);
  6769. OBSDataAutoRelease rwrapper =
  6770. obs_scene_save_transform_states(GetCurrentScene(), false);
  6771. std::string undo_data(obs_data_get_json(wrapper));
  6772. std::string redo_data(obs_data_get_json(rwrapper));
  6773. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6774. .arg(obs_source_get_name(obs_scene_get_source(
  6775. GetCurrentScene()))),
  6776. undo_redo, undo_redo, undo_data, redo_data);
  6777. }
  6778. void OBSBasic::on_actionFlipVertical_triggered()
  6779. {
  6780. vec2 scale;
  6781. vec2_set(&scale, 1.0f, -1.0f);
  6782. OBSDataAutoRelease wrapper =
  6783. obs_scene_save_transform_states(GetCurrentScene(), false);
  6784. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6785. &scale);
  6786. OBSDataAutoRelease rwrapper =
  6787. obs_scene_save_transform_states(GetCurrentScene(), false);
  6788. std::string undo_data(obs_data_get_json(wrapper));
  6789. std::string redo_data(obs_data_get_json(rwrapper));
  6790. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6791. .arg(obs_source_get_name(obs_scene_get_source(
  6792. GetCurrentScene()))),
  6793. undo_redo, undo_redo, undo_data, redo_data);
  6794. }
  6795. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6796. void *param)
  6797. {
  6798. obs_bounds_type boundsType =
  6799. *reinterpret_cast<obs_bounds_type *>(param);
  6800. if (obs_sceneitem_is_group(item))
  6801. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6802. param);
  6803. if (!obs_sceneitem_selected(item))
  6804. return true;
  6805. if (obs_sceneitem_locked(item))
  6806. return true;
  6807. obs_video_info ovi;
  6808. obs_get_video_info(&ovi);
  6809. obs_transform_info itemInfo;
  6810. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6811. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6812. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6813. itemInfo.rot = 0.0f;
  6814. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6815. float(ovi.base_height));
  6816. itemInfo.bounds_type = boundsType;
  6817. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6818. obs_sceneitem_set_info(item, &itemInfo);
  6819. UNUSED_PARAMETER(scene);
  6820. return true;
  6821. }
  6822. void OBSBasic::on_actionFitToScreen_triggered()
  6823. {
  6824. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6825. OBSDataAutoRelease wrapper =
  6826. obs_scene_save_transform_states(GetCurrentScene(), false);
  6827. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6828. &boundsType);
  6829. OBSDataAutoRelease rwrapper =
  6830. obs_scene_save_transform_states(GetCurrentScene(), false);
  6831. std::string undo_data(obs_data_get_json(wrapper));
  6832. std::string redo_data(obs_data_get_json(rwrapper));
  6833. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6834. .arg(obs_source_get_name(obs_scene_get_source(
  6835. GetCurrentScene()))),
  6836. undo_redo, undo_redo, undo_data, redo_data);
  6837. }
  6838. void OBSBasic::on_actionStretchToScreen_triggered()
  6839. {
  6840. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6841. OBSDataAutoRelease wrapper =
  6842. obs_scene_save_transform_states(GetCurrentScene(), false);
  6843. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6844. &boundsType);
  6845. OBSDataAutoRelease rwrapper =
  6846. obs_scene_save_transform_states(GetCurrentScene(), false);
  6847. std::string undo_data(obs_data_get_json(wrapper));
  6848. std::string redo_data(obs_data_get_json(rwrapper));
  6849. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6850. .arg(obs_source_get_name(obs_scene_get_source(
  6851. GetCurrentScene()))),
  6852. undo_redo, undo_redo, undo_data, redo_data);
  6853. }
  6854. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  6855. {
  6856. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  6857. if (!selectedItems.count())
  6858. return;
  6859. vector<OBSSceneItem> items;
  6860. // Filter out items that have no size
  6861. for (int x = 0; x < selectedItems.count(); x++) {
  6862. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  6863. obs_transform_info oti;
  6864. obs_sceneitem_get_info(item, &oti);
  6865. obs_source_t *source = obs_sceneitem_get_source(item);
  6866. float width = float(obs_source_get_width(source)) * oti.scale.x;
  6867. float height =
  6868. float(obs_source_get_height(source)) * oti.scale.y;
  6869. if (width == 0.0f || height == 0.0f)
  6870. continue;
  6871. items.emplace_back(item);
  6872. }
  6873. if (!items.size())
  6874. return;
  6875. // Get center x, y coordinates of items
  6876. vec3 center;
  6877. float top = M_INFINITE;
  6878. float left = M_INFINITE;
  6879. float right = 0.0f;
  6880. float bottom = 0.0f;
  6881. for (auto &item : items) {
  6882. vec3 tl, br;
  6883. GetItemBox(item, tl, br);
  6884. left = (std::min)(tl.x, left);
  6885. top = (std::min)(tl.y, top);
  6886. right = (std::max)(br.x, right);
  6887. bottom = (std::max)(br.y, bottom);
  6888. }
  6889. center.x = (right + left) / 2.0f;
  6890. center.y = (top + bottom) / 2.0f;
  6891. center.z = 0.0f;
  6892. // Get coordinates of screen center
  6893. obs_video_info ovi;
  6894. obs_get_video_info(&ovi);
  6895. vec3 screenCenter;
  6896. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  6897. 0.0f);
  6898. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6899. // Calculate difference between screen center and item center
  6900. vec3 offset;
  6901. vec3_sub(&offset, &screenCenter, &center);
  6902. // Shift items by offset
  6903. for (auto &item : items) {
  6904. vec3 tl, br;
  6905. GetItemBox(item, tl, br);
  6906. vec3_add(&tl, &tl, &offset);
  6907. vec3 itemTL = GetItemTL(item);
  6908. if (centerType == CenterType::Vertical)
  6909. tl.x = itemTL.x;
  6910. else if (centerType == CenterType::Horizontal)
  6911. tl.y = itemTL.y;
  6912. SetItemTL(item, tl);
  6913. }
  6914. }
  6915. void OBSBasic::on_actionCenterToScreen_triggered()
  6916. {
  6917. CenterType centerType = CenterType::Scene;
  6918. OBSDataAutoRelease wrapper =
  6919. obs_scene_save_transform_states(GetCurrentScene(), false);
  6920. CenterSelectedSceneItems(centerType);
  6921. OBSDataAutoRelease rwrapper =
  6922. obs_scene_save_transform_states(GetCurrentScene(), false);
  6923. std::string undo_data(obs_data_get_json(wrapper));
  6924. std::string redo_data(obs_data_get_json(rwrapper));
  6925. undo_s.add_action(QTStr("Undo.Transform.Center")
  6926. .arg(obs_source_get_name(obs_scene_get_source(
  6927. GetCurrentScene()))),
  6928. undo_redo, undo_redo, undo_data, redo_data);
  6929. }
  6930. void OBSBasic::on_actionVerticalCenter_triggered()
  6931. {
  6932. CenterType centerType = CenterType::Vertical;
  6933. OBSDataAutoRelease wrapper =
  6934. obs_scene_save_transform_states(GetCurrentScene(), false);
  6935. CenterSelectedSceneItems(centerType);
  6936. OBSDataAutoRelease rwrapper =
  6937. obs_scene_save_transform_states(GetCurrentScene(), false);
  6938. std::string undo_data(obs_data_get_json(wrapper));
  6939. std::string redo_data(obs_data_get_json(rwrapper));
  6940. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6941. .arg(obs_source_get_name(obs_scene_get_source(
  6942. GetCurrentScene()))),
  6943. undo_redo, undo_redo, undo_data, redo_data);
  6944. }
  6945. void OBSBasic::on_actionHorizontalCenter_triggered()
  6946. {
  6947. CenterType centerType = CenterType::Horizontal;
  6948. OBSDataAutoRelease wrapper =
  6949. obs_scene_save_transform_states(GetCurrentScene(), false);
  6950. CenterSelectedSceneItems(centerType);
  6951. OBSDataAutoRelease rwrapper =
  6952. obs_scene_save_transform_states(GetCurrentScene(), false);
  6953. std::string undo_data(obs_data_get_json(wrapper));
  6954. std::string redo_data(obs_data_get_json(rwrapper));
  6955. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6956. .arg(obs_source_get_name(obs_scene_get_source(
  6957. GetCurrentScene()))),
  6958. undo_redo, undo_redo, undo_data, redo_data);
  6959. }
  6960. void OBSBasic::EnablePreviewDisplay(bool enable)
  6961. {
  6962. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6963. ui->preview->setVisible(enable);
  6964. ui->previewDisabledWidget->setVisible(!enable);
  6965. }
  6966. void OBSBasic::TogglePreview()
  6967. {
  6968. previewEnabled = !previewEnabled;
  6969. EnablePreviewDisplay(previewEnabled);
  6970. }
  6971. void OBSBasic::EnablePreview()
  6972. {
  6973. if (previewProgramMode)
  6974. return;
  6975. previewEnabled = true;
  6976. EnablePreviewDisplay(true);
  6977. }
  6978. void OBSBasic::DisablePreview()
  6979. {
  6980. if (previewProgramMode)
  6981. return;
  6982. previewEnabled = false;
  6983. EnablePreviewDisplay(false);
  6984. }
  6985. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6986. {
  6987. if (obs_sceneitem_locked(item))
  6988. return true;
  6989. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6990. struct vec2 pos;
  6991. if (!obs_sceneitem_selected(item)) {
  6992. if (obs_sceneitem_is_group(item)) {
  6993. struct vec3 offset3;
  6994. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6995. struct matrix4 matrix;
  6996. obs_sceneitem_get_draw_transform(item, &matrix);
  6997. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6998. matrix4_inv(&matrix, &matrix);
  6999. vec3_transform(&offset3, &offset3, &matrix);
  7000. struct vec2 new_offset;
  7001. vec2_set(&new_offset, offset3.x, offset3.y);
  7002. obs_sceneitem_group_enum_items(item, nudge_callback,
  7003. &new_offset);
  7004. }
  7005. return true;
  7006. }
  7007. obs_sceneitem_get_pos(item, &pos);
  7008. vec2_add(&pos, &pos, &offset);
  7009. obs_sceneitem_set_pos(item, &pos);
  7010. return true;
  7011. }
  7012. void OBSBasic::Nudge(int dist, MoveDir dir)
  7013. {
  7014. if (ui->preview->Locked())
  7015. return;
  7016. struct vec2 offset;
  7017. vec2_set(&offset, 0.0f, 0.0f);
  7018. switch (dir) {
  7019. case MoveDir::Up:
  7020. offset.y = (float)-dist;
  7021. break;
  7022. case MoveDir::Down:
  7023. offset.y = (float)dist;
  7024. break;
  7025. case MoveDir::Left:
  7026. offset.x = (float)-dist;
  7027. break;
  7028. case MoveDir::Right:
  7029. offset.x = (float)dist;
  7030. break;
  7031. }
  7032. if (!recent_nudge) {
  7033. recent_nudge = true;
  7034. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7035. GetCurrentScene(), true);
  7036. std::string undo_data(obs_data_get_json(wrapper));
  7037. nudge_timer = new QTimer;
  7038. QObject::connect(
  7039. nudge_timer, &QTimer::timeout,
  7040. [this, &recent_nudge = recent_nudge, undo_data]() {
  7041. OBSDataAutoRelease rwrapper =
  7042. obs_scene_save_transform_states(
  7043. GetCurrentScene(), true);
  7044. std::string redo_data(
  7045. obs_data_get_json(rwrapper));
  7046. undo_s.add_action(
  7047. QTStr("Undo.Transform")
  7048. .arg(obs_source_get_name(
  7049. GetCurrentSceneSource())),
  7050. undo_redo, undo_redo, undo_data,
  7051. redo_data);
  7052. recent_nudge = false;
  7053. });
  7054. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7055. &QTimer::deleteLater);
  7056. nudge_timer->setSingleShot(true);
  7057. }
  7058. if (nudge_timer) {
  7059. nudge_timer->stop();
  7060. nudge_timer->start(1000);
  7061. } else {
  7062. blog(LOG_ERROR, "No nudge timer!");
  7063. }
  7064. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7065. }
  7066. void OBSBasic::NudgeUp()
  7067. {
  7068. Nudge(1, MoveDir::Up);
  7069. }
  7070. void OBSBasic::NudgeDown()
  7071. {
  7072. Nudge(1, MoveDir::Down);
  7073. }
  7074. void OBSBasic::NudgeLeft()
  7075. {
  7076. Nudge(1, MoveDir::Left);
  7077. }
  7078. void OBSBasic::NudgeRight()
  7079. {
  7080. Nudge(1, MoveDir::Right);
  7081. }
  7082. void OBSBasic::NudgeUpFar()
  7083. {
  7084. Nudge(10, MoveDir::Up);
  7085. }
  7086. void OBSBasic::NudgeDownFar()
  7087. {
  7088. Nudge(10, MoveDir::Down);
  7089. }
  7090. void OBSBasic::NudgeLeftFar()
  7091. {
  7092. Nudge(10, MoveDir::Left);
  7093. }
  7094. void OBSBasic::NudgeRightFar()
  7095. {
  7096. Nudge(10, MoveDir::Right);
  7097. }
  7098. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7099. {
  7100. for (size_t i = 0; i < projectors.size(); i++) {
  7101. if (projectors[i] == projector) {
  7102. projectors[i]->deleteLater();
  7103. projectors.erase(projectors.begin() + i);
  7104. break;
  7105. }
  7106. }
  7107. }
  7108. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7109. ProjectorType type)
  7110. {
  7111. /* seriously? 10 monitors? */
  7112. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7113. return nullptr;
  7114. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7115. "CloseExistingProjectors");
  7116. if (closeProjectors && monitor > -1) {
  7117. for (size_t i = projectors.size(); i > 0; i--) {
  7118. size_t idx = i - 1;
  7119. if (projectors[idx]->GetMonitor() == monitor)
  7120. DeleteProjector(projectors[idx]);
  7121. }
  7122. }
  7123. OBSProjector *projector =
  7124. new OBSProjector(nullptr, source, monitor, type);
  7125. projectors.emplace_back(projector);
  7126. return projector;
  7127. }
  7128. void OBSBasic::OpenStudioProgramProjector()
  7129. {
  7130. int monitor = sender()->property("monitor").toInt();
  7131. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7132. }
  7133. void OBSBasic::OpenPreviewProjector()
  7134. {
  7135. int monitor = sender()->property("monitor").toInt();
  7136. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7137. }
  7138. void OBSBasic::OpenSourceProjector()
  7139. {
  7140. int monitor = sender()->property("monitor").toInt();
  7141. OBSSceneItem item = GetCurrentSceneItem();
  7142. if (!item)
  7143. return;
  7144. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7145. ProjectorType::Source);
  7146. }
  7147. void OBSBasic::OpenMultiviewProjector()
  7148. {
  7149. int monitor = sender()->property("monitor").toInt();
  7150. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7151. }
  7152. void OBSBasic::OpenSceneProjector()
  7153. {
  7154. int monitor = sender()->property("monitor").toInt();
  7155. OBSScene scene = GetCurrentScene();
  7156. if (!scene)
  7157. return;
  7158. OpenProjector(obs_scene_get_source(scene), monitor,
  7159. ProjectorType::Scene);
  7160. }
  7161. void OBSBasic::OpenStudioProgramWindow()
  7162. {
  7163. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7164. }
  7165. void OBSBasic::OpenPreviewWindow()
  7166. {
  7167. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7168. }
  7169. void OBSBasic::OpenSourceWindow()
  7170. {
  7171. OBSSceneItem item = GetCurrentSceneItem();
  7172. if (!item)
  7173. return;
  7174. OBSSource source = obs_sceneitem_get_source(item);
  7175. OpenProjector(obs_sceneitem_get_source(item), -1,
  7176. ProjectorType::Source);
  7177. }
  7178. void OBSBasic::OpenMultiviewWindow()
  7179. {
  7180. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7181. }
  7182. void OBSBasic::OpenSceneWindow()
  7183. {
  7184. OBSScene scene = GetCurrentScene();
  7185. if (!scene)
  7186. return;
  7187. OBSSource source = obs_scene_get_source(scene);
  7188. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7189. }
  7190. void OBSBasic::OpenSavedProjectors()
  7191. {
  7192. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7193. OpenSavedProjector(info);
  7194. }
  7195. }
  7196. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7197. {
  7198. if (info) {
  7199. OBSProjector *projector = nullptr;
  7200. switch (info->type) {
  7201. case ProjectorType::Source:
  7202. case ProjectorType::Scene: {
  7203. OBSSourceAutoRelease source =
  7204. obs_get_source_by_name(info->name.c_str());
  7205. if (!source)
  7206. return;
  7207. projector = OpenProjector(source, info->monitor,
  7208. info->type);
  7209. break;
  7210. }
  7211. default: {
  7212. projector = OpenProjector(nullptr, info->monitor,
  7213. info->type);
  7214. break;
  7215. }
  7216. }
  7217. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7218. QByteArray byteArray = QByteArray::fromBase64(
  7219. QByteArray(info->geometry.c_str()));
  7220. projector->restoreGeometry(byteArray);
  7221. if (!WindowPositionValid(projector->normalGeometry())) {
  7222. QRect rect = QGuiApplication::primaryScreen()
  7223. ->geometry();
  7224. projector->setGeometry(QStyle::alignedRect(
  7225. Qt::LeftToRight, Qt::AlignCenter,
  7226. size(), rect));
  7227. }
  7228. if (info->alwaysOnTopOverridden)
  7229. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7230. true);
  7231. }
  7232. }
  7233. }
  7234. void OBSBasic::on_actionFullscreenInterface_triggered()
  7235. {
  7236. if (!isFullScreen())
  7237. showFullScreen();
  7238. else
  7239. showNormal();
  7240. }
  7241. void OBSBasic::UpdateTitleBar()
  7242. {
  7243. stringstream name;
  7244. const char *profile =
  7245. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7246. const char *sceneCollection = config_get_string(
  7247. App()->GlobalConfig(), "Basic", "SceneCollection");
  7248. name << "OBS ";
  7249. if (previewProgramMode)
  7250. name << "Studio ";
  7251. name << App()->GetVersionString();
  7252. if (App()->IsPortableMode())
  7253. name << " - Portable Mode";
  7254. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7255. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7256. setWindowTitle(QT_UTF8(name.str().c_str()));
  7257. }
  7258. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7259. {
  7260. char profiles_path[512];
  7261. const char *profile =
  7262. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7263. int ret;
  7264. if (!profile)
  7265. return -1;
  7266. if (!path)
  7267. return -1;
  7268. if (!file)
  7269. file = "";
  7270. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7271. if (ret <= 0)
  7272. return ret;
  7273. if (!*file)
  7274. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7275. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7276. }
  7277. void OBSBasic::on_resetDocks_triggered(bool force)
  7278. {
  7279. /* prune deleted extra docks */
  7280. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7281. if (!extraDocks[i]) {
  7282. extraDocks.removeAt(i);
  7283. }
  7284. }
  7285. if (extraDocks.size() && !force) {
  7286. QMessageBox::StandardButton button = QMessageBox::question(
  7287. this, QTStr("ResetUIWarning.Title"),
  7288. QTStr("ResetUIWarning.Text"));
  7289. if (button == QMessageBox::No)
  7290. return;
  7291. }
  7292. /* undock/hide/center extra docks */
  7293. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7294. if (extraDocks[i]) {
  7295. extraDocks[i]->setVisible(true);
  7296. extraDocks[i]->setFloating(true);
  7297. extraDocks[i]->move(frameGeometry().topLeft() +
  7298. rect().center() -
  7299. extraDocks[i]->rect().center());
  7300. extraDocks[i]->setVisible(false);
  7301. }
  7302. }
  7303. restoreState(startingDockLayout);
  7304. int cx = width();
  7305. int cy = height();
  7306. int cx22_5 = cx * 225 / 1000;
  7307. int cx5 = cx * 5 / 100;
  7308. int cx21 = cx * 21 / 100;
  7309. cy = cy * 225 / 1000;
  7310. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7311. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7312. ui->mixerDock, ui->transitionsDock,
  7313. ui->controlsDock};
  7314. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7315. ui->scenesDock->setVisible(true);
  7316. ui->sourcesDock->setVisible(true);
  7317. ui->mixerDock->setVisible(true);
  7318. ui->transitionsDock->setVisible(true);
  7319. ui->controlsDock->setVisible(true);
  7320. statsDock->setVisible(false);
  7321. statsDock->setFloating(true);
  7322. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7323. resizeDocks(docks, sizes, Qt::Horizontal);
  7324. activateWindow();
  7325. }
  7326. void OBSBasic::on_lockDocks_toggled(bool lock)
  7327. {
  7328. QDockWidget::DockWidgetFeatures features =
  7329. lock ? QDockWidget::NoDockWidgetFeatures
  7330. : (QDockWidget::DockWidgetClosable |
  7331. QDockWidget::DockWidgetMovable |
  7332. QDockWidget::DockWidgetFloatable);
  7333. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7334. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7335. ui->scenesDock->setFeatures(mainFeatures);
  7336. ui->sourcesDock->setFeatures(mainFeatures);
  7337. ui->mixerDock->setFeatures(mainFeatures);
  7338. ui->transitionsDock->setFeatures(mainFeatures);
  7339. ui->controlsDock->setFeatures(mainFeatures);
  7340. statsDock->setFeatures(features);
  7341. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7342. if (!extraDocks[i]) {
  7343. extraDocks.removeAt(i);
  7344. } else {
  7345. extraDocks[i]->setFeatures(features);
  7346. }
  7347. }
  7348. }
  7349. void OBSBasic::on_resetUI_triggered()
  7350. {
  7351. on_resetDocks_triggered();
  7352. ui->toggleListboxToolbars->setChecked(true);
  7353. ui->toggleContextBar->setChecked(true);
  7354. ui->toggleSourceIcons->setChecked(true);
  7355. ui->toggleStatusBar->setChecked(true);
  7356. }
  7357. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7358. {
  7359. ui->sourcesToolbar->setVisible(visible);
  7360. ui->scenesToolbar->setVisible(visible);
  7361. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7362. "ShowListboxToolbars", visible);
  7363. }
  7364. void OBSBasic::ShowContextBar()
  7365. {
  7366. on_toggleContextBar_toggled(true);
  7367. }
  7368. void OBSBasic::HideContextBar()
  7369. {
  7370. on_toggleContextBar_toggled(false);
  7371. }
  7372. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7373. {
  7374. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7375. "ShowContextToolbars", visible);
  7376. this->ui->contextContainer->setVisible(visible);
  7377. UpdateContextBar(true);
  7378. }
  7379. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7380. {
  7381. ui->statusbar->setVisible(visible);
  7382. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7383. visible);
  7384. }
  7385. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7386. {
  7387. ui->sources->SetIconsVisible(visible);
  7388. if (advAudioWindow != nullptr)
  7389. advAudioWindow->SetIconsVisible(visible);
  7390. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7391. visible);
  7392. }
  7393. void OBSBasic::on_actionLockPreview_triggered()
  7394. {
  7395. ui->preview->ToggleLocked();
  7396. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7397. }
  7398. void OBSBasic::on_scalingMenu_aboutToShow()
  7399. {
  7400. obs_video_info ovi;
  7401. obs_get_video_info(&ovi);
  7402. QAction *action = ui->actionScaleCanvas;
  7403. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7404. text = text.arg(QString::number(ovi.base_width),
  7405. QString::number(ovi.base_height));
  7406. action->setText(text);
  7407. action = ui->actionScaleOutput;
  7408. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7409. text = text.arg(QString::number(ovi.output_width),
  7410. QString::number(ovi.output_height));
  7411. action->setText(text);
  7412. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7413. ovi.output_height == ovi.base_height));
  7414. UpdatePreviewScalingMenu();
  7415. }
  7416. void OBSBasic::on_actionScaleWindow_triggered()
  7417. {
  7418. ui->preview->SetFixedScaling(false);
  7419. ui->preview->ResetScrollingOffset();
  7420. emit ui->preview->DisplayResized();
  7421. }
  7422. void OBSBasic::on_actionScaleCanvas_triggered()
  7423. {
  7424. ui->preview->SetFixedScaling(true);
  7425. ui->preview->SetScalingLevel(0);
  7426. emit ui->preview->DisplayResized();
  7427. }
  7428. void OBSBasic::on_actionScaleOutput_triggered()
  7429. {
  7430. obs_video_info ovi;
  7431. obs_get_video_info(&ovi);
  7432. ui->preview->SetFixedScaling(true);
  7433. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7434. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7435. int32_t approxScalingLevel =
  7436. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7437. ui->preview->SetScalingLevel(approxScalingLevel);
  7438. ui->preview->SetScalingAmount(scalingAmount);
  7439. emit ui->preview->DisplayResized();
  7440. }
  7441. void OBSBasic::SetShowing(bool showing)
  7442. {
  7443. if (!showing && isVisible()) {
  7444. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7445. "geometry",
  7446. saveGeometry().toBase64().constData());
  7447. /* hide all visible child dialogs */
  7448. visDlgPositions.clear();
  7449. if (!visDialogs.isEmpty()) {
  7450. for (QDialog *dlg : visDialogs) {
  7451. visDlgPositions.append(dlg->pos());
  7452. dlg->hide();
  7453. }
  7454. }
  7455. if (showHide)
  7456. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7457. QTimer::singleShot(0, this, SLOT(hide()));
  7458. if (previewEnabled)
  7459. EnablePreviewDisplay(false);
  7460. #ifdef __APPLE__
  7461. EnableOSXDockIcon(false);
  7462. #endif
  7463. } else if (showing && !isVisible()) {
  7464. if (showHide)
  7465. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7466. QTimer::singleShot(0, this, SLOT(show()));
  7467. if (previewEnabled)
  7468. EnablePreviewDisplay(true);
  7469. #ifdef __APPLE__
  7470. EnableOSXDockIcon(true);
  7471. #endif
  7472. /* raise and activate window to ensure it is on top */
  7473. raise();
  7474. activateWindow();
  7475. /* show all child dialogs that was visible earlier */
  7476. if (!visDialogs.isEmpty()) {
  7477. for (int i = 0; i < visDialogs.size(); ++i) {
  7478. QDialog *dlg = visDialogs[i];
  7479. dlg->move(visDlgPositions[i]);
  7480. dlg->show();
  7481. }
  7482. }
  7483. /* Unminimize window if it was hidden to tray instead of task
  7484. * bar. */
  7485. if (sysTrayMinimizeToTray()) {
  7486. Qt::WindowStates state;
  7487. state = windowState() & ~Qt::WindowMinimized;
  7488. state |= Qt::WindowActive;
  7489. setWindowState(state);
  7490. }
  7491. }
  7492. }
  7493. void OBSBasic::ToggleShowHide()
  7494. {
  7495. bool showing = isVisible();
  7496. if (showing) {
  7497. /* check for modal dialogs */
  7498. EnumDialogs();
  7499. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7500. return;
  7501. }
  7502. SetShowing(!showing);
  7503. }
  7504. void OBSBasic::SystemTrayInit()
  7505. {
  7506. #ifdef __APPLE__
  7507. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  7508. trayIconFile.setIsMask(true);
  7509. #else
  7510. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7511. #endif
  7512. trayIcon.reset(new QSystemTrayIcon(
  7513. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7514. trayIcon->setToolTip("OBS Studio");
  7515. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7516. sysTrayStream = new QAction(
  7517. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  7518. : QTStr("Basic.Main.StartStreaming"),
  7519. trayIcon.data());
  7520. sysTrayRecord = new QAction(
  7521. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  7522. : QTStr("Basic.Main.StartRecording"),
  7523. trayIcon.data());
  7524. sysTrayReplayBuffer = new QAction(
  7525. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  7526. : QTStr("Basic.Main.StartReplayBuffer"),
  7527. trayIcon.data());
  7528. sysTrayVirtualCam = new QAction(
  7529. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  7530. : QTStr("Basic.Main.StartVirtualCam"),
  7531. trayIcon.data());
  7532. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7533. trayMenu = new QMenu;
  7534. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7535. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7536. AddProjectorMenuMonitors(previewProjector, this,
  7537. SLOT(OpenPreviewProjector()));
  7538. AddProjectorMenuMonitors(studioProgramProjector, this,
  7539. SLOT(OpenStudioProgramProjector()));
  7540. trayMenu->addAction(showHide);
  7541. trayMenu->addSeparator();
  7542. trayMenu->addMenu(previewProjector);
  7543. trayMenu->addMenu(studioProgramProjector);
  7544. trayMenu->addSeparator();
  7545. trayMenu->addAction(sysTrayStream);
  7546. trayMenu->addAction(sysTrayRecord);
  7547. trayMenu->addAction(sysTrayReplayBuffer);
  7548. trayMenu->addAction(sysTrayVirtualCam);
  7549. trayMenu->addSeparator();
  7550. trayMenu->addAction(exit);
  7551. trayIcon->setContextMenu(trayMenu);
  7552. trayIcon->show();
  7553. if (outputHandler && !outputHandler->replayBuffer)
  7554. sysTrayReplayBuffer->setEnabled(false);
  7555. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7556. if (Active())
  7557. OnActivate(true);
  7558. connect(trayIcon.data(),
  7559. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7560. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7561. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7562. connect(sysTrayStream, SIGNAL(triggered()), this,
  7563. SLOT(on_streamButton_clicked()));
  7564. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7565. SLOT(on_recordButton_clicked()));
  7566. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7567. &OBSBasic::ReplayBufferClicked);
  7568. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7569. &OBSBasic::VCamButtonClicked);
  7570. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7571. }
  7572. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7573. {
  7574. // Refresh projector list
  7575. previewProjector->clear();
  7576. studioProgramProjector->clear();
  7577. AddProjectorMenuMonitors(previewProjector, this,
  7578. SLOT(OpenPreviewProjector()));
  7579. AddProjectorMenuMonitors(studioProgramProjector, this,
  7580. SLOT(OpenStudioProgramProjector()));
  7581. #ifdef __APPLE__
  7582. UNUSED_PARAMETER(reason);
  7583. #else
  7584. if (reason == QSystemTrayIcon::Trigger) {
  7585. EnablePreviewDisplay(previewEnabled && !isVisible());
  7586. ToggleShowHide();
  7587. }
  7588. #endif
  7589. }
  7590. void OBSBasic::SysTrayNotify(const QString &text,
  7591. QSystemTrayIcon::MessageIcon n)
  7592. {
  7593. if (trayIcon && trayIcon->isVisible() &&
  7594. QSystemTrayIcon::supportsMessages()) {
  7595. QSystemTrayIcon::MessageIcon icon =
  7596. QSystemTrayIcon::MessageIcon(n);
  7597. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7598. }
  7599. }
  7600. void OBSBasic::SystemTray(bool firstStarted)
  7601. {
  7602. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7603. return;
  7604. if (!trayIcon && !firstStarted)
  7605. return;
  7606. bool sysTrayWhenStarted = config_get_bool(
  7607. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7608. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7609. "SysTrayEnabled");
  7610. if (firstStarted)
  7611. SystemTrayInit();
  7612. if (!sysTrayEnabled) {
  7613. trayIcon->hide();
  7614. } else {
  7615. trayIcon->show();
  7616. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7617. EnablePreviewDisplay(false);
  7618. #ifdef __APPLE__
  7619. EnableOSXDockIcon(false);
  7620. #endif
  7621. opt_minimize_tray = false;
  7622. }
  7623. }
  7624. if (isVisible())
  7625. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7626. else
  7627. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7628. }
  7629. bool OBSBasic::sysTrayMinimizeToTray()
  7630. {
  7631. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7632. "SysTrayMinimizeToTray");
  7633. }
  7634. void OBSBasic::on_actionMainUndo_triggered()
  7635. {
  7636. undo_s.undo();
  7637. }
  7638. void OBSBasic::on_actionMainRedo_triggered()
  7639. {
  7640. undo_s.redo();
  7641. }
  7642. void OBSBasic::on_actionCopySource_triggered()
  7643. {
  7644. clipboard.clear();
  7645. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7646. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7647. if (!item)
  7648. continue;
  7649. OBSSource source = obs_sceneitem_get_source(item);
  7650. SourceCopyInfo copyInfo;
  7651. copyInfo.weak_source = OBSGetWeakRef(source);
  7652. obs_sceneitem_get_info(item, &copyInfo.transform);
  7653. obs_sceneitem_get_crop(item, &copyInfo.crop);
  7654. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  7655. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  7656. copyInfo.visible = obs_sceneitem_visible(item);
  7657. clipboard.push_back(copyInfo);
  7658. }
  7659. UpdateEditMenu();
  7660. }
  7661. void OBSBasic::on_actionPasteRef_triggered()
  7662. {
  7663. OBSSource scene_source = GetCurrentSceneSource();
  7664. OBSData undo_data = BackupScene(scene_source);
  7665. OBSScene scene = GetCurrentScene();
  7666. undo_s.push_disabled();
  7667. for (size_t i = clipboard.size(); i > 0; i--) {
  7668. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7669. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  7670. if (!source)
  7671. continue;
  7672. const char *name = obs_source_get_name(source);
  7673. /* do not allow duplicate refs of the same group in the same
  7674. * scene */
  7675. if (!!obs_scene_get_group(scene, name)) {
  7676. continue;
  7677. }
  7678. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  7679. }
  7680. undo_s.pop_disabled();
  7681. QString action_name = QTStr("Undo.PasteSourceRef");
  7682. const char *scene_name = obs_source_get_name(scene_source);
  7683. OBSData redo_data = BackupScene(scene_source);
  7684. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7685. redo_data);
  7686. }
  7687. void OBSBasic::on_actionPasteDup_triggered()
  7688. {
  7689. OBSSource scene_source = GetCurrentSceneSource();
  7690. OBSData undo_data = BackupScene(scene_source);
  7691. undo_s.push_disabled();
  7692. for (size_t i = clipboard.size(); i > 0; i--) {
  7693. SourceCopyInfo &copyInfo = clipboard[i - 1];
  7694. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  7695. }
  7696. undo_s.pop_disabled();
  7697. QString action_name = QTStr("Undo.PasteSource");
  7698. const char *scene_name = obs_source_get_name(scene_source);
  7699. OBSData redo_data = BackupScene(scene_source);
  7700. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7701. redo_data);
  7702. }
  7703. void OBSBasic::AudioMixerCopyFilters()
  7704. {
  7705. QAction *action = reinterpret_cast<QAction *>(sender());
  7706. VolControl *vol = action->property("volControl").value<VolControl *>();
  7707. obs_source_t *source = vol->GetSource();
  7708. copyFiltersSource = obs_source_get_weak_source(source);
  7709. }
  7710. void OBSBasic::AudioMixerPasteFilters()
  7711. {
  7712. QAction *action = reinterpret_cast<QAction *>(sender());
  7713. VolControl *vol = action->property("volControl").value<VolControl *>();
  7714. obs_source_t *dstSource = vol->GetSource();
  7715. OBSSourceAutoRelease source =
  7716. obs_weak_source_get_source(copyFiltersSource);
  7717. if (source == dstSource)
  7718. return;
  7719. obs_source_copy_filters(dstSource, source);
  7720. }
  7721. void OBSBasic::SceneCopyFilters()
  7722. {
  7723. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  7724. }
  7725. void OBSBasic::ScenePasteFilters()
  7726. {
  7727. OBSSourceAutoRelease source =
  7728. obs_weak_source_get_source(copyFiltersSource);
  7729. OBSSource dstSource = GetCurrentSceneSource();
  7730. if (source == dstSource)
  7731. return;
  7732. obs_source_copy_filters(dstSource, source);
  7733. }
  7734. void OBSBasic::on_actionCopyFilters_triggered()
  7735. {
  7736. OBSSceneItem item = GetCurrentSceneItem();
  7737. if (!item)
  7738. return;
  7739. OBSSource source = obs_sceneitem_get_source(item);
  7740. copyFiltersSource = obs_source_get_weak_source(source);
  7741. ui->actionPasteFilters->setEnabled(true);
  7742. }
  7743. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7744. obs_source_t *source,
  7745. obs_data_array_t *undo_array,
  7746. obs_data_array_t *redo_array)
  7747. {
  7748. auto undo_redo = [this](const std::string &json) {
  7749. OBSDataAutoRelease data =
  7750. obs_data_create_from_json(json.c_str());
  7751. OBSDataArrayAutoRelease array =
  7752. obs_data_get_array(data, "array");
  7753. const char *name = obs_data_get_string(data, "name");
  7754. OBSSourceAutoRelease source = obs_get_source_by_name(name);
  7755. obs_source_restore_filters(source, array);
  7756. if (filters)
  7757. filters->UpdateSource(source);
  7758. };
  7759. const char *name = obs_source_get_name(source);
  7760. OBSDataAutoRelease undo_data = obs_data_create();
  7761. OBSDataAutoRelease redo_data = obs_data_create();
  7762. obs_data_set_array(undo_data, "array", undo_array);
  7763. obs_data_set_array(redo_data, "array", redo_array);
  7764. obs_data_set_string(undo_data, "name", name);
  7765. obs_data_set_string(redo_data, "name", name);
  7766. undo_s.add_action(text, undo_redo, undo_redo,
  7767. obs_data_get_json(undo_data),
  7768. obs_data_get_json(redo_data));
  7769. }
  7770. void OBSBasic::on_actionPasteFilters_triggered()
  7771. {
  7772. OBSSourceAutoRelease source =
  7773. obs_weak_source_get_source(copyFiltersSource);
  7774. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7775. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7776. if (source == dstSource)
  7777. return;
  7778. OBSDataArrayAutoRelease undo_array =
  7779. obs_source_backup_filters(dstSource);
  7780. obs_source_copy_filters(dstSource, source);
  7781. OBSDataArrayAutoRelease redo_array =
  7782. obs_source_backup_filters(dstSource);
  7783. const char *srcName = obs_source_get_name(source);
  7784. const char *dstName = obs_source_get_name(dstSource);
  7785. QString text =
  7786. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7787. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7788. redo_array);
  7789. }
  7790. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7791. QModelIndexList selectedItems)
  7792. {
  7793. for (int x = 0; x < selectedItems.count(); x++) {
  7794. SourceTreeItem *treeItem =
  7795. sources->GetItemWidget(selectedItems[x].row());
  7796. treeItem->setStyleSheet("background: " +
  7797. color.name(QColor::HexArgb));
  7798. treeItem->style()->unpolish(treeItem);
  7799. treeItem->style()->polish(treeItem);
  7800. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7801. OBSDataAutoRelease privData =
  7802. obs_sceneitem_get_private_settings(sceneItem);
  7803. obs_data_set_int(privData, "color-preset", 1);
  7804. obs_data_set_string(privData, "color",
  7805. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7806. }
  7807. }
  7808. void OBSBasic::ColorChange()
  7809. {
  7810. QModelIndexList selectedItems =
  7811. ui->sources->selectionModel()->selectedIndexes();
  7812. QAction *action = qobject_cast<QAction *>(sender());
  7813. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7814. if (selectedItems.count() == 0)
  7815. return;
  7816. if (colorButton) {
  7817. int preset = colorButton->property("bgColor").value<int>();
  7818. for (int x = 0; x < selectedItems.count(); x++) {
  7819. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7820. selectedItems[x].row());
  7821. treeItem->setStyleSheet("");
  7822. treeItem->setProperty("bgColor", preset);
  7823. treeItem->style()->unpolish(treeItem);
  7824. treeItem->style()->polish(treeItem);
  7825. OBSSceneItem sceneItem =
  7826. ui->sources->Get(selectedItems[x].row());
  7827. OBSDataAutoRelease privData =
  7828. obs_sceneitem_get_private_settings(sceneItem);
  7829. obs_data_set_int(privData, "color-preset", preset + 1);
  7830. obs_data_set_string(privData, "color", "");
  7831. }
  7832. for (int i = 1; i < 9; i++) {
  7833. stringstream button;
  7834. button << "preset" << i;
  7835. QPushButton *cButton =
  7836. colorButton->parentWidget()
  7837. ->findChild<QPushButton *>(
  7838. button.str().c_str());
  7839. cButton->setStyleSheet("border: 1px solid black");
  7840. }
  7841. colorButton->setStyleSheet("border: 2px solid black");
  7842. } else if (action) {
  7843. int preset = action->property("bgColor").value<int>();
  7844. if (preset == 1) {
  7845. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7846. SourceTreeItem *curTreeItem =
  7847. GetItemWidgetFromSceneItem(curSceneItem);
  7848. OBSDataAutoRelease curPrivData =
  7849. obs_sceneitem_get_private_settings(
  7850. curSceneItem);
  7851. int oldPreset =
  7852. obs_data_get_int(curPrivData, "color-preset");
  7853. const QString oldSheet = curTreeItem->styleSheet();
  7854. auto liveChangeColor = [=](const QColor &color) {
  7855. if (color.isValid()) {
  7856. curTreeItem->setStyleSheet(
  7857. "background: " +
  7858. color.name(QColor::HexArgb));
  7859. }
  7860. };
  7861. auto changedColor = [=](const QColor &color) {
  7862. if (color.isValid()) {
  7863. ConfirmColor(ui->sources, color,
  7864. selectedItems);
  7865. }
  7866. };
  7867. auto rejected = [=]() {
  7868. if (oldPreset == 1) {
  7869. curTreeItem->setStyleSheet(oldSheet);
  7870. curTreeItem->setProperty("bgColor", 0);
  7871. } else if (oldPreset == 0) {
  7872. curTreeItem->setStyleSheet(
  7873. "background: none");
  7874. curTreeItem->setProperty("bgColor", 0);
  7875. } else {
  7876. curTreeItem->setStyleSheet("");
  7877. curTreeItem->setProperty("bgColor",
  7878. oldPreset - 1);
  7879. }
  7880. curTreeItem->style()->unpolish(curTreeItem);
  7881. curTreeItem->style()->polish(curTreeItem);
  7882. };
  7883. QColorDialog::ColorDialogOptions options =
  7884. QColorDialog::ShowAlphaChannel;
  7885. const char *oldColor =
  7886. obs_data_get_string(curPrivData, "color");
  7887. const char *customColor = *oldColor != 0 ? oldColor
  7888. : "#55FF0000";
  7889. #ifndef _WIN32
  7890. options |= QColorDialog::DontUseNativeDialog;
  7891. #endif
  7892. QColorDialog *colorDialog = new QColorDialog(this);
  7893. colorDialog->setOptions(options);
  7894. colorDialog->setCurrentColor(QColor(customColor));
  7895. connect(colorDialog, &QColorDialog::currentColorChanged,
  7896. liveChangeColor);
  7897. connect(colorDialog, &QColorDialog::colorSelected,
  7898. changedColor);
  7899. connect(colorDialog, &QColorDialog::rejected, rejected);
  7900. colorDialog->open();
  7901. } else {
  7902. for (int x = 0; x < selectedItems.count(); x++) {
  7903. SourceTreeItem *treeItem =
  7904. ui->sources->GetItemWidget(
  7905. selectedItems[x].row());
  7906. treeItem->setStyleSheet("background: none");
  7907. treeItem->setProperty("bgColor", preset);
  7908. treeItem->style()->unpolish(treeItem);
  7909. treeItem->style()->polish(treeItem);
  7910. OBSSceneItem sceneItem = ui->sources->Get(
  7911. selectedItems[x].row());
  7912. OBSDataAutoRelease privData =
  7913. obs_sceneitem_get_private_settings(
  7914. sceneItem);
  7915. obs_data_set_int(privData, "color-preset",
  7916. preset);
  7917. obs_data_set_string(privData, "color", "");
  7918. }
  7919. }
  7920. }
  7921. }
  7922. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7923. {
  7924. int i = 0;
  7925. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7926. OBSSceneItem item = ui->sources->Get(i);
  7927. int64_t id = obs_sceneitem_get_id(sceneItem);
  7928. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7929. i++;
  7930. treeItem = ui->sources->GetItemWidget(i);
  7931. item = ui->sources->Get(i);
  7932. }
  7933. if (treeItem)
  7934. return treeItem;
  7935. return nullptr;
  7936. }
  7937. void OBSBasic::on_autoConfigure_triggered()
  7938. {
  7939. AutoConfig test(this);
  7940. test.setModal(true);
  7941. test.show();
  7942. test.exec();
  7943. }
  7944. void OBSBasic::on_stats_triggered()
  7945. {
  7946. if (!stats.isNull()) {
  7947. stats->show();
  7948. stats->raise();
  7949. return;
  7950. }
  7951. OBSBasicStats *statsDlg;
  7952. statsDlg = new OBSBasicStats(nullptr);
  7953. statsDlg->show();
  7954. stats = statsDlg;
  7955. }
  7956. void OBSBasic::on_actionShowAbout_triggered()
  7957. {
  7958. if (about)
  7959. about->close();
  7960. about = new OBSAbout(this);
  7961. about->show();
  7962. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7963. }
  7964. void OBSBasic::ResizeOutputSizeOfSource()
  7965. {
  7966. if (obs_video_active())
  7967. return;
  7968. QMessageBox resize_output(this);
  7969. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  7970. QTStr("ResizeOutputSizeOfSource.Continue"));
  7971. QAbstractButton *Yes =
  7972. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  7973. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  7974. resize_output.setIcon(QMessageBox::Warning);
  7975. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  7976. resize_output.exec();
  7977. if (resize_output.clickedButton() != Yes)
  7978. return;
  7979. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  7980. int width = obs_source_get_width(source);
  7981. int height = obs_source_get_height(source);
  7982. config_set_uint(basicConfig, "Video", "BaseCX", width);
  7983. config_set_uint(basicConfig, "Video", "BaseCY", height);
  7984. config_set_uint(basicConfig, "Video", "OutputCX", width);
  7985. config_set_uint(basicConfig, "Video", "OutputCY", height);
  7986. ResetVideo();
  7987. ResetOutputs();
  7988. config_save_safe(basicConfig, "tmp", nullptr);
  7989. on_actionFitToScreen_triggered();
  7990. }
  7991. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7992. {
  7993. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  7994. action->setProperty("uuid", dock->property("uuid").toString());
  7995. action->setCheckable(true);
  7996. assignDockToggle(dock, action);
  7997. extraDocks.push_back(dock);
  7998. bool lock = ui->lockDocks->isChecked();
  7999. QDockWidget::DockWidgetFeatures features =
  8000. lock ? QDockWidget::NoDockWidgetFeatures
  8001. : (QDockWidget::DockWidgetClosable |
  8002. QDockWidget::DockWidgetMovable |
  8003. QDockWidget::DockWidgetFloatable);
  8004. dock->setFeatures(features);
  8005. /* prune deleted docks */
  8006. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  8007. if (!extraDocks[i]) {
  8008. extraDocks.removeAt(i);
  8009. }
  8010. }
  8011. return action;
  8012. }
  8013. OBSBasic *OBSBasic::Get()
  8014. {
  8015. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8016. }
  8017. bool OBSBasic::StreamingActive()
  8018. {
  8019. if (!outputHandler)
  8020. return false;
  8021. return outputHandler->StreamingActive();
  8022. }
  8023. bool OBSBasic::RecordingActive()
  8024. {
  8025. if (!outputHandler)
  8026. return false;
  8027. return outputHandler->RecordingActive();
  8028. }
  8029. bool OBSBasic::ReplayBufferActive()
  8030. {
  8031. if (!outputHandler)
  8032. return false;
  8033. return outputHandler->ReplayBufferActive();
  8034. }
  8035. bool OBSBasic::VirtualCamActive()
  8036. {
  8037. if (!outputHandler)
  8038. return false;
  8039. return outputHandler->VirtualCamActive();
  8040. }
  8041. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8042. : QStyledItemDelegate(parent)
  8043. {
  8044. }
  8045. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8046. const QModelIndex &index) const
  8047. {
  8048. QStyledItemDelegate::setEditorData(editor, index);
  8049. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8050. if (lineEdit)
  8051. lineEdit->selectAll();
  8052. }
  8053. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8054. {
  8055. if (event->type() == QEvent::KeyPress) {
  8056. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8057. if (keyEvent->key() == Qt::Key_Escape) {
  8058. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8059. if (lineEdit)
  8060. lineEdit->undo();
  8061. }
  8062. }
  8063. return QStyledItemDelegate::eventFilter(editor, event);
  8064. }
  8065. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8066. {
  8067. if (!error.isEmpty())
  8068. return;
  8069. patronJson = QT_TO_UTF8(text);
  8070. }
  8071. void OBSBasic::PauseRecording()
  8072. {
  8073. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8074. os_atomic_load_bool(&recording_paused))
  8075. return;
  8076. obs_output_t *output = outputHandler->fileOutput;
  8077. if (obs_output_pause(output, true)) {
  8078. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  8079. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  8080. pause->blockSignals(true);
  8081. pause->setChecked(true);
  8082. pause->blockSignals(false);
  8083. ui->statusbar->RecordingPaused();
  8084. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8085. if (trayIcon && trayIcon->isVisible()) {
  8086. #ifdef __APPLE__
  8087. QIcon trayIconFile =
  8088. QIcon(":/res/images/obs_paused_macos.svg");
  8089. trayIconFile.setIsMask(true);
  8090. #else
  8091. QIcon trayIconFile =
  8092. QIcon(":/res/images/obs_paused.png");
  8093. #endif
  8094. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8095. trayIconFile));
  8096. }
  8097. os_atomic_set_bool(&recording_paused, true);
  8098. auto replay = replayBufferButton ? replayBufferButton->second()
  8099. : nullptr;
  8100. if (replay)
  8101. replay->setEnabled(false);
  8102. if (api)
  8103. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8104. if (os_atomic_load_bool(&replaybuf_active))
  8105. ShowReplayBufferPauseWarning();
  8106. }
  8107. }
  8108. void OBSBasic::UnpauseRecording()
  8109. {
  8110. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8111. !os_atomic_load_bool(&recording_paused))
  8112. return;
  8113. obs_output_t *output = outputHandler->fileOutput;
  8114. if (obs_output_pause(output, false)) {
  8115. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8116. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8117. pause->blockSignals(true);
  8118. pause->setChecked(false);
  8119. pause->blockSignals(false);
  8120. ui->statusbar->RecordingUnpaused();
  8121. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8122. if (trayIcon && trayIcon->isVisible()) {
  8123. #ifdef __APPLE__
  8124. QIcon trayIconFile =
  8125. QIcon(":/res/images/tray_active_macos.svg");
  8126. trayIconFile.setIsMask(true);
  8127. #else
  8128. QIcon trayIconFile =
  8129. QIcon(":/res/images/tray_active.png");
  8130. #endif
  8131. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8132. trayIconFile));
  8133. }
  8134. os_atomic_set_bool(&recording_paused, false);
  8135. auto replay = replayBufferButton ? replayBufferButton->second()
  8136. : nullptr;
  8137. if (replay)
  8138. replay->setEnabled(true);
  8139. if (api)
  8140. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8141. }
  8142. }
  8143. void OBSBasic::PauseToggled()
  8144. {
  8145. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8146. return;
  8147. obs_output_t *output = outputHandler->fileOutput;
  8148. bool enable = !obs_output_paused(output);
  8149. if (enable)
  8150. PauseRecording();
  8151. else
  8152. UnpauseRecording();
  8153. }
  8154. void OBSBasic::UpdatePause(bool activate)
  8155. {
  8156. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8157. pause.reset();
  8158. return;
  8159. }
  8160. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8161. bool adv = astrcmpi(mode, "Advanced") == 0;
  8162. bool shared;
  8163. if (adv) {
  8164. const char *recType =
  8165. config_get_string(basicConfig, "AdvOut", "RecType");
  8166. if (astrcmpi(recType, "FFmpeg") == 0) {
  8167. shared = config_get_bool(basicConfig, "AdvOut",
  8168. "FFOutputToFile");
  8169. } else {
  8170. const char *recordEncoder = config_get_string(
  8171. basicConfig, "AdvOut", "RecEncoder");
  8172. shared = astrcmpi(recordEncoder, "none") == 0;
  8173. }
  8174. } else {
  8175. const char *quality = config_get_string(
  8176. basicConfig, "SimpleOutput", "RecQuality");
  8177. shared = strcmp(quality, "Stream") == 0;
  8178. }
  8179. if (!shared) {
  8180. pause.reset(new QPushButton());
  8181. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8182. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8183. pause->setCheckable(true);
  8184. pause->setChecked(false);
  8185. pause->setProperty("themeID",
  8186. QVariant(QStringLiteral("pauseIconSmall")));
  8187. QSizePolicy sp;
  8188. sp.setHeightForWidth(true);
  8189. pause->setSizePolicy(sp);
  8190. connect(pause.data(), &QAbstractButton::clicked, this,
  8191. &OBSBasic::PauseToggled);
  8192. ui->recordingLayout->addWidget(pause.data());
  8193. } else {
  8194. pause.reset();
  8195. }
  8196. }
  8197. void OBSBasic::UpdateReplayBuffer(bool activate)
  8198. {
  8199. if (!activate || !outputHandler ||
  8200. !outputHandler->ReplayBufferActive()) {
  8201. replayBufferButton->removeIcon();
  8202. return;
  8203. }
  8204. replayBufferButton->addIcon(QTStr("Basic.Main.SaveReplay"),
  8205. QStringLiteral("replayIconSmall"),
  8206. &OBSBasic::ReplayBufferSave);
  8207. }
  8208. #define MBYTE (1024ULL * 1024ULL)
  8209. #define MBYTES_LEFT_STOP_REC 50ULL
  8210. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8211. const char *OBSBasic::GetCurrentOutputPath()
  8212. {
  8213. const char *path = nullptr;
  8214. const char *mode = config_get_string(Config(), "Output", "Mode");
  8215. if (strcmp(mode, "Advanced") == 0) {
  8216. const char *advanced_mode =
  8217. config_get_string(Config(), "AdvOut", "RecType");
  8218. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8219. path = config_get_string(Config(), "AdvOut",
  8220. "FFFilePath");
  8221. } else {
  8222. path = config_get_string(Config(), "AdvOut",
  8223. "RecFilePath");
  8224. }
  8225. } else {
  8226. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8227. }
  8228. return path;
  8229. }
  8230. void OBSBasic::OutputPathInvalidMessage()
  8231. {
  8232. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8233. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8234. QTStr("Output.BadPath.Text"));
  8235. }
  8236. bool OBSBasic::OutputPathValid()
  8237. {
  8238. const char *mode = config_get_string(Config(), "Output", "Mode");
  8239. if (strcmp(mode, "Advanced") == 0) {
  8240. const char *advanced_mode =
  8241. config_get_string(Config(), "AdvOut", "RecType");
  8242. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8243. bool is_local = config_get_bool(Config(), "AdvOut",
  8244. "FFOutputToFile");
  8245. if (!is_local)
  8246. return true;
  8247. }
  8248. }
  8249. const char *path = GetCurrentOutputPath();
  8250. return path && *path && QDir(path).exists();
  8251. }
  8252. void OBSBasic::DiskSpaceMessage()
  8253. {
  8254. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8255. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8256. QTStr("Output.RecordNoSpace.Msg"));
  8257. }
  8258. bool OBSBasic::LowDiskSpace()
  8259. {
  8260. const char *path;
  8261. path = GetCurrentOutputPath();
  8262. if (!path)
  8263. return false;
  8264. uint64_t num_bytes = os_get_free_disk_space(path);
  8265. if (num_bytes < (MAX_BYTES_LEFT))
  8266. return true;
  8267. else
  8268. return false;
  8269. }
  8270. void OBSBasic::CheckDiskSpaceRemaining()
  8271. {
  8272. if (LowDiskSpace()) {
  8273. StopRecording();
  8274. StopReplayBuffer();
  8275. DiskSpaceMessage();
  8276. }
  8277. }
  8278. void OBSBasic::ScenesReordered()
  8279. {
  8280. OBSProjector::UpdateMultiviewProjectors();
  8281. }
  8282. void OBSBasic::ResetStatsHotkey()
  8283. {
  8284. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8285. foreach(OBSBasicStats * s, list) s->Reset();
  8286. }
  8287. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  8288. {
  8289. QWidget *widget = childAt(pos);
  8290. const char *className = nullptr;
  8291. QString objName;
  8292. if (widget != nullptr) {
  8293. className = widget->metaObject()->className();
  8294. objName = widget->objectName();
  8295. }
  8296. QPoint globalPos = mapToGlobal(pos);
  8297. if (className && strstr(className, "Dock") != nullptr &&
  8298. !objName.isEmpty()) {
  8299. if (objName.compare("scenesDock") == 0) {
  8300. ui->scenes->customContextMenuRequested(globalPos);
  8301. } else if (objName.compare("sourcesDock") == 0) {
  8302. ui->sources->customContextMenuRequested(globalPos);
  8303. } else if (objName.compare("mixerDock") == 0) {
  8304. StackedMixerAreaContextMenuRequested();
  8305. }
  8306. } else if (!className) {
  8307. ui->menuDocks->exec(globalPos);
  8308. }
  8309. }
  8310. void OBSBasic::UpdateProjectorHideCursor()
  8311. {
  8312. for (size_t i = 0; i < projectors.size(); i++)
  8313. projectors[i]->SetHideCursor();
  8314. }
  8315. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8316. {
  8317. for (size_t i = 0; i < projectors.size(); i++)
  8318. SetAlwaysOnTop(projectors[i], top);
  8319. }
  8320. void OBSBasic::ResetProjectors()
  8321. {
  8322. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8323. ClearProjectors();
  8324. LoadSavedProjectors(savedProjectorList);
  8325. OpenSavedProjectors();
  8326. }
  8327. void OBSBasic::on_sourcePropertiesButton_clicked()
  8328. {
  8329. on_actionSourceProperties_triggered();
  8330. }
  8331. void OBSBasic::on_sourceFiltersButton_clicked()
  8332. {
  8333. OpenFilters();
  8334. }
  8335. void OBSBasic::on_sourceInteractButton_clicked()
  8336. {
  8337. on_actionInteract_triggered();
  8338. }
  8339. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8340. {
  8341. ui->statusbar->clearMessage();
  8342. ui->statusbar->showMessage(message, 10000);
  8343. }
  8344. void OBSBasic::UpdatePreviewSafeAreas()
  8345. {
  8346. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8347. "ShowSafeAreas");
  8348. }
  8349. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8350. {
  8351. if (!SetDisplayAffinitySupported())
  8352. return;
  8353. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8354. "BasicWindow",
  8355. "HideOBSWindowsFromCapture");
  8356. // Don't hide projectors, those are designed to be visible / captured
  8357. if (window->property("isOBSProjectorWindow") == true)
  8358. return;
  8359. #ifdef _WIN32
  8360. HWND hwnd = (HWND)window->winId();
  8361. DWORD curAffinity;
  8362. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8363. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8364. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8365. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8366. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8367. }
  8368. #else
  8369. // TODO: Implement for other platforms if possible. Don't forget to
  8370. // implement SetDisplayAffinitySupported too!
  8371. UNUSED_PARAMETER(hideFromCapture);
  8372. #endif
  8373. }
  8374. static inline QColor color_from_int(long long val)
  8375. {
  8376. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  8377. (val >> 24) & 0xff);
  8378. }
  8379. QColor OBSBasic::GetSelectionColor() const
  8380. {
  8381. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8382. "OverrideColors")) {
  8383. return color_from_int(config_get_int(
  8384. GetGlobalConfig(), "Accessibility", "SelectRed"));
  8385. } else {
  8386. return QColor::fromRgb(255, 0, 0);
  8387. }
  8388. }
  8389. QColor OBSBasic::GetCropColor() const
  8390. {
  8391. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8392. "OverrideColors")) {
  8393. return color_from_int(config_get_int(
  8394. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  8395. } else {
  8396. return QColor::fromRgb(0, 255, 0);
  8397. }
  8398. }
  8399. QColor OBSBasic::GetHoverColor() const
  8400. {
  8401. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  8402. "OverrideColors")) {
  8403. return color_from_int(config_get_int(
  8404. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  8405. } else {
  8406. return QColor::fromRgb(0, 127, 255);
  8407. }
  8408. }
  8409. void OBSBasic::UpdatePreviewSpacingHelpers()
  8410. {
  8411. drawSpacingHelpers = config_get_bool(
  8412. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  8413. }
  8414. float OBSBasic::GetDevicePixelRatio()
  8415. {
  8416. return dpi;
  8417. }
  8418. void OBSBasic::ResetProxyStyleSliders()
  8419. {
  8420. /* Since volume/media sliders are using QProxyStyle, they are not
  8421. * updated when themes are changed, so re-initialize them. */
  8422. vector<OBSSource> sources;
  8423. for (size_t i = 0; i != volumes.size(); i++)
  8424. sources.emplace_back(volumes[i]->GetSource());
  8425. ClearVolumeControls();
  8426. for (const auto &source : sources)
  8427. ActivateAudioSource(source);
  8428. UpdateContextBar(true);
  8429. }