window-basic-main.cpp 214 KB

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