window-basic-main.cpp 183 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995
  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 <ctime>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QScreen>
  25. #include <QColorDialog>
  26. #include <QSizePolicy>
  27. #include <util/dstr.h>
  28. #include <util/util.hpp>
  29. #include <util/platform.h>
  30. #include <util/profiler.hpp>
  31. #include <util/dstr.hpp>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-log-reply.hpp"
  44. #include "window-projector.hpp"
  45. #include "window-remux.hpp"
  46. #include "qt-wrappers.hpp"
  47. #include "display-helpers.hpp"
  48. #include "volume-control.hpp"
  49. #include "remote-text.hpp"
  50. #include <fstream>
  51. #include <sstream>
  52. #ifdef _WIN32
  53. #include "win-update/win-update.hpp"
  54. #endif
  55. #include "ui_OBSBasic.h"
  56. #include "ui_ColorSelect.h"
  57. #include <fstream>
  58. #include <sstream>
  59. #include <QScreen>
  60. #include <QWindow>
  61. #include <json11.hpp>
  62. using namespace json11;
  63. using namespace std;
  64. #ifdef BROWSER_AVAILABLE
  65. #include <browser-panel.hpp>
  66. #endif
  67. #include "ui-config.h"
  68. struct QCef;
  69. struct QCefCookieManager;
  70. QCef *cef = nullptr;
  71. QCefCookieManager *panel_cookies = nullptr;
  72. void DestroyPanelCookieManager();
  73. namespace {
  74. template <typename OBSRef>
  75. struct SignalContainer {
  76. OBSRef ref;
  77. vector<shared_ptr<OBSSignal>> handlers;
  78. };
  79. }
  80. Q_DECLARE_METATYPE(OBSScene);
  81. Q_DECLARE_METATYPE(OBSSceneItem);
  82. Q_DECLARE_METATYPE(OBSSource);
  83. Q_DECLARE_METATYPE(obs_order_movement);
  84. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  85. template <typename T>
  86. static T GetOBSRef(QListWidgetItem *item)
  87. {
  88. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  89. }
  90. template <typename T>
  91. static void SetOBSRef(QListWidgetItem *item, T &&val)
  92. {
  93. item->setData(static_cast<int>(QtDataRole::OBSRef),
  94. QVariant::fromValue(val));
  95. }
  96. static void AddExtraModulePaths()
  97. {
  98. char base_module_dir[512];
  99. #if defined(_WIN32) || defined(__APPLE__)
  100. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  101. "obs-studio/plugins/%module%");
  102. #else
  103. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  104. "obs-studio/plugins/%module%");
  105. #endif
  106. if (ret <= 0)
  107. return;
  108. string path = (char*)base_module_dir;
  109. #if defined(__APPLE__)
  110. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  111. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  112. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  113. obs_add_module_path(config_bin, config_data);
  114. #elif ARCH_BITS == 64
  115. obs_add_module_path((path + "/bin/64bit").c_str(),
  116. (path + "/data").c_str());
  117. #else
  118. obs_add_module_path((path + "/bin/32bit").c_str(),
  119. (path + "/data").c_str());
  120. #endif
  121. }
  122. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  123. static int CountVideoSources()
  124. {
  125. int count = 0;
  126. auto countSources = [] (void *param, obs_source_t *source)
  127. {
  128. if (!source)
  129. return true;
  130. uint32_t flags = obs_source_get_output_flags(source);
  131. if ((flags & OBS_SOURCE_VIDEO) != 0)
  132. (*reinterpret_cast<int*>(param))++;
  133. return true;
  134. };
  135. obs_enum_sources(countSources, &count);
  136. return count;
  137. }
  138. void assignDockToggle(QDockWidget *dock, QAction *action)
  139. {
  140. auto handleWindowToggle = [action] (bool vis)
  141. {
  142. action->blockSignals(true);
  143. action->setChecked(vis);
  144. action->blockSignals(false);
  145. };
  146. auto handleMenuToggle = [dock] (bool check)
  147. {
  148. dock->blockSignals(true);
  149. dock->setVisible(check);
  150. dock->blockSignals(false);
  151. };
  152. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  153. handleWindowToggle);
  154. dock->connect(action, &QAction::toggled,
  155. handleMenuToggle);
  156. }
  157. extern void RegisterTwitchAuth();
  158. extern void RegisterMixerAuth();
  159. OBSBasic::OBSBasic(QWidget *parent)
  160. : OBSMainWindow (parent),
  161. ui (new Ui::OBSBasic)
  162. {
  163. setAttribute(Qt::WA_NativeWindow);
  164. #if TWITCH_ENABLED
  165. RegisterTwitchAuth();
  166. #endif
  167. #if MIXER_ENABLED
  168. RegisterMixerAuth();
  169. #endif
  170. setAcceptDrops(true);
  171. api = InitializeAPIInterface(this);
  172. ui->setupUi(this);
  173. ui->previewDisabledLabel->setVisible(false);
  174. startingDockLayout = saveState();
  175. statsDock = new QDockWidget();
  176. statsDock->setObjectName(QStringLiteral("statsDock"));
  177. statsDock->setFeatures(QDockWidget::AllDockWidgetFeatures);
  178. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  179. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  180. statsDock->setVisible(false);
  181. statsDock->setFloating(true);
  182. statsDock->resize(700, 200);
  183. copyActionsDynamicProperties();
  184. char styleSheetPath[512];
  185. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  186. "stylesheet.qss");
  187. if (ret > 0) {
  188. if (QFile::exists(styleSheetPath)) {
  189. QString path = QString("file:///") +
  190. QT_UTF8(styleSheetPath);
  191. App()->setStyleSheet(path);
  192. }
  193. }
  194. qRegisterMetaType<OBSScene> ("OBSScene");
  195. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  196. qRegisterMetaType<OBSSource> ("OBSSource");
  197. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  198. qRegisterMetaTypeStreamOperators<
  199. std::vector<std::shared_ptr<OBSSignal>>>(
  200. "std::vector<std::shared_ptr<OBSSignal>>");
  201. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  202. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  203. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  204. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  205. auto displayResize = [this]() {
  206. struct obs_video_info ovi;
  207. if (obs_get_video_info(&ovi))
  208. ResizePreview(ovi.base_width, ovi.base_height);
  209. };
  210. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  211. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  212. delete shortcutFilter;
  213. shortcutFilter = CreateShortcutFilter();
  214. installEventFilter(shortcutFilter);
  215. stringstream name;
  216. name << "OBS " << App()->GetVersionString();
  217. blog(LOG_INFO, "%s", name.str().c_str());
  218. blog(LOG_INFO, "---------------------------------");
  219. UpdateTitleBar();
  220. connect(ui->scenes->itemDelegate(),
  221. SIGNAL(closeEditor(QWidget*,
  222. QAbstractItemDelegate::EndEditHint)),
  223. this,
  224. SLOT(SceneNameEdited(QWidget*,
  225. QAbstractItemDelegate::EndEditHint)));
  226. cpuUsageInfo = os_cpu_usage_info_start();
  227. cpuUsageTimer = new QTimer(this);
  228. connect(cpuUsageTimer.data(), SIGNAL(timeout()),
  229. ui->statusbar, SLOT(UpdateCPUUsage()));
  230. cpuUsageTimer->start(3000);
  231. QAction *renameScene = new QAction(ui->scenesDock);
  232. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  233. connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
  234. ui->scenesDock->addAction(renameScene);
  235. QAction *renameSource = new QAction(ui->sourcesDock);
  236. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  237. connect(renameSource, SIGNAL(triggered()), this,
  238. SLOT(EditSceneItemName()));
  239. ui->sourcesDock->addAction(renameSource);
  240. #ifdef __APPLE__
  241. renameScene->setShortcut({Qt::Key_Return});
  242. renameSource->setShortcut({Qt::Key_Return});
  243. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  244. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  245. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  246. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  247. #else
  248. renameScene->setShortcut({Qt::Key_F2});
  249. renameSource->setShortcut({Qt::Key_F2});
  250. #endif
  251. auto addNudge = [this](const QKeySequence &seq, const char *s)
  252. {
  253. QAction *nudge = new QAction(ui->preview);
  254. nudge->setShortcut(seq);
  255. nudge->setShortcutContext(Qt::WidgetShortcut);
  256. ui->preview->addAction(nudge);
  257. connect(nudge, SIGNAL(triggered()), this, s);
  258. };
  259. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  260. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  261. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  262. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  263. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  264. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  265. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  266. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  267. assignDockToggle(ui->controlsDock, ui->toggleControls);
  268. assignDockToggle(statsDock, ui->toggleStats);
  269. //hide all docking panes
  270. ui->toggleScenes->setChecked(false);
  271. ui->toggleSources->setChecked(false);
  272. ui->toggleMixer->setChecked(false);
  273. ui->toggleTransitions->setChecked(false);
  274. ui->toggleControls->setChecked(false);
  275. ui->toggleStats->setChecked(false);
  276. QPoint curPos;
  277. //restore parent window geometry
  278. const char *geometry = config_get_string(App()->GlobalConfig(),
  279. "BasicWindow", "geometry");
  280. if (geometry != NULL) {
  281. QByteArray byteArray = QByteArray::fromBase64(
  282. QByteArray(geometry));
  283. restoreGeometry(byteArray);
  284. QRect windowGeometry = normalGeometry();
  285. if (!WindowPositionValid(windowGeometry)) {
  286. QRect rect = App()->desktop()->geometry();
  287. setGeometry(QStyle::alignedRect(
  288. Qt::LeftToRight,
  289. Qt::AlignCenter,
  290. size(), rect));
  291. }
  292. curPos = pos();
  293. } else {
  294. QRect desktopRect = QGuiApplication::primaryScreen()->geometry();
  295. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  296. curPos = QPoint(adjSize.width(), adjSize.height());
  297. }
  298. QPoint curSize(width(), height());
  299. QPoint statsDockSize(statsDock->width(), statsDock->height());
  300. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  301. QPoint newPos = curPos + statsDockPos;
  302. statsDock->move(newPos);
  303. }
  304. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  305. vector<OBSSource> &audioSources)
  306. {
  307. obs_source_t *source = obs_get_output_source(channel);
  308. if (!source)
  309. return;
  310. audioSources.push_back(source);
  311. obs_data_t *data = obs_save_source(source);
  312. obs_data_set_obj(parent, name, data);
  313. obs_data_release(data);
  314. obs_source_release(source);
  315. }
  316. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  317. obs_data_array_t *quickTransitionData, int transitionDuration,
  318. obs_data_array_t *transitions,
  319. OBSScene &scene, OBSSource &curProgramScene,
  320. obs_data_array_t *savedProjectorList)
  321. {
  322. obs_data_t *saveData = obs_data_create();
  323. vector<OBSSource> audioSources;
  324. audioSources.reserve(5);
  325. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  326. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  327. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  328. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  329. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  330. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  331. /* -------------------------------- */
  332. /* save non-group sources */
  333. auto FilterAudioSources = [&](obs_source_t *source)
  334. {
  335. if (obs_source_is_group(source))
  336. return false;
  337. return find(begin(audioSources), end(audioSources), source) ==
  338. end(audioSources);
  339. };
  340. using FilterAudioSources_t = decltype(FilterAudioSources);
  341. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  342. [](void *data, obs_source_t *source)
  343. {
  344. return (*static_cast<FilterAudioSources_t*>(data))(source);
  345. }, static_cast<void*>(&FilterAudioSources));
  346. /* -------------------------------- */
  347. /* save group sources separately */
  348. /* saving separately ensures they won't be loaded in older versions */
  349. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  350. [](void*, obs_source_t *source)
  351. {
  352. return obs_source_is_group(source);
  353. }, nullptr);
  354. /* -------------------------------- */
  355. obs_source_t *transition = obs_get_output_source(0);
  356. obs_source_t *currentScene = obs_scene_get_source(scene);
  357. const char *sceneName = obs_source_get_name(currentScene);
  358. const char *programName = obs_source_get_name(curProgramScene);
  359. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  360. "Basic", "SceneCollection");
  361. obs_data_set_string(saveData, "current_scene", sceneName);
  362. obs_data_set_string(saveData, "current_program_scene", programName);
  363. obs_data_set_array(saveData, "scene_order", sceneOrder);
  364. obs_data_set_string(saveData, "name", sceneCollection);
  365. obs_data_set_array(saveData, "sources", sourcesArray);
  366. obs_data_set_array(saveData, "groups", groupsArray);
  367. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  368. obs_data_set_array(saveData, "transitions", transitions);
  369. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  370. obs_data_array_release(sourcesArray);
  371. obs_data_array_release(groupsArray);
  372. obs_data_set_string(saveData, "current_transition",
  373. obs_source_get_name(transition));
  374. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  375. obs_source_release(transition);
  376. return saveData;
  377. }
  378. void OBSBasic::copyActionsDynamicProperties()
  379. {
  380. // Themes need the QAction dynamic properties
  381. for (QAction *x : ui->scenesToolbar->actions()) {
  382. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  383. for (QByteArray &y : x->dynamicPropertyNames()) {
  384. temp->setProperty(y, x->property(y));
  385. }
  386. }
  387. for (QAction *x : ui->sourcesToolbar->actions()) {
  388. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  389. for (QByteArray &y : x->dynamicPropertyNames()) {
  390. temp->setProperty(y, x->property(y));
  391. }
  392. }
  393. }
  394. void OBSBasic::UpdateVolumeControlsDecayRate()
  395. {
  396. double meterDecayRate = config_get_double(basicConfig, "Audio",
  397. "MeterDecayRate");
  398. for (size_t i = 0; i < volumes.size(); i++) {
  399. volumes[i]->SetMeterDecayRate(meterDecayRate);
  400. }
  401. }
  402. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  403. {
  404. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  405. "PeakMeterType");
  406. enum obs_peak_meter_type peakMeterType;
  407. switch (peakMeterTypeIdx) {
  408. case 0:
  409. peakMeterType = SAMPLE_PEAK_METER;
  410. break;
  411. case 1:
  412. peakMeterType = TRUE_PEAK_METER;
  413. break;
  414. default:
  415. peakMeterType = SAMPLE_PEAK_METER;
  416. break;
  417. }
  418. for (size_t i = 0; i < volumes.size(); i++) {
  419. volumes[i]->setPeakMeterType(peakMeterType);
  420. }
  421. }
  422. void OBSBasic::ClearVolumeControls()
  423. {
  424. for (VolControl *vol : volumes)
  425. delete vol;
  426. volumes.clear();
  427. }
  428. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  429. {
  430. obs_data_array_t *sceneOrder = obs_data_array_create();
  431. for (int i = 0; i < ui->scenes->count(); i++) {
  432. obs_data_t *data = obs_data_create();
  433. obs_data_set_string(data, "name",
  434. QT_TO_UTF8(ui->scenes->item(i)->text()));
  435. obs_data_array_push_back(sceneOrder, data);
  436. obs_data_release(data);
  437. }
  438. return sceneOrder;
  439. }
  440. obs_data_array_t *OBSBasic::SaveProjectors()
  441. {
  442. obs_data_array_t *savedProjectors = obs_data_array_create();
  443. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  444. if (!projector)
  445. return;
  446. obs_data_t *data = obs_data_create();
  447. ProjectorType type = projector->GetProjectorType();
  448. switch (type) {
  449. case ProjectorType::Scene:
  450. case ProjectorType::Source: {
  451. obs_source_t *source = projector->GetSource();
  452. const char *name = obs_source_get_name(source);
  453. obs_data_set_string(data, "name", name);
  454. break;
  455. }
  456. default:
  457. break;
  458. }
  459. obs_data_set_int(data, "monitor", projector->GetMonitor());
  460. obs_data_set_int(data, "type", static_cast<int>(type));
  461. obs_data_set_string(data, "geometry",
  462. projector->saveGeometry().toBase64()
  463. .constData());
  464. obs_data_array_push_back(savedProjectors, data);
  465. obs_data_release(data);
  466. };
  467. for (QPointer<QWidget> &proj : projectors)
  468. saveProjector(static_cast<OBSProjector *>(proj.data()));
  469. for (QPointer<QWidget> &proj : windowProjectors)
  470. saveProjector(static_cast<OBSProjector *>(proj.data()));
  471. return savedProjectors;
  472. }
  473. void OBSBasic::Save(const char *file)
  474. {
  475. OBSScene scene = GetCurrentScene();
  476. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  477. if (!curProgramScene)
  478. curProgramScene = obs_scene_get_source(scene);
  479. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  480. obs_data_array_t *transitions = SaveTransitions();
  481. obs_data_array_t *quickTrData = SaveQuickTransitions();
  482. obs_data_array_t *savedProjectorList = SaveProjectors();
  483. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  484. ui->transitionDuration->value(), transitions,
  485. scene, curProgramScene, savedProjectorList);
  486. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  487. obs_data_set_bool(saveData, "scaling_enabled",
  488. ui->preview->IsFixedScaling());
  489. obs_data_set_int(saveData, "scaling_level",
  490. ui->preview->GetScalingLevel());
  491. obs_data_set_double(saveData, "scaling_off_x",
  492. ui->preview->GetScrollX());
  493. obs_data_set_double(saveData, "scaling_off_y",
  494. ui->preview->GetScrollY());
  495. if (api) {
  496. obs_data_t *moduleObj = obs_data_create();
  497. api->on_save(moduleObj);
  498. obs_data_set_obj(saveData, "modules", moduleObj);
  499. obs_data_release(moduleObj);
  500. }
  501. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  502. blog(LOG_ERROR, "Could not save scene data to %s", file);
  503. obs_data_release(saveData);
  504. obs_data_array_release(sceneOrder);
  505. obs_data_array_release(quickTrData);
  506. obs_data_array_release(transitions);
  507. obs_data_array_release(savedProjectorList);
  508. }
  509. void OBSBasic::DeferSaveBegin()
  510. {
  511. os_atomic_inc_long(&disableSaving);
  512. }
  513. void OBSBasic::DeferSaveEnd()
  514. {
  515. long result = os_atomic_dec_long(&disableSaving);
  516. if (result == 0) {
  517. SaveProject();
  518. }
  519. }
  520. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  521. {
  522. obs_data_t *data = obs_data_get_obj(parent, name);
  523. if (!data)
  524. return;
  525. obs_source_t *source = obs_load_source(data);
  526. if (source) {
  527. obs_set_output_source(channel, source);
  528. obs_source_release(source);
  529. }
  530. obs_data_release(data);
  531. }
  532. static inline bool HasAudioDevices(const char *source_id)
  533. {
  534. const char *output_id = source_id;
  535. obs_properties_t *props = obs_get_source_properties(output_id);
  536. size_t count = 0;
  537. if (!props)
  538. return false;
  539. obs_property_t *devices = obs_properties_get(props, "device_id");
  540. if (devices)
  541. count = obs_property_list_item_count(devices);
  542. obs_properties_destroy(props);
  543. return count != 0;
  544. }
  545. void OBSBasic::CreateFirstRunSources()
  546. {
  547. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  548. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  549. if (hasDesktopAudio)
  550. ResetAudioDevice(App()->OutputAudioSource(), "default",
  551. Str("Basic.DesktopDevice1"), 1);
  552. if (hasInputAudio)
  553. ResetAudioDevice(App()->InputAudioSource(), "default",
  554. Str("Basic.AuxDevice1"), 3);
  555. }
  556. void OBSBasic::CreateDefaultScene(bool firstStart)
  557. {
  558. disableSaving++;
  559. ClearSceneData();
  560. InitDefaultTransitions();
  561. CreateDefaultQuickTransitions();
  562. ui->transitionDuration->setValue(300);
  563. SetTransition(fadeTransition);
  564. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  565. if (firstStart)
  566. CreateFirstRunSources();
  567. SetCurrentScene(scene, true);
  568. obs_scene_release(scene);
  569. disableSaving--;
  570. }
  571. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  572. {
  573. for (int i = 0; i < lw->count(); i++) {
  574. QListWidgetItem *item = lw->item(i);
  575. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  576. if (newIndex != i) {
  577. item = lw->takeItem(i);
  578. lw->insertItem(newIndex, item);
  579. }
  580. break;
  581. }
  582. }
  583. }
  584. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  585. {
  586. size_t num = obs_data_array_count(array);
  587. for (size_t i = 0; i < num; i++) {
  588. obs_data_t *data = obs_data_array_item(array, i);
  589. const char *name = obs_data_get_string(data, "name");
  590. ReorderItemByName(ui->scenes, name, (int)i);
  591. obs_data_release(data);
  592. }
  593. }
  594. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  595. {
  596. for (SavedProjectorInfo *info : savedProjectorsArray) {
  597. delete info;
  598. }
  599. savedProjectorsArray.clear();
  600. size_t num = obs_data_array_count(array);
  601. for (size_t i = 0; i < num; i++) {
  602. obs_data_t *data = obs_data_array_item(array, i);
  603. SavedProjectorInfo *info = new SavedProjectorInfo();
  604. info->monitor = obs_data_get_int(data, "monitor");
  605. info->type = static_cast<ProjectorType>(obs_data_get_int(data,
  606. "type"));
  607. info->geometry = std::string(
  608. obs_data_get_string(data, "geometry"));
  609. info->name = std::string(obs_data_get_string(data, "name"));
  610. savedProjectorsArray.emplace_back(info);
  611. obs_data_release(data);
  612. }
  613. }
  614. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  615. {
  616. const char *name = obs_source_get_name(filter);
  617. const char *id = obs_source_get_id(filter);
  618. int val = (int)(intptr_t)v_val;
  619. string indent;
  620. for (int i = 0; i < val; i++)
  621. indent += " ";
  622. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  623. }
  624. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  625. {
  626. obs_source_t *source = obs_sceneitem_get_source(item);
  627. const char *name = obs_source_get_name(source);
  628. const char *id = obs_source_get_id(source);
  629. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  630. obs_monitoring_type monitoring_type =
  631. obs_source_get_monitoring_type(source);
  632. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  633. const char *type =
  634. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  635. ? "monitor only"
  636. : "monitor and output";
  637. blog(LOG_INFO, " - monitoring: %s", type);
  638. }
  639. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  640. return true;
  641. }
  642. void OBSBasic::LogScenes()
  643. {
  644. blog(LOG_INFO, "------------------------------------------------");
  645. blog(LOG_INFO, "Loaded scenes:");
  646. for (int i = 0; i < ui->scenes->count(); i++) {
  647. QListWidgetItem *item = ui->scenes->item(i);
  648. OBSScene scene = GetOBSRef<OBSScene>(item);
  649. obs_source_t *source = obs_scene_get_source(scene);
  650. const char *name = obs_source_get_name(source);
  651. blog(LOG_INFO, "- scene '%s':", name);
  652. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  653. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  654. }
  655. blog(LOG_INFO, "------------------------------------------------");
  656. }
  657. void OBSBasic::Load(const char *file)
  658. {
  659. disableSaving++;
  660. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  661. if (!data) {
  662. disableSaving--;
  663. blog(LOG_INFO, "No scene file found, creating default scene");
  664. CreateDefaultScene(true);
  665. SaveProject();
  666. return;
  667. }
  668. ClearSceneData();
  669. InitDefaultTransitions();
  670. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  671. if (api)
  672. api->on_preload(modulesObj);
  673. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  674. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  675. obs_data_array_t *groups = obs_data_get_array(data, "groups");
  676. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  677. const char *sceneName = obs_data_get_string(data,
  678. "current_scene");
  679. const char *programSceneName = obs_data_get_string(data,
  680. "current_program_scene");
  681. const char *transitionName = obs_data_get_string(data,
  682. "current_transition");
  683. if (!opt_starting_scene.empty()) {
  684. programSceneName = opt_starting_scene.c_str();
  685. if (!IsPreviewProgramMode())
  686. sceneName = opt_starting_scene.c_str();
  687. }
  688. int newDuration = obs_data_get_int(data, "transition_duration");
  689. if (!newDuration)
  690. newDuration = 300;
  691. if (!transitionName)
  692. transitionName = obs_source_get_name(fadeTransition);
  693. const char *curSceneCollection = config_get_string(
  694. App()->GlobalConfig(), "Basic", "SceneCollection");
  695. obs_data_set_default_string(data, "name", curSceneCollection);
  696. const char *name = obs_data_get_string(data, "name");
  697. obs_source_t *curScene;
  698. obs_source_t *curProgramScene;
  699. obs_source_t *curTransition;
  700. if (!name || !*name)
  701. name = curSceneCollection;
  702. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  703. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  704. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  705. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  706. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  707. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  708. if (!sources) {
  709. sources = groups;
  710. groups = nullptr;
  711. } else {
  712. obs_data_array_push_back_array(sources, groups);
  713. }
  714. obs_load_sources(sources, nullptr, nullptr);
  715. if (transitions)
  716. LoadTransitions(transitions);
  717. if (sceneOrder)
  718. LoadSceneListOrder(sceneOrder);
  719. obs_data_array_release(transitions);
  720. curTransition = FindTransition(transitionName);
  721. if (!curTransition)
  722. curTransition = fadeTransition;
  723. ui->transitionDuration->setValue(newDuration);
  724. SetTransition(curTransition);
  725. retryScene:
  726. curScene = obs_get_source_by_name(sceneName);
  727. curProgramScene = obs_get_source_by_name(programSceneName);
  728. /* if the starting scene command line parameter is bad at all,
  729. * fall back to original settings */
  730. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  731. sceneName = obs_data_get_string(data, "current_scene");
  732. programSceneName = obs_data_get_string(data,
  733. "current_program_scene");
  734. obs_source_release(curScene);
  735. obs_source_release(curProgramScene);
  736. opt_starting_scene.clear();
  737. goto retryScene;
  738. }
  739. if (!curProgramScene) {
  740. curProgramScene = curScene;
  741. obs_source_addref(curScene);
  742. }
  743. SetCurrentScene(curScene, true);
  744. if (IsPreviewProgramMode())
  745. TransitionToScene(curProgramScene, true);
  746. obs_source_release(curScene);
  747. obs_source_release(curProgramScene);
  748. obs_data_array_release(sources);
  749. obs_data_array_release(groups);
  750. obs_data_array_release(sceneOrder);
  751. /* ------------------- */
  752. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  753. "SaveProjectors");
  754. if (projectorSave) {
  755. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  756. "saved_projectors");
  757. if (savedProjectors) {
  758. LoadSavedProjectors(savedProjectors);
  759. OpenSavedProjectors();
  760. activateWindow();
  761. }
  762. obs_data_array_release(savedProjectors);
  763. }
  764. /* ------------------- */
  765. std::string file_base = strrchr(file, '/') + 1;
  766. file_base.erase(file_base.size() - 5, 5);
  767. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  768. name);
  769. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  770. file_base.c_str());
  771. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  772. "quick_transitions");
  773. LoadQuickTransitions(quickTransitionData);
  774. obs_data_array_release(quickTransitionData);
  775. RefreshQuickTransitions();
  776. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  777. ui->preview->SetLocked(previewLocked);
  778. ui->actionLockPreview->setChecked(previewLocked);
  779. /* ---------------------- */
  780. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  781. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  782. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  783. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  784. if (fixedScaling) {
  785. ui->preview->SetScalingLevel(scalingLevel);
  786. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  787. }
  788. ui->preview->SetFixedScaling(fixedScaling);
  789. /* ---------------------- */
  790. if (api)
  791. api->on_load(modulesObj);
  792. obs_data_release(modulesObj);
  793. obs_data_release(data);
  794. if (!opt_starting_scene.empty())
  795. opt_starting_scene.clear();
  796. if (opt_start_streaming) {
  797. blog(LOG_INFO, "Starting stream due to command line parameter");
  798. QMetaObject::invokeMethod(this, "StartStreaming",
  799. Qt::QueuedConnection);
  800. opt_start_streaming = false;
  801. }
  802. if (opt_start_recording) {
  803. blog(LOG_INFO, "Starting recording due to command line parameter");
  804. QMetaObject::invokeMethod(this, "StartRecording",
  805. Qt::QueuedConnection);
  806. opt_start_recording = false;
  807. }
  808. if (opt_start_replaybuffer) {
  809. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  810. Qt::QueuedConnection);
  811. opt_start_replaybuffer = false;
  812. }
  813. LogScenes();
  814. disableSaving--;
  815. if (api) {
  816. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  817. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  818. }
  819. }
  820. #define SERVICE_PATH "service.json"
  821. void OBSBasic::SaveService()
  822. {
  823. if (!service)
  824. return;
  825. char serviceJsonPath[512];
  826. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  827. SERVICE_PATH);
  828. if (ret <= 0)
  829. return;
  830. obs_data_t *data = obs_data_create();
  831. obs_data_t *settings = obs_service_get_settings(service);
  832. obs_data_set_string(data, "type", obs_service_get_type(service));
  833. obs_data_set_obj(data, "settings", settings);
  834. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  835. blog(LOG_WARNING, "Failed to save service");
  836. obs_data_release(settings);
  837. obs_data_release(data);
  838. }
  839. bool OBSBasic::LoadService()
  840. {
  841. const char *type;
  842. char serviceJsonPath[512];
  843. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  844. SERVICE_PATH);
  845. if (ret <= 0)
  846. return false;
  847. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  848. "bak");
  849. obs_data_set_default_string(data, "type", "rtmp_common");
  850. type = obs_data_get_string(data, "type");
  851. obs_data_t *settings = obs_data_get_obj(data, "settings");
  852. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  853. service = obs_service_create(type, "default_service", settings,
  854. hotkey_data);
  855. obs_service_release(service);
  856. obs_data_release(hotkey_data);
  857. obs_data_release(settings);
  858. obs_data_release(data);
  859. return !!service;
  860. }
  861. bool OBSBasic::InitService()
  862. {
  863. ProfileScope("OBSBasic::InitService");
  864. if (LoadService())
  865. return true;
  866. service = obs_service_create("rtmp_common", "default_service", nullptr,
  867. nullptr);
  868. if (!service)
  869. return false;
  870. obs_service_release(service);
  871. return true;
  872. }
  873. static const double scaled_vals[] =
  874. {
  875. 1.0,
  876. 1.25,
  877. (1.0/0.75),
  878. 1.5,
  879. (1.0/0.6),
  880. 1.75,
  881. 2.0,
  882. 2.25,
  883. 2.5,
  884. 2.75,
  885. 3.0,
  886. 0.0
  887. };
  888. extern void CheckExistingCookieId();
  889. bool OBSBasic::InitBasicConfigDefaults()
  890. {
  891. QList<QScreen*> screens = QGuiApplication::screens();
  892. if (!screens.size()) {
  893. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  894. "technically shouldn't be possible.");
  895. return false;
  896. }
  897. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  898. uint32_t cx = primaryScreen->size().width();
  899. uint32_t cy = primaryScreen->size().height();
  900. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  901. "General", "Pre19Defaults");
  902. /* use 1920x1080 for new default base res if main monitor is above
  903. * 1920x1080, but don't apply for people from older builds -- only to
  904. * new users */
  905. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  906. cx = 1920;
  907. cy = 1080;
  908. }
  909. bool changed = false;
  910. /* ----------------------------------------------------- */
  911. /* move over old FFmpeg track settings */
  912. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  913. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  914. int track = (int)config_get_int(basicConfig, "AdvOut",
  915. "FFAudioTrack");
  916. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  917. 1LL << (track - 1));
  918. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  919. changed = true;
  920. }
  921. /* ----------------------------------------------------- */
  922. /* move over mixer values in advanced if older config */
  923. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  924. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  925. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  926. "RecTrackIndex");
  927. track = 1ULL << (track - 1);
  928. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  929. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  930. changed = true;
  931. }
  932. /* ----------------------------------------------------- */
  933. if (changed)
  934. config_save_safe(basicConfig, "tmp", nullptr);
  935. /* ----------------------------------------------------- */
  936. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  937. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  938. GetDefaultVideoSavePath().c_str());
  939. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  940. "flv");
  941. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  942. 2500);
  943. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  944. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  945. false);
  946. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  947. true);
  948. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  949. "veryfast");
  950. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  951. "Stream");
  952. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  953. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  954. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  955. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  956. "Replay");
  957. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  958. true);
  959. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  960. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  961. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  962. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  963. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  964. GetDefaultVideoSavePath().c_str());
  965. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  966. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  967. false);
  968. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  969. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  970. "none");
  971. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  972. true);
  973. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  974. GetDefaultVideoSavePath().c_str());
  975. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  976. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  977. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  978. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  979. false);
  980. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  981. false);
  982. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  983. config_set_default_uint (basicConfig, "AdvOut", "FFAudioMixes", 1);
  984. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  985. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  986. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  987. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  988. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  989. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  990. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  991. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  992. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  993. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  994. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  995. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  996. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  997. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  998. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  999. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1000. config_save_safe(basicConfig, "tmp", nullptr);
  1001. }
  1002. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1003. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1004. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  1005. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  1006. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  1007. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  1008. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  1009. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  1010. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1011. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  1012. false);
  1013. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  1014. false);
  1015. int i = 0;
  1016. uint32_t scale_cx = cx;
  1017. uint32_t scale_cy = cy;
  1018. /* use a default scaled resolution that has a pixel count no higher
  1019. * than 1280x720 */
  1020. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1021. double scale = scaled_vals[i++];
  1022. scale_cx = uint32_t(double(cx) / scale);
  1023. scale_cy = uint32_t(double(cy) / scale);
  1024. }
  1025. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  1026. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  1027. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1028. * changing */
  1029. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1030. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1031. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1032. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1033. config_save_safe(basicConfig, "tmp", nullptr);
  1034. }
  1035. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  1036. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1037. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  1038. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  1039. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  1040. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1041. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1042. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  1043. config_set_default_string(basicConfig, "Video", "ColorRange",
  1044. "Partial");
  1045. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1046. "default");
  1047. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  1048. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1049. ".Default"));
  1050. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  1051. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1052. "Stereo");
  1053. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1054. VOLUME_METER_DECAY_FAST);
  1055. config_set_default_uint (basicConfig, "Audio", "PeakMeterType", 0);
  1056. CheckExistingCookieId();
  1057. return true;
  1058. }
  1059. extern bool EncoderAvailable(const char *encoder);
  1060. void OBSBasic::InitBasicConfigDefaults2()
  1061. {
  1062. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(),
  1063. "General", "Pre23Defaults");
  1064. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1065. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1066. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1067. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1068. useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264);
  1069. }
  1070. bool OBSBasic::InitBasicConfig()
  1071. {
  1072. ProfileScope("OBSBasic::InitBasicConfig");
  1073. char configPath[512];
  1074. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1075. if (ret <= 0) {
  1076. OBSErrorBox(nullptr, "Failed to get profile path");
  1077. return false;
  1078. }
  1079. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1080. OBSErrorBox(nullptr, "Failed to create profile path");
  1081. return false;
  1082. }
  1083. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1084. if (ret <= 0) {
  1085. OBSErrorBox(nullptr, "Failed to get base.ini path");
  1086. return false;
  1087. }
  1088. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1089. if (code != CONFIG_SUCCESS) {
  1090. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1091. return false;
  1092. }
  1093. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1094. const char *curName = config_get_string(App()->GlobalConfig(),
  1095. "Basic", "Profile");
  1096. config_set_string(basicConfig, "General", "Name", curName);
  1097. basicConfig.SaveSafe("tmp");
  1098. }
  1099. return InitBasicConfigDefaults();
  1100. }
  1101. void OBSBasic::InitOBSCallbacks()
  1102. {
  1103. ProfileScope("OBSBasic::InitOBSCallbacks");
  1104. signalHandlers.reserve(signalHandlers.size() + 6);
  1105. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1106. OBSBasic::SourceCreated, this);
  1107. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1108. OBSBasic::SourceRemoved, this);
  1109. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1110. OBSBasic::SourceActivated, this);
  1111. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  1112. OBSBasic::SourceDeactivated, this);
  1113. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1114. OBSBasic::SourceRenamed, this);
  1115. }
  1116. void OBSBasic::InitPrimitives()
  1117. {
  1118. ProfileScope("OBSBasic::InitPrimitives");
  1119. obs_enter_graphics();
  1120. gs_render_start(true);
  1121. gs_vertex2f(0.0f, 0.0f);
  1122. gs_vertex2f(0.0f, 1.0f);
  1123. gs_vertex2f(1.0f, 1.0f);
  1124. gs_vertex2f(1.0f, 0.0f);
  1125. gs_vertex2f(0.0f, 0.0f);
  1126. box = gs_render_save();
  1127. gs_render_start(true);
  1128. gs_vertex2f(0.0f, 0.0f);
  1129. gs_vertex2f(0.0f, 1.0f);
  1130. boxLeft = gs_render_save();
  1131. gs_render_start(true);
  1132. gs_vertex2f(0.0f, 0.0f);
  1133. gs_vertex2f(1.0f, 0.0f);
  1134. boxTop = gs_render_save();
  1135. gs_render_start(true);
  1136. gs_vertex2f(1.0f, 0.0f);
  1137. gs_vertex2f(1.0f, 1.0f);
  1138. boxRight = gs_render_save();
  1139. gs_render_start(true);
  1140. gs_vertex2f(0.0f, 1.0f);
  1141. gs_vertex2f(1.0f, 1.0f);
  1142. boxBottom = gs_render_save();
  1143. gs_render_start(true);
  1144. for (int i = 0; i <= 360; i += (360/20)) {
  1145. float pos = RAD(float(i));
  1146. gs_vertex2f(cosf(pos), sinf(pos));
  1147. }
  1148. circle = gs_render_save();
  1149. obs_leave_graphics();
  1150. }
  1151. void OBSBasic::ReplayBufferClicked()
  1152. {
  1153. if (outputHandler->ReplayBufferActive())
  1154. StopReplayBuffer();
  1155. else
  1156. StartReplayBuffer();
  1157. };
  1158. void OBSBasic::ResetOutputs()
  1159. {
  1160. ProfileScope("OBSBasic::ResetOutputs");
  1161. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1162. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1163. if (!outputHandler || !outputHandler->Active()) {
  1164. outputHandler.reset();
  1165. outputHandler.reset(advOut ?
  1166. CreateAdvancedOutputHandler(this) :
  1167. CreateSimpleOutputHandler(this));
  1168. delete replayBufferButton;
  1169. if (outputHandler->replayBuffer) {
  1170. replayBufferButton = new QPushButton(
  1171. QTStr("Basic.Main.StartReplayBuffer"),
  1172. this);
  1173. replayBufferButton->setCheckable(true);
  1174. connect(replayBufferButton.data(),
  1175. &QPushButton::clicked,
  1176. this,
  1177. &OBSBasic::ReplayBufferClicked);
  1178. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1179. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1180. }
  1181. if (sysTrayReplayBuffer)
  1182. sysTrayReplayBuffer->setEnabled(
  1183. !!outputHandler->replayBuffer);
  1184. } else {
  1185. outputHandler->Update();
  1186. }
  1187. }
  1188. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1189. const char *slot);
  1190. #define STARTUP_SEPARATOR \
  1191. "==== Startup complete ==============================================="
  1192. #define SHUTDOWN_SEPARATOR \
  1193. "==== Shutting down =================================================="
  1194. #define UNSUPPORTED_ERROR \
  1195. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1196. "not found. Your GPU may not be supported."
  1197. #define UNKNOWN_ERROR \
  1198. "Failed to initialize video. Your GPU may not be supported, " \
  1199. "or your graphics drivers may need to be updated."
  1200. void OBSBasic::OBSInit()
  1201. {
  1202. ProfileScope("OBSBasic::OBSInit");
  1203. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1204. "Basic", "SceneCollectionFile");
  1205. char savePath[512];
  1206. char fileName[512];
  1207. int ret;
  1208. if (!sceneCollection)
  1209. throw "Failed to get scene collection name";
  1210. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1211. sceneCollection);
  1212. if (ret <= 0)
  1213. throw "Failed to create scene collection file name";
  1214. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1215. if (ret <= 0)
  1216. throw "Failed to get scene collection json file path";
  1217. if (!InitBasicConfig())
  1218. throw "Failed to load basic.ini";
  1219. if (!ResetAudio())
  1220. throw "Failed to initialize audio";
  1221. ret = ResetVideo();
  1222. switch (ret) {
  1223. case OBS_VIDEO_MODULE_NOT_FOUND:
  1224. throw "Failed to initialize video: Graphics module not found";
  1225. case OBS_VIDEO_NOT_SUPPORTED:
  1226. throw UNSUPPORTED_ERROR;
  1227. case OBS_VIDEO_INVALID_PARAM:
  1228. throw "Failed to initialize video: Invalid parameters";
  1229. default:
  1230. if (ret != OBS_VIDEO_SUCCESS)
  1231. throw UNKNOWN_ERROR;
  1232. }
  1233. /* load audio monitoring */
  1234. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1235. const char *device_name = config_get_string(basicConfig, "Audio",
  1236. "MonitoringDeviceName");
  1237. const char *device_id = config_get_string(basicConfig, "Audio",
  1238. "MonitoringDeviceId");
  1239. obs_set_audio_monitoring_device(device_name, device_id);
  1240. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1241. device_name, device_id);
  1242. #endif
  1243. InitOBSCallbacks();
  1244. InitHotkeys();
  1245. AddExtraModulePaths();
  1246. blog(LOG_INFO, "---------------------------------");
  1247. obs_load_all_modules();
  1248. blog(LOG_INFO, "---------------------------------");
  1249. obs_log_loaded_modules();
  1250. blog(LOG_INFO, "---------------------------------");
  1251. obs_post_load_modules();
  1252. #ifdef BROWSER_AVAILABLE
  1253. cef = obs_browser_init_panel();
  1254. #endif
  1255. InitBasicConfigDefaults2();
  1256. CheckForSimpleModeX264Fallback();
  1257. blog(LOG_INFO, STARTUP_SEPARATOR);
  1258. ResetOutputs();
  1259. CreateHotkeys();
  1260. if (!InitService())
  1261. throw "Failed to initialize service";
  1262. InitPrimitives();
  1263. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1264. "BasicWindow", "SceneDuplicationMode");
  1265. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1266. "BasicWindow", "SwapScenesMode");
  1267. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1268. "BasicWindow", "EditPropertiesMode");
  1269. if (!opt_studio_mode) {
  1270. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1271. "BasicWindow", "PreviewProgramMode"));
  1272. } else {
  1273. SetPreviewProgramMode(true);
  1274. opt_studio_mode = false;
  1275. }
  1276. #define SET_VISIBILITY(name, control) \
  1277. do { \
  1278. if (config_has_user_value(App()->GlobalConfig(), \
  1279. "BasicWindow", name)) { \
  1280. bool visible = config_get_bool(App()->GlobalConfig(), \
  1281. "BasicWindow", name); \
  1282. ui->control->setChecked(visible); \
  1283. } \
  1284. } while (false)
  1285. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1286. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1287. #undef SET_VISIBILITY
  1288. #ifndef __APPLE__
  1289. {
  1290. ProfileScope("OBSBasic::Load");
  1291. disableSaving--;
  1292. Load(savePath);
  1293. disableSaving++;
  1294. }
  1295. #endif
  1296. TimedCheckForUpdates();
  1297. loaded = true;
  1298. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1299. "BasicWindow", "PreviewEnabled");
  1300. if (!previewEnabled && !IsPreviewProgramMode())
  1301. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1302. Qt::QueuedConnection,
  1303. Q_ARG(bool, previewEnabled));
  1304. #ifdef _WIN32
  1305. uint32_t winVer = GetWindowsVersion();
  1306. if (winVer > 0 && winVer < 0x602) {
  1307. bool disableAero = config_get_bool(basicConfig, "Video",
  1308. "DisableAero");
  1309. SetAeroEnabled(!disableAero);
  1310. }
  1311. #endif
  1312. #ifndef __APPLE__
  1313. RefreshSceneCollections();
  1314. #endif
  1315. RefreshProfiles();
  1316. disableSaving--;
  1317. auto addDisplay = [this] (OBSQTDisplay *window)
  1318. {
  1319. obs_display_add_draw_callback(window->GetDisplay(),
  1320. OBSBasic::RenderMain, this);
  1321. struct obs_video_info ovi;
  1322. if (obs_get_video_info(&ovi))
  1323. ResizePreview(ovi.base_width, ovi.base_height);
  1324. };
  1325. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1326. #ifdef _WIN32
  1327. SetWin32DropStyle(this);
  1328. show();
  1329. #endif
  1330. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1331. "AlwaysOnTop");
  1332. if (alwaysOnTop || opt_always_on_top) {
  1333. SetAlwaysOnTop(this, true);
  1334. ui->actionAlwaysOnTop->setChecked(true);
  1335. }
  1336. #ifndef _WIN32
  1337. show();
  1338. #endif
  1339. /* setup stats dock */
  1340. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1341. statsDock->setWidget(statsDlg);
  1342. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1343. "BasicWindow", "DockState");
  1344. if (!dockStateStr) {
  1345. on_resetUI_triggered();
  1346. } else {
  1347. QByteArray dockState =
  1348. QByteArray::fromBase64(QByteArray(dockStateStr));
  1349. if (!restoreState(dockState))
  1350. on_resetUI_triggered();
  1351. }
  1352. bool pre23Defaults = config_get_bool(App()->GlobalConfig(),
  1353. "General", "Pre23Defaults");
  1354. if (pre23Defaults) {
  1355. bool resetDockLock23 = config_get_bool(App()->GlobalConfig(),
  1356. "General", "ResetDockLock23");
  1357. if (!resetDockLock23) {
  1358. config_set_bool(App()->GlobalConfig(),
  1359. "General", "ResetDockLock23", true);
  1360. config_remove_value(App()->GlobalConfig(),
  1361. "BasicWindow", "DocksLocked");
  1362. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1363. }
  1364. }
  1365. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1366. "BasicWindow", "DocksLocked");
  1367. on_lockUI_toggled(docksLocked);
  1368. ui->lockUI->blockSignals(true);
  1369. ui->lockUI->setChecked(docksLocked);
  1370. ui->lockUI->blockSignals(false);
  1371. #ifndef __APPLE__
  1372. SystemTray(true);
  1373. #endif
  1374. if (windowState().testFlag(Qt::WindowFullScreen))
  1375. fullscreenInterface = true;
  1376. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1377. "General", "LastVersion");
  1378. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1379. "FirstRun");
  1380. if (!first_run) {
  1381. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1382. true);
  1383. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1384. }
  1385. if (!first_run && !has_last_version && !Active()) {
  1386. QString msg;
  1387. msg = QTStr("Basic.FirstStartup.RunWizard");
  1388. QMessageBox::StandardButton button =
  1389. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1390. msg);
  1391. if (button == QMessageBox::Yes) {
  1392. on_autoConfigure_triggered();
  1393. } else {
  1394. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1395. OBSMessageBox::information(this,
  1396. QTStr("Basic.AutoConfig"), msg);
  1397. }
  1398. }
  1399. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1400. "VerticalVolControl"));
  1401. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1402. on_stats_triggered();
  1403. OBSBasicStats::InitializeValues();
  1404. /* ----------------------- */
  1405. /* Add multiview menu */
  1406. ui->viewMenu->addSeparator();
  1407. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1408. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1409. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1410. SLOT(OpenMultiviewProjector()));
  1411. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1412. &OBSBasic::UpdateMultiviewProjectorMenu);
  1413. ui->viewMenu->addAction(QTStr("MultiviewWindowed"),
  1414. this, SLOT(OpenMultiviewWindow()));
  1415. #if !defined(_WIN32) && !defined(__APPLE__)
  1416. delete ui->actionShowCrashLogs;
  1417. delete ui->actionUploadLastCrashLog;
  1418. delete ui->menuCrashLogs;
  1419. delete ui->actionCheckForUpdates;
  1420. ui->actionShowCrashLogs = nullptr;
  1421. ui->actionUploadLastCrashLog = nullptr;
  1422. ui->menuCrashLogs = nullptr;
  1423. ui->actionCheckForUpdates = nullptr;
  1424. #endif
  1425. #ifdef __APPLE__
  1426. /* This is an incredibly unpleasant hack for macOS to isolate CEF
  1427. * initialization until after all tasks related to Qt startup and main
  1428. * window initialization have completed. There is a macOS-specific bug
  1429. * within either CEF and/or Qt that can cause a crash if both Qt and
  1430. * CEF are loading at the same time.
  1431. *
  1432. * CEF will typically load fine after about two iterations from this
  1433. * point, and all Qt tasks are typically fully completed after about
  1434. * four or five iterations, but to be "ultra" safe, an arbitrarily
  1435. * large number such as 10 is used. This hack is extremely unpleasant,
  1436. * but is worth doing instead of being forced to isolate the entire
  1437. * browser plugin in to a separate process as before.
  1438. *
  1439. * Again, this hack is specific to macOS only. Fortunately, on other
  1440. * operating systems, such issues do not occur. */
  1441. QMetaObject::invokeMethod(this, "DeferredLoad",
  1442. Qt::QueuedConnection,
  1443. Q_ARG(QString, QT_UTF8(savePath)),
  1444. Q_ARG(int, 10));
  1445. #else
  1446. OnFirstLoad();
  1447. #endif
  1448. }
  1449. void OBSBasic::OnFirstLoad()
  1450. {
  1451. if (api)
  1452. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1453. #ifdef BROWSER_AVAILABLE
  1454. /* Attempt to load init screen if available */
  1455. if (cef) {
  1456. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1457. if (wnit) {
  1458. connect(wnit, &WhatsNewInfoThread::Result,
  1459. this, &OBSBasic::ReceivedIntroJson);
  1460. }
  1461. if (wnit) {
  1462. introCheckThread.reset(wnit);
  1463. introCheckThread->start();
  1464. }
  1465. }
  1466. #endif
  1467. Auth::Load();
  1468. }
  1469. void OBSBasic::DeferredLoad(const QString &file, int requeueCount)
  1470. {
  1471. if (--requeueCount > 0) {
  1472. QMetaObject::invokeMethod(this, "DeferredLoad",
  1473. Qt::QueuedConnection,
  1474. Q_ARG(QString, file),
  1475. Q_ARG(int, requeueCount));
  1476. return;
  1477. }
  1478. Load(QT_TO_UTF8(file));
  1479. RefreshSceneCollections();
  1480. OnFirstLoad();
  1481. /* Minimizng to tray on initial startup does not work on mac
  1482. * unless it is done in the deferred load */
  1483. SystemTray(true);
  1484. }
  1485. /* shows a "what's new" page on startup of new versions using CEF */
  1486. void OBSBasic::ReceivedIntroJson(const QString &text)
  1487. {
  1488. #ifdef BROWSER_AVAILABLE
  1489. #ifdef _WIN32
  1490. std::string err;
  1491. Json json = Json::parse(QT_TO_UTF8(text), err);
  1492. if (!err.empty())
  1493. return;
  1494. std::string info_url;
  1495. int info_increment = -1;
  1496. /* check to see if there's an info page for this version */
  1497. const Json::array &items = json.array_items();
  1498. for (const Json &item : items) {
  1499. const std::string &version = item["version"].string_value();
  1500. const std::string &url = item["url"].string_value();
  1501. int increment = item["increment"].int_value();
  1502. int rc = item["RC"].int_value();
  1503. int major = 0;
  1504. int minor = 0;
  1505. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1506. #if OBS_RELEASE_CANDIDATE > 0
  1507. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1508. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1509. rc == OBS_RELEASE_CANDIDATE) {
  1510. #else
  1511. if (major == LIBOBS_API_MAJOR_VER &&
  1512. minor == LIBOBS_API_MINOR_VER &&
  1513. rc == 0) {
  1514. #endif
  1515. info_url = url;
  1516. info_increment = increment;
  1517. }
  1518. }
  1519. /* this version was not found, or no info for this version */
  1520. if (info_increment == -1) {
  1521. return;
  1522. }
  1523. #if OBS_RELEASE_CANDIDATE > 0
  1524. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1525. "LastRCVersion");
  1526. #else
  1527. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1528. "LastVersion");
  1529. #endif
  1530. int current_version_increment = -1;
  1531. #if OBS_RELEASE_CANDIDATE > 0
  1532. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1533. #else
  1534. if (lastVersion < LIBOBS_API_VER) {
  1535. #endif
  1536. config_set_int(App()->GlobalConfig(), "General",
  1537. "InfoIncrement", -1);
  1538. } else {
  1539. current_version_increment = config_get_int(
  1540. App()->GlobalConfig(), "General",
  1541. "InfoIncrement");
  1542. }
  1543. if (info_increment <= current_version_increment) {
  1544. return;
  1545. }
  1546. config_set_int(App()->GlobalConfig(), "General",
  1547. "InfoIncrement", info_increment);
  1548. QDialog *dlg = new QDialog(this);
  1549. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1550. dlg->setWindowTitle("What's New");
  1551. dlg->resize(700, 600);
  1552. Qt::WindowFlags flags = dlg->windowFlags();
  1553. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1554. dlg->setWindowFlags(flags & (~helpFlag));
  1555. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1556. if (!cefWidget) {
  1557. return;
  1558. }
  1559. connect(cefWidget, SIGNAL(titleChanged(const QString &)),
  1560. dlg, SLOT(setWindowTitle(const QString &)));
  1561. QPushButton *close = new QPushButton(QTStr("Close"));
  1562. connect(close, &QAbstractButton::clicked,
  1563. dlg, &QDialog::accept);
  1564. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1565. bottomLayout->addStretch();
  1566. bottomLayout->addWidget(close);
  1567. bottomLayout->addStretch();
  1568. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1569. topLayout->addWidget(cefWidget);
  1570. topLayout->addLayout(bottomLayout);
  1571. dlg->show();
  1572. #else
  1573. UNUSED_PARAMETER(text);
  1574. #endif
  1575. #else
  1576. UNUSED_PARAMETER(text);
  1577. #endif
  1578. }
  1579. void OBSBasic::UpdateMultiviewProjectorMenu()
  1580. {
  1581. multiviewProjectorMenu->clear();
  1582. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1583. SLOT(OpenMultiviewProjector()));
  1584. }
  1585. void OBSBasic::InitHotkeys()
  1586. {
  1587. ProfileScope("OBSBasic::InitHotkeys");
  1588. struct obs_hotkeys_translations t = {};
  1589. t.insert = Str("Hotkeys.Insert");
  1590. t.del = Str("Hotkeys.Delete");
  1591. t.home = Str("Hotkeys.Home");
  1592. t.end = Str("Hotkeys.End");
  1593. t.page_up = Str("Hotkeys.PageUp");
  1594. t.page_down = Str("Hotkeys.PageDown");
  1595. t.num_lock = Str("Hotkeys.NumLock");
  1596. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1597. t.caps_lock = Str("Hotkeys.CapsLock");
  1598. t.backspace = Str("Hotkeys.Backspace");
  1599. t.tab = Str("Hotkeys.Tab");
  1600. t.print = Str("Hotkeys.Print");
  1601. t.pause = Str("Hotkeys.Pause");
  1602. t.left = Str("Hotkeys.Left");
  1603. t.right = Str("Hotkeys.Right");
  1604. t.up = Str("Hotkeys.Up");
  1605. t.down = Str("Hotkeys.Down");
  1606. #ifdef _WIN32
  1607. t.meta = Str("Hotkeys.Windows");
  1608. #else
  1609. t.meta = Str("Hotkeys.Super");
  1610. #endif
  1611. t.menu = Str("Hotkeys.Menu");
  1612. t.space = Str("Hotkeys.Space");
  1613. t.numpad_num = Str("Hotkeys.NumpadNum");
  1614. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1615. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1616. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1617. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1618. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1619. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1620. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1621. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1622. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1623. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1624. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1625. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1626. t.mouse_num = Str("Hotkeys.MouseButton");
  1627. obs_hotkeys_set_translations(&t);
  1628. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1629. Str("Push-to-mute"), Str("Push-to-talk"));
  1630. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1631. Str("SceneItemShow"), Str("SceneItemHide"));
  1632. obs_hotkey_enable_callback_rerouting(true);
  1633. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1634. }
  1635. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1636. {
  1637. obs_hotkey_trigger_routed_callback(id, pressed);
  1638. }
  1639. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1640. {
  1641. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1642. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1643. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1644. }
  1645. void OBSBasic::CreateHotkeys()
  1646. {
  1647. ProfileScope("OBSBasic::CreateHotkeys");
  1648. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1649. {
  1650. const char *info = config_get_string(basicConfig,
  1651. "Hotkeys", name);
  1652. if (!info)
  1653. return {};
  1654. obs_data_t *data = obs_data_create_from_json(info);
  1655. if (!data)
  1656. return {};
  1657. OBSData res = data;
  1658. obs_data_release(data);
  1659. return res;
  1660. };
  1661. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1662. {
  1663. obs_data_array_t *array =
  1664. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1665. obs_hotkey_load(id, array);
  1666. obs_data_array_release(array);
  1667. };
  1668. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1669. const char *name1)
  1670. {
  1671. obs_data_array_t *array0 =
  1672. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1673. obs_data_array_t *array1 =
  1674. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1675. obs_hotkey_pair_load(id, array0, array1);
  1676. obs_data_array_release(array0);
  1677. obs_data_array_release(array1);
  1678. };
  1679. #define MAKE_CALLBACK(pred, method, log_action) \
  1680. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1681. { \
  1682. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1683. if ((pred) && pressed) { \
  1684. blog(LOG_INFO, log_action " due to hotkey"); \
  1685. method(); \
  1686. return true; \
  1687. } \
  1688. return false; \
  1689. }
  1690. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1691. "OBSBasic.StartStreaming",
  1692. Str("Basic.Main.StartStreaming"),
  1693. "OBSBasic.StopStreaming",
  1694. Str("Basic.Main.StopStreaming"),
  1695. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1696. basic.ui->streamButton->isEnabled(),
  1697. basic.StartStreaming, "Starting stream"),
  1698. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1699. basic.ui->streamButton->isEnabled(),
  1700. basic.StopStreaming, "Stopping stream"),
  1701. this, this);
  1702. LoadHotkeyPair(streamingHotkeys,
  1703. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1704. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1705. {
  1706. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1707. if (basic.outputHandler->StreamingActive() && pressed) {
  1708. basic.ForceStopStreaming();
  1709. }
  1710. };
  1711. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1712. "OBSBasic.ForceStopStreaming",
  1713. Str("Basic.Main.ForceStopStreaming"),
  1714. cb, this);
  1715. LoadHotkey(forceStreamingStopHotkey,
  1716. "OBSBasic.ForceStopStreaming");
  1717. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1718. "OBSBasic.StartRecording",
  1719. Str("Basic.Main.StartRecording"),
  1720. "OBSBasic.StopRecording",
  1721. Str("Basic.Main.StopRecording"),
  1722. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1723. !basic.ui->recordButton->isChecked(),
  1724. basic.StartRecording, "Starting recording"),
  1725. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1726. basic.ui->recordButton->isChecked(),
  1727. basic.StopRecording, "Stopping recording"),
  1728. this, this);
  1729. LoadHotkeyPair(recordingHotkeys,
  1730. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1731. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1732. "OBSBasic.StartReplayBuffer",
  1733. Str("Basic.Main.StartReplayBuffer"),
  1734. "OBSBasic.StopReplayBuffer",
  1735. Str("Basic.Main.StopReplayBuffer"),
  1736. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1737. basic.StartReplayBuffer, "Starting replay buffer"),
  1738. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1739. basic.StopReplayBuffer, "Stopping replay buffer"),
  1740. this, this);
  1741. LoadHotkeyPair(replayBufHotkeys,
  1742. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1743. #undef MAKE_CALLBACK
  1744. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1745. obs_hotkey_t*, bool pressed)
  1746. {
  1747. if (pressed)
  1748. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1749. "on_modeSwitch_clicked",
  1750. Qt::QueuedConnection);
  1751. };
  1752. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1753. "OBSBasic.TogglePreviewProgram",
  1754. Str("Basic.TogglePreviewProgramMode"),
  1755. togglePreviewProgram, this);
  1756. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1757. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1758. bool pressed)
  1759. {
  1760. if (pressed)
  1761. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1762. "TransitionClicked",
  1763. Qt::QueuedConnection);
  1764. };
  1765. transitionHotkey = obs_hotkey_register_frontend(
  1766. "OBSBasic.Transition",
  1767. Str("Transition"), transition, this);
  1768. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1769. }
  1770. void OBSBasic::ClearHotkeys()
  1771. {
  1772. obs_hotkey_pair_unregister(streamingHotkeys);
  1773. obs_hotkey_pair_unregister(recordingHotkeys);
  1774. obs_hotkey_pair_unregister(replayBufHotkeys);
  1775. obs_hotkey_unregister(forceStreamingStopHotkey);
  1776. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1777. obs_hotkey_unregister(transitionHotkey);
  1778. }
  1779. OBSBasic::~OBSBasic()
  1780. {
  1781. if (updateCheckThread && updateCheckThread->isRunning())
  1782. updateCheckThread->wait();
  1783. delete multiviewProjectorMenu;
  1784. delete previewProjector;
  1785. delete studioProgramProjector;
  1786. delete previewProjectorSource;
  1787. delete previewProjectorMain;
  1788. delete sourceProjector;
  1789. delete sceneProjectorMenu;
  1790. delete scaleFilteringMenu;
  1791. delete colorMenu;
  1792. delete colorWidgetAction;
  1793. delete colorSelect;
  1794. delete deinterlaceMenu;
  1795. delete perSceneTransitionMenu;
  1796. delete shortcutFilter;
  1797. delete trayMenu;
  1798. delete programOptions;
  1799. delete program;
  1800. /* XXX: any obs data must be released before calling obs_shutdown.
  1801. * currently, we can't automate this with C++ RAII because of the
  1802. * delicate nature of obs_shutdown needing to be freed before the UI
  1803. * can be freed, and we have no control over the destruction order of
  1804. * the Qt UI stuff, so we have to manually clear any references to
  1805. * libobs. */
  1806. delete cpuUsageTimer;
  1807. os_cpu_usage_info_destroy(cpuUsageInfo);
  1808. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1809. ClearHotkeys();
  1810. service = nullptr;
  1811. outputHandler.reset();
  1812. if (interaction)
  1813. delete interaction;
  1814. if (properties)
  1815. delete properties;
  1816. if (filters)
  1817. delete filters;
  1818. if (transformWindow)
  1819. delete transformWindow;
  1820. if (advAudioWindow)
  1821. delete advAudioWindow;
  1822. if (about)
  1823. delete about;
  1824. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1825. OBSBasic::RenderMain, this);
  1826. obs_enter_graphics();
  1827. gs_vertexbuffer_destroy(box);
  1828. gs_vertexbuffer_destroy(boxLeft);
  1829. gs_vertexbuffer_destroy(boxTop);
  1830. gs_vertexbuffer_destroy(boxRight);
  1831. gs_vertexbuffer_destroy(boxBottom);
  1832. gs_vertexbuffer_destroy(circle);
  1833. obs_leave_graphics();
  1834. /* When shutting down, sometimes source references can get in to the
  1835. * event queue, and if we don't forcibly process those events they
  1836. * won't get processed until after obs_shutdown has been called. I
  1837. * really wish there were a more elegant way to deal with this via C++,
  1838. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1839. * normal C++ behavior for your data to be freed in the order that you
  1840. * expect or want it to. */
  1841. QApplication::sendPostedEvents(this);
  1842. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1843. LIBOBS_API_VER);
  1844. #if OBS_RELEASE_CANDIDATE > 0
  1845. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1846. OBS_RELEASE_CANDIDATE_VER);
  1847. #endif
  1848. bool alwaysOnTop = IsAlwaysOnTop(this);
  1849. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1850. previewEnabled);
  1851. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1852. alwaysOnTop);
  1853. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1854. "SceneDuplicationMode", sceneDuplicationMode);
  1855. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1856. "SwapScenesMode", swapScenesMode);
  1857. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1858. "EditPropertiesMode", editPropertiesMode);
  1859. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1860. "PreviewProgramMode", IsPreviewProgramMode());
  1861. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1862. "DocksLocked", ui->lockUI->isChecked());
  1863. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1864. #ifdef _WIN32
  1865. uint32_t winVer = GetWindowsVersion();
  1866. if (winVer > 0 && winVer < 0x602) {
  1867. bool disableAero = config_get_bool(basicConfig, "Video",
  1868. "DisableAero");
  1869. if (disableAero) {
  1870. SetAeroEnabled(true);
  1871. }
  1872. }
  1873. #endif
  1874. #ifdef BROWSER_AVAILABLE
  1875. DestroyPanelCookieManager();
  1876. delete cef;
  1877. cef = nullptr;
  1878. #endif
  1879. }
  1880. void OBSBasic::SaveProjectNow()
  1881. {
  1882. if (disableSaving)
  1883. return;
  1884. projectChanged = true;
  1885. SaveProjectDeferred();
  1886. }
  1887. void OBSBasic::SaveProject()
  1888. {
  1889. if (disableSaving)
  1890. return;
  1891. projectChanged = true;
  1892. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1893. Qt::QueuedConnection);
  1894. }
  1895. void OBSBasic::SaveProjectDeferred()
  1896. {
  1897. if (disableSaving)
  1898. return;
  1899. if (!projectChanged)
  1900. return;
  1901. projectChanged = false;
  1902. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1903. "Basic", "SceneCollectionFile");
  1904. char savePath[512];
  1905. char fileName[512];
  1906. int ret;
  1907. if (!sceneCollection)
  1908. return;
  1909. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1910. sceneCollection);
  1911. if (ret <= 0)
  1912. return;
  1913. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1914. if (ret <= 0)
  1915. return;
  1916. Save(savePath);
  1917. }
  1918. OBSSource OBSBasic::GetProgramSource()
  1919. {
  1920. return OBSGetStrongRef(programScene);
  1921. }
  1922. OBSScene OBSBasic::GetCurrentScene()
  1923. {
  1924. QListWidgetItem *item = ui->scenes->currentItem();
  1925. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1926. }
  1927. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1928. {
  1929. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1930. }
  1931. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1932. {
  1933. return ui->sources->Get(GetTopSelectedSourceItem());
  1934. }
  1935. void OBSBasic::UpdatePreviewScalingMenu()
  1936. {
  1937. bool fixedScaling = ui->preview->IsFixedScaling();
  1938. float scalingAmount = ui->preview->GetScalingAmount();
  1939. if (!fixedScaling) {
  1940. ui->actionScaleWindow->setChecked(true);
  1941. ui->actionScaleCanvas->setChecked(false);
  1942. ui->actionScaleOutput->setChecked(false);
  1943. return;
  1944. }
  1945. obs_video_info ovi;
  1946. obs_get_video_info(&ovi);
  1947. ui->actionScaleWindow->setChecked(false);
  1948. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1949. ui->actionScaleOutput->setChecked(
  1950. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1951. }
  1952. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1953. {
  1954. if (interaction)
  1955. interaction->close();
  1956. interaction = new OBSBasicInteraction(this, source);
  1957. interaction->Init();
  1958. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1959. }
  1960. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1961. {
  1962. if (properties)
  1963. properties->close();
  1964. properties = new OBSBasicProperties(this, source);
  1965. properties->Init();
  1966. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1967. }
  1968. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1969. {
  1970. if (filters)
  1971. filters->close();
  1972. filters = new OBSBasicFilters(this, source);
  1973. filters->Init();
  1974. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1975. }
  1976. /* Qt callbacks for invokeMethod */
  1977. void OBSBasic::AddScene(OBSSource source)
  1978. {
  1979. const char *name = obs_source_get_name(source);
  1980. obs_scene_t *scene = obs_scene_from_source(source);
  1981. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1982. SetOBSRef(item, OBSScene(scene));
  1983. ui->scenes->addItem(item);
  1984. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1985. Str("Basic.Hotkeys.SelectScene"),
  1986. [](void *data,
  1987. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1988. {
  1989. OBSBasic *main =
  1990. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1991. auto potential_source = static_cast<obs_source_t*>(data);
  1992. auto source = obs_source_get_ref(potential_source);
  1993. if (source && pressed)
  1994. main->SetCurrentScene(source);
  1995. obs_source_release(source);
  1996. }, static_cast<obs_source_t*>(source));
  1997. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1998. SignalContainer<OBSScene> container;
  1999. container.ref = scene;
  2000. container.handlers.assign({
  2001. std::make_shared<OBSSignal>(handler, "item_add",
  2002. OBSBasic::SceneItemAdded, this),
  2003. std::make_shared<OBSSignal>(handler, "item_select",
  2004. OBSBasic::SceneItemSelected, this),
  2005. std::make_shared<OBSSignal>(handler, "item_deselect",
  2006. OBSBasic::SceneItemDeselected, this),
  2007. std::make_shared<OBSSignal>(handler, "reorder",
  2008. OBSBasic::SceneReordered, this),
  2009. });
  2010. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2011. QVariant::fromValue(container));
  2012. /* if the scene already has items (a duplicated scene) add them */
  2013. auto addSceneItem = [this] (obs_sceneitem_t *item)
  2014. {
  2015. AddSceneItem(item);
  2016. };
  2017. using addSceneItem_t = decltype(addSceneItem);
  2018. obs_scene_enum_items(scene,
  2019. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  2020. {
  2021. addSceneItem_t *func;
  2022. func = reinterpret_cast<addSceneItem_t*>(param);
  2023. (*func)(item);
  2024. return true;
  2025. }, &addSceneItem);
  2026. SaveProject();
  2027. if (!disableSaving) {
  2028. obs_source_t *source = obs_scene_get_source(scene);
  2029. blog(LOG_INFO, "User added scene '%s'",
  2030. obs_source_get_name(source));
  2031. OBSProjector::UpdateMultiviewProjectors();
  2032. }
  2033. if (api)
  2034. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2035. }
  2036. void OBSBasic::RemoveScene(OBSSource source)
  2037. {
  2038. obs_scene_t *scene = obs_scene_from_source(source);
  2039. QListWidgetItem *sel = nullptr;
  2040. int count = ui->scenes->count();
  2041. for (int i = 0; i < count; i++) {
  2042. auto item = ui->scenes->item(i);
  2043. auto cur_scene = GetOBSRef<OBSScene>(item);
  2044. if (cur_scene != scene)
  2045. continue;
  2046. sel = item;
  2047. break;
  2048. }
  2049. if (sel != nullptr) {
  2050. if (sel == ui->scenes->currentItem())
  2051. ui->sources->Clear();
  2052. delete sel;
  2053. }
  2054. SaveProject();
  2055. if (!disableSaving) {
  2056. blog(LOG_INFO, "User Removed scene '%s'",
  2057. obs_source_get_name(source));
  2058. OBSProjector::UpdateMultiviewProjectors();
  2059. }
  2060. if (api)
  2061. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2062. }
  2063. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2064. {
  2065. obs_sceneitem_t *selectedItem =
  2066. reinterpret_cast<obs_sceneitem_t*>(param);
  2067. if (obs_sceneitem_is_group(item))
  2068. obs_sceneitem_group_enum_items(item, select_one, param);
  2069. obs_sceneitem_select(item, (selectedItem == item));
  2070. UNUSED_PARAMETER(scene);
  2071. return true;
  2072. }
  2073. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2074. {
  2075. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2076. if (GetCurrentScene() == scene)
  2077. ui->sources->Add(item);
  2078. SaveProject();
  2079. if (!disableSaving) {
  2080. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2081. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2082. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2083. obs_source_get_name(itemSource),
  2084. obs_source_get_id(itemSource),
  2085. obs_source_get_name(sceneSource));
  2086. obs_scene_enum_items(scene, select_one, (obs_sceneitem_t*)item);
  2087. }
  2088. }
  2089. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2090. {
  2091. if (source) {
  2092. obs_scene_t *scene = obs_scene_from_source(source);
  2093. const char *name = obs_source_get_name(source);
  2094. if (!scene)
  2095. return;
  2096. QList<QListWidgetItem*> items =
  2097. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2098. if (items.count()) {
  2099. sceneChanging = true;
  2100. ui->scenes->setCurrentItem(items.first());
  2101. sceneChanging = false;
  2102. OBSScene curScene =
  2103. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2104. if (api && scene != curScene)
  2105. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2106. }
  2107. }
  2108. }
  2109. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2110. const QString &prevName)
  2111. {
  2112. QList<QListWidgetItem*> items =
  2113. listWidget->findItems(prevName, Qt::MatchExactly);
  2114. for (int i = 0; i < items.count(); i++)
  2115. items[i]->setText(newName);
  2116. }
  2117. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2118. QString prevName)
  2119. {
  2120. RenameListValues(ui->scenes, newName, prevName);
  2121. for (size_t i = 0; i < volumes.size(); i++) {
  2122. if (volumes[i]->GetName().compare(prevName) == 0)
  2123. volumes[i]->SetName(newName);
  2124. }
  2125. OBSProjector::RenameProjector(prevName, newName);
  2126. SaveProject();
  2127. obs_scene_t *scene = obs_scene_from_source(source);
  2128. if (scene)
  2129. OBSProjector::UpdateMultiviewProjectors();
  2130. }
  2131. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2132. {
  2133. SignalBlocker sourcesSignalBlocker(ui->sources);
  2134. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2135. return;
  2136. ui->sources->SelectItem(item, select);
  2137. }
  2138. static inline bool SourceMixerHidden(obs_source_t *source)
  2139. {
  2140. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2141. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2142. obs_data_release(priv_settings);
  2143. return hidden;
  2144. }
  2145. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2146. {
  2147. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2148. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2149. obs_data_release(priv_settings);
  2150. }
  2151. void OBSBasic::GetAudioSourceFilters()
  2152. {
  2153. QAction *action = reinterpret_cast<QAction*>(sender());
  2154. VolControl *vol = action->property("volControl").value<VolControl*>();
  2155. obs_source_t *source = vol->GetSource();
  2156. CreateFiltersWindow(source);
  2157. }
  2158. void OBSBasic::GetAudioSourceProperties()
  2159. {
  2160. QAction *action = reinterpret_cast<QAction*>(sender());
  2161. VolControl *vol = action->property("volControl").value<VolControl*>();
  2162. obs_source_t *source = vol->GetSource();
  2163. CreatePropertiesWindow(source);
  2164. }
  2165. void OBSBasic::HideAudioControl()
  2166. {
  2167. QAction *action = reinterpret_cast<QAction*>(sender());
  2168. VolControl *vol = action->property("volControl").value<VolControl*>();
  2169. obs_source_t *source = vol->GetSource();
  2170. if (!SourceMixerHidden(source)) {
  2171. SetSourceMixerHidden(source, true);
  2172. DeactivateAudioSource(source);
  2173. }
  2174. }
  2175. void OBSBasic::UnhideAllAudioControls()
  2176. {
  2177. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  2178. {
  2179. if (!obs_source_active(source))
  2180. return true;
  2181. if (!SourceMixerHidden(source))
  2182. return true;
  2183. SetSourceMixerHidden(source, false);
  2184. ActivateAudioSource(source);
  2185. return true;
  2186. };
  2187. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2188. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  2189. {
  2190. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2191. };
  2192. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2193. }
  2194. void OBSBasic::ToggleHideMixer()
  2195. {
  2196. OBSSceneItem item = GetCurrentSceneItem();
  2197. OBSSource source = obs_sceneitem_get_source(item);
  2198. if (!SourceMixerHidden(source)) {
  2199. SetSourceMixerHidden(source, true);
  2200. DeactivateAudioSource(source);
  2201. } else {
  2202. SetSourceMixerHidden(source, false);
  2203. ActivateAudioSource(source);
  2204. }
  2205. }
  2206. void OBSBasic::MixerRenameSource()
  2207. {
  2208. QAction *action = reinterpret_cast<QAction*>(sender());
  2209. VolControl *vol = action->property("volControl").value<VolControl*>();
  2210. OBSSource source = vol->GetSource();
  2211. const char *prevName = obs_source_get_name(source);
  2212. for (;;) {
  2213. string name;
  2214. bool accepted = NameDialog::AskForName(this,
  2215. QTStr("Basic.Main.MixerRename.Title"),
  2216. QTStr("Basic.Main.MixerRename.Text"),
  2217. name,
  2218. QT_UTF8(prevName));
  2219. if (!accepted)
  2220. return;
  2221. if (name.empty()) {
  2222. OBSMessageBox::information(this,
  2223. QTStr("NoNameEntered.Title"),
  2224. QTStr("NoNameEntered.Text"));
  2225. continue;
  2226. }
  2227. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2228. obs_source_release(sourceTest);
  2229. if (sourceTest) {
  2230. OBSMessageBox::information(this,
  2231. QTStr("NameExists.Title"),
  2232. QTStr("NameExists.Text"));
  2233. continue;
  2234. }
  2235. obs_source_set_name(source, name.c_str());
  2236. break;
  2237. }
  2238. }
  2239. void OBSBasic::VolControlContextMenu()
  2240. {
  2241. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  2242. /* ------------------- */
  2243. QAction hideAction(QTStr("Hide"), this);
  2244. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2245. QAction mixerRenameAction(QTStr("Rename"), this);
  2246. QAction filtersAction(QTStr("Filters"), this);
  2247. QAction propertiesAction(QTStr("Properties"), this);
  2248. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2249. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2250. toggleControlLayoutAction.setCheckable(true);
  2251. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2252. "BasicWindow", "VerticalVolControl"));
  2253. /* ------------------- */
  2254. connect(&hideAction, &QAction::triggered,
  2255. this, &OBSBasic::HideAudioControl,
  2256. Qt::DirectConnection);
  2257. connect(&unhideAllAction, &QAction::triggered,
  2258. this, &OBSBasic::UnhideAllAudioControls,
  2259. Qt::DirectConnection);
  2260. connect(&mixerRenameAction, &QAction::triggered,
  2261. this, &OBSBasic::MixerRenameSource,
  2262. Qt::DirectConnection);
  2263. connect(&filtersAction, &QAction::triggered,
  2264. this, &OBSBasic::GetAudioSourceFilters,
  2265. Qt::DirectConnection);
  2266. connect(&propertiesAction, &QAction::triggered,
  2267. this, &OBSBasic::GetAudioSourceProperties,
  2268. Qt::DirectConnection);
  2269. connect(&advPropAction, &QAction::triggered,
  2270. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2271. Qt::DirectConnection);
  2272. /* ------------------- */
  2273. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2274. &OBSBasic::ToggleVolControlLayout,
  2275. Qt::DirectConnection);
  2276. /* ------------------- */
  2277. hideAction.setProperty("volControl",
  2278. QVariant::fromValue<VolControl*>(vol));
  2279. mixerRenameAction.setProperty("volControl",
  2280. QVariant::fromValue<VolControl*>(vol));
  2281. filtersAction.setProperty("volControl",
  2282. QVariant::fromValue<VolControl*>(vol));
  2283. propertiesAction.setProperty("volControl",
  2284. QVariant::fromValue<VolControl*>(vol));
  2285. /* ------------------- */
  2286. QMenu popup;
  2287. popup.addAction(&unhideAllAction);
  2288. popup.addAction(&hideAction);
  2289. popup.addAction(&mixerRenameAction);
  2290. popup.addSeparator();
  2291. popup.addAction(&toggleControlLayoutAction);
  2292. popup.addSeparator();
  2293. popup.addAction(&filtersAction);
  2294. popup.addAction(&propertiesAction);
  2295. popup.addAction(&advPropAction);
  2296. popup.exec(QCursor::pos());
  2297. }
  2298. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2299. {
  2300. StackedMixerAreaContextMenuRequested();
  2301. }
  2302. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2303. {
  2304. StackedMixerAreaContextMenuRequested();
  2305. }
  2306. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2307. {
  2308. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2309. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2310. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2311. toggleControlLayoutAction.setCheckable(true);
  2312. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2313. "BasicWindow", "VerticalVolControl"));
  2314. /* ------------------- */
  2315. connect(&unhideAllAction, &QAction::triggered,
  2316. this, &OBSBasic::UnhideAllAudioControls,
  2317. Qt::DirectConnection);
  2318. connect(&advPropAction, &QAction::triggered,
  2319. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2320. Qt::DirectConnection);
  2321. /* ------------------- */
  2322. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2323. &OBSBasic::ToggleVolControlLayout,
  2324. Qt::DirectConnection);
  2325. /* ------------------- */
  2326. QMenu popup;
  2327. popup.addAction(&unhideAllAction);
  2328. popup.addSeparator();
  2329. popup.addAction(&toggleControlLayoutAction);
  2330. popup.addSeparator();
  2331. popup.addAction(&advPropAction);
  2332. popup.exec(QCursor::pos());
  2333. }
  2334. void OBSBasic::ToggleMixerLayout(bool vertical)
  2335. {
  2336. if (vertical) {
  2337. ui->stackedMixerArea->setMinimumSize(180, 220);
  2338. ui->stackedMixerArea->setCurrentIndex(1);
  2339. } else {
  2340. ui->stackedMixerArea->setMinimumSize(220, 0);
  2341. ui->stackedMixerArea->setCurrentIndex(0);
  2342. }
  2343. }
  2344. void OBSBasic::ToggleVolControlLayout()
  2345. {
  2346. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2347. "VerticalVolControl");
  2348. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2349. vertical);
  2350. ToggleMixerLayout(vertical);
  2351. // We need to store it so we can delete current and then add
  2352. // at the right order
  2353. vector<OBSSource> sources;
  2354. for (size_t i = 0; i != volumes.size(); i++)
  2355. sources.emplace_back(volumes[i]->GetSource());
  2356. ClearVolumeControls();
  2357. for (const auto &source : sources)
  2358. ActivateAudioSource(source);
  2359. }
  2360. void OBSBasic::ActivateAudioSource(OBSSource source)
  2361. {
  2362. if (SourceMixerHidden(source))
  2363. return;
  2364. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2365. "VerticalVolControl");
  2366. VolControl *vol = new VolControl(source, true, vertical);
  2367. double meterDecayRate = config_get_double(basicConfig, "Audio",
  2368. "MeterDecayRate");
  2369. vol->SetMeterDecayRate(meterDecayRate);
  2370. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  2371. "PeakMeterType");
  2372. enum obs_peak_meter_type peakMeterType;
  2373. switch (peakMeterTypeIdx) {
  2374. case 0:
  2375. peakMeterType = SAMPLE_PEAK_METER;
  2376. break;
  2377. case 1:
  2378. peakMeterType = TRUE_PEAK_METER;
  2379. break;
  2380. default:
  2381. peakMeterType = SAMPLE_PEAK_METER;
  2382. break;
  2383. }
  2384. vol->setPeakMeterType(peakMeterType);
  2385. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2386. connect(vol, &QWidget::customContextMenuRequested,
  2387. this, &OBSBasic::VolControlContextMenu);
  2388. connect(vol, &VolControl::ConfigClicked,
  2389. this, &OBSBasic::VolControlContextMenu);
  2390. InsertQObjectByName(volumes, vol);
  2391. for (auto volume : volumes) {
  2392. if (vertical)
  2393. ui->vVolControlLayout->addWidget(volume);
  2394. else
  2395. ui->hVolControlLayout->addWidget(volume);
  2396. }
  2397. }
  2398. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2399. {
  2400. for (size_t i = 0; i < volumes.size(); i++) {
  2401. if (volumes[i]->GetSource() == source) {
  2402. delete volumes[i];
  2403. volumes.erase(volumes.begin() + i);
  2404. break;
  2405. }
  2406. }
  2407. }
  2408. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2409. {
  2410. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2411. !obs_source_is_group(source)) {
  2412. int count = ui->scenes->count();
  2413. if (count == 1) {
  2414. OBSMessageBox::information(this,
  2415. QTStr("FinalScene.Title"),
  2416. QTStr("FinalScene.Text"));
  2417. return false;
  2418. }
  2419. }
  2420. const char *name = obs_source_get_name(source);
  2421. QString text = QTStr("ConfirmRemove.Text");
  2422. text.replace("$1", QT_UTF8(name));
  2423. QMessageBox remove_source(this);
  2424. remove_source.setText(text);
  2425. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  2426. QMessageBox::YesRole);
  2427. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2428. remove_source.setIcon(QMessageBox::Question);
  2429. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2430. remove_source.exec();
  2431. return Yes == remove_source.clickedButton();
  2432. }
  2433. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  2434. #ifdef UPDATE_SPARKLE
  2435. void init_sparkle_updater(bool update_to_undeployed);
  2436. void trigger_sparkle_update();
  2437. #endif
  2438. void OBSBasic::TimedCheckForUpdates()
  2439. {
  2440. if (!config_get_bool(App()->GlobalConfig(), "General",
  2441. "EnableAutoUpdates"))
  2442. return;
  2443. #ifdef UPDATE_SPARKLE
  2444. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2445. "UpdateToUndeployed"));
  2446. #elif _WIN32
  2447. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2448. "LastUpdateCheck");
  2449. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2450. "LastVersion");
  2451. if (lastVersion < LIBOBS_API_VER) {
  2452. lastUpdate = 0;
  2453. config_set_int(App()->GlobalConfig(), "General",
  2454. "LastUpdateCheck", 0);
  2455. }
  2456. long long t = (long long)time(nullptr);
  2457. long long secs = t - lastUpdate;
  2458. if (secs > UPDATE_CHECK_INTERVAL)
  2459. CheckForUpdates(false);
  2460. #endif
  2461. }
  2462. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2463. {
  2464. #ifdef UPDATE_SPARKLE
  2465. trigger_sparkle_update();
  2466. #elif _WIN32
  2467. ui->actionCheckForUpdates->setEnabled(false);
  2468. if (updateCheckThread && updateCheckThread->isRunning())
  2469. return;
  2470. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2471. updateCheckThread->start();
  2472. #endif
  2473. UNUSED_PARAMETER(manualUpdate);
  2474. }
  2475. void OBSBasic::updateCheckFinished()
  2476. {
  2477. ui->actionCheckForUpdates->setEnabled(true);
  2478. }
  2479. void OBSBasic::DuplicateSelectedScene()
  2480. {
  2481. OBSScene curScene = GetCurrentScene();
  2482. if (!curScene)
  2483. return;
  2484. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2485. QString format{obs_source_get_name(curSceneSource)};
  2486. format += " %1";
  2487. int i = 2;
  2488. QString placeHolderText = format.arg(i);
  2489. obs_source_t *source = nullptr;
  2490. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2491. obs_source_release(source);
  2492. placeHolderText = format.arg(++i);
  2493. }
  2494. for (;;) {
  2495. string name;
  2496. bool accepted = NameDialog::AskForName(this,
  2497. QTStr("Basic.Main.AddSceneDlg.Title"),
  2498. QTStr("Basic.Main.AddSceneDlg.Text"),
  2499. name,
  2500. placeHolderText);
  2501. if (!accepted)
  2502. return;
  2503. if (name.empty()) {
  2504. OBSMessageBox::information(this,
  2505. QTStr("NoNameEntered.Title"),
  2506. QTStr("NoNameEntered.Text"));
  2507. continue;
  2508. }
  2509. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2510. if (source) {
  2511. OBSMessageBox::information(this,
  2512. QTStr("NameExists.Title"),
  2513. QTStr("NameExists.Text"));
  2514. obs_source_release(source);
  2515. continue;
  2516. }
  2517. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2518. name.c_str(), OBS_SCENE_DUP_REFS);
  2519. source = obs_scene_get_source(scene);
  2520. SetCurrentScene(source, true);
  2521. obs_scene_release(scene);
  2522. break;
  2523. }
  2524. }
  2525. void OBSBasic::RemoveSelectedScene()
  2526. {
  2527. OBSScene scene = GetCurrentScene();
  2528. if (scene) {
  2529. obs_source_t *source = obs_scene_get_source(scene);
  2530. if (QueryRemoveSource(source)) {
  2531. obs_source_remove(source);
  2532. if (api)
  2533. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2534. }
  2535. }
  2536. }
  2537. void OBSBasic::RemoveSelectedSceneItem()
  2538. {
  2539. OBSSceneItem item = GetCurrentSceneItem();
  2540. if (item) {
  2541. obs_source_t *source = obs_sceneitem_get_source(item);
  2542. if (QueryRemoveSource(source))
  2543. obs_sceneitem_remove(item);
  2544. }
  2545. }
  2546. void OBSBasic::ReorderSources(OBSScene scene)
  2547. {
  2548. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2549. return;
  2550. ui->sources->ReorderItems();
  2551. SaveProject();
  2552. }
  2553. /* OBS Callbacks */
  2554. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2555. {
  2556. OBSBasic *window = static_cast<OBSBasic*>(data);
  2557. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2558. QMetaObject::invokeMethod(window, "ReorderSources",
  2559. Q_ARG(OBSScene, OBSScene(scene)));
  2560. }
  2561. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2562. {
  2563. OBSBasic *window = static_cast<OBSBasic*>(data);
  2564. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2565. QMetaObject::invokeMethod(window, "AddSceneItem",
  2566. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2567. }
  2568. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2569. {
  2570. OBSBasic *window = static_cast<OBSBasic*>(data);
  2571. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2572. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2573. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2574. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2575. Q_ARG(bool, true));
  2576. }
  2577. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2578. {
  2579. OBSBasic *window = static_cast<OBSBasic*>(data);
  2580. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2581. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2582. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2583. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2584. Q_ARG(bool, false));
  2585. }
  2586. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2587. {
  2588. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2589. if (obs_scene_from_source(source) != NULL)
  2590. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2591. "AddScene", WaitConnection(),
  2592. Q_ARG(OBSSource, OBSSource(source)));
  2593. }
  2594. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2595. {
  2596. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2597. if (obs_scene_from_source(source) != NULL)
  2598. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2599. "RemoveScene",
  2600. Q_ARG(OBSSource, OBSSource(source)));
  2601. }
  2602. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2603. {
  2604. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2605. uint32_t flags = obs_source_get_output_flags(source);
  2606. if (flags & OBS_SOURCE_AUDIO)
  2607. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2608. "ActivateAudioSource",
  2609. Q_ARG(OBSSource, OBSSource(source)));
  2610. }
  2611. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2612. {
  2613. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2614. uint32_t flags = obs_source_get_output_flags(source);
  2615. if (flags & OBS_SOURCE_AUDIO)
  2616. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2617. "DeactivateAudioSource",
  2618. Q_ARG(OBSSource, OBSSource(source)));
  2619. }
  2620. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2621. {
  2622. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2623. const char *newName = calldata_string(params, "new_name");
  2624. const char *prevName = calldata_string(params, "prev_name");
  2625. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2626. "RenameSources",
  2627. Q_ARG(OBSSource, source),
  2628. Q_ARG(QString, QT_UTF8(newName)),
  2629. Q_ARG(QString, QT_UTF8(prevName)));
  2630. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2631. }
  2632. void OBSBasic::DrawBackdrop(float cx, float cy)
  2633. {
  2634. if (!box)
  2635. return;
  2636. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2637. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2638. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2639. vec4 colorVal;
  2640. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2641. gs_effect_set_vec4(color, &colorVal);
  2642. gs_technique_begin(tech);
  2643. gs_technique_begin_pass(tech, 0);
  2644. gs_matrix_push();
  2645. gs_matrix_identity();
  2646. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2647. gs_load_vertexbuffer(box);
  2648. gs_draw(GS_TRISTRIP, 0, 0);
  2649. gs_matrix_pop();
  2650. gs_technique_end_pass(tech);
  2651. gs_technique_end(tech);
  2652. gs_load_vertexbuffer(nullptr);
  2653. }
  2654. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2655. {
  2656. OBSBasic *window = static_cast<OBSBasic*>(data);
  2657. obs_video_info ovi;
  2658. obs_get_video_info(&ovi);
  2659. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2660. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2661. gs_viewport_push();
  2662. gs_projection_push();
  2663. QSize previewSize = GetPixelSize(window->ui->preview);
  2664. float right = float(previewSize.width()) - window->previewX;
  2665. float bottom = float(previewSize.height()) - window->previewY;
  2666. gs_ortho(-window->previewX, right,
  2667. -window->previewY, bottom,
  2668. -100.0f, 100.0f);
  2669. window->ui->preview->DrawOverflow();
  2670. /* --------------------------------------- */
  2671. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2672. -100.0f, 100.0f);
  2673. gs_set_viewport(window->previewX, window->previewY,
  2674. window->previewCX, window->previewCY);
  2675. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2676. if (window->IsPreviewProgramMode()) {
  2677. OBSScene scene = window->GetCurrentScene();
  2678. obs_source_t *source = obs_scene_get_source(scene);
  2679. if (source)
  2680. obs_source_video_render(source);
  2681. } else {
  2682. obs_render_main_texture();
  2683. }
  2684. gs_load_vertexbuffer(nullptr);
  2685. /* --------------------------------------- */
  2686. gs_ortho(-window->previewX, right,
  2687. -window->previewY, bottom,
  2688. -100.0f, 100.0f);
  2689. gs_reset_viewport();
  2690. window->ui->preview->DrawSceneEditing();
  2691. /* --------------------------------------- */
  2692. gs_projection_pop();
  2693. gs_viewport_pop();
  2694. UNUSED_PARAMETER(cx);
  2695. UNUSED_PARAMETER(cy);
  2696. }
  2697. /* Main class functions */
  2698. obs_service_t *OBSBasic::GetService()
  2699. {
  2700. if (!service) {
  2701. service = obs_service_create("rtmp_common", NULL, NULL,
  2702. nullptr);
  2703. obs_service_release(service);
  2704. }
  2705. return service;
  2706. }
  2707. void OBSBasic::SetService(obs_service_t *newService)
  2708. {
  2709. if (newService)
  2710. service = newService;
  2711. }
  2712. bool OBSBasic::StreamingActive() const
  2713. {
  2714. if (!outputHandler)
  2715. return false;
  2716. return outputHandler->StreamingActive();
  2717. }
  2718. bool OBSBasic::Active() const
  2719. {
  2720. if (!outputHandler)
  2721. return false;
  2722. return outputHandler->Active();
  2723. }
  2724. #ifdef _WIN32
  2725. #define IS_WIN32 1
  2726. #else
  2727. #define IS_WIN32 0
  2728. #endif
  2729. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2730. {
  2731. return obs_reset_video(ovi);
  2732. }
  2733. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2734. {
  2735. const char *scaleTypeStr = config_get_string(basicConfig,
  2736. "Video", "ScaleType");
  2737. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2738. return OBS_SCALE_BILINEAR;
  2739. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2740. return OBS_SCALE_LANCZOS;
  2741. else
  2742. return OBS_SCALE_BICUBIC;
  2743. }
  2744. static inline enum video_format GetVideoFormatFromName(const char *name)
  2745. {
  2746. if (astrcmpi(name, "I420") == 0)
  2747. return VIDEO_FORMAT_I420;
  2748. else if (astrcmpi(name, "NV12") == 0)
  2749. return VIDEO_FORMAT_NV12;
  2750. else if (astrcmpi(name, "I444") == 0)
  2751. return VIDEO_FORMAT_I444;
  2752. #if 0 //currently unsupported
  2753. else if (astrcmpi(name, "YVYU") == 0)
  2754. return VIDEO_FORMAT_YVYU;
  2755. else if (astrcmpi(name, "YUY2") == 0)
  2756. return VIDEO_FORMAT_YUY2;
  2757. else if (astrcmpi(name, "UYVY") == 0)
  2758. return VIDEO_FORMAT_UYVY;
  2759. #endif
  2760. else
  2761. return VIDEO_FORMAT_RGBA;
  2762. }
  2763. void OBSBasic::ResetUI()
  2764. {
  2765. bool studioPortraitLayout = config_get_bool(GetGlobalConfig(),
  2766. "BasicWindow", "StudioPortraitLayout");
  2767. if (studioPortraitLayout)
  2768. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2769. else
  2770. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2771. }
  2772. int OBSBasic::ResetVideo()
  2773. {
  2774. if (outputHandler && outputHandler->Active())
  2775. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2776. ProfileScope("OBSBasic::ResetVideo");
  2777. struct obs_video_info ovi;
  2778. int ret;
  2779. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2780. const char *colorFormat = config_get_string(basicConfig, "Video",
  2781. "ColorFormat");
  2782. const char *colorSpace = config_get_string(basicConfig, "Video",
  2783. "ColorSpace");
  2784. const char *colorRange = config_get_string(basicConfig, "Video",
  2785. "ColorRange");
  2786. ovi.graphics_module = App()->GetRenderModule();
  2787. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2788. "Video", "BaseCX");
  2789. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2790. "Video", "BaseCY");
  2791. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2792. "Video", "OutputCX");
  2793. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2794. "Video", "OutputCY");
  2795. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2796. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2797. VIDEO_CS_601 : VIDEO_CS_709;
  2798. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2799. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2800. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2801. "Video", "AdapterIdx");
  2802. ovi.gpu_conversion = true;
  2803. ovi.scale_type = GetScaleType(basicConfig);
  2804. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2805. ovi.base_width = 1920;
  2806. ovi.base_height = 1080;
  2807. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2808. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2809. }
  2810. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2811. ovi.output_width = ovi.base_width;
  2812. ovi.output_height = ovi.base_height;
  2813. config_set_uint(basicConfig, "Video", "OutputCX",
  2814. ovi.base_width);
  2815. config_set_uint(basicConfig, "Video", "OutputCY",
  2816. ovi.base_height);
  2817. }
  2818. ret = AttemptToResetVideo(&ovi);
  2819. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2820. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2821. blog(LOG_WARNING, "Tried to reset when "
  2822. "already active");
  2823. return ret;
  2824. }
  2825. /* Try OpenGL if DirectX fails on windows */
  2826. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2827. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2828. "with graphics_module='%s', retrying "
  2829. "with graphics_module='%s'",
  2830. ret, ovi.graphics_module,
  2831. DL_OPENGL);
  2832. ovi.graphics_module = DL_OPENGL;
  2833. ret = AttemptToResetVideo(&ovi);
  2834. }
  2835. } else if (ret == OBS_VIDEO_SUCCESS) {
  2836. ResizePreview(ovi.base_width, ovi.base_height);
  2837. if (program)
  2838. ResizeProgram(ovi.base_width, ovi.base_height);
  2839. }
  2840. if (ret == OBS_VIDEO_SUCCESS) {
  2841. OBSBasicStats::InitializeValues();
  2842. OBSProjector::UpdateMultiviewProjectors();
  2843. }
  2844. return ret;
  2845. }
  2846. bool OBSBasic::ResetAudio()
  2847. {
  2848. ProfileScope("OBSBasic::ResetAudio");
  2849. struct obs_audio_info ai;
  2850. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2851. "SampleRate");
  2852. const char *channelSetupStr = config_get_string(basicConfig,
  2853. "Audio", "ChannelSetup");
  2854. if (strcmp(channelSetupStr, "Mono") == 0)
  2855. ai.speakers = SPEAKERS_MONO;
  2856. else if (strcmp(channelSetupStr, "2.1") == 0)
  2857. ai.speakers = SPEAKERS_2POINT1;
  2858. else if (strcmp(channelSetupStr, "4.0") == 0)
  2859. ai.speakers = SPEAKERS_4POINT0;
  2860. else if (strcmp(channelSetupStr, "4.1") == 0)
  2861. ai.speakers = SPEAKERS_4POINT1;
  2862. else if (strcmp(channelSetupStr, "5.1") == 0)
  2863. ai.speakers = SPEAKERS_5POINT1;
  2864. else if (strcmp(channelSetupStr, "7.1") == 0)
  2865. ai.speakers = SPEAKERS_7POINT1;
  2866. else
  2867. ai.speakers = SPEAKERS_STEREO;
  2868. return obs_reset_audio(&ai);
  2869. }
  2870. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2871. const char *deviceDesc, int channel)
  2872. {
  2873. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2874. obs_source_t *source;
  2875. obs_data_t *settings;
  2876. source = obs_get_output_source(channel);
  2877. if (source) {
  2878. if (disable) {
  2879. obs_set_output_source(channel, nullptr);
  2880. } else {
  2881. settings = obs_source_get_settings(source);
  2882. const char *oldId = obs_data_get_string(settings,
  2883. "device_id");
  2884. if (strcmp(oldId, deviceId) != 0) {
  2885. obs_data_set_string(settings, "device_id",
  2886. deviceId);
  2887. obs_source_update(source, settings);
  2888. }
  2889. obs_data_release(settings);
  2890. }
  2891. obs_source_release(source);
  2892. } else if (!disable) {
  2893. settings = obs_data_create();
  2894. obs_data_set_string(settings, "device_id", deviceId);
  2895. source = obs_source_create(sourceId, deviceDesc, settings,
  2896. nullptr);
  2897. obs_data_release(settings);
  2898. obs_set_output_source(channel, source);
  2899. obs_source_release(source);
  2900. }
  2901. }
  2902. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2903. {
  2904. QSize targetSize;
  2905. bool isFixedScaling;
  2906. obs_video_info ovi;
  2907. /* resize preview panel to fix to the top section of the window */
  2908. targetSize = GetPixelSize(ui->preview);
  2909. isFixedScaling = ui->preview->IsFixedScaling();
  2910. obs_get_video_info(&ovi);
  2911. if (isFixedScaling) {
  2912. previewScale = ui->preview->GetScalingAmount();
  2913. GetCenterPosFromFixedScale(int(cx), int(cy),
  2914. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2915. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2916. previewX, previewY, previewScale);
  2917. previewX += ui->preview->GetScrollX();
  2918. previewY += ui->preview->GetScrollY();
  2919. } else {
  2920. GetScaleAndCenterPos(int(cx), int(cy),
  2921. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2922. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2923. previewX, previewY, previewScale);
  2924. }
  2925. previewX += float(PREVIEW_EDGE_SIZE);
  2926. previewY += float(PREVIEW_EDGE_SIZE);
  2927. }
  2928. void OBSBasic::CloseDialogs()
  2929. {
  2930. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2931. if (!childDialogs.isEmpty()) {
  2932. for (int i = 0; i < childDialogs.size(); ++i) {
  2933. childDialogs.at(i)->close();
  2934. }
  2935. }
  2936. for (QPointer<QWidget> &projector : windowProjectors) {
  2937. delete projector;
  2938. projector.clear();
  2939. }
  2940. for (QPointer<QWidget> &projector : projectors) {
  2941. delete projector;
  2942. projector.clear();
  2943. }
  2944. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2945. if (!remux.isNull()) remux->close();
  2946. }
  2947. void OBSBasic::EnumDialogs()
  2948. {
  2949. visDialogs.clear();
  2950. modalDialogs.clear();
  2951. visMsgBoxes.clear();
  2952. /* fill list of Visible dialogs and Modal dialogs */
  2953. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2954. for (QDialog *dialog : dialogs) {
  2955. if (dialog->isVisible())
  2956. visDialogs.append(dialog);
  2957. if (dialog->isModal())
  2958. modalDialogs.append(dialog);
  2959. }
  2960. /* fill list of Visible message boxes */
  2961. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2962. for (QMessageBox *msgbox : msgBoxes) {
  2963. if (msgbox->isVisible())
  2964. visMsgBoxes.append(msgbox);
  2965. }
  2966. }
  2967. void OBSBasic::ClearSceneData()
  2968. {
  2969. disableSaving++;
  2970. CloseDialogs();
  2971. ClearVolumeControls();
  2972. ClearListItems(ui->scenes);
  2973. ui->sources->Clear();
  2974. ClearQuickTransitions();
  2975. ui->transitions->clear();
  2976. obs_set_output_source(0, nullptr);
  2977. obs_set_output_source(1, nullptr);
  2978. obs_set_output_source(2, nullptr);
  2979. obs_set_output_source(3, nullptr);
  2980. obs_set_output_source(4, nullptr);
  2981. obs_set_output_source(5, nullptr);
  2982. lastScene = nullptr;
  2983. swapScene = nullptr;
  2984. programScene = nullptr;
  2985. auto cb = [](void *unused, obs_source_t *source)
  2986. {
  2987. obs_source_remove(source);
  2988. UNUSED_PARAMETER(unused);
  2989. return true;
  2990. };
  2991. obs_enum_sources(cb, nullptr);
  2992. if (api)
  2993. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  2994. disableSaving--;
  2995. blog(LOG_INFO, "All scene data cleared");
  2996. blog(LOG_INFO, "------------------------------------------------");
  2997. }
  2998. void OBSBasic::closeEvent(QCloseEvent *event)
  2999. {
  3000. if (isVisible())
  3001. config_set_string(App()->GlobalConfig(),
  3002. "BasicWindow", "geometry",
  3003. saveGeometry().toBase64().constData());
  3004. if (outputHandler && outputHandler->Active()) {
  3005. SetShowing(true);
  3006. QMessageBox::StandardButton button = OBSMessageBox::question(
  3007. this, QTStr("ConfirmExit.Title"),
  3008. QTStr("ConfirmExit.Text"));
  3009. if (button == QMessageBox::No) {
  3010. event->ignore();
  3011. return;
  3012. }
  3013. }
  3014. QWidget::closeEvent(event);
  3015. if (!event->isAccepted())
  3016. return;
  3017. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3018. if (introCheckThread)
  3019. introCheckThread->wait();
  3020. if (updateCheckThread)
  3021. updateCheckThread->wait();
  3022. if (logUploadThread)
  3023. logUploadThread->wait();
  3024. signalHandlers.clear();
  3025. Auth::Save();
  3026. SaveProjectNow();
  3027. auth.reset();
  3028. config_set_string(App()->GlobalConfig(),
  3029. "BasicWindow", "DockState",
  3030. saveState().toBase64().constData());
  3031. if (api)
  3032. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3033. disableSaving++;
  3034. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3035. * sources, etc) so that all references are released before shutdown */
  3036. ClearSceneData();
  3037. App()->quit();
  3038. }
  3039. void OBSBasic::changeEvent(QEvent *event)
  3040. {
  3041. if (event->type() == QEvent::WindowStateChange &&
  3042. isMinimized() &&
  3043. trayIcon &&
  3044. trayIcon->isVisible() &&
  3045. sysTrayMinimizeToTray()) {
  3046. ToggleShowHide();
  3047. }
  3048. }
  3049. void OBSBasic::on_actionShow_Recordings_triggered()
  3050. {
  3051. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3052. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3053. const char *adv_path = strcmp(type, "Standard") ?
  3054. config_get_string(basicConfig, "AdvOut", "FFFilePath") :
  3055. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3056. const char *path = strcmp(mode, "Advanced") ?
  3057. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3058. adv_path;
  3059. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3060. }
  3061. void OBSBasic::on_actionRemux_triggered()
  3062. {
  3063. if (!remux.isNull()) {
  3064. remux->show();
  3065. remux->raise();
  3066. return;
  3067. }
  3068. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3069. const char *path = strcmp(mode, "Advanced") ?
  3070. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  3071. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  3072. OBSRemux *remuxDlg;
  3073. remuxDlg = new OBSRemux(path, this);
  3074. remuxDlg->show();
  3075. remux = remuxDlg;
  3076. }
  3077. void OBSBasic::on_action_Settings_triggered()
  3078. {
  3079. OBSBasicSettings settings(this);
  3080. settings.exec();
  3081. SystemTray(false);
  3082. }
  3083. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3084. {
  3085. if (advAudioWindow != nullptr) {
  3086. advAudioWindow->raise();
  3087. return;
  3088. }
  3089. advAudioWindow = new OBSBasicAdvAudio(this);
  3090. advAudioWindow->show();
  3091. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3092. connect(advAudioWindow, SIGNAL(destroyed()),
  3093. this, SLOT(on_advAudioProps_destroyed()));
  3094. }
  3095. void OBSBasic::on_advAudioProps_clicked()
  3096. {
  3097. on_actionAdvAudioProperties_triggered();
  3098. }
  3099. void OBSBasic::on_advAudioProps_destroyed()
  3100. {
  3101. advAudioWindow = nullptr;
  3102. }
  3103. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3104. QListWidgetItem *prev)
  3105. {
  3106. obs_source_t *source = NULL;
  3107. if (sceneChanging)
  3108. return;
  3109. if (current) {
  3110. obs_scene_t *scene;
  3111. scene = GetOBSRef<OBSScene>(current);
  3112. source = obs_scene_get_source(scene);
  3113. }
  3114. SetCurrentScene(source);
  3115. if (api)
  3116. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3117. UNUSED_PARAMETER(prev);
  3118. }
  3119. void OBSBasic::EditSceneName()
  3120. {
  3121. QListWidgetItem *item = ui->scenes->currentItem();
  3122. Qt::ItemFlags flags = item->flags();
  3123. item->setFlags(flags | Qt::ItemIsEditable);
  3124. ui->scenes->editItem(item);
  3125. item->setFlags(flags);
  3126. }
  3127. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3128. const char *slot)
  3129. {
  3130. QAction *action;
  3131. QList<QScreen*> screens = QGuiApplication::screens();
  3132. for (int i = 0; i < screens.size(); i++) {
  3133. QRect screenGeometry = screens[i]->geometry();
  3134. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  3135. arg(QTStr("Display"),
  3136. QString::number(i + 1),
  3137. QString::number(screenGeometry.width()),
  3138. QString::number(screenGeometry.height()),
  3139. QString::number(screenGeometry.x()),
  3140. QString::number(screenGeometry.y()));
  3141. action = parent->addAction(str, target, slot);
  3142. action->setProperty("monitor", i);
  3143. }
  3144. }
  3145. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3146. {
  3147. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3148. QMenu popup(this);
  3149. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3150. popup.addAction(QTStr("Add"),
  3151. this, SLOT(on_actionAddScene_triggered()));
  3152. if (item) {
  3153. popup.addSeparator();
  3154. popup.addAction(QTStr("Duplicate"),
  3155. this, SLOT(DuplicateSelectedScene()));
  3156. popup.addAction(QTStr("Rename"),
  3157. this, SLOT(EditSceneName()));
  3158. popup.addAction(QTStr("Remove"),
  3159. this, SLOT(RemoveSelectedScene()));
  3160. popup.addSeparator();
  3161. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  3162. this, SLOT(on_actionSceneUp_triggered()));
  3163. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3164. this, SLOT(on_actionSceneDown_triggered()));
  3165. order.addSeparator();
  3166. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3167. this, SLOT(MoveSceneToTop()));
  3168. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3169. this, SLOT(MoveSceneToBottom()));
  3170. popup.addMenu(&order);
  3171. popup.addSeparator();
  3172. delete sceneProjectorMenu;
  3173. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3174. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3175. SLOT(OpenSceneProjector()));
  3176. popup.addMenu(sceneProjectorMenu);
  3177. QAction *sceneWindow = popup.addAction(
  3178. QTStr("SceneWindow"),
  3179. this, SLOT(OpenSceneWindow()));
  3180. popup.addAction(sceneWindow);
  3181. popup.addSeparator();
  3182. popup.addAction(QTStr("Filters"), this,
  3183. SLOT(OpenSceneFilters()));
  3184. popup.addSeparator();
  3185. delete perSceneTransitionMenu;
  3186. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3187. popup.addMenu(perSceneTransitionMenu);
  3188. /* ---------------------- */
  3189. QAction *multiviewAction = popup.addAction(
  3190. QTStr("ShowInMultiview"));
  3191. OBSSource source = GetCurrentSceneSource();
  3192. OBSData data = obs_source_get_private_settings(source);
  3193. obs_data_release(data);
  3194. obs_data_set_default_bool(data, "show_in_multiview",
  3195. true);
  3196. bool show = obs_data_get_bool(data, "show_in_multiview");
  3197. multiviewAction->setCheckable(true);
  3198. multiviewAction->setChecked(show);
  3199. auto showInMultiview = [] (OBSData data)
  3200. {
  3201. bool show = obs_data_get_bool(data,
  3202. "show_in_multiview");
  3203. obs_data_set_bool(data, "show_in_multiview",
  3204. !show);
  3205. OBSProjector::UpdateMultiviewProjectors();
  3206. };
  3207. connect(multiviewAction, &QAction::triggered,
  3208. std::bind(showInMultiview, data));
  3209. }
  3210. popup.exec(QCursor::pos());
  3211. }
  3212. void OBSBasic::on_actionAddScene_triggered()
  3213. {
  3214. string name;
  3215. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3216. int i = 2;
  3217. QString placeHolderText = format.arg(i);
  3218. obs_source_t *source = nullptr;
  3219. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3220. obs_source_release(source);
  3221. placeHolderText = format.arg(++i);
  3222. }
  3223. bool accepted = NameDialog::AskForName(this,
  3224. QTStr("Basic.Main.AddSceneDlg.Title"),
  3225. QTStr("Basic.Main.AddSceneDlg.Text"),
  3226. name,
  3227. placeHolderText);
  3228. if (accepted) {
  3229. if (name.empty()) {
  3230. OBSMessageBox::information(this,
  3231. QTStr("NoNameEntered.Title"),
  3232. QTStr("NoNameEntered.Text"));
  3233. on_actionAddScene_triggered();
  3234. return;
  3235. }
  3236. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3237. if (source) {
  3238. OBSMessageBox::information(this,
  3239. QTStr("NameExists.Title"),
  3240. QTStr("NameExists.Text"));
  3241. obs_source_release(source);
  3242. on_actionAddScene_triggered();
  3243. return;
  3244. }
  3245. obs_scene_t *scene = obs_scene_create(name.c_str());
  3246. source = obs_scene_get_source(scene);
  3247. SetCurrentScene(source);
  3248. obs_scene_release(scene);
  3249. }
  3250. }
  3251. void OBSBasic::on_actionRemoveScene_triggered()
  3252. {
  3253. OBSScene scene = GetCurrentScene();
  3254. obs_source_t *source = obs_scene_get_source(scene);
  3255. if (source && QueryRemoveSource(source))
  3256. obs_source_remove(source);
  3257. }
  3258. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3259. {
  3260. int idx = ui->scenes->currentRow();
  3261. if (idx == -1 || idx == invalidIdx)
  3262. return;
  3263. sceneChanging = true;
  3264. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3265. if (!relative)
  3266. idx = 0;
  3267. ui->scenes->insertItem(idx + offset, item);
  3268. ui->scenes->setCurrentRow(idx + offset);
  3269. item->setSelected(true);
  3270. sceneChanging = false;
  3271. OBSProjector::UpdateMultiviewProjectors();
  3272. }
  3273. void OBSBasic::on_actionSceneUp_triggered()
  3274. {
  3275. ChangeSceneIndex(true, -1, 0);
  3276. }
  3277. void OBSBasic::on_actionSceneDown_triggered()
  3278. {
  3279. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3280. }
  3281. void OBSBasic::MoveSceneToTop()
  3282. {
  3283. ChangeSceneIndex(false, 0, 0);
  3284. }
  3285. void OBSBasic::MoveSceneToBottom()
  3286. {
  3287. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3288. ui->scenes->count() - 1);
  3289. }
  3290. void OBSBasic::EditSceneItemName()
  3291. {
  3292. int idx = GetTopSelectedSourceItem();
  3293. ui->sources->Edit(idx);
  3294. }
  3295. void OBSBasic::SetDeinterlacingMode()
  3296. {
  3297. QAction *action = reinterpret_cast<QAction*>(sender());
  3298. obs_deinterlace_mode mode =
  3299. (obs_deinterlace_mode)action->property("mode").toInt();
  3300. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3301. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3302. obs_source_set_deinterlace_mode(source, mode);
  3303. }
  3304. void OBSBasic::SetDeinterlacingOrder()
  3305. {
  3306. QAction *action = reinterpret_cast<QAction*>(sender());
  3307. obs_deinterlace_field_order order =
  3308. (obs_deinterlace_field_order)action->property("order").toInt();
  3309. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3310. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3311. obs_source_set_deinterlace_field_order(source, order);
  3312. }
  3313. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3314. {
  3315. obs_deinterlace_mode deinterlaceMode =
  3316. obs_source_get_deinterlace_mode(source);
  3317. obs_deinterlace_field_order deinterlaceOrder =
  3318. obs_source_get_deinterlace_field_order(source);
  3319. QAction *action;
  3320. #define ADD_MODE(name, mode) \
  3321. action = menu->addAction(QTStr("" name), this, \
  3322. SLOT(SetDeinterlacingMode())); \
  3323. action->setProperty("mode", (int)mode); \
  3324. action->setCheckable(true); \
  3325. action->setChecked(deinterlaceMode == mode);
  3326. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3327. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3328. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3329. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3330. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3331. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3332. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3333. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3334. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3335. #undef ADD_MODE
  3336. menu->addSeparator();
  3337. #define ADD_ORDER(name, order) \
  3338. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3339. SLOT(SetDeinterlacingOrder())); \
  3340. action->setProperty("order", (int)order); \
  3341. action->setCheckable(true); \
  3342. action->setChecked(deinterlaceOrder == order);
  3343. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3344. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3345. #undef ADD_ORDER
  3346. return menu;
  3347. }
  3348. void OBSBasic::SetScaleFilter()
  3349. {
  3350. QAction *action = reinterpret_cast<QAction*>(sender());
  3351. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3352. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3353. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3354. }
  3355. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3356. {
  3357. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3358. QAction *action;
  3359. #define ADD_MODE(name, mode) \
  3360. action = menu->addAction(QTStr("" name), this, \
  3361. SLOT(SetScaleFilter())); \
  3362. action->setProperty("mode", (int)mode); \
  3363. action->setCheckable(true); \
  3364. action->setChecked(scaleFilter == mode);
  3365. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3366. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3367. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3368. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3369. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3370. #undef ADD_MODE
  3371. return menu;
  3372. }
  3373. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction,
  3374. ColorSelect *select, obs_sceneitem_t *item)
  3375. {
  3376. QAction *action;
  3377. menu->setStyleSheet(QString(
  3378. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" \
  3379. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" \
  3380. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" \
  3381. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" \
  3382. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" \
  3383. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" \
  3384. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" \
  3385. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3386. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3387. obs_data_release(privData);
  3388. obs_data_set_default_int(privData, "color-preset", 0);
  3389. int preset = obs_data_get_int(privData, "color-preset");
  3390. action = menu->addAction(QTStr("Clear"), this,
  3391. + SLOT(ColorChange()));
  3392. action->setCheckable(true);
  3393. action->setProperty("bgColor", 0);
  3394. action->setChecked(preset == 0);
  3395. action = menu->addAction(QTStr("CustomColor"), this,
  3396. + SLOT(ColorChange()));
  3397. action->setCheckable(true);
  3398. action->setProperty("bgColor", 1);
  3399. action->setChecked(preset == 1);
  3400. menu->addSeparator();
  3401. widgetAction->setDefaultWidget(select);
  3402. for (int i = 1; i < 9; i++) {
  3403. stringstream button;
  3404. button << "preset" << i;
  3405. QPushButton *colorButton = select->findChild<QPushButton *>(
  3406. button.str().c_str());
  3407. if (preset == i + 1)
  3408. colorButton->setStyleSheet("border: 2px solid black");
  3409. colorButton->setProperty("bgColor", i);
  3410. select->connect(colorButton, SIGNAL(released()), this,
  3411. SLOT(ColorChange()));
  3412. }
  3413. menu->addAction(widgetAction);
  3414. return menu;
  3415. }
  3416. ColorSelect::ColorSelect(QWidget *parent)
  3417. : QWidget(parent),
  3418. ui(new Ui::ColorSelect)
  3419. {
  3420. ui->setupUi(this);
  3421. }
  3422. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3423. {
  3424. QMenu popup(this);
  3425. delete previewProjectorSource;
  3426. delete sourceProjector;
  3427. delete scaleFilteringMenu;
  3428. delete colorMenu;
  3429. delete colorWidgetAction;
  3430. delete colorSelect;
  3431. delete deinterlaceMenu;
  3432. if (preview) {
  3433. QAction *action = popup.addAction(
  3434. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3435. this, SLOT(TogglePreview()));
  3436. action->setCheckable(true);
  3437. action->setChecked(
  3438. obs_display_enabled(ui->preview->GetDisplay()));
  3439. if (IsPreviewProgramMode())
  3440. action->setEnabled(false);
  3441. popup.addAction(ui->actionLockPreview);
  3442. popup.addMenu(ui->scalingMenu);
  3443. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3444. AddProjectorMenuMonitors(previewProjectorSource, this,
  3445. SLOT(OpenPreviewProjector()));
  3446. popup.addMenu(previewProjectorSource);
  3447. QAction *previewWindow = popup.addAction(
  3448. QTStr("PreviewWindow"),
  3449. this, SLOT(OpenPreviewWindow()));
  3450. popup.addAction(previewWindow);
  3451. popup.addSeparator();
  3452. }
  3453. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3454. if (addSourceMenu)
  3455. popup.addMenu(addSourceMenu);
  3456. ui->actionCopyFilters->setEnabled(false);
  3457. ui->actionCopySource->setEnabled(false);
  3458. if (ui->sources->MultipleBaseSelected()) {
  3459. popup.addSeparator();
  3460. popup.addAction(QTStr("Basic.Main.GroupItems"),
  3461. ui->sources, SLOT(GroupSelectedItems()));
  3462. } else if (ui->sources->GroupsSelected()) {
  3463. popup.addSeparator();
  3464. popup.addAction(QTStr("Basic.Main.Ungroup"),
  3465. ui->sources, SLOT(UngroupSelectedGroups()));
  3466. }
  3467. popup.addSeparator();
  3468. popup.addAction(ui->actionCopySource);
  3469. popup.addAction(ui->actionPasteRef);
  3470. popup.addAction(ui->actionPasteDup);
  3471. popup.addSeparator();
  3472. popup.addSeparator();
  3473. popup.addAction(ui->actionCopyFilters);
  3474. popup.addAction(ui->actionPasteFilters);
  3475. popup.addSeparator();
  3476. if (idx != -1) {
  3477. if (addSourceMenu)
  3478. popup.addSeparator();
  3479. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3480. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3481. uint32_t flags = obs_source_get_output_flags(source);
  3482. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3483. OBS_SOURCE_ASYNC_VIDEO;
  3484. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  3485. OBS_SOURCE_AUDIO;
  3486. QAction *action;
  3487. colorMenu = new QMenu(QTStr("ChangeBG"));
  3488. colorWidgetAction = new QWidgetAction(colorMenu);
  3489. colorSelect = new ColorSelect(colorMenu);
  3490. popup.addMenu(AddBackgroundColorMenu(colorMenu,
  3491. colorWidgetAction, colorSelect, sceneItem));
  3492. popup.addAction(QTStr("Rename"), this,
  3493. SLOT(EditSceneItemName()));
  3494. popup.addAction(QTStr("Remove"), this,
  3495. SLOT(on_actionRemoveSource_triggered()));
  3496. popup.addSeparator();
  3497. popup.addMenu(ui->orderMenu);
  3498. popup.addMenu(ui->transformMenu);
  3499. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3500. AddProjectorMenuMonitors(sourceProjector, this,
  3501. SLOT(OpenSourceProjector()));
  3502. QAction *sourceWindow = popup.addAction(
  3503. QTStr("SourceWindow"),
  3504. this, SLOT(OpenSourceWindow()));
  3505. popup.addAction(sourceWindow);
  3506. popup.addSeparator();
  3507. if (hasAudio) {
  3508. QAction *actionHideMixer = popup.addAction(
  3509. QTStr("HideMixer"),
  3510. this, SLOT(ToggleHideMixer()));
  3511. actionHideMixer->setCheckable(true);
  3512. actionHideMixer->setChecked(SourceMixerHidden(source));
  3513. }
  3514. if (isAsyncVideo) {
  3515. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3516. popup.addMenu(AddDeinterlacingMenu(deinterlaceMenu, source));
  3517. popup.addSeparator();
  3518. }
  3519. QAction *resizeOutput = popup.addAction(
  3520. QTStr("ResizeOutputSizeOfSource"), this,
  3521. SLOT(ResizeOutputSizeOfSource()));
  3522. int width = obs_source_get_width(source);
  3523. int height = obs_source_get_height(source);
  3524. resizeOutput->setEnabled(!(ui->streamButton->isChecked() ||
  3525. ui->recordButton->isChecked() ||
  3526. (replayBufferButton &&
  3527. replayBufferButton->isChecked())));
  3528. if (width == 0 || height == 0)
  3529. resizeOutput->setEnabled(false);
  3530. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3531. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3532. popup.addSeparator();
  3533. popup.addMenu(sourceProjector);
  3534. popup.addAction(sourceWindow);
  3535. popup.addSeparator();
  3536. action = popup.addAction(QTStr("Interact"), this,
  3537. SLOT(on_actionInteract_triggered()));
  3538. action->setEnabled(obs_source_get_output_flags(source) &
  3539. OBS_SOURCE_INTERACTION);
  3540. popup.addAction(QTStr("Filters"), this,
  3541. SLOT(OpenFilters()));
  3542. popup.addAction(QTStr("Properties"), this,
  3543. SLOT(on_actionSourceProperties_triggered()));
  3544. ui->actionCopyFilters->setEnabled(true);
  3545. ui->actionCopySource->setEnabled(true);
  3546. } else {
  3547. ui->actionPasteFilters->setEnabled(false);
  3548. }
  3549. popup.exec(QCursor::pos());
  3550. }
  3551. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3552. {
  3553. if (ui->scenes->count()) {
  3554. QModelIndex idx = ui->sources->indexAt(pos);
  3555. CreateSourcePopupMenu(idx.row(), false);
  3556. }
  3557. }
  3558. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3559. {
  3560. if (!witem)
  3561. return;
  3562. if (IsPreviewProgramMode()) {
  3563. bool doubleClickSwitch = config_get_bool(App()->GlobalConfig(),
  3564. "BasicWindow", "TransitionOnDoubleClick");
  3565. if (doubleClickSwitch) {
  3566. OBSScene scene = GetCurrentScene();
  3567. if (scene)
  3568. SetCurrentScene(scene, false, true);
  3569. }
  3570. }
  3571. }
  3572. void OBSBasic::AddSource(const char *id)
  3573. {
  3574. if (id && *id) {
  3575. OBSBasicSourceSelect sourceSelect(this, id);
  3576. sourceSelect.exec();
  3577. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3578. CreatePropertiesWindow(sourceSelect.newSource);
  3579. }
  3580. }
  3581. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3582. {
  3583. const char *type;
  3584. bool foundValues = false;
  3585. bool foundDeprecated = false;
  3586. size_t idx = 0;
  3587. QMenu *popup = new QMenu(QTStr("Add"), this);
  3588. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3589. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3590. {
  3591. QList<QAction*> actions = menu->actions();
  3592. for (QAction *menuAction : actions) {
  3593. if (menuAction->text().compare(name) >= 0)
  3594. return menuAction;
  3595. }
  3596. return (QAction*)nullptr;
  3597. };
  3598. auto addSource = [this, getActionAfter] (QMenu *popup,
  3599. const char *type, const char *name)
  3600. {
  3601. QString qname = QT_UTF8(name);
  3602. QAction *popupItem = new QAction(qname, this);
  3603. popupItem->setData(QT_UTF8(type));
  3604. connect(popupItem, SIGNAL(triggered(bool)),
  3605. this, SLOT(AddSourceFromAction()));
  3606. QAction *after = getActionAfter(popup, qname);
  3607. popup->insertAction(after, popupItem);
  3608. };
  3609. while (obs_enum_input_types(idx++, &type)) {
  3610. const char *name = obs_source_get_display_name(type);
  3611. uint32_t caps = obs_get_source_output_flags(type);
  3612. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3613. continue;
  3614. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3615. addSource(popup, type, name);
  3616. } else {
  3617. addSource(deprecated, type, name);
  3618. foundDeprecated = true;
  3619. }
  3620. foundValues = true;
  3621. }
  3622. addSource(popup, "scene", Str("Basic.Scene"));
  3623. popup->addSeparator();
  3624. QAction *addGroup = new QAction(QTStr("Group"), this);
  3625. addGroup->setData(QT_UTF8("group"));
  3626. connect(addGroup, SIGNAL(triggered(bool)),
  3627. this, SLOT(AddSourceFromAction()));
  3628. popup->addAction(addGroup);
  3629. if (!foundDeprecated) {
  3630. delete deprecated;
  3631. deprecated = nullptr;
  3632. }
  3633. if (!foundValues) {
  3634. delete popup;
  3635. popup = nullptr;
  3636. } else if (foundDeprecated) {
  3637. popup->addSeparator();
  3638. popup->addMenu(deprecated);
  3639. }
  3640. return popup;
  3641. }
  3642. void OBSBasic::AddSourceFromAction()
  3643. {
  3644. QAction *action = qobject_cast<QAction*>(sender());
  3645. if (!action)
  3646. return;
  3647. AddSource(QT_TO_UTF8(action->data().toString()));
  3648. }
  3649. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3650. {
  3651. if (!GetCurrentScene()) {
  3652. // Tell the user he needs a scene first (help beginners).
  3653. OBSMessageBox::information(this,
  3654. QTStr("Basic.Main.AddSourceHelp.Title"),
  3655. QTStr("Basic.Main.AddSourceHelp.Text"));
  3656. return;
  3657. }
  3658. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3659. if (popup)
  3660. popup->exec(pos);
  3661. }
  3662. void OBSBasic::on_actionAddSource_triggered()
  3663. {
  3664. AddSourcePopupMenu(QCursor::pos());
  3665. }
  3666. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3667. {
  3668. vector<OBSSceneItem> &items =
  3669. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3670. if (obs_sceneitem_selected(item)) {
  3671. items.emplace_back(item);
  3672. } else if (obs_sceneitem_is_group(item)) {
  3673. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3674. }
  3675. return true;
  3676. };
  3677. void OBSBasic::on_actionRemoveSource_triggered()
  3678. {
  3679. vector<OBSSceneItem> items;
  3680. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3681. if (!items.size())
  3682. return;
  3683. auto removeMultiple = [this] (size_t count)
  3684. {
  3685. QString text = QTStr("ConfirmRemove.TextMultiple")
  3686. .arg(QString::number(count));
  3687. QMessageBox remove_items(this);
  3688. remove_items.setText(text);
  3689. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3690. QMessageBox::YesRole);
  3691. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3692. remove_items.setIcon(QMessageBox::Question);
  3693. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3694. remove_items.exec();
  3695. return Yes == remove_items.clickedButton();
  3696. };
  3697. if (items.size() == 1) {
  3698. OBSSceneItem &item = items[0];
  3699. obs_source_t *source = obs_sceneitem_get_source(item);
  3700. if (source && QueryRemoveSource(source))
  3701. obs_sceneitem_remove(item);
  3702. } else {
  3703. if (removeMultiple(items.size())) {
  3704. for (auto &item : items)
  3705. obs_sceneitem_remove(item);
  3706. }
  3707. }
  3708. }
  3709. void OBSBasic::on_actionInteract_triggered()
  3710. {
  3711. OBSSceneItem item = GetCurrentSceneItem();
  3712. OBSSource source = obs_sceneitem_get_source(item);
  3713. if (source)
  3714. CreateInteractionWindow(source);
  3715. }
  3716. void OBSBasic::on_actionSourceProperties_triggered()
  3717. {
  3718. OBSSceneItem item = GetCurrentSceneItem();
  3719. OBSSource source = obs_sceneitem_get_source(item);
  3720. if (source)
  3721. CreatePropertiesWindow(source);
  3722. }
  3723. void OBSBasic::on_actionSourceUp_triggered()
  3724. {
  3725. OBSSceneItem item = GetCurrentSceneItem();
  3726. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3727. }
  3728. void OBSBasic::on_actionSourceDown_triggered()
  3729. {
  3730. OBSSceneItem item = GetCurrentSceneItem();
  3731. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3732. }
  3733. void OBSBasic::on_actionMoveUp_triggered()
  3734. {
  3735. OBSSceneItem item = GetCurrentSceneItem();
  3736. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3737. }
  3738. void OBSBasic::on_actionMoveDown_triggered()
  3739. {
  3740. OBSSceneItem item = GetCurrentSceneItem();
  3741. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3742. }
  3743. void OBSBasic::on_actionMoveToTop_triggered()
  3744. {
  3745. OBSSceneItem item = GetCurrentSceneItem();
  3746. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3747. }
  3748. void OBSBasic::on_actionMoveToBottom_triggered()
  3749. {
  3750. OBSSceneItem item = GetCurrentSceneItem();
  3751. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3752. }
  3753. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3754. {
  3755. char logDir[512];
  3756. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3757. return nullptr;
  3758. string path = (char*)logDir;
  3759. path += "/";
  3760. path += log;
  3761. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3762. if (!file)
  3763. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3764. return file;
  3765. }
  3766. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3767. {
  3768. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3769. if (!fileString)
  3770. return;
  3771. if (!*fileString)
  3772. return;
  3773. ui->menuLogFiles->setEnabled(false);
  3774. stringstream ss;
  3775. ss << "OBS " << App()->GetVersionString()
  3776. << " log file uploaded at " << CurrentDateTimeString()
  3777. << "\n\n" << fileString;
  3778. if (logUploadThread) {
  3779. logUploadThread->wait();
  3780. }
  3781. RemoteTextThread *thread = new RemoteTextThread(
  3782. "https://obsproject.com/logs/upload",
  3783. "text/plain", ss.str().c_str());
  3784. logUploadThread.reset(thread);
  3785. connect(thread, &RemoteTextThread::Result,
  3786. this, &OBSBasic::logUploadFinished);
  3787. logUploadThread->start();
  3788. }
  3789. void OBSBasic::on_actionShowLogs_triggered()
  3790. {
  3791. char logDir[512];
  3792. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3793. return;
  3794. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3795. QDesktopServices::openUrl(url);
  3796. }
  3797. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3798. {
  3799. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3800. }
  3801. void OBSBasic::on_actionUploadLastLog_triggered()
  3802. {
  3803. UploadLog("obs-studio/logs", App()->GetLastLog());
  3804. }
  3805. void OBSBasic::on_actionViewCurrentLog_triggered()
  3806. {
  3807. char logDir[512];
  3808. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3809. return;
  3810. const char* log = App()->GetCurrentLog();
  3811. string path = (char*)logDir;
  3812. path += "/";
  3813. path += log;
  3814. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3815. QDesktopServices::openUrl(url);
  3816. }
  3817. void OBSBasic::on_actionShowCrashLogs_triggered()
  3818. {
  3819. char logDir[512];
  3820. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3821. return;
  3822. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3823. QDesktopServices::openUrl(url);
  3824. }
  3825. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3826. {
  3827. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3828. }
  3829. void OBSBasic::on_actionCheckForUpdates_triggered()
  3830. {
  3831. CheckForUpdates(true);
  3832. }
  3833. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3834. {
  3835. ui->menuLogFiles->setEnabled(true);
  3836. if (text.isEmpty()) {
  3837. OBSMessageBox::information(this,
  3838. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3839. error);
  3840. return;
  3841. }
  3842. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3843. string resURL = obs_data_get_string(returnData, "url");
  3844. QString logURL = resURL.c_str();
  3845. obs_data_release(returnData);
  3846. OBSLogReply logDialog(this, logURL);
  3847. logDialog.exec();
  3848. }
  3849. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3850. obs_source_t *source, const string &name)
  3851. {
  3852. const char *prevName = obs_source_get_name(source);
  3853. if (name == prevName)
  3854. return;
  3855. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3856. QListWidgetItem *listItem = listWidget->currentItem();
  3857. if (foundSource || name.empty()) {
  3858. listItem->setText(QT_UTF8(prevName));
  3859. if (foundSource) {
  3860. OBSMessageBox::information(parent,
  3861. QTStr("NameExists.Title"),
  3862. QTStr("NameExists.Text"));
  3863. } else if (name.empty()) {
  3864. OBSMessageBox::information(parent,
  3865. QTStr("NoNameEntered.Title"),
  3866. QTStr("NoNameEntered.Text"));
  3867. }
  3868. obs_source_release(foundSource);
  3869. } else {
  3870. listItem->setText(QT_UTF8(name.c_str()));
  3871. obs_source_set_name(source, name.c_str());
  3872. }
  3873. }
  3874. void OBSBasic::SceneNameEdited(QWidget *editor,
  3875. QAbstractItemDelegate::EndEditHint endHint)
  3876. {
  3877. OBSScene scene = GetCurrentScene();
  3878. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3879. string text = QT_TO_UTF8(edit->text().trimmed());
  3880. if (!scene)
  3881. return;
  3882. obs_source_t *source = obs_scene_get_source(scene);
  3883. RenameListItem(this, ui->scenes, source, text);
  3884. if (api)
  3885. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3886. UNUSED_PARAMETER(endHint);
  3887. }
  3888. void OBSBasic::OpenFilters()
  3889. {
  3890. OBSSceneItem item = GetCurrentSceneItem();
  3891. OBSSource source = obs_sceneitem_get_source(item);
  3892. CreateFiltersWindow(source);
  3893. }
  3894. void OBSBasic::OpenSceneFilters()
  3895. {
  3896. OBSScene scene = GetCurrentScene();
  3897. OBSSource source = obs_scene_get_source(scene);
  3898. CreateFiltersWindow(source);
  3899. }
  3900. #define RECORDING_START \
  3901. "==== Recording Start ==============================================="
  3902. #define RECORDING_STOP \
  3903. "==== Recording Stop ================================================"
  3904. #define REPLAY_BUFFER_START \
  3905. "==== Replay Buffer Start ==========================================="
  3906. #define REPLAY_BUFFER_STOP \
  3907. "==== Replay Buffer Stop ============================================"
  3908. #define STREAMING_START \
  3909. "==== Streaming Start ==============================================="
  3910. #define STREAMING_STOP \
  3911. "==== Streaming Stop ================================================"
  3912. void OBSBasic::StartStreaming()
  3913. {
  3914. if (outputHandler->StreamingActive())
  3915. return;
  3916. if (disableOutputsRef)
  3917. return;
  3918. if (api)
  3919. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3920. SaveProject();
  3921. ui->streamButton->setEnabled(false);
  3922. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3923. if (sysTrayStream) {
  3924. sysTrayStream->setEnabled(false);
  3925. sysTrayStream->setText(ui->streamButton->text());
  3926. }
  3927. if (!outputHandler->StartStreaming(service)) {
  3928. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3929. ui->streamButton->setEnabled(true);
  3930. ui->streamButton->setChecked(false);
  3931. if (sysTrayStream) {
  3932. sysTrayStream->setText(ui->streamButton->text());
  3933. sysTrayStream->setEnabled(true);
  3934. }
  3935. QMessageBox::critical(this,
  3936. QTStr("Output.StartStreamFailed"),
  3937. QTStr("Output.StartFailedGeneric"));
  3938. return;
  3939. }
  3940. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3941. "BasicWindow", "RecordWhenStreaming");
  3942. if (recordWhenStreaming)
  3943. StartRecording();
  3944. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3945. "BasicWindow", "ReplayBufferWhileStreaming");
  3946. if (replayBufferWhileStreaming)
  3947. StartReplayBuffer();
  3948. }
  3949. #ifdef _WIN32
  3950. static inline void UpdateProcessPriority()
  3951. {
  3952. const char *priority = config_get_string(App()->GlobalConfig(),
  3953. "General", "ProcessPriority");
  3954. if (priority && strcmp(priority, "Normal") != 0)
  3955. SetProcessPriority(priority);
  3956. }
  3957. static inline void ClearProcessPriority()
  3958. {
  3959. const char *priority = config_get_string(App()->GlobalConfig(),
  3960. "General", "ProcessPriority");
  3961. if (priority && strcmp(priority, "Normal") != 0)
  3962. SetProcessPriority("Normal");
  3963. }
  3964. #else
  3965. #define UpdateProcessPriority() do {} while(false)
  3966. #define ClearProcessPriority() do {} while(false)
  3967. #endif
  3968. inline void OBSBasic::OnActivate()
  3969. {
  3970. if (ui->profileMenu->isEnabled()) {
  3971. ui->profileMenu->setEnabled(false);
  3972. ui->autoConfigure->setEnabled(false);
  3973. App()->IncrementSleepInhibition();
  3974. UpdateProcessPriority();
  3975. if (trayIcon)
  3976. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3977. }
  3978. }
  3979. inline void OBSBasic::OnDeactivate()
  3980. {
  3981. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3982. ui->profileMenu->setEnabled(true);
  3983. ui->autoConfigure->setEnabled(true);
  3984. App()->DecrementSleepInhibition();
  3985. ClearProcessPriority();
  3986. if (trayIcon)
  3987. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3988. }
  3989. }
  3990. void OBSBasic::StopStreaming()
  3991. {
  3992. SaveProject();
  3993. if (outputHandler->StreamingActive())
  3994. outputHandler->StopStreaming(streamingStopping);
  3995. OnDeactivate();
  3996. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3997. "BasicWindow", "RecordWhenStreaming");
  3998. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3999. "BasicWindow", "KeepRecordingWhenStreamStops");
  4000. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4001. StopRecording();
  4002. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4003. "BasicWindow", "ReplayBufferWhileStreaming");
  4004. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4005. "BasicWindow", "KeepReplayBufferStreamStops");
  4006. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4007. StopReplayBuffer();
  4008. }
  4009. void OBSBasic::ForceStopStreaming()
  4010. {
  4011. SaveProject();
  4012. if (outputHandler->StreamingActive())
  4013. outputHandler->StopStreaming(true);
  4014. OnDeactivate();
  4015. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  4016. "BasicWindow", "RecordWhenStreaming");
  4017. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  4018. "BasicWindow", "KeepRecordingWhenStreamStops");
  4019. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4020. StopRecording();
  4021. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  4022. "BasicWindow", "ReplayBufferWhileStreaming");
  4023. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  4024. "BasicWindow", "KeepReplayBufferStreamStops");
  4025. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4026. StopReplayBuffer();
  4027. }
  4028. void OBSBasic::StreamDelayStarting(int sec)
  4029. {
  4030. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4031. ui->streamButton->setEnabled(true);
  4032. ui->streamButton->setChecked(true);
  4033. if (sysTrayStream) {
  4034. sysTrayStream->setText(ui->streamButton->text());
  4035. sysTrayStream->setEnabled(true);
  4036. }
  4037. if (!startStreamMenu.isNull())
  4038. startStreamMenu->deleteLater();
  4039. startStreamMenu = new QMenu();
  4040. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  4041. this, SLOT(StopStreaming()));
  4042. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4043. this, SLOT(ForceStopStreaming()));
  4044. ui->streamButton->setMenu(startStreamMenu);
  4045. ui->statusbar->StreamDelayStarting(sec);
  4046. OnActivate();
  4047. }
  4048. void OBSBasic::StreamDelayStopping(int sec)
  4049. {
  4050. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4051. ui->streamButton->setEnabled(true);
  4052. ui->streamButton->setChecked(false);
  4053. if (sysTrayStream) {
  4054. sysTrayStream->setText(ui->streamButton->text());
  4055. sysTrayStream->setEnabled(true);
  4056. }
  4057. if (!startStreamMenu.isNull())
  4058. startStreamMenu->deleteLater();
  4059. startStreamMenu = new QMenu();
  4060. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  4061. this, SLOT(StartStreaming()));
  4062. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  4063. this, SLOT(ForceStopStreaming()));
  4064. ui->streamButton->setMenu(startStreamMenu);
  4065. ui->statusbar->StreamDelayStopping(sec);
  4066. if (api)
  4067. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4068. }
  4069. void OBSBasic::StreamingStart()
  4070. {
  4071. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4072. ui->streamButton->setEnabled(true);
  4073. ui->streamButton->setChecked(true);
  4074. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4075. if (sysTrayStream) {
  4076. sysTrayStream->setText(ui->streamButton->text());
  4077. sysTrayStream->setEnabled(true);
  4078. }
  4079. if (api)
  4080. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4081. OnActivate();
  4082. blog(LOG_INFO, STREAMING_START);
  4083. }
  4084. void OBSBasic::StreamStopping()
  4085. {
  4086. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4087. if (sysTrayStream)
  4088. sysTrayStream->setText(ui->streamButton->text());
  4089. streamingStopping = true;
  4090. if (api)
  4091. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4092. }
  4093. void OBSBasic::StreamingStop(int code, QString last_error)
  4094. {
  4095. const char *errorDescription;
  4096. DStr errorMessage;
  4097. bool use_last_error = false;
  4098. switch (code) {
  4099. case OBS_OUTPUT_BAD_PATH:
  4100. errorDescription = Str("Output.ConnectFail.BadPath");
  4101. break;
  4102. case OBS_OUTPUT_CONNECT_FAILED:
  4103. use_last_error = true;
  4104. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4105. break;
  4106. case OBS_OUTPUT_INVALID_STREAM:
  4107. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4108. break;
  4109. default:
  4110. case OBS_OUTPUT_ERROR:
  4111. use_last_error = true;
  4112. errorDescription = Str("Output.ConnectFail.Error");
  4113. break;
  4114. case OBS_OUTPUT_DISCONNECTED:
  4115. /* doesn't happen if output is set to reconnect. note that
  4116. * reconnects are handled in the output, not in the UI */
  4117. use_last_error = true;
  4118. errorDescription = Str("Output.ConnectFail.Disconnected");
  4119. }
  4120. if (use_last_error && !last_error.isEmpty())
  4121. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4122. QT_TO_UTF8(last_error));
  4123. else
  4124. dstr_copy(errorMessage, errorDescription);
  4125. ui->statusbar->StreamStopped();
  4126. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4127. ui->streamButton->setEnabled(true);
  4128. ui->streamButton->setChecked(false);
  4129. if (sysTrayStream) {
  4130. sysTrayStream->setText(ui->streamButton->text());
  4131. sysTrayStream->setEnabled(true);
  4132. }
  4133. streamingStopping = false;
  4134. if (api)
  4135. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4136. OnDeactivate();
  4137. blog(LOG_INFO, STREAMING_STOP);
  4138. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4139. OBSMessageBox::information(this,
  4140. QTStr("Output.ConnectFail.Title"),
  4141. QT_UTF8(errorMessage));
  4142. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4143. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  4144. }
  4145. if (!startStreamMenu.isNull()) {
  4146. ui->streamButton->setMenu(nullptr);
  4147. startStreamMenu->deleteLater();
  4148. startStreamMenu = nullptr;
  4149. }
  4150. }
  4151. void OBSBasic::AutoRemux()
  4152. {
  4153. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4154. const char *path = strcmp(mode, "Advanced") ?
  4155. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  4156. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  4157. std::string s(path);
  4158. s += "/";
  4159. s += remuxFilename;
  4160. const QString &str = QString::fromStdString(s);
  4161. QString file = str.section(".", 0, 0);
  4162. OBSRemux *remux = new OBSRemux(path, this, true);
  4163. remux->show();
  4164. remux->AutoRemux(str, file + ".mp4");
  4165. }
  4166. void OBSBasic::StartRecording()
  4167. {
  4168. if (outputHandler->RecordingActive())
  4169. return;
  4170. if (disableOutputsRef)
  4171. return;
  4172. if (api)
  4173. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4174. SaveProject();
  4175. if (!outputHandler->StartRecording())
  4176. ui->recordButton->setChecked(false);
  4177. }
  4178. void OBSBasic::RecordStopping()
  4179. {
  4180. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4181. if (sysTrayRecord)
  4182. sysTrayRecord->setText(ui->recordButton->text());
  4183. recordingStopping = true;
  4184. if (api)
  4185. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4186. }
  4187. void OBSBasic::StopRecording()
  4188. {
  4189. SaveProject();
  4190. if (outputHandler->RecordingActive())
  4191. outputHandler->StopRecording(recordingStopping);
  4192. OnDeactivate();
  4193. }
  4194. void OBSBasic::RecordingStart()
  4195. {
  4196. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4197. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4198. ui->recordButton->setChecked(true);
  4199. if (sysTrayRecord)
  4200. sysTrayRecord->setText(ui->recordButton->text());
  4201. recordingStopping = false;
  4202. if (api)
  4203. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4204. OnActivate();
  4205. blog(LOG_INFO, RECORDING_START);
  4206. }
  4207. void OBSBasic::RecordingStop(int code)
  4208. {
  4209. ui->statusbar->RecordingStopped();
  4210. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4211. ui->recordButton->setChecked(false);
  4212. if (sysTrayRecord)
  4213. sysTrayRecord->setText(ui->recordButton->text());
  4214. blog(LOG_INFO, RECORDING_STOP);
  4215. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4216. OBSMessageBox::information(this,
  4217. QTStr("Output.RecordFail.Title"),
  4218. QTStr("Output.RecordFail.Unsupported"));
  4219. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4220. OBSMessageBox::information(this,
  4221. QTStr("Output.RecordNoSpace.Title"),
  4222. QTStr("Output.RecordNoSpace.Msg"));
  4223. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4224. OBSMessageBox::information(this,
  4225. QTStr("Output.RecordError.Title"),
  4226. QTStr("Output.RecordError.Msg"));
  4227. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4228. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4229. QSystemTrayIcon::Warning);
  4230. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4231. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4232. QSystemTrayIcon::Warning);
  4233. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4234. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4235. QSystemTrayIcon::Warning);
  4236. }
  4237. if (api)
  4238. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4239. if (remuxAfterRecord)
  4240. AutoRemux();
  4241. OnDeactivate();
  4242. }
  4243. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4244. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4245. void OBSBasic::StartReplayBuffer()
  4246. {
  4247. if (!outputHandler || !outputHandler->replayBuffer)
  4248. return;
  4249. if (outputHandler->ReplayBufferActive())
  4250. return;
  4251. if (disableOutputsRef)
  4252. return;
  4253. if (!NoSourcesConfirmation()) {
  4254. replayBufferButton->setChecked(false);
  4255. return;
  4256. }
  4257. obs_output_t *output = outputHandler->replayBuffer;
  4258. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4259. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  4260. "ReplayBuffer.Save");
  4261. size_t count = obs_data_array_count(bindings);
  4262. obs_data_array_release(bindings);
  4263. obs_data_release(hotkeys);
  4264. if (!count) {
  4265. OBSMessageBox::information(this,
  4266. RP_NO_HOTKEY_TITLE,
  4267. RP_NO_HOTKEY_TEXT);
  4268. return;
  4269. }
  4270. if (api)
  4271. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4272. SaveProject();
  4273. if (!outputHandler->StartReplayBuffer())
  4274. replayBufferButton->setChecked(false);
  4275. }
  4276. void OBSBasic::ReplayBufferStopping()
  4277. {
  4278. if (!outputHandler || !outputHandler->replayBuffer)
  4279. return;
  4280. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4281. if (sysTrayReplayBuffer)
  4282. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4283. replayBufferStopping = true;
  4284. if (api)
  4285. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4286. }
  4287. void OBSBasic::StopReplayBuffer()
  4288. {
  4289. if (!outputHandler || !outputHandler->replayBuffer)
  4290. return;
  4291. SaveProject();
  4292. if (outputHandler->ReplayBufferActive())
  4293. outputHandler->StopReplayBuffer(replayBufferStopping);
  4294. OnDeactivate();
  4295. }
  4296. void OBSBasic::ReplayBufferStart()
  4297. {
  4298. if (!outputHandler || !outputHandler->replayBuffer)
  4299. return;
  4300. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4301. if (sysTrayReplayBuffer)
  4302. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4303. replayBufferStopping = false;
  4304. if (api)
  4305. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4306. OnActivate();
  4307. blog(LOG_INFO, REPLAY_BUFFER_START);
  4308. }
  4309. void OBSBasic::ReplayBufferSave()
  4310. {
  4311. if (!outputHandler || !outputHandler->replayBuffer)
  4312. return;
  4313. if (!outputHandler->ReplayBufferActive())
  4314. return;
  4315. calldata_t cd = {0};
  4316. proc_handler_t *ph = obs_output_get_proc_handler(
  4317. outputHandler->replayBuffer);
  4318. proc_handler_call(ph, "save", &cd);
  4319. calldata_free(&cd);
  4320. }
  4321. void OBSBasic::ReplayBufferStop(int code)
  4322. {
  4323. if (!outputHandler || !outputHandler->replayBuffer)
  4324. return;
  4325. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4326. if (sysTrayReplayBuffer)
  4327. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4328. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4329. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4330. OBSMessageBox::information(this,
  4331. QTStr("Output.RecordFail.Title"),
  4332. QTStr("Output.RecordFail.Unsupported"));
  4333. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4334. OBSMessageBox::information(this,
  4335. QTStr("Output.RecordNoSpace.Title"),
  4336. QTStr("Output.RecordNoSpace.Msg"));
  4337. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4338. OBSMessageBox::information(this,
  4339. QTStr("Output.RecordError.Title"),
  4340. QTStr("Output.RecordError.Msg"));
  4341. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4342. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4343. QSystemTrayIcon::Warning);
  4344. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4345. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4346. QSystemTrayIcon::Warning);
  4347. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4348. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4349. QSystemTrayIcon::Warning);
  4350. }
  4351. if (api)
  4352. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4353. OnDeactivate();
  4354. }
  4355. bool OBSBasic::NoSourcesConfirmation()
  4356. {
  4357. if (CountVideoSources() == 0 && isVisible()) {
  4358. QString msg;
  4359. msg = QTStr("NoSources.Text");
  4360. msg += "\n\n";
  4361. msg += QTStr("NoSources.Text.AddSource");
  4362. QMessageBox messageBox(QMessageBox::Question,
  4363. QTStr("NoSources.title"),
  4364. msg,
  4365. QMessageBox::Yes | QMessageBox::No,
  4366. this);
  4367. messageBox.setDefaultButton(QMessageBox::No);
  4368. if (QMessageBox::No == messageBox.exec())
  4369. return false;
  4370. }
  4371. return true;
  4372. }
  4373. void OBSBasic::on_streamButton_clicked()
  4374. {
  4375. if (outputHandler->StreamingActive()) {
  4376. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4377. "WarnBeforeStoppingStream");
  4378. if (confirm && isVisible()) {
  4379. QMessageBox::StandardButton button =
  4380. OBSMessageBox::question(this,
  4381. QTStr("ConfirmStop.Title"),
  4382. QTStr("ConfirmStop.Text"));
  4383. if (button == QMessageBox::No) {
  4384. ui->streamButton->setChecked(true);
  4385. return;
  4386. }
  4387. }
  4388. StopStreaming();
  4389. } else {
  4390. if (!NoSourcesConfirmation()) {
  4391. ui->streamButton->setChecked(false);
  4392. return;
  4393. }
  4394. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4395. "WarnBeforeStartingStream");
  4396. if (confirm && isVisible()) {
  4397. QMessageBox::StandardButton button =
  4398. OBSMessageBox::question(this,
  4399. QTStr("ConfirmStart.Title"),
  4400. QTStr("ConfirmStart.Text"));
  4401. if (button == QMessageBox::No) {
  4402. ui->streamButton->setChecked(false);
  4403. return;
  4404. }
  4405. }
  4406. StartStreaming();
  4407. }
  4408. }
  4409. void OBSBasic::on_recordButton_clicked()
  4410. {
  4411. if (outputHandler->RecordingActive()) {
  4412. StopRecording();
  4413. } else {
  4414. if (!NoSourcesConfirmation()) {
  4415. ui->recordButton->setChecked(false);
  4416. return;
  4417. }
  4418. StartRecording();
  4419. }
  4420. }
  4421. void OBSBasic::on_settingsButton_clicked()
  4422. {
  4423. on_action_Settings_triggered();
  4424. }
  4425. void OBSBasic::on_actionHelpPortal_triggered()
  4426. {
  4427. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4428. QDesktopServices::openUrl(url);
  4429. }
  4430. void OBSBasic::on_actionWebsite_triggered()
  4431. {
  4432. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4433. QDesktopServices::openUrl(url);
  4434. }
  4435. void OBSBasic::on_actionDiscord_triggered()
  4436. {
  4437. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4438. QDesktopServices::openUrl(url);
  4439. }
  4440. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4441. {
  4442. char path[512];
  4443. int ret = GetConfigPath(path, 512, "obs-studio");
  4444. if (ret <= 0)
  4445. return;
  4446. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4447. }
  4448. void OBSBasic::on_actionShowProfileFolder_triggered()
  4449. {
  4450. char path[512];
  4451. int ret = GetProfilePath(path, 512, "");
  4452. if (ret <= 0)
  4453. return;
  4454. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4455. }
  4456. int OBSBasic::GetTopSelectedSourceItem()
  4457. {
  4458. QModelIndexList selectedItems =
  4459. ui->sources->selectionModel()->selectedIndexes();
  4460. return selectedItems.count() ? selectedItems[0].row() : -1;
  4461. }
  4462. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4463. {
  4464. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4465. UNUSED_PARAMETER(pos);
  4466. }
  4467. void OBSBasic::on_program_customContextMenuRequested(const QPoint&)
  4468. {
  4469. QMenu popup(this);
  4470. QPointer<QMenu> studioProgramProjector;
  4471. studioProgramProjector = new QMenu(
  4472. QTStr("StudioProgramProjector"));
  4473. AddProjectorMenuMonitors(studioProgramProjector, this,
  4474. SLOT(OpenStudioProgramProjector()));
  4475. popup.addMenu(studioProgramProjector);
  4476. QAction *studioProgramWindow = popup.addAction(
  4477. QTStr("StudioProgramWindow"),
  4478. this, SLOT(OpenStudioProgramWindow()));
  4479. popup.addAction(studioProgramWindow);
  4480. popup.exec(QCursor::pos());
  4481. }
  4482. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  4483. const QPoint &pos)
  4484. {
  4485. QMenu popup(this);
  4486. delete previewProjectorMain;
  4487. QAction *action = popup.addAction(
  4488. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4489. this, SLOT(TogglePreview()));
  4490. action->setCheckable(true);
  4491. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4492. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4493. AddProjectorMenuMonitors(previewProjectorMain, this,
  4494. SLOT(OpenPreviewProjector()));
  4495. QAction *previewWindow = popup.addAction(
  4496. QTStr("PreviewWindow"),
  4497. this, SLOT(OpenPreviewWindow()));
  4498. popup.addMenu(previewProjectorMain);
  4499. popup.addAction(previewWindow);
  4500. popup.exec(QCursor::pos());
  4501. UNUSED_PARAMETER(pos);
  4502. }
  4503. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4504. {
  4505. #ifndef _WIN32
  4506. /* Make sure all dialogs are safely and successfully closed before
  4507. * switching the always on top mode due to the fact that windows all
  4508. * have to be recreated, so queue the actual toggle to happen after
  4509. * all events related to closing the dialogs have finished */
  4510. CloseDialogs();
  4511. #endif
  4512. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4513. Qt::QueuedConnection);
  4514. }
  4515. void OBSBasic::ToggleAlwaysOnTop()
  4516. {
  4517. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4518. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4519. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4520. show();
  4521. }
  4522. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4523. {
  4524. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4525. if (strcmp(val, "10") == 0) {
  4526. num = 10;
  4527. den = 1;
  4528. } else if (strcmp(val, "20") == 0) {
  4529. num = 20;
  4530. den = 1;
  4531. } else if (strcmp(val, "24 NTSC") == 0) {
  4532. num = 24000;
  4533. den = 1001;
  4534. } else if (strcmp(val, "25") == 0) {
  4535. num = 25;
  4536. den = 1;
  4537. } else if (strcmp(val, "29.97") == 0) {
  4538. num = 30000;
  4539. den = 1001;
  4540. } else if (strcmp(val, "48") == 0) {
  4541. num = 48;
  4542. den = 1;
  4543. } else if (strcmp(val, "59.94") == 0) {
  4544. num = 60000;
  4545. den = 1001;
  4546. } else if (strcmp(val, "60") == 0) {
  4547. num = 60;
  4548. den = 1;
  4549. } else {
  4550. num = 30;
  4551. den = 1;
  4552. }
  4553. }
  4554. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4555. {
  4556. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4557. den = 1;
  4558. }
  4559. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4560. {
  4561. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4562. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4563. }
  4564. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4565. {
  4566. num = 1000000000;
  4567. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4568. }
  4569. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4570. {
  4571. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4572. if (type == 1) //"Integer"
  4573. GetFPSInteger(num, den);
  4574. else if (type == 2) //"Fraction"
  4575. GetFPSFraction(num, den);
  4576. else if (false) //"Nanoseconds", currently not implemented
  4577. GetFPSNanoseconds(num, den);
  4578. else
  4579. GetFPSCommon(num, den);
  4580. }
  4581. config_t *OBSBasic::Config() const
  4582. {
  4583. return basicConfig;
  4584. }
  4585. void OBSBasic::on_actionEditTransform_triggered()
  4586. {
  4587. if (transformWindow)
  4588. transformWindow->close();
  4589. transformWindow = new OBSBasicTransform(this);
  4590. transformWindow->show();
  4591. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4592. }
  4593. static obs_transform_info copiedTransformInfo;
  4594. static obs_sceneitem_crop copiedCropInfo;
  4595. void OBSBasic::on_actionCopyTransform_triggered()
  4596. {
  4597. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4598. {
  4599. if (!obs_sceneitem_selected(item))
  4600. return true;
  4601. obs_sceneitem_defer_update_begin(item);
  4602. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4603. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4604. obs_sceneitem_defer_update_end(item);
  4605. UNUSED_PARAMETER(scene);
  4606. UNUSED_PARAMETER(param);
  4607. return true;
  4608. };
  4609. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4610. ui->actionPasteTransform->setEnabled(true);
  4611. }
  4612. void OBSBasic::on_actionPasteTransform_triggered()
  4613. {
  4614. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4615. {
  4616. if (!obs_sceneitem_selected(item))
  4617. return true;
  4618. obs_sceneitem_defer_update_begin(item);
  4619. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4620. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4621. obs_sceneitem_defer_update_end(item);
  4622. UNUSED_PARAMETER(scene);
  4623. UNUSED_PARAMETER(param);
  4624. return true;
  4625. };
  4626. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4627. }
  4628. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4629. {
  4630. if (obs_sceneitem_is_group(item))
  4631. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  4632. if (!obs_sceneitem_selected(item))
  4633. return true;
  4634. obs_sceneitem_defer_update_begin(item);
  4635. obs_transform_info info;
  4636. vec2_set(&info.pos, 0.0f, 0.0f);
  4637. vec2_set(&info.scale, 1.0f, 1.0f);
  4638. info.rot = 0.0f;
  4639. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4640. info.bounds_type = OBS_BOUNDS_NONE;
  4641. info.bounds_alignment = OBS_ALIGN_CENTER;
  4642. vec2_set(&info.bounds, 0.0f, 0.0f);
  4643. obs_sceneitem_set_info(item, &info);
  4644. obs_sceneitem_crop crop = {};
  4645. obs_sceneitem_set_crop(item, &crop);
  4646. obs_sceneitem_defer_update_end(item);
  4647. UNUSED_PARAMETER(scene);
  4648. UNUSED_PARAMETER(param);
  4649. return true;
  4650. }
  4651. void OBSBasic::on_actionResetTransform_triggered()
  4652. {
  4653. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  4654. }
  4655. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4656. {
  4657. matrix4 boxTransform;
  4658. obs_sceneitem_get_box_transform(item, &boxTransform);
  4659. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4660. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4661. auto GetMinPos = [&] (float x, float y)
  4662. {
  4663. vec3 pos;
  4664. vec3_set(&pos, x, y, 0.0f);
  4665. vec3_transform(&pos, &pos, &boxTransform);
  4666. vec3_min(&tl, &tl, &pos);
  4667. vec3_max(&br, &br, &pos);
  4668. };
  4669. GetMinPos(0.0f, 0.0f);
  4670. GetMinPos(1.0f, 0.0f);
  4671. GetMinPos(0.0f, 1.0f);
  4672. GetMinPos(1.0f, 1.0f);
  4673. }
  4674. static vec3 GetItemTL(obs_sceneitem_t *item)
  4675. {
  4676. vec3 tl, br;
  4677. GetItemBox(item, tl, br);
  4678. return tl;
  4679. }
  4680. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4681. {
  4682. vec3 newTL;
  4683. vec2 pos;
  4684. obs_sceneitem_get_pos(item, &pos);
  4685. newTL = GetItemTL(item);
  4686. pos.x += tl.x - newTL.x;
  4687. pos.y += tl.y - newTL.y;
  4688. obs_sceneitem_set_pos(item, &pos);
  4689. }
  4690. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4691. void *param)
  4692. {
  4693. if (obs_sceneitem_is_group(item))
  4694. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  4695. param);
  4696. if (!obs_sceneitem_selected(item))
  4697. return true;
  4698. float rot = *reinterpret_cast<float*>(param);
  4699. vec3 tl = GetItemTL(item);
  4700. rot += obs_sceneitem_get_rot(item);
  4701. if (rot >= 360.0f) rot -= 360.0f;
  4702. else if (rot <= -360.0f) rot += 360.0f;
  4703. obs_sceneitem_set_rot(item, rot);
  4704. obs_sceneitem_force_update_transform(item);
  4705. SetItemTL(item, tl);
  4706. UNUSED_PARAMETER(scene);
  4707. return true;
  4708. };
  4709. void OBSBasic::on_actionRotate90CW_triggered()
  4710. {
  4711. float f90CW = 90.0f;
  4712. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4713. }
  4714. void OBSBasic::on_actionRotate90CCW_triggered()
  4715. {
  4716. float f90CCW = -90.0f;
  4717. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4718. }
  4719. void OBSBasic::on_actionRotate180_triggered()
  4720. {
  4721. float f180 = 180.0f;
  4722. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4723. }
  4724. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4725. void *param)
  4726. {
  4727. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4728. if (obs_sceneitem_is_group(item))
  4729. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  4730. param);
  4731. if (!obs_sceneitem_selected(item))
  4732. return true;
  4733. vec3 tl = GetItemTL(item);
  4734. vec2 scale;
  4735. obs_sceneitem_get_scale(item, &scale);
  4736. vec2_mul(&scale, &scale, &mul);
  4737. obs_sceneitem_set_scale(item, &scale);
  4738. obs_sceneitem_force_update_transform(item);
  4739. SetItemTL(item, tl);
  4740. UNUSED_PARAMETER(scene);
  4741. return true;
  4742. }
  4743. void OBSBasic::on_actionFlipHorizontal_triggered()
  4744. {
  4745. vec2 scale;
  4746. vec2_set(&scale, -1.0f, 1.0f);
  4747. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4748. &scale);
  4749. }
  4750. void OBSBasic::on_actionFlipVertical_triggered()
  4751. {
  4752. vec2 scale;
  4753. vec2_set(&scale, 1.0f, -1.0f);
  4754. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4755. &scale);
  4756. }
  4757. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4758. void *param)
  4759. {
  4760. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4761. if (obs_sceneitem_is_group(item))
  4762. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  4763. param);
  4764. if (!obs_sceneitem_selected(item))
  4765. return true;
  4766. obs_video_info ovi;
  4767. obs_get_video_info(&ovi);
  4768. obs_transform_info itemInfo;
  4769. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4770. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4771. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4772. itemInfo.rot = 0.0f;
  4773. vec2_set(&itemInfo.bounds,
  4774. float(ovi.base_width), float(ovi.base_height));
  4775. itemInfo.bounds_type = boundsType;
  4776. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4777. obs_sceneitem_set_info(item, &itemInfo);
  4778. UNUSED_PARAMETER(scene);
  4779. return true;
  4780. }
  4781. void OBSBasic::on_actionFitToScreen_triggered()
  4782. {
  4783. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4784. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4785. &boundsType);
  4786. }
  4787. void OBSBasic::on_actionStretchToScreen_triggered()
  4788. {
  4789. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4790. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4791. &boundsType);
  4792. }
  4793. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *)
  4794. {
  4795. vec3 tl, br, itemCenter, screenCenter, offset;
  4796. obs_video_info ovi;
  4797. if (obs_sceneitem_is_group(item))
  4798. obs_sceneitem_group_enum_items(item, center_to_scene, nullptr);
  4799. if (!obs_sceneitem_selected(item))
  4800. return true;
  4801. obs_get_video_info(&ovi);
  4802. vec3_set(&screenCenter, float(ovi.base_width),
  4803. float(ovi.base_height), 0.0f);
  4804. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4805. GetItemBox(item, tl, br);
  4806. vec3_sub(&itemCenter, &br, &tl);
  4807. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4808. vec3_add(&itemCenter, &itemCenter, &tl);
  4809. vec3_sub(&offset, &screenCenter, &itemCenter);
  4810. vec3_add(&tl, &tl, &offset);
  4811. SetItemTL(item, tl);
  4812. return true;
  4813. };
  4814. void OBSBasic::on_actionCenterToScreen_triggered()
  4815. {
  4816. obs_scene_enum_items(GetCurrentScene(), center_to_scene, nullptr);
  4817. }
  4818. void OBSBasic::EnablePreviewDisplay(bool enable)
  4819. {
  4820. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4821. ui->preview->setVisible(enable);
  4822. ui->previewDisabledLabel->setVisible(!enable);
  4823. }
  4824. void OBSBasic::TogglePreview()
  4825. {
  4826. previewEnabled = !previewEnabled;
  4827. EnablePreviewDisplay(previewEnabled);
  4828. }
  4829. static bool nudge_callback(obs_scene_t*, obs_sceneitem_t *item, void *param)
  4830. {
  4831. if (obs_sceneitem_locked(item))
  4832. return true;
  4833. struct vec2 &offset = *reinterpret_cast<struct vec2*>(param);
  4834. struct vec2 pos;
  4835. if (!obs_sceneitem_selected(item)) {
  4836. if (obs_sceneitem_is_group(item)) {
  4837. struct vec3 offset3;
  4838. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  4839. struct matrix4 matrix;
  4840. obs_sceneitem_get_draw_transform(item, &matrix);
  4841. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  4842. matrix4_inv(&matrix, &matrix);
  4843. vec3_transform(&offset3, &offset3, &matrix);
  4844. struct vec2 new_offset;
  4845. vec2_set(&new_offset, offset3.x, offset3.y);
  4846. obs_sceneitem_group_enum_items(item, nudge_callback,
  4847. &new_offset);
  4848. }
  4849. return true;
  4850. }
  4851. obs_sceneitem_get_pos(item, &pos);
  4852. vec2_add(&pos, &pos, &offset);
  4853. obs_sceneitem_set_pos(item, &pos);
  4854. return true;
  4855. }
  4856. void OBSBasic::Nudge(int dist, MoveDir dir)
  4857. {
  4858. if (ui->preview->Locked())
  4859. return;
  4860. struct vec2 offset;
  4861. vec2_set(&offset, 0.0f, 0.0f);
  4862. switch (dir) {
  4863. case MoveDir::Up: offset.y = (float)-dist; break;
  4864. case MoveDir::Down: offset.y = (float) dist; break;
  4865. case MoveDir::Left: offset.x = (float)-dist; break;
  4866. case MoveDir::Right: offset.x = (float) dist; break;
  4867. }
  4868. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  4869. }
  4870. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4871. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4872. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4873. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4874. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  4875. QString title, ProjectorType type)
  4876. {
  4877. /* seriously? 10 monitors? */
  4878. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4879. return nullptr;
  4880. OBSProjector *projector = new OBSProjector(nullptr, source, monitor,
  4881. title, type);
  4882. if (monitor < 0) {
  4883. for (auto &projPtr : windowProjectors) {
  4884. if (!projPtr) {
  4885. projPtr = projector;
  4886. projector = nullptr;
  4887. }
  4888. }
  4889. if (projector)
  4890. windowProjectors.push_back(projector);
  4891. } else {
  4892. delete projectors[monitor];
  4893. projectors[monitor].clear();
  4894. projectors[monitor] = projector;
  4895. }
  4896. return projector;
  4897. }
  4898. void OBSBasic::OpenStudioProgramProjector()
  4899. {
  4900. int monitor = sender()->property("monitor").toInt();
  4901. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  4902. }
  4903. void OBSBasic::OpenPreviewProjector()
  4904. {
  4905. int monitor = sender()->property("monitor").toInt();
  4906. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  4907. }
  4908. void OBSBasic::OpenSourceProjector()
  4909. {
  4910. int monitor = sender()->property("monitor").toInt();
  4911. OBSSceneItem item = GetCurrentSceneItem();
  4912. if (!item)
  4913. return;
  4914. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  4915. ProjectorType::Source);
  4916. }
  4917. void OBSBasic::OpenMultiviewProjector()
  4918. {
  4919. int monitor = sender()->property("monitor").toInt();
  4920. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  4921. }
  4922. void OBSBasic::OpenSceneProjector()
  4923. {
  4924. int monitor = sender()->property("monitor").toInt();
  4925. OBSScene scene = GetCurrentScene();
  4926. if (!scene)
  4927. return;
  4928. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  4929. ProjectorType::Scene);
  4930. }
  4931. void OBSBasic::OpenStudioProgramWindow()
  4932. {
  4933. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  4934. ProjectorType::StudioProgram);
  4935. }
  4936. void OBSBasic::OpenPreviewWindow()
  4937. {
  4938. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  4939. ProjectorType::Preview);
  4940. }
  4941. void OBSBasic::OpenSourceWindow()
  4942. {
  4943. OBSSceneItem item = GetCurrentSceneItem();
  4944. if (!item)
  4945. return;
  4946. OBSSource source = obs_sceneitem_get_source(item);
  4947. QString title = QString::fromUtf8(obs_source_get_name(source));
  4948. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  4949. ProjectorType::Source);
  4950. }
  4951. void OBSBasic::OpenMultiviewWindow()
  4952. {
  4953. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  4954. ProjectorType::Multiview);
  4955. }
  4956. void OBSBasic::OpenSceneWindow()
  4957. {
  4958. OBSScene scene = GetCurrentScene();
  4959. if (!scene)
  4960. return;
  4961. OBSSource source = obs_scene_get_source(scene);
  4962. QString title = QString::fromUtf8(obs_source_get_name(source));
  4963. OpenProjector(obs_scene_get_source(scene), -1, title,
  4964. ProjectorType::Scene);
  4965. }
  4966. void OBSBasic::OpenSavedProjectors()
  4967. {
  4968. for (SavedProjectorInfo *info : savedProjectorsArray) {
  4969. OBSProjector *projector = nullptr;
  4970. switch (info->type) {
  4971. case ProjectorType::Source:
  4972. case ProjectorType::Scene: {
  4973. OBSSource source = obs_get_source_by_name(
  4974. info->name.c_str());
  4975. if (!source)
  4976. continue;
  4977. QString title = nullptr;
  4978. if (info->monitor < 0)
  4979. title = QString::fromUtf8(
  4980. obs_source_get_name(source));
  4981. projector = OpenProjector(source, info->monitor, title,
  4982. info->type);
  4983. obs_source_release(source);
  4984. break;
  4985. }
  4986. case ProjectorType::Preview: {
  4987. projector = OpenProjector(nullptr, info->monitor,
  4988. QTStr("PreviewWindow"),
  4989. ProjectorType::Preview);
  4990. break;
  4991. }
  4992. case ProjectorType::StudioProgram: {
  4993. projector = OpenProjector(nullptr, info->monitor,
  4994. QTStr("StudioProgramWindow"),
  4995. ProjectorType::StudioProgram);
  4996. break;
  4997. }
  4998. case ProjectorType::Multiview: {
  4999. projector = OpenProjector(nullptr, info->monitor,
  5000. QTStr("MultiviewWindowed"),
  5001. ProjectorType::Multiview);
  5002. break;
  5003. }
  5004. }
  5005. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5006. QByteArray byteArray = QByteArray::fromBase64(
  5007. QByteArray(info->geometry.c_str()));
  5008. projector->restoreGeometry(byteArray);
  5009. if (!WindowPositionValid(projector->normalGeometry())) {
  5010. QRect rect = App()->desktop()->geometry();
  5011. projector->setGeometry(QStyle::alignedRect(
  5012. Qt::LeftToRight,
  5013. Qt::AlignCenter, size(), rect));
  5014. }
  5015. }
  5016. }
  5017. }
  5018. void OBSBasic::on_actionFullscreenInterface_triggered()
  5019. {
  5020. if (!fullscreenInterface)
  5021. showFullScreen();
  5022. else
  5023. showNormal();
  5024. fullscreenInterface = !fullscreenInterface;
  5025. }
  5026. void OBSBasic::UpdateTitleBar()
  5027. {
  5028. stringstream name;
  5029. const char *profile = config_get_string(App()->GlobalConfig(),
  5030. "Basic", "Profile");
  5031. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  5032. "Basic", "SceneCollection");
  5033. name << "OBS ";
  5034. if (previewProgramMode)
  5035. name << "Studio ";
  5036. name << App()->GetVersionString();
  5037. if (App()->IsPortableMode())
  5038. name << " - Portable Mode";
  5039. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5040. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5041. setWindowTitle(QT_UTF8(name.str().c_str()));
  5042. }
  5043. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5044. {
  5045. char profiles_path[512];
  5046. const char *profile = config_get_string(App()->GlobalConfig(),
  5047. "Basic", "ProfileDir");
  5048. int ret;
  5049. if (!profile)
  5050. return -1;
  5051. if (!path)
  5052. return -1;
  5053. if (!file)
  5054. file = "";
  5055. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5056. if (ret <= 0)
  5057. return ret;
  5058. if (!*file)
  5059. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5060. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5061. }
  5062. void OBSBasic::on_resetUI_triggered()
  5063. {
  5064. /* prune deleted extra docks */
  5065. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5066. if (!extraDocks[i]) {
  5067. extraDocks.removeAt(i);
  5068. }
  5069. }
  5070. if (extraDocks.size()) {
  5071. QMessageBox::StandardButton button = QMessageBox::question(
  5072. this,
  5073. QTStr("ResetUIWarning.Title"),
  5074. QTStr("ResetUIWarning.Text"));
  5075. if (button == QMessageBox::No)
  5076. return;
  5077. }
  5078. /* undock/hide/center extra docks */
  5079. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5080. if (extraDocks[i]) {
  5081. extraDocks[i]->setVisible(true);
  5082. extraDocks[i]->setFloating(true);
  5083. extraDocks[i]->move(
  5084. frameGeometry().topLeft() +
  5085. rect().center() -
  5086. extraDocks[i]->rect().center());
  5087. extraDocks[i]->setVisible(false);
  5088. }
  5089. }
  5090. restoreState(startingDockLayout);
  5091. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5092. int cx = width();
  5093. int cy = height();
  5094. int cx22_5 = cx * 225 / 1000;
  5095. int cx5 = cx * 5 / 100;
  5096. cy = cy * 225 / 1000;
  5097. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5098. QList<QDockWidget*> docks {
  5099. ui->scenesDock,
  5100. ui->sourcesDock,
  5101. ui->mixerDock,
  5102. ui->transitionsDock,
  5103. ui->controlsDock
  5104. };
  5105. QList<int> sizes {
  5106. cx22_5,
  5107. cx22_5,
  5108. mixerSize,
  5109. cx5,
  5110. cx5
  5111. };
  5112. ui->scenesDock->setVisible(true);
  5113. ui->sourcesDock->setVisible(true);
  5114. ui->mixerDock->setVisible(true);
  5115. ui->transitionsDock->setVisible(true);
  5116. ui->controlsDock->setVisible(true);
  5117. statsDock->setVisible(false);
  5118. statsDock->setFloating(true);
  5119. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5120. resizeDocks(docks, sizes, Qt::Horizontal);
  5121. #endif
  5122. }
  5123. void OBSBasic::on_lockUI_toggled(bool lock)
  5124. {
  5125. QDockWidget::DockWidgetFeatures features = lock
  5126. ? QDockWidget::NoDockWidgetFeatures
  5127. : QDockWidget::AllDockWidgetFeatures;
  5128. ui->scenesDock->setFeatures(features);
  5129. ui->sourcesDock->setFeatures(features);
  5130. ui->mixerDock->setFeatures(features);
  5131. ui->transitionsDock->setFeatures(features);
  5132. ui->controlsDock->setFeatures(features);
  5133. statsDock->setFeatures(features);
  5134. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5135. if (!extraDocks[i]) {
  5136. extraDocks.removeAt(i);
  5137. } else {
  5138. extraDocks[i]->setFeatures(features);
  5139. }
  5140. }
  5141. }
  5142. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5143. {
  5144. ui->sourcesToolbar->setVisible(visible);
  5145. ui->scenesToolbar->setVisible(visible);
  5146. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5147. "ShowListboxToolbars", visible);
  5148. }
  5149. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5150. {
  5151. ui->statusbar->setVisible(visible);
  5152. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5153. "ShowStatusBar", visible);
  5154. }
  5155. void OBSBasic::on_actionLockPreview_triggered()
  5156. {
  5157. ui->preview->ToggleLocked();
  5158. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5159. }
  5160. void OBSBasic::on_scalingMenu_aboutToShow()
  5161. {
  5162. obs_video_info ovi;
  5163. obs_get_video_info(&ovi);
  5164. QAction *action = ui->actionScaleCanvas;
  5165. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5166. text = text.arg(QString::number(ovi.base_width),
  5167. QString::number(ovi.base_height));
  5168. action->setText(text);
  5169. action = ui->actionScaleOutput;
  5170. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5171. text = text.arg(QString::number(ovi.output_width),
  5172. QString::number(ovi.output_height));
  5173. action->setText(text);
  5174. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5175. ovi.output_height == ovi.base_height));
  5176. UpdatePreviewScalingMenu();
  5177. }
  5178. void OBSBasic::on_actionScaleWindow_triggered()
  5179. {
  5180. ui->preview->SetFixedScaling(false);
  5181. ui->preview->ResetScrollingOffset();
  5182. emit ui->preview->DisplayResized();
  5183. }
  5184. void OBSBasic::on_actionScaleCanvas_triggered()
  5185. {
  5186. ui->preview->SetFixedScaling(true);
  5187. ui->preview->SetScalingLevel(0);
  5188. emit ui->preview->DisplayResized();
  5189. }
  5190. void OBSBasic::on_actionScaleOutput_triggered()
  5191. {
  5192. obs_video_info ovi;
  5193. obs_get_video_info(&ovi);
  5194. ui->preview->SetFixedScaling(true);
  5195. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5196. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5197. int32_t approxScalingLevel = int32_t(
  5198. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5199. ui->preview->SetScalingLevel(approxScalingLevel);
  5200. ui->preview->SetScalingAmount(scalingAmount);
  5201. emit ui->preview->DisplayResized();
  5202. }
  5203. void OBSBasic::SetShowing(bool showing)
  5204. {
  5205. if (!showing && isVisible()) {
  5206. config_set_string(App()->GlobalConfig(),
  5207. "BasicWindow", "geometry",
  5208. saveGeometry().toBase64().constData());
  5209. /* hide all visible child dialogs */
  5210. visDlgPositions.clear();
  5211. if (!visDialogs.isEmpty()) {
  5212. for (QDialog *dlg : visDialogs) {
  5213. visDlgPositions.append(dlg->pos());
  5214. dlg->hide();
  5215. }
  5216. }
  5217. if (showHide)
  5218. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5219. QTimer::singleShot(250, this, SLOT(hide()));
  5220. if (previewEnabled)
  5221. EnablePreviewDisplay(false);
  5222. setVisible(false);
  5223. #ifdef __APPLE__
  5224. EnableOSXDockIcon(false);
  5225. #endif
  5226. } else if (showing && !isVisible()) {
  5227. if (showHide)
  5228. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5229. QTimer::singleShot(250, this, SLOT(show()));
  5230. if (previewEnabled)
  5231. EnablePreviewDisplay(true);
  5232. setVisible(true);
  5233. #ifdef __APPLE__
  5234. EnableOSXDockIcon(true);
  5235. #endif
  5236. /* raise and activate window to ensure it is on top */
  5237. raise();
  5238. activateWindow();
  5239. /* show all child dialogs that was visible earlier */
  5240. if (!visDialogs.isEmpty()) {
  5241. for (int i = 0; i < visDialogs.size(); ++i) {
  5242. QDialog *dlg = visDialogs[i];
  5243. dlg->move(visDlgPositions[i]);
  5244. dlg->show();
  5245. }
  5246. }
  5247. /* Unminimize window if it was hidden to tray instead of task
  5248. * bar. */
  5249. if (sysTrayMinimizeToTray()) {
  5250. Qt::WindowStates state;
  5251. state = windowState() & ~Qt::WindowMinimized;
  5252. state |= Qt::WindowActive;
  5253. setWindowState(state);
  5254. }
  5255. }
  5256. }
  5257. void OBSBasic::ToggleShowHide()
  5258. {
  5259. bool showing = isVisible();
  5260. if (showing) {
  5261. /* check for modal dialogs */
  5262. EnumDialogs();
  5263. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5264. return;
  5265. }
  5266. SetShowing(!showing);
  5267. }
  5268. void OBSBasic::SystemTrayInit()
  5269. {
  5270. trayIcon.reset(new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  5271. this));
  5272. trayIcon->setToolTip("OBS Studio");
  5273. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  5274. trayIcon.data());
  5275. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5276. trayIcon.data());
  5277. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5278. trayIcon.data());
  5279. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5280. trayIcon.data());
  5281. exit = new QAction(QTStr("Exit"),
  5282. trayIcon.data());
  5283. trayMenu = new QMenu;
  5284. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5285. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5286. AddProjectorMenuMonitors(previewProjector, this,
  5287. SLOT(OpenPreviewProjector()));
  5288. AddProjectorMenuMonitors(studioProgramProjector, this,
  5289. SLOT(OpenStudioProgramProjector()));
  5290. trayMenu->addAction(showHide);
  5291. trayMenu->addMenu(previewProjector);
  5292. trayMenu->addMenu(studioProgramProjector);
  5293. trayMenu->addAction(sysTrayStream);
  5294. trayMenu->addAction(sysTrayRecord);
  5295. trayMenu->addAction(sysTrayReplayBuffer);
  5296. trayMenu->addAction(exit);
  5297. trayIcon->setContextMenu(trayMenu);
  5298. if (outputHandler && !outputHandler->replayBuffer)
  5299. sysTrayReplayBuffer->setEnabled(false);
  5300. connect(trayIcon.data(),
  5301. SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  5302. this,
  5303. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5304. connect(showHide, SIGNAL(triggered()),
  5305. this, SLOT(ToggleShowHide()));
  5306. connect(sysTrayStream, SIGNAL(triggered()),
  5307. this, SLOT(on_streamButton_clicked()));
  5308. connect(sysTrayRecord, SIGNAL(triggered()),
  5309. this, SLOT(on_recordButton_clicked()));
  5310. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  5311. this, &OBSBasic::ReplayBufferClicked);
  5312. connect(exit, SIGNAL(triggered()),
  5313. this, SLOT(close()));
  5314. }
  5315. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5316. {
  5317. // Refresh projector list
  5318. previewProjector->clear();
  5319. studioProgramProjector->clear();
  5320. AddProjectorMenuMonitors(previewProjector, this,
  5321. SLOT(OpenPreviewProjector()));
  5322. AddProjectorMenuMonitors(studioProgramProjector, this,
  5323. SLOT(OpenStudioProgramProjector()));
  5324. if (reason == QSystemTrayIcon::Trigger)
  5325. ToggleShowHide();
  5326. }
  5327. void OBSBasic::SysTrayNotify(const QString &text,
  5328. QSystemTrayIcon::MessageIcon n)
  5329. {
  5330. if (QSystemTrayIcon::supportsMessages()) {
  5331. QSystemTrayIcon::MessageIcon icon =
  5332. QSystemTrayIcon::MessageIcon(n);
  5333. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5334. }
  5335. }
  5336. void OBSBasic::SystemTray(bool firstStarted)
  5337. {
  5338. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5339. return;
  5340. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  5341. "BasicWindow", "SysTrayWhenStarted");
  5342. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  5343. "BasicWindow", "SysTrayEnabled");
  5344. if (firstStarted)
  5345. SystemTrayInit();
  5346. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5347. trayIcon->hide();
  5348. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  5349. || opt_minimize_tray) {
  5350. trayIcon->show();
  5351. if (firstStarted) {
  5352. QTimer::singleShot(50, this, SLOT(hide()));
  5353. EnablePreviewDisplay(false);
  5354. setVisible(false);
  5355. #ifdef __APPLE__
  5356. EnableOSXDockIcon(false);
  5357. #endif
  5358. opt_minimize_tray = false;
  5359. }
  5360. } else if (sysTrayEnabled) {
  5361. trayIcon->show();
  5362. } else if (!sysTrayEnabled) {
  5363. trayIcon->hide();
  5364. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5365. trayIcon->hide();
  5366. }
  5367. if (isVisible())
  5368. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5369. else
  5370. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5371. }
  5372. bool OBSBasic::sysTrayMinimizeToTray()
  5373. {
  5374. return config_get_bool(GetGlobalConfig(),
  5375. "BasicWindow", "SysTrayMinimizeToTray");
  5376. }
  5377. void OBSBasic::on_actionCopySource_triggered()
  5378. {
  5379. OBSSceneItem item = GetCurrentSceneItem();
  5380. if (!item)
  5381. return;
  5382. on_actionCopyTransform_triggered();
  5383. OBSSource source = obs_sceneitem_get_source(item);
  5384. copyString = obs_source_get_name(source);
  5385. copyVisible = obs_sceneitem_visible(item);
  5386. ui->actionPasteRef->setEnabled(true);
  5387. uint32_t output_flags = obs_source_get_output_flags(source);
  5388. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5389. ui->actionPasteDup->setEnabled(true);
  5390. else
  5391. ui->actionPasteDup->setEnabled(false);
  5392. }
  5393. void OBSBasic::on_actionPasteRef_triggered()
  5394. {
  5395. /* do not allow duplicate refs of the same group in the same scene */
  5396. OBSScene scene = GetCurrentScene();
  5397. if (!!obs_scene_get_group(scene, copyString))
  5398. return;
  5399. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  5400. on_actionPasteTransform_triggered();
  5401. }
  5402. void OBSBasic::on_actionPasteDup_triggered()
  5403. {
  5404. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  5405. on_actionPasteTransform_triggered();
  5406. }
  5407. void OBSBasic::on_actionCopyFilters_triggered()
  5408. {
  5409. OBSSceneItem item = GetCurrentSceneItem();
  5410. if (!item)
  5411. return;
  5412. OBSSource source = obs_sceneitem_get_source(item);
  5413. copyFiltersString = obs_source_get_name(source);
  5414. ui->actionPasteFilters->setEnabled(true);
  5415. }
  5416. void OBSBasic::on_actionPasteFilters_triggered()
  5417. {
  5418. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5419. obs_source_release(source);
  5420. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5421. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5422. if (source == dstSource)
  5423. return;
  5424. obs_source_copy_filters(dstSource, source);
  5425. }
  5426. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5427. QModelIndexList selectedItems)
  5428. {
  5429. for (int x = 0; x < selectedItems.count(); x++) {
  5430. SourceTreeItem *treeItem = sources
  5431. ->GetItemWidget(selectedItems[x].row());
  5432. treeItem->setStyleSheet("background: "
  5433. + color.name(QColor::HexArgb));
  5434. treeItem->style()->unpolish(treeItem);
  5435. treeItem->style()->polish(treeItem);
  5436. OBSSceneItem sceneItem = sources->Get(
  5437. selectedItems[x].row());
  5438. obs_data_t *privData =
  5439. obs_sceneitem_get_private_settings(sceneItem);
  5440. obs_data_set_int(privData, "color-preset", 1);
  5441. obs_data_set_string(privData, "color",
  5442. QT_TO_UTF8(color.name(
  5443. QColor::HexArgb)));
  5444. obs_data_release(privData);
  5445. }
  5446. }
  5447. void OBSBasic::ColorChange()
  5448. {
  5449. QModelIndexList selectedItems =
  5450. ui->sources->selectionModel()->selectedIndexes();
  5451. QAction *action = qobject_cast<QAction*>(sender());
  5452. QPushButton *colorButton = qobject_cast<QPushButton*>(sender());
  5453. if (selectedItems.count() == 0)
  5454. return;
  5455. if (colorButton) {
  5456. int preset = colorButton->property("bgColor").value<int>();
  5457. for (int x = 0; x < selectedItems.count(); x++) {
  5458. SourceTreeItem *treeItem = ui->sources
  5459. ->GetItemWidget(selectedItems[x].row());
  5460. treeItem->setStyleSheet("");
  5461. treeItem->setProperty("bgColor", preset);
  5462. treeItem->style()->unpolish(treeItem);
  5463. treeItem->style()->polish(treeItem);
  5464. OBSSceneItem sceneItem = ui->sources->Get(
  5465. selectedItems[x].row());
  5466. obs_data_t *privData =
  5467. obs_sceneitem_get_private_settings(sceneItem);
  5468. obs_data_set_int(privData, "color-preset", preset + 1);
  5469. obs_data_set_string(privData, "color", "");
  5470. obs_data_release(privData);
  5471. }
  5472. for (int i = 1; i < 9; i++) {
  5473. stringstream button;
  5474. button << "preset" << i;
  5475. QPushButton *cButton = colorButton->parentWidget()
  5476. ->findChild<QPushButton *>(button.str().c_str());
  5477. cButton->setStyleSheet("border: 1px solid black");
  5478. }
  5479. colorButton->setStyleSheet("border: 2px solid black");
  5480. } else if (action) {
  5481. int preset = action->property("bgColor").value<int>();
  5482. if (preset == 1) {
  5483. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5484. SourceTreeItem *curTreeItem =
  5485. GetItemWidgetFromSceneItem(curSceneItem);
  5486. obs_data_t *curPrivData =
  5487. obs_sceneitem_get_private_settings(curSceneItem);
  5488. int oldPreset = obs_data_get_int(
  5489. curPrivData, "color-preset");
  5490. const QString oldSheet = curTreeItem->styleSheet();
  5491. auto liveChangeColor = [=](const QColor &color) {
  5492. if (color.isValid()) {
  5493. curTreeItem->setStyleSheet(
  5494. "background: "
  5495. + color.name(QColor::HexArgb));
  5496. }
  5497. };
  5498. auto changedColor = [=](const QColor &color) {
  5499. if (color.isValid()) {
  5500. ConfirmColor(ui->sources, color,
  5501. selectedItems);
  5502. }
  5503. };
  5504. auto rejected = [=]() {
  5505. if (oldPreset == 1) {
  5506. curTreeItem->setStyleSheet(oldSheet);
  5507. curTreeItem->setProperty("bgColor", 0);
  5508. } else if (oldPreset == 0) {
  5509. curTreeItem->setStyleSheet(
  5510. "background: none");
  5511. curTreeItem->setProperty("bgColor", 0);
  5512. } else {
  5513. curTreeItem->setStyleSheet("");
  5514. curTreeItem->setProperty("bgColor",
  5515. oldPreset - 1);
  5516. }
  5517. curTreeItem->style()->unpolish(curTreeItem);
  5518. curTreeItem->style()->polish(curTreeItem);
  5519. };
  5520. QColorDialog::ColorDialogOptions options =
  5521. QColorDialog::ShowAlphaChannel;
  5522. const char *oldColor = obs_data_get_string(curPrivData,
  5523. "color");
  5524. const char *customColor = *oldColor != 0 ? oldColor
  5525. : "#55FF0000";
  5526. #ifdef __APPLE__
  5527. options |= QColorDialog::DontUseNativeDialog;
  5528. #endif
  5529. QColorDialog *colorDialog = new QColorDialog(this);
  5530. colorDialog->setOptions(options);
  5531. colorDialog->setCurrentColor(
  5532. QColor(customColor));
  5533. connect(colorDialog, &QColorDialog::currentColorChanged,
  5534. liveChangeColor);
  5535. connect(colorDialog, &QColorDialog::colorSelected,
  5536. changedColor);
  5537. connect(colorDialog, &QColorDialog::rejected,
  5538. rejected);
  5539. colorDialog->open();
  5540. obs_data_release(curPrivData);
  5541. } else {
  5542. for (int x = 0; x < selectedItems.count(); x++) {
  5543. SourceTreeItem *treeItem = ui->sources
  5544. ->GetItemWidget(selectedItems[x].row());
  5545. treeItem->setStyleSheet("background: none");
  5546. treeItem->setProperty("bgColor", preset);
  5547. treeItem->style()->unpolish(treeItem);
  5548. treeItem->style()->polish(treeItem);
  5549. OBSSceneItem sceneItem = ui->sources->Get(
  5550. selectedItems[x].row());
  5551. obs_data_t *privData =
  5552. obs_sceneitem_get_private_settings(
  5553. sceneItem);
  5554. obs_data_set_int(privData, "color-preset",
  5555. preset);
  5556. obs_data_set_string(privData, "color", "");
  5557. obs_data_release(privData);
  5558. }
  5559. }
  5560. }
  5561. }
  5562. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(
  5563. obs_sceneitem_t *sceneItem)
  5564. {
  5565. int i = 0;
  5566. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  5567. OBSSceneItem item = ui->sources->Get(i);
  5568. int64_t id = obs_sceneitem_get_id(sceneItem);
  5569. while (treeItem && obs_sceneitem_get_id(item) != id) {
  5570. i++;
  5571. treeItem = ui->sources->GetItemWidget(i);
  5572. item = ui->sources->Get(i);
  5573. }
  5574. if(treeItem)
  5575. return treeItem;
  5576. return nullptr;
  5577. }
  5578. void OBSBasic::on_autoConfigure_triggered()
  5579. {
  5580. AutoConfig test(this);
  5581. test.setModal(true);
  5582. test.show();
  5583. test.exec();
  5584. }
  5585. void OBSBasic::on_stats_triggered()
  5586. {
  5587. if (!stats.isNull()) {
  5588. stats->show();
  5589. stats->raise();
  5590. return;
  5591. }
  5592. OBSBasicStats *statsDlg;
  5593. statsDlg = new OBSBasicStats(nullptr);
  5594. statsDlg->show();
  5595. stats = statsDlg;
  5596. }
  5597. void OBSBasic::on_actionShowAbout_triggered()
  5598. {
  5599. if (about)
  5600. about->close();
  5601. about = new OBSAbout(this);
  5602. about->show();
  5603. about->setAttribute(Qt::WA_DeleteOnClose, true);
  5604. }
  5605. void OBSBasic::ResizeOutputSizeOfSource()
  5606. {
  5607. if (ui->streamButton->isChecked() || ui->recordButton->isChecked() ||
  5608. (replayBufferButton && replayBufferButton->isChecked()))
  5609. return;
  5610. QMessageBox resize_output(this);
  5611. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") +
  5612. "\n\n" + QTStr("ResizeOutputSizeOfSource.Continue"));
  5613. QAbstractButton *Yes = resize_output.addButton(QTStr("Yes"),
  5614. QMessageBox::YesRole);
  5615. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  5616. resize_output.setIcon(QMessageBox::Warning);
  5617. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  5618. resize_output.exec();
  5619. if (resize_output.clickedButton() != Yes)
  5620. return;
  5621. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  5622. int width = obs_source_get_width(source);
  5623. int height = obs_source_get_height(source);
  5624. config_set_uint(basicConfig, "Video", "BaseCX", width);
  5625. config_set_uint(basicConfig, "Video", "BaseCY", height);
  5626. config_set_uint(basicConfig, "Video", "OutputCX", width);
  5627. config_set_uint(basicConfig, "Video", "OutputCY", height);
  5628. ResetVideo();
  5629. on_actionFitToScreen_triggered();
  5630. }
  5631. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  5632. {
  5633. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  5634. action->setCheckable(true);
  5635. assignDockToggle(dock, action);
  5636. extraDocks.push_back(dock);
  5637. bool lock = ui->lockUI->isChecked();
  5638. QDockWidget::DockWidgetFeatures features = lock
  5639. ? QDockWidget::NoDockWidgetFeatures
  5640. : QDockWidget::AllDockWidgetFeatures;
  5641. dock->setFeatures(features);
  5642. /* prune deleted docks */
  5643. for (int i = extraDocks.size() - 1; i >= 0 ; i--) {
  5644. if (!extraDocks[i]) {
  5645. extraDocks.removeAt(i);
  5646. }
  5647. }
  5648. return action;
  5649. }
  5650. OBSBasic *OBSBasic::Get()
  5651. {
  5652. return reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  5653. }