window-basic-main.cpp 208 KB

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