window-basic-main.cpp 276 KB

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