window-basic-main.cpp 176 KB

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