window-basic-main.cpp 272 KB

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