window-basic-main.cpp 219 KB

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