window-basic-main.cpp 211 KB

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