window-basic-main.cpp 245 KB

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