1
0

window-basic-main.cpp 184 KB

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