window-basic-main.cpp 269 KB

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