window-basic-main.cpp 210 KB

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