window-basic-main.cpp 191 KB

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