window-basic-main.cpp 215 KB

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