window-basic-main.cpp 175 KB

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