window-basic-main.cpp 259 KB

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