window-basic-main.cpp 214 KB

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