window-basic-main.cpp 182 KB

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