window-basic-main.cpp 184 KB

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