window-basic-main.cpp 185 KB

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