window-basic-main.cpp 209 KB

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