window-basic-main.cpp 225 KB

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