window-basic-main.cpp 266 KB

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