window-basic-main.cpp 184 KB

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