window-basic-main.cpp 277 KB

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