1
0

window-basic-main.cpp 273 KB

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