1
0

window-basic-main.cpp 275 KB

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