1
0

window-basic-main.cpp 269 KB

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