window-basic-main.cpp 198 KB

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