window-basic-main.cpp 210 KB

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