window-basic-main.cpp 198 KB

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