window-basic-main.cpp 277 KB

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