window-basic-main.cpp 268 KB

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