window-basic-main.cpp 209 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895
  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. /* clear out UI event queue */
  1845. QApplication::sendPostedEvents(App());
  1846. if (updateCheckThread && updateCheckThread->isRunning())
  1847. updateCheckThread->wait();
  1848. delete multiviewProjectorMenu;
  1849. delete previewProjector;
  1850. delete studioProgramProjector;
  1851. delete previewProjectorSource;
  1852. delete previewProjectorMain;
  1853. delete sourceProjector;
  1854. delete sceneProjectorMenu;
  1855. delete scaleFilteringMenu;
  1856. delete colorMenu;
  1857. delete colorWidgetAction;
  1858. delete colorSelect;
  1859. delete deinterlaceMenu;
  1860. delete perSceneTransitionMenu;
  1861. delete shortcutFilter;
  1862. delete trayMenu;
  1863. delete programOptions;
  1864. delete program;
  1865. /* XXX: any obs data must be released before calling obs_shutdown.
  1866. * currently, we can't automate this with C++ RAII because of the
  1867. * delicate nature of obs_shutdown needing to be freed before the UI
  1868. * can be freed, and we have no control over the destruction order of
  1869. * the Qt UI stuff, so we have to manually clear any references to
  1870. * libobs. */
  1871. delete cpuUsageTimer;
  1872. os_cpu_usage_info_destroy(cpuUsageInfo);
  1873. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1874. ClearHotkeys();
  1875. service = nullptr;
  1876. outputHandler.reset();
  1877. if (interaction)
  1878. delete interaction;
  1879. if (properties)
  1880. delete properties;
  1881. if (filters)
  1882. delete filters;
  1883. if (transformWindow)
  1884. delete transformWindow;
  1885. if (advAudioWindow)
  1886. delete advAudioWindow;
  1887. if (about)
  1888. delete about;
  1889. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1890. OBSBasic::RenderMain, this);
  1891. obs_enter_graphics();
  1892. gs_vertexbuffer_destroy(box);
  1893. gs_vertexbuffer_destroy(boxLeft);
  1894. gs_vertexbuffer_destroy(boxTop);
  1895. gs_vertexbuffer_destroy(boxRight);
  1896. gs_vertexbuffer_destroy(boxBottom);
  1897. gs_vertexbuffer_destroy(circle);
  1898. obs_leave_graphics();
  1899. /* When shutting down, sometimes source references can get in to the
  1900. * event queue, and if we don't forcibly process those events they
  1901. * won't get processed until after obs_shutdown has been called. I
  1902. * really wish there were a more elegant way to deal with this via C++,
  1903. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1904. * normal C++ behavior for your data to be freed in the order that you
  1905. * expect or want it to. */
  1906. QApplication::sendPostedEvents(this);
  1907. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1908. LIBOBS_API_VER);
  1909. #if OBS_RELEASE_CANDIDATE > 0
  1910. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  1911. OBS_RELEASE_CANDIDATE_VER);
  1912. #endif
  1913. bool alwaysOnTop = IsAlwaysOnTop(this);
  1914. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1915. previewEnabled);
  1916. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1917. alwaysOnTop);
  1918. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1919. "SceneDuplicationMode", sceneDuplicationMode);
  1920. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  1921. swapScenesMode);
  1922. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1923. "EditPropertiesMode", editPropertiesMode);
  1924. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1925. "PreviewProgramMode", IsPreviewProgramMode());
  1926. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  1927. ui->lockUI->isChecked());
  1928. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1929. #ifdef _WIN32
  1930. uint32_t winVer = GetWindowsVersion();
  1931. if (winVer > 0 && winVer < 0x602) {
  1932. bool disableAero =
  1933. config_get_bool(basicConfig, "Video", "DisableAero");
  1934. if (disableAero) {
  1935. SetAeroEnabled(true);
  1936. }
  1937. }
  1938. #endif
  1939. #ifdef BROWSER_AVAILABLE
  1940. DestroyPanelCookieManager();
  1941. delete cef;
  1942. cef = nullptr;
  1943. #endif
  1944. }
  1945. void OBSBasic::SaveProjectNow()
  1946. {
  1947. if (disableSaving)
  1948. return;
  1949. projectChanged = true;
  1950. SaveProjectDeferred();
  1951. }
  1952. void OBSBasic::SaveProject()
  1953. {
  1954. if (disableSaving)
  1955. return;
  1956. projectChanged = true;
  1957. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1958. Qt::QueuedConnection);
  1959. }
  1960. void OBSBasic::SaveProjectDeferred()
  1961. {
  1962. if (disableSaving)
  1963. return;
  1964. if (!projectChanged)
  1965. return;
  1966. projectChanged = false;
  1967. const char *sceneCollection = config_get_string(
  1968. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1969. char savePath[512];
  1970. char fileName[512];
  1971. int ret;
  1972. if (!sceneCollection)
  1973. return;
  1974. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1975. sceneCollection);
  1976. if (ret <= 0)
  1977. return;
  1978. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1979. if (ret <= 0)
  1980. return;
  1981. Save(savePath);
  1982. }
  1983. OBSSource OBSBasic::GetProgramSource()
  1984. {
  1985. return OBSGetStrongRef(programScene);
  1986. }
  1987. OBSScene OBSBasic::GetCurrentScene()
  1988. {
  1989. QListWidgetItem *item = ui->scenes->currentItem();
  1990. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1991. }
  1992. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1993. {
  1994. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1995. }
  1996. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1997. {
  1998. return ui->sources->Get(GetTopSelectedSourceItem());
  1999. }
  2000. void OBSBasic::UpdatePreviewScalingMenu()
  2001. {
  2002. bool fixedScaling = ui->preview->IsFixedScaling();
  2003. float scalingAmount = ui->preview->GetScalingAmount();
  2004. if (!fixedScaling) {
  2005. ui->actionScaleWindow->setChecked(true);
  2006. ui->actionScaleCanvas->setChecked(false);
  2007. ui->actionScaleOutput->setChecked(false);
  2008. return;
  2009. }
  2010. obs_video_info ovi;
  2011. obs_get_video_info(&ovi);
  2012. ui->actionScaleWindow->setChecked(false);
  2013. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2014. ui->actionScaleOutput->setChecked(scalingAmount ==
  2015. float(ovi.output_width) /
  2016. float(ovi.base_width));
  2017. }
  2018. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2019. {
  2020. if (interaction)
  2021. interaction->close();
  2022. interaction = new OBSBasicInteraction(this, source);
  2023. interaction->Init();
  2024. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2025. }
  2026. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2027. {
  2028. if (properties)
  2029. properties->close();
  2030. properties = new OBSBasicProperties(this, source);
  2031. properties->Init();
  2032. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2033. }
  2034. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2035. {
  2036. if (filters)
  2037. filters->close();
  2038. filters = new OBSBasicFilters(this, source);
  2039. filters->Init();
  2040. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2041. }
  2042. /* Qt callbacks for invokeMethod */
  2043. void OBSBasic::AddScene(OBSSource source)
  2044. {
  2045. const char *name = obs_source_get_name(source);
  2046. obs_scene_t *scene = obs_scene_from_source(source);
  2047. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2048. SetOBSRef(item, OBSScene(scene));
  2049. ui->scenes->addItem(item);
  2050. obs_hotkey_register_source(
  2051. source, "OBSBasic.SelectScene",
  2052. Str("Basic.Hotkeys.SelectScene"),
  2053. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2054. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2055. App()->GetMainWindow());
  2056. auto potential_source =
  2057. static_cast<obs_source_t *>(data);
  2058. auto source = obs_source_get_ref(potential_source);
  2059. if (source && pressed)
  2060. main->SetCurrentScene(source);
  2061. obs_source_release(source);
  2062. },
  2063. static_cast<obs_source_t *>(source));
  2064. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2065. SignalContainer<OBSScene> container;
  2066. container.ref = scene;
  2067. container.handlers.assign({
  2068. std::make_shared<OBSSignal>(handler, "item_add",
  2069. OBSBasic::SceneItemAdded, this),
  2070. std::make_shared<OBSSignal>(handler, "item_select",
  2071. OBSBasic::SceneItemSelected, this),
  2072. std::make_shared<OBSSignal>(handler, "item_deselect",
  2073. OBSBasic::SceneItemDeselected,
  2074. this),
  2075. std::make_shared<OBSSignal>(handler, "reorder",
  2076. OBSBasic::SceneReordered, this),
  2077. std::make_shared<OBSSignal>(handler, "refresh",
  2078. OBSBasic::SceneRefreshed, this),
  2079. });
  2080. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2081. QVariant::fromValue(container));
  2082. /* if the scene already has items (a duplicated scene) add them */
  2083. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2084. AddSceneItem(item);
  2085. };
  2086. using addSceneItem_t = decltype(addSceneItem);
  2087. obs_scene_enum_items(
  2088. scene,
  2089. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2090. addSceneItem_t *func;
  2091. func = reinterpret_cast<addSceneItem_t *>(param);
  2092. (*func)(item);
  2093. return true;
  2094. },
  2095. &addSceneItem);
  2096. SaveProject();
  2097. if (!disableSaving) {
  2098. obs_source_t *source = obs_scene_get_source(scene);
  2099. blog(LOG_INFO, "User added scene '%s'",
  2100. obs_source_get_name(source));
  2101. OBSProjector::UpdateMultiviewProjectors();
  2102. }
  2103. if (api)
  2104. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2105. }
  2106. void OBSBasic::RemoveScene(OBSSource source)
  2107. {
  2108. obs_scene_t *scene = obs_scene_from_source(source);
  2109. QListWidgetItem *sel = nullptr;
  2110. int count = ui->scenes->count();
  2111. for (int i = 0; i < count; i++) {
  2112. auto item = ui->scenes->item(i);
  2113. auto cur_scene = GetOBSRef<OBSScene>(item);
  2114. if (cur_scene != scene)
  2115. continue;
  2116. sel = item;
  2117. break;
  2118. }
  2119. if (sel != nullptr) {
  2120. if (sel == ui->scenes->currentItem())
  2121. ui->sources->Clear();
  2122. delete sel;
  2123. }
  2124. SaveProject();
  2125. if (!disableSaving) {
  2126. blog(LOG_INFO, "User Removed scene '%s'",
  2127. obs_source_get_name(source));
  2128. OBSProjector::UpdateMultiviewProjectors();
  2129. }
  2130. if (api)
  2131. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2132. }
  2133. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2134. {
  2135. obs_sceneitem_t *selectedItem =
  2136. reinterpret_cast<obs_sceneitem_t *>(param);
  2137. if (obs_sceneitem_is_group(item))
  2138. obs_sceneitem_group_enum_items(item, select_one, param);
  2139. obs_sceneitem_select(item, (selectedItem == item));
  2140. UNUSED_PARAMETER(scene);
  2141. return true;
  2142. }
  2143. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2144. {
  2145. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2146. if (GetCurrentScene() == scene)
  2147. ui->sources->Add(item);
  2148. SaveProject();
  2149. if (!disableSaving) {
  2150. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2151. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2152. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2153. obs_source_get_name(itemSource),
  2154. obs_source_get_id(itemSource),
  2155. obs_source_get_name(sceneSource));
  2156. obs_scene_enum_items(scene, select_one,
  2157. (obs_sceneitem_t *)item);
  2158. }
  2159. }
  2160. void OBSBasic::UpdateSceneSelection(OBSSource source)
  2161. {
  2162. if (source) {
  2163. obs_scene_t *scene = obs_scene_from_source(source);
  2164. const char *name = obs_source_get_name(source);
  2165. if (!scene)
  2166. return;
  2167. QList<QListWidgetItem *> items =
  2168. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  2169. if (items.count()) {
  2170. sceneChanging = true;
  2171. ui->scenes->setCurrentItem(items.first());
  2172. sceneChanging = false;
  2173. OBSScene curScene =
  2174. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  2175. if (api && scene != curScene)
  2176. api->on_event(
  2177. OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2178. }
  2179. }
  2180. }
  2181. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2182. const QString &prevName)
  2183. {
  2184. QList<QListWidgetItem *> items =
  2185. listWidget->findItems(prevName, Qt::MatchExactly);
  2186. for (int i = 0; i < items.count(); i++)
  2187. items[i]->setText(newName);
  2188. }
  2189. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2190. QString prevName)
  2191. {
  2192. RenameListValues(ui->scenes, newName, prevName);
  2193. for (size_t i = 0; i < volumes.size(); i++) {
  2194. if (volumes[i]->GetName().compare(prevName) == 0)
  2195. volumes[i]->SetName(newName);
  2196. }
  2197. for (size_t i = 0; i < projectors.size(); i++) {
  2198. if (projectors[i]->GetSource() == source)
  2199. projectors[i]->RenameProjector(prevName, newName);
  2200. }
  2201. SaveProject();
  2202. obs_scene_t *scene = obs_scene_from_source(source);
  2203. if (scene)
  2204. OBSProjector::UpdateMultiviewProjectors();
  2205. }
  2206. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  2207. {
  2208. SignalBlocker sourcesSignalBlocker(ui->sources);
  2209. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  2210. return;
  2211. ui->sources->SelectItem(item, select);
  2212. }
  2213. static inline bool SourceMixerHidden(obs_source_t *source)
  2214. {
  2215. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2216. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2217. obs_data_release(priv_settings);
  2218. return hidden;
  2219. }
  2220. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2221. {
  2222. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2223. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2224. obs_data_release(priv_settings);
  2225. }
  2226. void OBSBasic::GetAudioSourceFilters()
  2227. {
  2228. QAction *action = reinterpret_cast<QAction *>(sender());
  2229. VolControl *vol = action->property("volControl").value<VolControl *>();
  2230. obs_source_t *source = vol->GetSource();
  2231. CreateFiltersWindow(source);
  2232. }
  2233. void OBSBasic::GetAudioSourceProperties()
  2234. {
  2235. QAction *action = reinterpret_cast<QAction *>(sender());
  2236. VolControl *vol = action->property("volControl").value<VolControl *>();
  2237. obs_source_t *source = vol->GetSource();
  2238. CreatePropertiesWindow(source);
  2239. }
  2240. void OBSBasic::HideAudioControl()
  2241. {
  2242. QAction *action = reinterpret_cast<QAction *>(sender());
  2243. VolControl *vol = action->property("volControl").value<VolControl *>();
  2244. obs_source_t *source = vol->GetSource();
  2245. if (!SourceMixerHidden(source)) {
  2246. SetSourceMixerHidden(source, true);
  2247. DeactivateAudioSource(source);
  2248. }
  2249. }
  2250. void OBSBasic::UnhideAllAudioControls()
  2251. {
  2252. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2253. {
  2254. if (!obs_source_active(source))
  2255. return true;
  2256. if (!SourceMixerHidden(source))
  2257. return true;
  2258. SetSourceMixerHidden(source, false);
  2259. ActivateAudioSource(source);
  2260. return true;
  2261. };
  2262. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2263. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2264. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2265. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2266. }
  2267. void OBSBasic::ToggleHideMixer()
  2268. {
  2269. OBSSceneItem item = GetCurrentSceneItem();
  2270. OBSSource source = obs_sceneitem_get_source(item);
  2271. if (!SourceMixerHidden(source)) {
  2272. SetSourceMixerHidden(source, true);
  2273. DeactivateAudioSource(source);
  2274. } else {
  2275. SetSourceMixerHidden(source, false);
  2276. ActivateAudioSource(source);
  2277. }
  2278. }
  2279. void OBSBasic::MixerRenameSource()
  2280. {
  2281. QAction *action = reinterpret_cast<QAction *>(sender());
  2282. VolControl *vol = action->property("volControl").value<VolControl *>();
  2283. OBSSource source = vol->GetSource();
  2284. const char *prevName = obs_source_get_name(source);
  2285. for (;;) {
  2286. string name;
  2287. bool accepted = NameDialog::AskForName(
  2288. this, QTStr("Basic.Main.MixerRename.Title"),
  2289. QTStr("Basic.Main.MixerRename.Text"), name,
  2290. QT_UTF8(prevName));
  2291. if (!accepted)
  2292. return;
  2293. if (name.empty()) {
  2294. OBSMessageBox::warning(this,
  2295. QTStr("NoNameEntered.Title"),
  2296. QTStr("NoNameEntered.Text"));
  2297. continue;
  2298. }
  2299. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2300. obs_source_release(sourceTest);
  2301. if (sourceTest) {
  2302. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2303. QTStr("NameExists.Text"));
  2304. continue;
  2305. }
  2306. obs_source_set_name(source, name.c_str());
  2307. break;
  2308. }
  2309. }
  2310. static inline bool SourceVolumeLocked(obs_source_t *source)
  2311. {
  2312. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2313. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2314. obs_data_release(priv_settings);
  2315. return lock;
  2316. }
  2317. void OBSBasic::LockVolumeControl(bool lock)
  2318. {
  2319. QAction *action = reinterpret_cast<QAction *>(sender());
  2320. VolControl *vol = action->property("volControl").value<VolControl *>();
  2321. obs_source_t *source = vol->GetSource();
  2322. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2323. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2324. obs_data_release(priv_settings);
  2325. vol->EnableSlider(!lock);
  2326. }
  2327. void OBSBasic::VolControlContextMenu()
  2328. {
  2329. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2330. /* ------------------- */
  2331. QAction lockAction(QTStr("LockVolume"), this);
  2332. lockAction.setCheckable(true);
  2333. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2334. QAction hideAction(QTStr("Hide"), this);
  2335. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2336. QAction mixerRenameAction(QTStr("Rename"), this);
  2337. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2338. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2339. QAction filtersAction(QTStr("Filters"), this);
  2340. QAction propertiesAction(QTStr("Properties"), this);
  2341. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2342. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2343. toggleControlLayoutAction.setCheckable(true);
  2344. toggleControlLayoutAction.setChecked(config_get_bool(
  2345. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2346. /* ------------------- */
  2347. connect(&hideAction, &QAction::triggered, this,
  2348. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2349. connect(&unhideAllAction, &QAction::triggered, this,
  2350. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2351. connect(&lockAction, &QAction::toggled, this,
  2352. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2353. connect(&mixerRenameAction, &QAction::triggered, this,
  2354. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2355. connect(&copyFiltersAction, &QAction::triggered, this,
  2356. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2357. connect(&pasteFiltersAction, &QAction::triggered, this,
  2358. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2359. connect(&filtersAction, &QAction::triggered, this,
  2360. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2361. connect(&propertiesAction, &QAction::triggered, this,
  2362. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2363. connect(&advPropAction, &QAction::triggered, this,
  2364. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2365. Qt::DirectConnection);
  2366. /* ------------------- */
  2367. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2368. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2369. /* ------------------- */
  2370. hideAction.setProperty("volControl",
  2371. QVariant::fromValue<VolControl *>(vol));
  2372. lockAction.setProperty("volControl",
  2373. QVariant::fromValue<VolControl *>(vol));
  2374. mixerRenameAction.setProperty("volControl",
  2375. QVariant::fromValue<VolControl *>(vol));
  2376. copyFiltersAction.setProperty("volControl",
  2377. QVariant::fromValue<VolControl *>(vol));
  2378. pasteFiltersAction.setProperty("volControl",
  2379. QVariant::fromValue<VolControl *>(vol));
  2380. filtersAction.setProperty("volControl",
  2381. QVariant::fromValue<VolControl *>(vol));
  2382. propertiesAction.setProperty("volControl",
  2383. QVariant::fromValue<VolControl *>(vol));
  2384. /* ------------------- */
  2385. if (copyFiltersString == nullptr)
  2386. pasteFiltersAction.setEnabled(false);
  2387. else
  2388. pasteFiltersAction.setEnabled(true);
  2389. QMenu popup;
  2390. popup.addAction(&lockAction);
  2391. popup.addSeparator();
  2392. popup.addAction(&unhideAllAction);
  2393. popup.addAction(&hideAction);
  2394. popup.addAction(&mixerRenameAction);
  2395. popup.addSeparator();
  2396. popup.addAction(&copyFiltersAction);
  2397. popup.addAction(&pasteFiltersAction);
  2398. popup.addSeparator();
  2399. popup.addAction(&toggleControlLayoutAction);
  2400. popup.addSeparator();
  2401. popup.addAction(&filtersAction);
  2402. popup.addAction(&propertiesAction);
  2403. popup.addAction(&advPropAction);
  2404. popup.exec(QCursor::pos());
  2405. }
  2406. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2407. {
  2408. StackedMixerAreaContextMenuRequested();
  2409. }
  2410. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2411. {
  2412. StackedMixerAreaContextMenuRequested();
  2413. }
  2414. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2415. {
  2416. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2417. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2418. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2419. toggleControlLayoutAction.setCheckable(true);
  2420. toggleControlLayoutAction.setChecked(config_get_bool(
  2421. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2422. /* ------------------- */
  2423. connect(&unhideAllAction, &QAction::triggered, this,
  2424. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2425. connect(&advPropAction, &QAction::triggered, this,
  2426. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2427. Qt::DirectConnection);
  2428. /* ------------------- */
  2429. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2430. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2431. /* ------------------- */
  2432. QMenu popup;
  2433. popup.addAction(&unhideAllAction);
  2434. popup.addSeparator();
  2435. popup.addAction(&toggleControlLayoutAction);
  2436. popup.addSeparator();
  2437. popup.addAction(&advPropAction);
  2438. popup.exec(QCursor::pos());
  2439. }
  2440. void OBSBasic::ToggleMixerLayout(bool vertical)
  2441. {
  2442. if (vertical) {
  2443. ui->stackedMixerArea->setMinimumSize(180, 220);
  2444. ui->stackedMixerArea->setCurrentIndex(1);
  2445. } else {
  2446. ui->stackedMixerArea->setMinimumSize(220, 0);
  2447. ui->stackedMixerArea->setCurrentIndex(0);
  2448. }
  2449. }
  2450. void OBSBasic::ToggleVolControlLayout()
  2451. {
  2452. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2453. "VerticalVolControl");
  2454. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2455. vertical);
  2456. ToggleMixerLayout(vertical);
  2457. // We need to store it so we can delete current and then add
  2458. // at the right order
  2459. vector<OBSSource> sources;
  2460. for (size_t i = 0; i != volumes.size(); i++)
  2461. sources.emplace_back(volumes[i]->GetSource());
  2462. ClearVolumeControls();
  2463. for (const auto &source : sources)
  2464. ActivateAudioSource(source);
  2465. }
  2466. void OBSBasic::ActivateAudioSource(OBSSource source)
  2467. {
  2468. if (SourceMixerHidden(source))
  2469. return;
  2470. if (!obs_source_audio_active(source))
  2471. return;
  2472. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2473. "VerticalVolControl");
  2474. VolControl *vol = new VolControl(source, true, vertical);
  2475. vol->EnableSlider(!SourceVolumeLocked(source));
  2476. double meterDecayRate =
  2477. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2478. vol->SetMeterDecayRate(meterDecayRate);
  2479. uint32_t peakMeterTypeIdx =
  2480. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2481. enum obs_peak_meter_type peakMeterType;
  2482. switch (peakMeterTypeIdx) {
  2483. case 0:
  2484. peakMeterType = SAMPLE_PEAK_METER;
  2485. break;
  2486. case 1:
  2487. peakMeterType = TRUE_PEAK_METER;
  2488. break;
  2489. default:
  2490. peakMeterType = SAMPLE_PEAK_METER;
  2491. break;
  2492. }
  2493. vol->setPeakMeterType(peakMeterType);
  2494. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2495. connect(vol, &QWidget::customContextMenuRequested, this,
  2496. &OBSBasic::VolControlContextMenu);
  2497. connect(vol, &VolControl::ConfigClicked, this,
  2498. &OBSBasic::VolControlContextMenu);
  2499. InsertQObjectByName(volumes, vol);
  2500. for (auto volume : volumes) {
  2501. if (vertical)
  2502. ui->vVolControlLayout->addWidget(volume);
  2503. else
  2504. ui->hVolControlLayout->addWidget(volume);
  2505. }
  2506. }
  2507. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2508. {
  2509. for (size_t i = 0; i < volumes.size(); i++) {
  2510. if (volumes[i]->GetSource() == source) {
  2511. delete volumes[i];
  2512. volumes.erase(volumes.begin() + i);
  2513. break;
  2514. }
  2515. }
  2516. }
  2517. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2518. {
  2519. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2520. !obs_source_is_group(source)) {
  2521. int count = ui->scenes->count();
  2522. if (count == 1) {
  2523. OBSMessageBox::information(this,
  2524. QTStr("FinalScene.Title"),
  2525. QTStr("FinalScene.Text"));
  2526. return false;
  2527. }
  2528. }
  2529. const char *name = obs_source_get_name(source);
  2530. QString text = QTStr("ConfirmRemove.Text");
  2531. text.replace("$1", QT_UTF8(name));
  2532. QMessageBox remove_source(this);
  2533. remove_source.setText(text);
  2534. QAbstractButton *Yes =
  2535. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2536. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2537. remove_source.setIcon(QMessageBox::Question);
  2538. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2539. remove_source.exec();
  2540. return Yes == remove_source.clickedButton();
  2541. }
  2542. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2543. #ifdef UPDATE_SPARKLE
  2544. void init_sparkle_updater(bool update_to_undeployed);
  2545. void trigger_sparkle_update();
  2546. #endif
  2547. void OBSBasic::TimedCheckForUpdates()
  2548. {
  2549. if (!config_get_bool(App()->GlobalConfig(), "General",
  2550. "EnableAutoUpdates"))
  2551. return;
  2552. #ifdef UPDATE_SPARKLE
  2553. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2554. "UpdateToUndeployed"));
  2555. #elif _WIN32
  2556. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2557. "LastUpdateCheck");
  2558. uint32_t lastVersion =
  2559. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2560. if (lastVersion < LIBOBS_API_VER) {
  2561. lastUpdate = 0;
  2562. config_set_int(App()->GlobalConfig(), "General",
  2563. "LastUpdateCheck", 0);
  2564. }
  2565. long long t = (long long)time(nullptr);
  2566. long long secs = t - lastUpdate;
  2567. if (secs > UPDATE_CHECK_INTERVAL)
  2568. CheckForUpdates(false);
  2569. #endif
  2570. }
  2571. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2572. {
  2573. #ifdef UPDATE_SPARKLE
  2574. trigger_sparkle_update();
  2575. #elif _WIN32
  2576. ui->actionCheckForUpdates->setEnabled(false);
  2577. if (updateCheckThread && updateCheckThread->isRunning())
  2578. return;
  2579. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2580. updateCheckThread->start();
  2581. #endif
  2582. UNUSED_PARAMETER(manualUpdate);
  2583. }
  2584. void OBSBasic::updateCheckFinished()
  2585. {
  2586. ui->actionCheckForUpdates->setEnabled(true);
  2587. }
  2588. void OBSBasic::DuplicateSelectedScene()
  2589. {
  2590. OBSScene curScene = GetCurrentScene();
  2591. if (!curScene)
  2592. return;
  2593. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2594. QString format{obs_source_get_name(curSceneSource)};
  2595. format += " %1";
  2596. int i = 2;
  2597. QString placeHolderText = format.arg(i);
  2598. obs_source_t *source = nullptr;
  2599. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2600. obs_source_release(source);
  2601. placeHolderText = format.arg(++i);
  2602. }
  2603. for (;;) {
  2604. string name;
  2605. bool accepted = NameDialog::AskForName(
  2606. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2607. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2608. placeHolderText);
  2609. if (!accepted)
  2610. return;
  2611. if (name.empty()) {
  2612. OBSMessageBox::warning(this,
  2613. QTStr("NoNameEntered.Title"),
  2614. QTStr("NoNameEntered.Text"));
  2615. continue;
  2616. }
  2617. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2618. if (source) {
  2619. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2620. QTStr("NameExists.Text"));
  2621. obs_source_release(source);
  2622. continue;
  2623. }
  2624. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2625. OBS_SCENE_DUP_REFS);
  2626. source = obs_scene_get_source(scene);
  2627. SetCurrentScene(source, true);
  2628. obs_scene_release(scene);
  2629. break;
  2630. }
  2631. }
  2632. void OBSBasic::RemoveSelectedScene()
  2633. {
  2634. OBSScene scene = GetCurrentScene();
  2635. if (scene) {
  2636. obs_source_t *source = obs_scene_get_source(scene);
  2637. if (QueryRemoveSource(source)) {
  2638. obs_source_remove(source);
  2639. if (api)
  2640. api->on_event(
  2641. OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2642. }
  2643. }
  2644. }
  2645. void OBSBasic::RemoveSelectedSceneItem()
  2646. {
  2647. OBSSceneItem item = GetCurrentSceneItem();
  2648. if (item) {
  2649. obs_source_t *source = obs_sceneitem_get_source(item);
  2650. if (QueryRemoveSource(source))
  2651. obs_sceneitem_remove(item);
  2652. }
  2653. }
  2654. void OBSBasic::ReorderSources(OBSScene scene)
  2655. {
  2656. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2657. return;
  2658. ui->sources->ReorderItems();
  2659. SaveProject();
  2660. }
  2661. void OBSBasic::RefreshSources(OBSScene scene)
  2662. {
  2663. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2664. return;
  2665. ui->sources->RefreshItems();
  2666. SaveProject();
  2667. }
  2668. /* OBS Callbacks */
  2669. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2670. {
  2671. OBSBasic *window = static_cast<OBSBasic *>(data);
  2672. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2673. QMetaObject::invokeMethod(window, "ReorderSources",
  2674. Q_ARG(OBSScene, OBSScene(scene)));
  2675. }
  2676. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  2677. {
  2678. OBSBasic *window = static_cast<OBSBasic *>(data);
  2679. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2680. QMetaObject::invokeMethod(window, "RefreshSources",
  2681. Q_ARG(OBSScene, OBSScene(scene)));
  2682. }
  2683. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2684. {
  2685. OBSBasic *window = static_cast<OBSBasic *>(data);
  2686. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2687. QMetaObject::invokeMethod(window, "AddSceneItem",
  2688. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2689. }
  2690. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2691. {
  2692. OBSBasic *window = static_cast<OBSBasic *>(data);
  2693. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2694. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2695. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2696. Q_ARG(OBSScene, scene),
  2697. Q_ARG(OBSSceneItem, item), Q_ARG(bool, true));
  2698. }
  2699. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2700. {
  2701. OBSBasic *window = static_cast<OBSBasic *>(data);
  2702. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  2703. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  2704. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2705. Q_ARG(OBSScene, scene),
  2706. Q_ARG(OBSSceneItem, item),
  2707. Q_ARG(bool, false));
  2708. }
  2709. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2710. {
  2711. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2712. if (obs_scene_from_source(source) != NULL)
  2713. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2714. "AddScene", WaitConnection(),
  2715. Q_ARG(OBSSource, OBSSource(source)));
  2716. }
  2717. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2718. {
  2719. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2720. if (obs_scene_from_source(source) != NULL)
  2721. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2722. "RemoveScene",
  2723. Q_ARG(OBSSource, OBSSource(source)));
  2724. }
  2725. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2726. {
  2727. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2728. uint32_t flags = obs_source_get_output_flags(source);
  2729. if (flags & OBS_SOURCE_AUDIO)
  2730. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2731. "ActivateAudioSource",
  2732. Q_ARG(OBSSource, OBSSource(source)));
  2733. }
  2734. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2735. {
  2736. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2737. uint32_t flags = obs_source_get_output_flags(source);
  2738. if (flags & OBS_SOURCE_AUDIO)
  2739. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2740. "DeactivateAudioSource",
  2741. Q_ARG(OBSSource, OBSSource(source)));
  2742. }
  2743. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  2744. {
  2745. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2746. if (obs_source_active(source))
  2747. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2748. "ActivateAudioSource",
  2749. Q_ARG(OBSSource, OBSSource(source)));
  2750. }
  2751. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  2752. {
  2753. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2754. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2755. "DeactivateAudioSource",
  2756. Q_ARG(OBSSource, OBSSource(source)));
  2757. }
  2758. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2759. {
  2760. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  2761. const char *newName = calldata_string(params, "new_name");
  2762. const char *prevName = calldata_string(params, "prev_name");
  2763. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2764. "RenameSources", Q_ARG(OBSSource, source),
  2765. Q_ARG(QString, QT_UTF8(newName)),
  2766. Q_ARG(QString, QT_UTF8(prevName)));
  2767. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2768. }
  2769. void OBSBasic::DrawBackdrop(float cx, float cy)
  2770. {
  2771. if (!box)
  2772. return;
  2773. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  2774. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2775. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2776. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2777. vec4 colorVal;
  2778. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2779. gs_effect_set_vec4(color, &colorVal);
  2780. gs_technique_begin(tech);
  2781. gs_technique_begin_pass(tech, 0);
  2782. gs_matrix_push();
  2783. gs_matrix_identity();
  2784. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2785. gs_load_vertexbuffer(box);
  2786. gs_draw(GS_TRISTRIP, 0, 0);
  2787. gs_matrix_pop();
  2788. gs_technique_end_pass(tech);
  2789. gs_technique_end(tech);
  2790. gs_load_vertexbuffer(nullptr);
  2791. GS_DEBUG_MARKER_END();
  2792. }
  2793. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2794. {
  2795. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  2796. OBSBasic *window = static_cast<OBSBasic *>(data);
  2797. obs_video_info ovi;
  2798. obs_get_video_info(&ovi);
  2799. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2800. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2801. gs_viewport_push();
  2802. gs_projection_push();
  2803. obs_display_t *display = window->ui->preview->GetDisplay();
  2804. uint32_t width, height;
  2805. obs_display_size(display, &width, &height);
  2806. float right = float(width) - window->previewX;
  2807. float bottom = float(height) - window->previewY;
  2808. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2809. 100.0f);
  2810. window->ui->preview->DrawOverflow();
  2811. /* --------------------------------------- */
  2812. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2813. -100.0f, 100.0f);
  2814. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  2815. window->previewCY);
  2816. if (window->IsPreviewProgramMode()) {
  2817. window->DrawBackdrop(float(ovi.base_width),
  2818. float(ovi.base_height));
  2819. OBSScene scene = window->GetCurrentScene();
  2820. obs_source_t *source = obs_scene_get_source(scene);
  2821. if (source)
  2822. obs_source_video_render(source);
  2823. } else {
  2824. obs_render_main_texture_src_color_only();
  2825. }
  2826. gs_load_vertexbuffer(nullptr);
  2827. /* --------------------------------------- */
  2828. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  2829. 100.0f);
  2830. gs_reset_viewport();
  2831. window->ui->preview->DrawSceneEditing();
  2832. /* --------------------------------------- */
  2833. gs_projection_pop();
  2834. gs_viewport_pop();
  2835. GS_DEBUG_MARKER_END();
  2836. UNUSED_PARAMETER(cx);
  2837. UNUSED_PARAMETER(cy);
  2838. }
  2839. /* Main class functions */
  2840. obs_service_t *OBSBasic::GetService()
  2841. {
  2842. if (!service) {
  2843. service =
  2844. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  2845. obs_service_release(service);
  2846. }
  2847. return service;
  2848. }
  2849. void OBSBasic::SetService(obs_service_t *newService)
  2850. {
  2851. if (newService)
  2852. service = newService;
  2853. }
  2854. int OBSBasic::GetTransitionDuration()
  2855. {
  2856. return ui->transitionDuration->value();
  2857. }
  2858. bool OBSBasic::StreamingActive() const
  2859. {
  2860. if (!outputHandler)
  2861. return false;
  2862. return outputHandler->StreamingActive();
  2863. }
  2864. bool OBSBasic::Active() const
  2865. {
  2866. if (!outputHandler)
  2867. return false;
  2868. return outputHandler->Active();
  2869. }
  2870. #ifdef _WIN32
  2871. #define IS_WIN32 1
  2872. #else
  2873. #define IS_WIN32 0
  2874. #endif
  2875. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2876. {
  2877. return obs_reset_video(ovi);
  2878. }
  2879. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2880. {
  2881. const char *scaleTypeStr =
  2882. config_get_string(basicConfig, "Video", "ScaleType");
  2883. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2884. return OBS_SCALE_BILINEAR;
  2885. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2886. return OBS_SCALE_LANCZOS;
  2887. else if (astrcmpi(scaleTypeStr, "area") == 0)
  2888. return OBS_SCALE_AREA;
  2889. else
  2890. return OBS_SCALE_BICUBIC;
  2891. }
  2892. static inline enum video_format GetVideoFormatFromName(const char *name)
  2893. {
  2894. if (astrcmpi(name, "I420") == 0)
  2895. return VIDEO_FORMAT_I420;
  2896. else if (astrcmpi(name, "NV12") == 0)
  2897. return VIDEO_FORMAT_NV12;
  2898. else if (astrcmpi(name, "I444") == 0)
  2899. return VIDEO_FORMAT_I444;
  2900. #if 0 //currently unsupported
  2901. else if (astrcmpi(name, "YVYU") == 0)
  2902. return VIDEO_FORMAT_YVYU;
  2903. else if (astrcmpi(name, "YUY2") == 0)
  2904. return VIDEO_FORMAT_YUY2;
  2905. else if (astrcmpi(name, "UYVY") == 0)
  2906. return VIDEO_FORMAT_UYVY;
  2907. #endif
  2908. else
  2909. return VIDEO_FORMAT_RGBA;
  2910. }
  2911. void OBSBasic::ResetUI()
  2912. {
  2913. bool studioPortraitLayout = config_get_bool(
  2914. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  2915. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2916. "StudioModeLabels");
  2917. if (studioPortraitLayout)
  2918. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2919. else
  2920. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2921. if (previewProgramMode)
  2922. ui->previewLabel->setHidden(!labels);
  2923. if (programLabel)
  2924. programLabel->setHidden(!labels);
  2925. }
  2926. int OBSBasic::ResetVideo()
  2927. {
  2928. if (outputHandler && outputHandler->Active())
  2929. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2930. ProfileScope("OBSBasic::ResetVideo");
  2931. struct obs_video_info ovi;
  2932. int ret;
  2933. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2934. const char *colorFormat =
  2935. config_get_string(basicConfig, "Video", "ColorFormat");
  2936. const char *colorSpace =
  2937. config_get_string(basicConfig, "Video", "ColorSpace");
  2938. const char *colorRange =
  2939. config_get_string(basicConfig, "Video", "ColorRange");
  2940. ovi.graphics_module = App()->GetRenderModule();
  2941. ovi.base_width =
  2942. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  2943. ovi.base_height =
  2944. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  2945. ovi.output_width =
  2946. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  2947. ovi.output_height =
  2948. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  2949. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2950. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ? VIDEO_CS_601
  2951. : VIDEO_CS_709;
  2952. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  2953. : VIDEO_RANGE_PARTIAL;
  2954. ovi.adapter =
  2955. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  2956. ovi.gpu_conversion = true;
  2957. ovi.scale_type = GetScaleType(basicConfig);
  2958. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2959. ovi.base_width = 1920;
  2960. ovi.base_height = 1080;
  2961. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2962. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2963. }
  2964. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2965. ovi.output_width = ovi.base_width;
  2966. ovi.output_height = ovi.base_height;
  2967. config_set_uint(basicConfig, "Video", "OutputCX",
  2968. ovi.base_width);
  2969. config_set_uint(basicConfig, "Video", "OutputCY",
  2970. ovi.base_height);
  2971. }
  2972. ret = AttemptToResetVideo(&ovi);
  2973. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2974. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2975. blog(LOG_WARNING, "Tried to reset when "
  2976. "already active");
  2977. return ret;
  2978. }
  2979. /* Try OpenGL if DirectX fails on windows */
  2980. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2981. blog(LOG_WARNING,
  2982. "Failed to initialize obs video (%d) "
  2983. "with graphics_module='%s', retrying "
  2984. "with graphics_module='%s'",
  2985. ret, ovi.graphics_module, DL_OPENGL);
  2986. ovi.graphics_module = DL_OPENGL;
  2987. ret = AttemptToResetVideo(&ovi);
  2988. }
  2989. } else if (ret == OBS_VIDEO_SUCCESS) {
  2990. ResizePreview(ovi.base_width, ovi.base_height);
  2991. if (program)
  2992. ResizeProgram(ovi.base_width, ovi.base_height);
  2993. }
  2994. if (ret == OBS_VIDEO_SUCCESS) {
  2995. OBSBasicStats::InitializeValues();
  2996. OBSProjector::UpdateMultiviewProjectors();
  2997. }
  2998. return ret;
  2999. }
  3000. bool OBSBasic::ResetAudio()
  3001. {
  3002. ProfileScope("OBSBasic::ResetAudio");
  3003. struct obs_audio_info ai;
  3004. ai.samples_per_sec =
  3005. config_get_uint(basicConfig, "Audio", "SampleRate");
  3006. const char *channelSetupStr =
  3007. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3008. if (strcmp(channelSetupStr, "Mono") == 0)
  3009. ai.speakers = SPEAKERS_MONO;
  3010. else if (strcmp(channelSetupStr, "2.1") == 0)
  3011. ai.speakers = SPEAKERS_2POINT1;
  3012. else if (strcmp(channelSetupStr, "4.0") == 0)
  3013. ai.speakers = SPEAKERS_4POINT0;
  3014. else if (strcmp(channelSetupStr, "4.1") == 0)
  3015. ai.speakers = SPEAKERS_4POINT1;
  3016. else if (strcmp(channelSetupStr, "5.1") == 0)
  3017. ai.speakers = SPEAKERS_5POINT1;
  3018. else if (strcmp(channelSetupStr, "7.1") == 0)
  3019. ai.speakers = SPEAKERS_7POINT1;
  3020. else
  3021. ai.speakers = SPEAKERS_STEREO;
  3022. return obs_reset_audio(&ai);
  3023. }
  3024. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3025. const char *deviceDesc, int channel)
  3026. {
  3027. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3028. obs_source_t *source;
  3029. obs_data_t *settings;
  3030. source = obs_get_output_source(channel);
  3031. if (source) {
  3032. if (disable) {
  3033. obs_set_output_source(channel, nullptr);
  3034. } else {
  3035. settings = obs_source_get_settings(source);
  3036. const char *oldId =
  3037. obs_data_get_string(settings, "device_id");
  3038. if (strcmp(oldId, deviceId) != 0) {
  3039. obs_data_set_string(settings, "device_id",
  3040. deviceId);
  3041. obs_source_update(source, settings);
  3042. }
  3043. obs_data_release(settings);
  3044. }
  3045. obs_source_release(source);
  3046. } else if (!disable) {
  3047. settings = obs_data_create();
  3048. obs_data_set_string(settings, "device_id", deviceId);
  3049. source = obs_source_create(sourceId, deviceDesc, settings,
  3050. nullptr);
  3051. obs_data_release(settings);
  3052. obs_set_output_source(channel, source);
  3053. obs_source_release(source);
  3054. }
  3055. }
  3056. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3057. {
  3058. QSize targetSize;
  3059. bool isFixedScaling;
  3060. obs_video_info ovi;
  3061. /* resize preview panel to fix to the top section of the window */
  3062. targetSize = GetPixelSize(ui->preview);
  3063. isFixedScaling = ui->preview->IsFixedScaling();
  3064. obs_get_video_info(&ovi);
  3065. if (isFixedScaling) {
  3066. previewScale = ui->preview->GetScalingAmount();
  3067. GetCenterPosFromFixedScale(
  3068. int(cx), int(cy),
  3069. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3070. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3071. previewY, previewScale);
  3072. previewX += ui->preview->GetScrollX();
  3073. previewY += ui->preview->GetScrollY();
  3074. } else {
  3075. GetScaleAndCenterPos(int(cx), int(cy),
  3076. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3077. targetSize.height() -
  3078. PREVIEW_EDGE_SIZE * 2,
  3079. previewX, previewY, previewScale);
  3080. }
  3081. previewX += float(PREVIEW_EDGE_SIZE);
  3082. previewY += float(PREVIEW_EDGE_SIZE);
  3083. }
  3084. void OBSBasic::CloseDialogs()
  3085. {
  3086. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3087. if (!childDialogs.isEmpty()) {
  3088. for (int i = 0; i < childDialogs.size(); ++i) {
  3089. childDialogs.at(i)->close();
  3090. }
  3091. }
  3092. if (!stats.isNull())
  3093. stats->close(); //call close to save Stats geometry
  3094. if (!remux.isNull())
  3095. remux->close();
  3096. }
  3097. void OBSBasic::EnumDialogs()
  3098. {
  3099. visDialogs.clear();
  3100. modalDialogs.clear();
  3101. visMsgBoxes.clear();
  3102. /* fill list of Visible dialogs and Modal dialogs */
  3103. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3104. for (QDialog *dialog : dialogs) {
  3105. if (dialog->isVisible())
  3106. visDialogs.append(dialog);
  3107. if (dialog->isModal())
  3108. modalDialogs.append(dialog);
  3109. }
  3110. /* fill list of Visible message boxes */
  3111. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3112. for (QMessageBox *msgbox : msgBoxes) {
  3113. if (msgbox->isVisible())
  3114. visMsgBoxes.append(msgbox);
  3115. }
  3116. }
  3117. void OBSBasic::ClearSceneData()
  3118. {
  3119. disableSaving++;
  3120. CloseDialogs();
  3121. ClearVolumeControls();
  3122. ClearListItems(ui->scenes);
  3123. ui->sources->Clear();
  3124. ClearQuickTransitions();
  3125. ui->transitions->clear();
  3126. for (size_t i = 0; i < projectors.size(); i++) {
  3127. if (projectors[i])
  3128. delete projectors[i];
  3129. }
  3130. projectors.clear();
  3131. obs_set_output_source(0, nullptr);
  3132. obs_set_output_source(1, nullptr);
  3133. obs_set_output_source(2, nullptr);
  3134. obs_set_output_source(3, nullptr);
  3135. obs_set_output_source(4, nullptr);
  3136. obs_set_output_source(5, nullptr);
  3137. lastScene = nullptr;
  3138. swapScene = nullptr;
  3139. programScene = nullptr;
  3140. auto cb = [](void *unused, obs_source_t *source) {
  3141. obs_source_remove(source);
  3142. UNUSED_PARAMETER(unused);
  3143. return true;
  3144. };
  3145. obs_enum_sources(cb, nullptr);
  3146. if (api)
  3147. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3148. disableSaving--;
  3149. blog(LOG_INFO, "All scene data cleared");
  3150. blog(LOG_INFO, "------------------------------------------------");
  3151. }
  3152. void OBSBasic::closeEvent(QCloseEvent *event)
  3153. {
  3154. /* Do not close window if inside of a temporary event loop because we
  3155. * could be inside of an Auth::LoadUI call. Keep trying once per
  3156. * second until we've exit any known sub-loops. */
  3157. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3158. QTimer::singleShot(1000, this, SLOT(close()));
  3159. event->ignore();
  3160. return;
  3161. }
  3162. if (isVisible())
  3163. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3164. "geometry",
  3165. saveGeometry().toBase64().constData());
  3166. if (outputHandler && outputHandler->Active()) {
  3167. SetShowing(true);
  3168. QMessageBox::StandardButton button = OBSMessageBox::question(
  3169. this, QTStr("ConfirmExit.Title"),
  3170. QTStr("ConfirmExit.Text"));
  3171. if (button == QMessageBox::No) {
  3172. event->ignore();
  3173. restart = false;
  3174. return;
  3175. }
  3176. }
  3177. QWidget::closeEvent(event);
  3178. if (!event->isAccepted())
  3179. return;
  3180. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3181. if (introCheckThread)
  3182. introCheckThread->wait();
  3183. if (updateCheckThread)
  3184. updateCheckThread->wait();
  3185. if (logUploadThread)
  3186. logUploadThread->wait();
  3187. signalHandlers.clear();
  3188. Auth::Save();
  3189. SaveProjectNow();
  3190. auth.reset();
  3191. delete extraBrowsers;
  3192. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3193. saveState().toBase64().constData());
  3194. #ifdef BROWSER_AVAILABLE
  3195. SaveExtraBrowserDocks();
  3196. ClearExtraBrowserDocks();
  3197. #endif
  3198. if (api)
  3199. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3200. disableSaving++;
  3201. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3202. * sources, etc) so that all references are released before shutdown */
  3203. ClearSceneData();
  3204. App()->quit();
  3205. }
  3206. void OBSBasic::changeEvent(QEvent *event)
  3207. {
  3208. if (event->type() == QEvent::WindowStateChange) {
  3209. QWindowStateChangeEvent *stateEvent =
  3210. (QWindowStateChangeEvent *)event;
  3211. if (isMinimized()) {
  3212. if (trayIcon && trayIcon->isVisible() &&
  3213. sysTrayMinimizeToTray()) {
  3214. ToggleShowHide();
  3215. }
  3216. if (previewEnabled)
  3217. EnablePreviewDisplay(false);
  3218. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3219. isVisible()) {
  3220. if (previewEnabled)
  3221. EnablePreviewDisplay(true);
  3222. }
  3223. }
  3224. }
  3225. void OBSBasic::on_actionShow_Recordings_triggered()
  3226. {
  3227. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3228. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3229. const char *adv_path =
  3230. strcmp(type, "Standard")
  3231. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3232. : config_get_string(basicConfig, "AdvOut",
  3233. "RecFilePath");
  3234. const char *path = strcmp(mode, "Advanced")
  3235. ? config_get_string(basicConfig,
  3236. "SimpleOutput",
  3237. "FilePath")
  3238. : adv_path;
  3239. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3240. }
  3241. void OBSBasic::on_actionRemux_triggered()
  3242. {
  3243. if (!remux.isNull()) {
  3244. remux->show();
  3245. remux->raise();
  3246. return;
  3247. }
  3248. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3249. const char *path = strcmp(mode, "Advanced")
  3250. ? config_get_string(basicConfig,
  3251. "SimpleOutput",
  3252. "FilePath")
  3253. : config_get_string(basicConfig, "AdvOut",
  3254. "RecFilePath");
  3255. OBSRemux *remuxDlg;
  3256. remuxDlg = new OBSRemux(path, this);
  3257. remuxDlg->show();
  3258. remux = remuxDlg;
  3259. }
  3260. void OBSBasic::on_action_Settings_triggered()
  3261. {
  3262. static bool settings_already_executing = false;
  3263. /* Do not load settings window if inside of a temporary event loop
  3264. * because we could be inside of an Auth::LoadUI call. Keep trying
  3265. * once per second until we've exit any known sub-loops. */
  3266. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3267. QTimer::singleShot(1000, this,
  3268. SLOT(on_action_Settings_triggered()));
  3269. return;
  3270. }
  3271. if (settings_already_executing) {
  3272. return;
  3273. }
  3274. settings_already_executing = true;
  3275. {
  3276. OBSBasicSettings settings(this);
  3277. settings.exec();
  3278. }
  3279. SystemTray(false);
  3280. settings_already_executing = false;
  3281. if (restart) {
  3282. QMessageBox::StandardButton button = OBSMessageBox::question(
  3283. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3284. if (button == QMessageBox::Yes)
  3285. close();
  3286. else
  3287. restart = false;
  3288. }
  3289. }
  3290. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3291. {
  3292. if (advAudioWindow != nullptr) {
  3293. advAudioWindow->raise();
  3294. return;
  3295. }
  3296. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3297. "BasicWindow", "ShowSourceIcons");
  3298. advAudioWindow = new OBSBasicAdvAudio(this);
  3299. advAudioWindow->show();
  3300. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3301. advAudioWindow->SetIconsVisible(iconsVisible);
  3302. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3303. SLOT(on_advAudioProps_destroyed()));
  3304. }
  3305. void OBSBasic::on_advAudioProps_clicked()
  3306. {
  3307. on_actionAdvAudioProperties_triggered();
  3308. }
  3309. void OBSBasic::on_advAudioProps_destroyed()
  3310. {
  3311. advAudioWindow = nullptr;
  3312. }
  3313. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3314. QListWidgetItem *prev)
  3315. {
  3316. obs_source_t *source = NULL;
  3317. if (sceneChanging)
  3318. return;
  3319. if (current) {
  3320. obs_scene_t *scene;
  3321. scene = GetOBSRef<OBSScene>(current);
  3322. source = obs_scene_get_source(scene);
  3323. }
  3324. SetCurrentScene(source);
  3325. if (api)
  3326. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3327. UNUSED_PARAMETER(prev);
  3328. }
  3329. void OBSBasic::EditSceneName()
  3330. {
  3331. QListWidgetItem *item = ui->scenes->currentItem();
  3332. Qt::ItemFlags flags = item->flags();
  3333. item->setFlags(flags | Qt::ItemIsEditable);
  3334. ui->scenes->editItem(item);
  3335. item->setFlags(flags);
  3336. }
  3337. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3338. const char *slot)
  3339. {
  3340. QAction *action;
  3341. QList<QScreen *> screens = QGuiApplication::screens();
  3342. for (int i = 0; i < screens.size(); i++) {
  3343. QScreen *screen = screens[i];
  3344. QRect screenGeometry = screen->geometry();
  3345. QString name = "";
  3346. #ifdef _WIN32
  3347. DISPLAY_DEVICE ddev;
  3348. ddev.cb = sizeof(ddev);
  3349. BPtr<wchar_t> wideName;
  3350. os_utf8_to_wcs_ptr(screen->name().toStdString().c_str(), 0,
  3351. &wideName);
  3352. EnumDisplayDevices(wideName, 0, &ddev, 1);
  3353. BPtr<char> newName;
  3354. os_wcs_to_utf8_ptr(ddev.DeviceString, 0, &newName);
  3355. name = newName;
  3356. #elif defined(__APPLE__)
  3357. name = screen->name();
  3358. #elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
  3359. name = screen->model().simplified();
  3360. if (name.length() > 1 && name.endsWith("-"))
  3361. name.chop(1);
  3362. #endif
  3363. name = name.simplified();
  3364. if (name.length() == 0) {
  3365. name = QString("%1 %2")
  3366. .arg(QTStr("Display"))
  3367. .arg(QString::number(i + 1));
  3368. }
  3369. QString str =
  3370. QString("%1: %2x%3 @ %4,%5")
  3371. .arg(name,
  3372. QString::number(screenGeometry.width()),
  3373. QString::number(screenGeometry.height()),
  3374. QString::number(screenGeometry.x()),
  3375. QString::number(screenGeometry.y()));
  3376. action = parent->addAction(str, target, slot);
  3377. action->setProperty("monitor", i);
  3378. }
  3379. }
  3380. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3381. {
  3382. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3383. QMenu popup(this);
  3384. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3385. popup.addAction(QTStr("Add"), this,
  3386. SLOT(on_actionAddScene_triggered()));
  3387. if (item) {
  3388. QAction *pasteFilters =
  3389. new QAction(QTStr("Paste.Filters"), this);
  3390. pasteFilters->setEnabled(copyFiltersString);
  3391. connect(pasteFilters, SIGNAL(triggered()), this,
  3392. SLOT(ScenePasteFilters()));
  3393. popup.addSeparator();
  3394. popup.addAction(QTStr("Duplicate"), this,
  3395. SLOT(DuplicateSelectedScene()));
  3396. popup.addAction(QTStr("Copy.Filters"), this,
  3397. SLOT(SceneCopyFilters()));
  3398. popup.addAction(pasteFilters);
  3399. popup.addSeparator();
  3400. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3401. popup.addAction(QTStr("Remove"), this,
  3402. SLOT(RemoveSelectedScene()));
  3403. popup.addSeparator();
  3404. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3405. SLOT(on_actionSceneUp_triggered()));
  3406. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3407. this, SLOT(on_actionSceneDown_triggered()));
  3408. order.addSeparator();
  3409. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3410. this, SLOT(MoveSceneToTop()));
  3411. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3412. this, SLOT(MoveSceneToBottom()));
  3413. popup.addMenu(&order);
  3414. popup.addSeparator();
  3415. delete sceneProjectorMenu;
  3416. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3417. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3418. SLOT(OpenSceneProjector()));
  3419. popup.addMenu(sceneProjectorMenu);
  3420. QAction *sceneWindow = popup.addAction(
  3421. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  3422. popup.addAction(sceneWindow);
  3423. popup.addSeparator();
  3424. popup.addAction(QTStr("Filters"), this,
  3425. SLOT(OpenSceneFilters()));
  3426. popup.addSeparator();
  3427. delete perSceneTransitionMenu;
  3428. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  3429. popup.addMenu(perSceneTransitionMenu);
  3430. /* ---------------------- */
  3431. QAction *multiviewAction =
  3432. popup.addAction(QTStr("ShowInMultiview"));
  3433. OBSSource source = GetCurrentSceneSource();
  3434. OBSData data = obs_source_get_private_settings(source);
  3435. obs_data_release(data);
  3436. obs_data_set_default_bool(data, "show_in_multiview", true);
  3437. bool show = obs_data_get_bool(data, "show_in_multiview");
  3438. multiviewAction->setCheckable(true);
  3439. multiviewAction->setChecked(show);
  3440. auto showInMultiview = [](OBSData data) {
  3441. bool show =
  3442. obs_data_get_bool(data, "show_in_multiview");
  3443. obs_data_set_bool(data, "show_in_multiview", !show);
  3444. OBSProjector::UpdateMultiviewProjectors();
  3445. };
  3446. connect(multiviewAction, &QAction::triggered,
  3447. std::bind(showInMultiview, data));
  3448. }
  3449. popup.addSeparator();
  3450. bool grid = ui->scenes->GetGridMode();
  3451. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  3452. : QTStr("Basic.Main.GridMode"),
  3453. this);
  3454. connect(gridAction, SIGNAL(triggered()), this,
  3455. SLOT(on_actionGridMode_triggered()));
  3456. popup.addAction(gridAction);
  3457. popup.exec(QCursor::pos());
  3458. }
  3459. void OBSBasic::on_actionGridMode_triggered()
  3460. {
  3461. bool gridMode = !ui->scenes->GetGridMode();
  3462. ui->scenes->SetGridMode(gridMode);
  3463. }
  3464. void OBSBasic::on_actionAddScene_triggered()
  3465. {
  3466. string name;
  3467. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  3468. int i = 2;
  3469. QString placeHolderText = format.arg(i);
  3470. obs_source_t *source = nullptr;
  3471. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3472. obs_source_release(source);
  3473. placeHolderText = format.arg(++i);
  3474. }
  3475. bool accepted = NameDialog::AskForName(
  3476. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3477. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  3478. if (accepted) {
  3479. if (name.empty()) {
  3480. OBSMessageBox::warning(this,
  3481. QTStr("NoNameEntered.Title"),
  3482. QTStr("NoNameEntered.Text"));
  3483. on_actionAddScene_triggered();
  3484. return;
  3485. }
  3486. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3487. if (source) {
  3488. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3489. QTStr("NameExists.Text"));
  3490. obs_source_release(source);
  3491. on_actionAddScene_triggered();
  3492. return;
  3493. }
  3494. obs_scene_t *scene = obs_scene_create(name.c_str());
  3495. source = obs_scene_get_source(scene);
  3496. SetCurrentScene(source);
  3497. obs_scene_release(scene);
  3498. }
  3499. }
  3500. void OBSBasic::on_actionRemoveScene_triggered()
  3501. {
  3502. OBSScene scene = GetCurrentScene();
  3503. obs_source_t *source = obs_scene_get_source(scene);
  3504. if (source && QueryRemoveSource(source))
  3505. obs_source_remove(source);
  3506. }
  3507. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  3508. {
  3509. int idx = ui->scenes->currentRow();
  3510. if (idx == -1 || idx == invalidIdx)
  3511. return;
  3512. sceneChanging = true;
  3513. QListWidgetItem *item = ui->scenes->takeItem(idx);
  3514. if (!relative)
  3515. idx = 0;
  3516. ui->scenes->insertItem(idx + offset, item);
  3517. ui->scenes->setCurrentRow(idx + offset);
  3518. item->setSelected(true);
  3519. sceneChanging = false;
  3520. OBSProjector::UpdateMultiviewProjectors();
  3521. }
  3522. void OBSBasic::on_actionSceneUp_triggered()
  3523. {
  3524. ChangeSceneIndex(true, -1, 0);
  3525. }
  3526. void OBSBasic::on_actionSceneDown_triggered()
  3527. {
  3528. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  3529. }
  3530. void OBSBasic::MoveSceneToTop()
  3531. {
  3532. ChangeSceneIndex(false, 0, 0);
  3533. }
  3534. void OBSBasic::MoveSceneToBottom()
  3535. {
  3536. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3537. ui->scenes->count() - 1);
  3538. }
  3539. void OBSBasic::EditSceneItemName()
  3540. {
  3541. int idx = GetTopSelectedSourceItem();
  3542. ui->sources->Edit(idx);
  3543. }
  3544. void OBSBasic::SetDeinterlacingMode()
  3545. {
  3546. QAction *action = reinterpret_cast<QAction *>(sender());
  3547. obs_deinterlace_mode mode =
  3548. (obs_deinterlace_mode)action->property("mode").toInt();
  3549. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3550. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3551. obs_source_set_deinterlace_mode(source, mode);
  3552. }
  3553. void OBSBasic::SetDeinterlacingOrder()
  3554. {
  3555. QAction *action = reinterpret_cast<QAction *>(sender());
  3556. obs_deinterlace_field_order order =
  3557. (obs_deinterlace_field_order)action->property("order").toInt();
  3558. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3559. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3560. obs_source_set_deinterlace_field_order(source, order);
  3561. }
  3562. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  3563. {
  3564. obs_deinterlace_mode deinterlaceMode =
  3565. obs_source_get_deinterlace_mode(source);
  3566. obs_deinterlace_field_order deinterlaceOrder =
  3567. obs_source_get_deinterlace_field_order(source);
  3568. QAction *action;
  3569. #define ADD_MODE(name, mode) \
  3570. action = menu->addAction(QTStr("" name), this, \
  3571. SLOT(SetDeinterlacingMode())); \
  3572. action->setProperty("mode", (int)mode); \
  3573. action->setCheckable(true); \
  3574. action->setChecked(deinterlaceMode == mode);
  3575. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3576. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3577. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3578. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3579. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3580. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3581. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3582. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3583. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3584. #undef ADD_MODE
  3585. menu->addSeparator();
  3586. #define ADD_ORDER(name, order) \
  3587. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3588. SLOT(SetDeinterlacingOrder())); \
  3589. action->setProperty("order", (int)order); \
  3590. action->setCheckable(true); \
  3591. action->setChecked(deinterlaceOrder == order);
  3592. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3593. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3594. #undef ADD_ORDER
  3595. return menu;
  3596. }
  3597. void OBSBasic::SetScaleFilter()
  3598. {
  3599. QAction *action = reinterpret_cast<QAction *>(sender());
  3600. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3601. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3602. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3603. }
  3604. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  3605. {
  3606. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3607. QAction *action;
  3608. #define ADD_MODE(name, mode) \
  3609. action = \
  3610. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  3611. action->setProperty("mode", (int)mode); \
  3612. action->setCheckable(true); \
  3613. action->setChecked(scaleFilter == mode);
  3614. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3615. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3616. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3617. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3618. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3619. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  3620. #undef ADD_MODE
  3621. return menu;
  3622. }
  3623. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  3624. QWidgetAction *widgetAction,
  3625. ColorSelect *select,
  3626. obs_sceneitem_t *item)
  3627. {
  3628. QAction *action;
  3629. menu->setStyleSheet(QString(
  3630. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  3631. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  3632. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  3633. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  3634. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  3635. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  3636. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  3637. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  3638. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  3639. obs_data_release(privData);
  3640. obs_data_set_default_int(privData, "color-preset", 0);
  3641. int preset = obs_data_get_int(privData, "color-preset");
  3642. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  3643. action->setCheckable(true);
  3644. action->setProperty("bgColor", 0);
  3645. action->setChecked(preset == 0);
  3646. action = menu->addAction(QTStr("CustomColor"), this,
  3647. +SLOT(ColorChange()));
  3648. action->setCheckable(true);
  3649. action->setProperty("bgColor", 1);
  3650. action->setChecked(preset == 1);
  3651. menu->addSeparator();
  3652. widgetAction->setDefaultWidget(select);
  3653. for (int i = 1; i < 9; i++) {
  3654. stringstream button;
  3655. button << "preset" << i;
  3656. QPushButton *colorButton =
  3657. select->findChild<QPushButton *>(button.str().c_str());
  3658. if (preset == i + 1)
  3659. colorButton->setStyleSheet("border: 2px solid black");
  3660. colorButton->setProperty("bgColor", i);
  3661. select->connect(colorButton, SIGNAL(released()), this,
  3662. SLOT(ColorChange()));
  3663. }
  3664. menu->addAction(widgetAction);
  3665. return menu;
  3666. }
  3667. ColorSelect::ColorSelect(QWidget *parent)
  3668. : QWidget(parent), ui(new Ui::ColorSelect)
  3669. {
  3670. ui->setupUi(this);
  3671. }
  3672. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3673. {
  3674. QMenu popup(this);
  3675. delete previewProjectorSource;
  3676. delete sourceProjector;
  3677. delete scaleFilteringMenu;
  3678. delete colorMenu;
  3679. delete colorWidgetAction;
  3680. delete colorSelect;
  3681. delete deinterlaceMenu;
  3682. if (preview) {
  3683. QAction *action = popup.addAction(
  3684. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  3685. SLOT(TogglePreview()));
  3686. action->setCheckable(true);
  3687. action->setChecked(
  3688. obs_display_enabled(ui->preview->GetDisplay()));
  3689. if (IsPreviewProgramMode())
  3690. action->setEnabled(false);
  3691. popup.addAction(ui->actionLockPreview);
  3692. popup.addMenu(ui->scalingMenu);
  3693. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  3694. AddProjectorMenuMonitors(previewProjectorSource, this,
  3695. SLOT(OpenPreviewProjector()));
  3696. popup.addMenu(previewProjectorSource);
  3697. QAction *previewWindow =
  3698. popup.addAction(QTStr("PreviewWindow"), this,
  3699. SLOT(OpenPreviewWindow()));
  3700. popup.addAction(previewWindow);
  3701. popup.addSeparator();
  3702. }
  3703. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3704. if (addSourceMenu)
  3705. popup.addMenu(addSourceMenu);
  3706. ui->actionCopyFilters->setEnabled(false);
  3707. ui->actionCopySource->setEnabled(false);
  3708. if (ui->sources->MultipleBaseSelected()) {
  3709. popup.addSeparator();
  3710. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  3711. SLOT(GroupSelectedItems()));
  3712. } else if (ui->sources->GroupsSelected()) {
  3713. popup.addSeparator();
  3714. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  3715. SLOT(UngroupSelectedGroups()));
  3716. }
  3717. popup.addSeparator();
  3718. popup.addAction(ui->actionCopySource);
  3719. popup.addAction(ui->actionPasteRef);
  3720. popup.addAction(ui->actionPasteDup);
  3721. popup.addSeparator();
  3722. popup.addSeparator();
  3723. popup.addAction(ui->actionCopyFilters);
  3724. popup.addAction(ui->actionPasteFilters);
  3725. popup.addSeparator();
  3726. if (idx != -1) {
  3727. if (addSourceMenu)
  3728. popup.addSeparator();
  3729. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3730. bool lock = obs_sceneitem_locked(sceneItem);
  3731. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3732. uint32_t flags = obs_source_get_output_flags(source);
  3733. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3734. OBS_SOURCE_ASYNC_VIDEO;
  3735. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  3736. QAction *action;
  3737. colorMenu = new QMenu(QTStr("ChangeBG"));
  3738. colorWidgetAction = new QWidgetAction(colorMenu);
  3739. colorSelect = new ColorSelect(colorMenu);
  3740. popup.addMenu(AddBackgroundColorMenu(
  3741. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  3742. popup.addAction(QTStr("Rename"), this,
  3743. SLOT(EditSceneItemName()));
  3744. popup.addAction(QTStr("Remove"), this,
  3745. SLOT(on_actionRemoveSource_triggered()));
  3746. popup.addSeparator();
  3747. popup.addMenu(ui->orderMenu);
  3748. popup.addMenu(ui->transformMenu);
  3749. ui->actionResetTransform->setEnabled(!lock);
  3750. ui->actionRotate90CW->setEnabled(!lock);
  3751. ui->actionRotate90CCW->setEnabled(!lock);
  3752. ui->actionRotate180->setEnabled(!lock);
  3753. ui->actionFlipHorizontal->setEnabled(!lock);
  3754. ui->actionFlipVertical->setEnabled(!lock);
  3755. ui->actionFitToScreen->setEnabled(!lock);
  3756. ui->actionStretchToScreen->setEnabled(!lock);
  3757. ui->actionCenterToScreen->setEnabled(!lock);
  3758. ui->actionVerticalCenter->setEnabled(!lock);
  3759. ui->actionHorizontalCenter->setEnabled(!lock);
  3760. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3761. AddProjectorMenuMonitors(sourceProjector, this,
  3762. SLOT(OpenSourceProjector()));
  3763. QAction *sourceWindow = popup.addAction(
  3764. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  3765. popup.addAction(sourceWindow);
  3766. popup.addSeparator();
  3767. if (hasAudio) {
  3768. QAction *actionHideMixer =
  3769. popup.addAction(QTStr("HideMixer"), this,
  3770. SLOT(ToggleHideMixer()));
  3771. actionHideMixer->setCheckable(true);
  3772. actionHideMixer->setChecked(SourceMixerHidden(source));
  3773. }
  3774. if (isAsyncVideo) {
  3775. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  3776. popup.addMenu(
  3777. AddDeinterlacingMenu(deinterlaceMenu, source));
  3778. popup.addSeparator();
  3779. }
  3780. QAction *resizeOutput =
  3781. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  3782. SLOT(ResizeOutputSizeOfSource()));
  3783. int width = obs_source_get_width(source);
  3784. int height = obs_source_get_height(source);
  3785. resizeOutput->setEnabled(!obs_video_active());
  3786. if (width == 0 || height == 0)
  3787. resizeOutput->setEnabled(false);
  3788. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  3789. popup.addMenu(
  3790. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  3791. popup.addSeparator();
  3792. popup.addMenu(sourceProjector);
  3793. popup.addAction(sourceWindow);
  3794. popup.addSeparator();
  3795. action = popup.addAction(QTStr("Interact"), this,
  3796. SLOT(on_actionInteract_triggered()));
  3797. action->setEnabled(obs_source_get_output_flags(source) &
  3798. OBS_SOURCE_INTERACTION);
  3799. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  3800. popup.addAction(QTStr("Properties"), this,
  3801. SLOT(on_actionSourceProperties_triggered()));
  3802. ui->actionCopyFilters->setEnabled(true);
  3803. ui->actionCopySource->setEnabled(true);
  3804. } else {
  3805. ui->actionPasteFilters->setEnabled(false);
  3806. }
  3807. popup.exec(QCursor::pos());
  3808. }
  3809. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3810. {
  3811. if (ui->scenes->count()) {
  3812. QModelIndex idx = ui->sources->indexAt(pos);
  3813. CreateSourcePopupMenu(idx.row(), false);
  3814. }
  3815. }
  3816. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3817. {
  3818. if (!witem)
  3819. return;
  3820. if (IsPreviewProgramMode()) {
  3821. bool doubleClickSwitch =
  3822. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  3823. "TransitionOnDoubleClick");
  3824. if (doubleClickSwitch)
  3825. TransitionClicked();
  3826. }
  3827. }
  3828. void OBSBasic::AddSource(const char *id)
  3829. {
  3830. if (id && *id) {
  3831. OBSBasicSourceSelect sourceSelect(this, id);
  3832. sourceSelect.exec();
  3833. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3834. CreatePropertiesWindow(sourceSelect.newSource);
  3835. }
  3836. }
  3837. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3838. {
  3839. const char *unversioned_type;
  3840. const char *type;
  3841. bool foundValues = false;
  3842. bool foundDeprecated = false;
  3843. size_t idx = 0;
  3844. QMenu *popup = new QMenu(QTStr("Add"), this);
  3845. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3846. auto getActionAfter = [](QMenu *menu, const QString &name) {
  3847. QList<QAction *> actions = menu->actions();
  3848. for (QAction *menuAction : actions) {
  3849. if (menuAction->text().compare(name) >= 0)
  3850. return menuAction;
  3851. }
  3852. return (QAction *)nullptr;
  3853. };
  3854. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  3855. const char *name) {
  3856. QString qname = QT_UTF8(name);
  3857. QAction *popupItem = new QAction(qname, this);
  3858. popupItem->setData(QT_UTF8(type));
  3859. connect(popupItem, SIGNAL(triggered(bool)), this,
  3860. SLOT(AddSourceFromAction()));
  3861. QIcon icon;
  3862. if (strcmp(type, "scene") == 0)
  3863. icon = GetSceneIcon();
  3864. else
  3865. icon = GetSourceIcon(type);
  3866. popupItem->setIcon(icon);
  3867. QAction *after = getActionAfter(popup, qname);
  3868. popup->insertAction(after, popupItem);
  3869. };
  3870. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  3871. const char *name = obs_source_get_display_name(type);
  3872. uint32_t caps = obs_get_source_output_flags(type);
  3873. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3874. continue;
  3875. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3876. addSource(popup, unversioned_type, name);
  3877. } else {
  3878. addSource(deprecated, unversioned_type, name);
  3879. foundDeprecated = true;
  3880. }
  3881. foundValues = true;
  3882. }
  3883. addSource(popup, "scene", Str("Basic.Scene"));
  3884. popup->addSeparator();
  3885. QAction *addGroup = new QAction(QTStr("Group"), this);
  3886. addGroup->setData(QT_UTF8("group"));
  3887. addGroup->setIcon(GetGroupIcon());
  3888. connect(addGroup, SIGNAL(triggered(bool)), this,
  3889. SLOT(AddSourceFromAction()));
  3890. popup->addAction(addGroup);
  3891. if (!foundDeprecated) {
  3892. delete deprecated;
  3893. deprecated = nullptr;
  3894. }
  3895. if (!foundValues) {
  3896. delete popup;
  3897. popup = nullptr;
  3898. } else if (foundDeprecated) {
  3899. popup->addSeparator();
  3900. popup->addMenu(deprecated);
  3901. }
  3902. return popup;
  3903. }
  3904. void OBSBasic::AddSourceFromAction()
  3905. {
  3906. QAction *action = qobject_cast<QAction *>(sender());
  3907. if (!action)
  3908. return;
  3909. AddSource(QT_TO_UTF8(action->data().toString()));
  3910. }
  3911. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3912. {
  3913. if (!GetCurrentScene()) {
  3914. // Tell the user he needs a scene first (help beginners).
  3915. OBSMessageBox::information(
  3916. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  3917. QTStr("Basic.Main.AddSourceHelp.Text"));
  3918. return;
  3919. }
  3920. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  3921. if (popup)
  3922. popup->exec(pos);
  3923. }
  3924. void OBSBasic::on_actionAddSource_triggered()
  3925. {
  3926. AddSourcePopupMenu(QCursor::pos());
  3927. }
  3928. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3929. {
  3930. vector<OBSSceneItem> &items =
  3931. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  3932. if (obs_sceneitem_selected(item)) {
  3933. items.emplace_back(item);
  3934. } else if (obs_sceneitem_is_group(item)) {
  3935. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3936. }
  3937. return true;
  3938. };
  3939. void OBSBasic::on_actionRemoveSource_triggered()
  3940. {
  3941. vector<OBSSceneItem> items;
  3942. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3943. if (!items.size())
  3944. return;
  3945. auto removeMultiple = [this](size_t count) {
  3946. QString text = QTStr("ConfirmRemove.TextMultiple")
  3947. .arg(QString::number(count));
  3948. QMessageBox remove_items(this);
  3949. remove_items.setText(text);
  3950. QAbstractButton *Yes = remove_items.addButton(
  3951. QTStr("Yes"), QMessageBox::YesRole);
  3952. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3953. remove_items.setIcon(QMessageBox::Question);
  3954. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3955. remove_items.exec();
  3956. return Yes == remove_items.clickedButton();
  3957. };
  3958. if (items.size() == 1) {
  3959. OBSSceneItem &item = items[0];
  3960. obs_source_t *source = obs_sceneitem_get_source(item);
  3961. if (source && QueryRemoveSource(source))
  3962. obs_sceneitem_remove(item);
  3963. } else {
  3964. if (removeMultiple(items.size())) {
  3965. for (auto &item : items)
  3966. obs_sceneitem_remove(item);
  3967. }
  3968. }
  3969. }
  3970. void OBSBasic::on_actionInteract_triggered()
  3971. {
  3972. OBSSceneItem item = GetCurrentSceneItem();
  3973. OBSSource source = obs_sceneitem_get_source(item);
  3974. if (source)
  3975. CreateInteractionWindow(source);
  3976. }
  3977. void OBSBasic::on_actionSourceProperties_triggered()
  3978. {
  3979. OBSSceneItem item = GetCurrentSceneItem();
  3980. OBSSource source = obs_sceneitem_get_source(item);
  3981. if (source)
  3982. CreatePropertiesWindow(source);
  3983. }
  3984. void OBSBasic::on_actionSourceUp_triggered()
  3985. {
  3986. OBSSceneItem item = GetCurrentSceneItem();
  3987. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3988. }
  3989. void OBSBasic::on_actionSourceDown_triggered()
  3990. {
  3991. OBSSceneItem item = GetCurrentSceneItem();
  3992. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3993. }
  3994. void OBSBasic::on_actionMoveUp_triggered()
  3995. {
  3996. OBSSceneItem item = GetCurrentSceneItem();
  3997. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3998. }
  3999. void OBSBasic::on_actionMoveDown_triggered()
  4000. {
  4001. OBSSceneItem item = GetCurrentSceneItem();
  4002. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  4003. }
  4004. void OBSBasic::on_actionMoveToTop_triggered()
  4005. {
  4006. OBSSceneItem item = GetCurrentSceneItem();
  4007. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  4008. }
  4009. void OBSBasic::on_actionMoveToBottom_triggered()
  4010. {
  4011. OBSSceneItem item = GetCurrentSceneItem();
  4012. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  4013. }
  4014. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4015. {
  4016. char logDir[512];
  4017. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4018. return nullptr;
  4019. string path = logDir;
  4020. path += "/";
  4021. path += log;
  4022. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4023. if (!file)
  4024. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4025. return file;
  4026. }
  4027. void OBSBasic::UploadLog(const char *subdir, const char *file)
  4028. {
  4029. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4030. if (!fileString)
  4031. return;
  4032. if (!*fileString)
  4033. return;
  4034. ui->menuLogFiles->setEnabled(false);
  4035. stringstream ss;
  4036. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4037. << CurrentDateTimeString() << "\n\n"
  4038. << fileString;
  4039. if (logUploadThread) {
  4040. logUploadThread->wait();
  4041. }
  4042. RemoteTextThread *thread =
  4043. new RemoteTextThread("https://obsproject.com/logs/upload",
  4044. "text/plain", ss.str().c_str());
  4045. logUploadThread.reset(thread);
  4046. connect(thread, &RemoteTextThread::Result, this,
  4047. &OBSBasic::logUploadFinished);
  4048. logUploadThread->start();
  4049. }
  4050. void OBSBasic::on_actionShowLogs_triggered()
  4051. {
  4052. char logDir[512];
  4053. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4054. return;
  4055. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4056. QDesktopServices::openUrl(url);
  4057. }
  4058. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4059. {
  4060. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  4061. }
  4062. void OBSBasic::on_actionUploadLastLog_triggered()
  4063. {
  4064. UploadLog("obs-studio/logs", App()->GetLastLog());
  4065. }
  4066. void OBSBasic::on_actionViewCurrentLog_triggered()
  4067. {
  4068. char logDir[512];
  4069. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4070. return;
  4071. const char *log = App()->GetCurrentLog();
  4072. string path = logDir;
  4073. path += "/";
  4074. path += log;
  4075. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  4076. QDesktopServices::openUrl(url);
  4077. }
  4078. void OBSBasic::on_actionShowCrashLogs_triggered()
  4079. {
  4080. char logDir[512];
  4081. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4082. return;
  4083. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4084. QDesktopServices::openUrl(url);
  4085. }
  4086. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4087. {
  4088. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  4089. }
  4090. void OBSBasic::on_actionCheckForUpdates_triggered()
  4091. {
  4092. CheckForUpdates(true);
  4093. }
  4094. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4095. {
  4096. ui->menuLogFiles->setEnabled(true);
  4097. if (text.isEmpty()) {
  4098. OBSMessageBox::critical(
  4099. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4100. error);
  4101. return;
  4102. }
  4103. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4104. string resURL = obs_data_get_string(returnData, "url");
  4105. QString logURL = resURL.c_str();
  4106. obs_data_release(returnData);
  4107. OBSLogReply logDialog(this, logURL);
  4108. logDialog.exec();
  4109. }
  4110. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4111. obs_source_t *source, const string &name)
  4112. {
  4113. const char *prevName = obs_source_get_name(source);
  4114. if (name == prevName)
  4115. return;
  4116. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4117. QListWidgetItem *listItem = listWidget->currentItem();
  4118. if (foundSource || name.empty()) {
  4119. listItem->setText(QT_UTF8(prevName));
  4120. if (foundSource) {
  4121. OBSMessageBox::warning(parent,
  4122. QTStr("NameExists.Title"),
  4123. QTStr("NameExists.Text"));
  4124. } else if (name.empty()) {
  4125. OBSMessageBox::warning(parent,
  4126. QTStr("NoNameEntered.Title"),
  4127. QTStr("NoNameEntered.Text"));
  4128. }
  4129. obs_source_release(foundSource);
  4130. } else {
  4131. listItem->setText(QT_UTF8(name.c_str()));
  4132. obs_source_set_name(source, name.c_str());
  4133. }
  4134. }
  4135. void OBSBasic::SceneNameEdited(QWidget *editor,
  4136. QAbstractItemDelegate::EndEditHint endHint)
  4137. {
  4138. OBSScene scene = GetCurrentScene();
  4139. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4140. string text = QT_TO_UTF8(edit->text().trimmed());
  4141. if (!scene)
  4142. return;
  4143. obs_source_t *source = obs_scene_get_source(scene);
  4144. RenameListItem(this, ui->scenes, source, text);
  4145. if (api)
  4146. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4147. UNUSED_PARAMETER(endHint);
  4148. }
  4149. void OBSBasic::OpenFilters()
  4150. {
  4151. OBSSceneItem item = GetCurrentSceneItem();
  4152. OBSSource source = obs_sceneitem_get_source(item);
  4153. CreateFiltersWindow(source);
  4154. }
  4155. void OBSBasic::OpenSceneFilters()
  4156. {
  4157. OBSScene scene = GetCurrentScene();
  4158. OBSSource source = obs_scene_get_source(scene);
  4159. CreateFiltersWindow(source);
  4160. }
  4161. #define RECORDING_START \
  4162. "==== Recording Start ==============================================="
  4163. #define RECORDING_STOP \
  4164. "==== Recording Stop ================================================"
  4165. #define REPLAY_BUFFER_START \
  4166. "==== Replay Buffer Start ==========================================="
  4167. #define REPLAY_BUFFER_STOP \
  4168. "==== Replay Buffer Stop ============================================"
  4169. #define STREAMING_START \
  4170. "==== Streaming Start ==============================================="
  4171. #define STREAMING_STOP \
  4172. "==== Streaming Stop ================================================"
  4173. void OBSBasic::StartStreaming()
  4174. {
  4175. if (outputHandler->StreamingActive())
  4176. return;
  4177. if (disableOutputsRef)
  4178. return;
  4179. if (api)
  4180. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  4181. SaveProject();
  4182. ui->streamButton->setEnabled(false);
  4183. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  4184. if (sysTrayStream) {
  4185. sysTrayStream->setEnabled(false);
  4186. sysTrayStream->setText(ui->streamButton->text());
  4187. }
  4188. if (!outputHandler->StartStreaming(service)) {
  4189. QString message =
  4190. !outputHandler->lastError.empty()
  4191. ? QTStr(outputHandler->lastError.c_str())
  4192. : QTStr("Output.StartFailedGeneric");
  4193. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4194. ui->streamButton->setEnabled(true);
  4195. ui->streamButton->setChecked(false);
  4196. if (sysTrayStream) {
  4197. sysTrayStream->setText(ui->streamButton->text());
  4198. sysTrayStream->setEnabled(true);
  4199. }
  4200. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
  4201. message);
  4202. return;
  4203. }
  4204. bool recordWhenStreaming = config_get_bool(
  4205. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4206. if (recordWhenStreaming)
  4207. StartRecording();
  4208. bool replayBufferWhileStreaming = config_get_bool(
  4209. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4210. if (replayBufferWhileStreaming)
  4211. StartReplayBuffer();
  4212. }
  4213. #ifdef _WIN32
  4214. static inline void UpdateProcessPriority()
  4215. {
  4216. const char *priority = config_get_string(App()->GlobalConfig(),
  4217. "General", "ProcessPriority");
  4218. if (priority && strcmp(priority, "Normal") != 0)
  4219. SetProcessPriority(priority);
  4220. }
  4221. static inline void ClearProcessPriority()
  4222. {
  4223. const char *priority = config_get_string(App()->GlobalConfig(),
  4224. "General", "ProcessPriority");
  4225. if (priority && strcmp(priority, "Normal") != 0)
  4226. SetProcessPriority("Normal");
  4227. }
  4228. #else
  4229. #define UpdateProcessPriority() \
  4230. do { \
  4231. } while (false)
  4232. #define ClearProcessPriority() \
  4233. do { \
  4234. } while (false)
  4235. #endif
  4236. inline void OBSBasic::OnActivate()
  4237. {
  4238. if (ui->profileMenu->isEnabled()) {
  4239. ui->profileMenu->setEnabled(false);
  4240. ui->autoConfigure->setEnabled(false);
  4241. App()->IncrementSleepInhibition();
  4242. UpdateProcessPriority();
  4243. if (trayIcon)
  4244. trayIcon->setIcon(QIcon::fromTheme(
  4245. "obs-tray-active",
  4246. QIcon(":/res/images/tray_active.png")));
  4247. }
  4248. }
  4249. extern volatile bool recording_paused;
  4250. extern volatile bool replaybuf_active;
  4251. inline void OBSBasic::OnDeactivate()
  4252. {
  4253. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  4254. ui->profileMenu->setEnabled(true);
  4255. ui->autoConfigure->setEnabled(true);
  4256. App()->DecrementSleepInhibition();
  4257. ClearProcessPriority();
  4258. if (trayIcon)
  4259. trayIcon->setIcon(QIcon::fromTheme(
  4260. "obs-tray", QIcon(":/res/images/obs.png")));
  4261. } else if (trayIcon) {
  4262. if (os_atomic_load_bool(&recording_paused))
  4263. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  4264. else
  4265. trayIcon->setIcon(
  4266. QIcon(":/res/images/tray_active.png"));
  4267. }
  4268. }
  4269. void OBSBasic::StopStreaming()
  4270. {
  4271. SaveProject();
  4272. if (outputHandler->StreamingActive())
  4273. outputHandler->StopStreaming(streamingStopping);
  4274. OnDeactivate();
  4275. bool recordWhenStreaming = config_get_bool(
  4276. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4277. bool keepRecordingWhenStreamStops =
  4278. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4279. "KeepRecordingWhenStreamStops");
  4280. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4281. StopRecording();
  4282. bool replayBufferWhileStreaming = config_get_bool(
  4283. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4284. bool keepReplayBufferStreamStops =
  4285. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4286. "KeepReplayBufferStreamStops");
  4287. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4288. StopReplayBuffer();
  4289. }
  4290. void OBSBasic::ForceStopStreaming()
  4291. {
  4292. SaveProject();
  4293. if (outputHandler->StreamingActive())
  4294. outputHandler->StopStreaming(true);
  4295. OnDeactivate();
  4296. bool recordWhenStreaming = config_get_bool(
  4297. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  4298. bool keepRecordingWhenStreamStops =
  4299. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4300. "KeepRecordingWhenStreamStops");
  4301. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  4302. StopRecording();
  4303. bool replayBufferWhileStreaming = config_get_bool(
  4304. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  4305. bool keepReplayBufferStreamStops =
  4306. config_get_bool(GetGlobalConfig(), "BasicWindow",
  4307. "KeepReplayBufferStreamStops");
  4308. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  4309. StopReplayBuffer();
  4310. }
  4311. void OBSBasic::StreamDelayStarting(int sec)
  4312. {
  4313. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4314. ui->streamButton->setEnabled(true);
  4315. ui->streamButton->setChecked(true);
  4316. if (sysTrayStream) {
  4317. sysTrayStream->setText(ui->streamButton->text());
  4318. sysTrayStream->setEnabled(true);
  4319. }
  4320. if (!startStreamMenu.isNull())
  4321. startStreamMenu->deleteLater();
  4322. startStreamMenu = new QMenu();
  4323. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  4324. SLOT(StopStreaming()));
  4325. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4326. SLOT(ForceStopStreaming()));
  4327. ui->streamButton->setMenu(startStreamMenu);
  4328. ui->statusbar->StreamDelayStarting(sec);
  4329. OnActivate();
  4330. }
  4331. void OBSBasic::StreamDelayStopping(int sec)
  4332. {
  4333. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4334. ui->streamButton->setEnabled(true);
  4335. ui->streamButton->setChecked(false);
  4336. if (sysTrayStream) {
  4337. sysTrayStream->setText(ui->streamButton->text());
  4338. sysTrayStream->setEnabled(true);
  4339. }
  4340. if (!startStreamMenu.isNull())
  4341. startStreamMenu->deleteLater();
  4342. startStreamMenu = new QMenu();
  4343. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  4344. SLOT(StartStreaming()));
  4345. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  4346. SLOT(ForceStopStreaming()));
  4347. ui->streamButton->setMenu(startStreamMenu);
  4348. ui->statusbar->StreamDelayStopping(sec);
  4349. if (api)
  4350. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4351. }
  4352. void OBSBasic::StreamingStart()
  4353. {
  4354. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  4355. ui->streamButton->setEnabled(true);
  4356. ui->streamButton->setChecked(true);
  4357. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  4358. if (sysTrayStream) {
  4359. sysTrayStream->setText(ui->streamButton->text());
  4360. sysTrayStream->setEnabled(true);
  4361. }
  4362. if (api)
  4363. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  4364. OnActivate();
  4365. blog(LOG_INFO, STREAMING_START);
  4366. }
  4367. void OBSBasic::StreamStopping()
  4368. {
  4369. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  4370. if (sysTrayStream)
  4371. sysTrayStream->setText(ui->streamButton->text());
  4372. streamingStopping = true;
  4373. if (api)
  4374. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  4375. }
  4376. void OBSBasic::StreamingStop(int code, QString last_error)
  4377. {
  4378. const char *errorDescription = "";
  4379. DStr errorMessage;
  4380. bool use_last_error = false;
  4381. bool encode_error = false;
  4382. switch (code) {
  4383. case OBS_OUTPUT_BAD_PATH:
  4384. errorDescription = Str("Output.ConnectFail.BadPath");
  4385. break;
  4386. case OBS_OUTPUT_CONNECT_FAILED:
  4387. use_last_error = true;
  4388. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  4389. break;
  4390. case OBS_OUTPUT_INVALID_STREAM:
  4391. errorDescription = Str("Output.ConnectFail.InvalidStream");
  4392. break;
  4393. case OBS_OUTPUT_ENCODE_ERROR:
  4394. encode_error = true;
  4395. break;
  4396. default:
  4397. case OBS_OUTPUT_ERROR:
  4398. use_last_error = true;
  4399. errorDescription = Str("Output.ConnectFail.Error");
  4400. break;
  4401. case OBS_OUTPUT_DISCONNECTED:
  4402. /* doesn't happen if output is set to reconnect. note that
  4403. * reconnects are handled in the output, not in the UI */
  4404. use_last_error = true;
  4405. errorDescription = Str("Output.ConnectFail.Disconnected");
  4406. }
  4407. if (use_last_error && !last_error.isEmpty())
  4408. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4409. QT_TO_UTF8(last_error));
  4410. else
  4411. dstr_copy(errorMessage, errorDescription);
  4412. ui->statusbar->StreamStopped();
  4413. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4414. ui->streamButton->setEnabled(true);
  4415. ui->streamButton->setChecked(false);
  4416. if (sysTrayStream) {
  4417. sysTrayStream->setText(ui->streamButton->text());
  4418. sysTrayStream->setEnabled(true);
  4419. }
  4420. streamingStopping = false;
  4421. if (api)
  4422. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  4423. OnDeactivate();
  4424. blog(LOG_INFO, STREAMING_STOP);
  4425. if (encode_error) {
  4426. OBSMessageBox::information(
  4427. this, QTStr("Output.StreamEncodeError.Title"),
  4428. QTStr("Output.StreamEncodeError.Msg"));
  4429. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4430. OBSMessageBox::information(this,
  4431. QTStr("Output.ConnectFail.Title"),
  4432. QT_UTF8(errorMessage));
  4433. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4434. SysTrayNotify(QT_UTF8(errorDescription),
  4435. QSystemTrayIcon::Warning);
  4436. }
  4437. if (!startStreamMenu.isNull()) {
  4438. ui->streamButton->setMenu(nullptr);
  4439. startStreamMenu->deleteLater();
  4440. startStreamMenu = nullptr;
  4441. }
  4442. }
  4443. void OBSBasic::AutoRemux()
  4444. {
  4445. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4446. bool advanced = astrcmpi(mode, "Advanced") == 0;
  4447. const char *path = !advanced ? config_get_string(basicConfig,
  4448. "SimpleOutput",
  4449. "FilePath")
  4450. : config_get_string(basicConfig, "AdvOut",
  4451. "RecFilePath");
  4452. /* do not save if using FFmpeg output in advanced output mode */
  4453. if (advanced) {
  4454. const char *type =
  4455. config_get_string(basicConfig, "AdvOut", "RecType");
  4456. if (astrcmpi(type, "FFmpeg") == 0) {
  4457. return;
  4458. }
  4459. }
  4460. QString input;
  4461. input += path;
  4462. input += "/";
  4463. input += remuxFilename.c_str();
  4464. QFileInfo fi(remuxFilename.c_str());
  4465. /* do not remux if lossless */
  4466. if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
  4467. return;
  4468. }
  4469. QString output;
  4470. output += path;
  4471. output += "/";
  4472. output += fi.completeBaseName();
  4473. output += ".mp4";
  4474. OBSRemux *remux = new OBSRemux(path, this, true);
  4475. remux->show();
  4476. remux->AutoRemux(input, output);
  4477. }
  4478. void OBSBasic::StartRecording()
  4479. {
  4480. if (outputHandler->RecordingActive())
  4481. return;
  4482. if (disableOutputsRef)
  4483. return;
  4484. if (!OutputPathValid()) {
  4485. OutputPathInvalidMessage();
  4486. ui->recordButton->setChecked(false);
  4487. return;
  4488. }
  4489. if (LowDiskSpace()) {
  4490. DiskSpaceMessage();
  4491. ui->recordButton->setChecked(false);
  4492. return;
  4493. }
  4494. if (api)
  4495. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  4496. SaveProject();
  4497. if (!outputHandler->StartRecording())
  4498. ui->recordButton->setChecked(false);
  4499. }
  4500. void OBSBasic::RecordStopping()
  4501. {
  4502. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  4503. if (sysTrayRecord)
  4504. sysTrayRecord->setText(ui->recordButton->text());
  4505. recordingStopping = true;
  4506. if (api)
  4507. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  4508. }
  4509. void OBSBasic::StopRecording()
  4510. {
  4511. SaveProject();
  4512. if (outputHandler->RecordingActive())
  4513. outputHandler->StopRecording(recordingStopping);
  4514. OnDeactivate();
  4515. }
  4516. void OBSBasic::RecordingStart()
  4517. {
  4518. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  4519. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  4520. ui->recordButton->setChecked(true);
  4521. if (sysTrayRecord)
  4522. sysTrayRecord->setText(ui->recordButton->text());
  4523. recordingStopping = false;
  4524. if (api)
  4525. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  4526. if (!diskFullTimer->isActive())
  4527. diskFullTimer->start(1000);
  4528. OnActivate();
  4529. UpdatePause();
  4530. blog(LOG_INFO, RECORDING_START);
  4531. }
  4532. void OBSBasic::RecordingStop(int code, QString last_error)
  4533. {
  4534. ui->statusbar->RecordingStopped();
  4535. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  4536. ui->recordButton->setChecked(false);
  4537. if (sysTrayRecord)
  4538. sysTrayRecord->setText(ui->recordButton->text());
  4539. blog(LOG_INFO, RECORDING_STOP);
  4540. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4541. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4542. QTStr("Output.RecordFail.Unsupported"));
  4543. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  4544. OBSMessageBox::warning(
  4545. this, QTStr("Output.RecordError.Title"),
  4546. QTStr("Output.RecordError.EncodeErrorMsg"));
  4547. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4548. OBSMessageBox::warning(this,
  4549. QTStr("Output.RecordNoSpace.Title"),
  4550. QTStr("Output.RecordNoSpace.Msg"));
  4551. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4552. const char *errorDescription;
  4553. DStr errorMessage;
  4554. bool use_last_error = true;
  4555. errorDescription = Str("Output.RecordError.Msg");
  4556. if (use_last_error && !last_error.isEmpty())
  4557. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  4558. QT_TO_UTF8(last_error));
  4559. else
  4560. dstr_copy(errorMessage, errorDescription);
  4561. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4562. QT_UTF8(errorMessage));
  4563. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4564. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4565. QSystemTrayIcon::Warning);
  4566. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4567. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4568. QSystemTrayIcon::Warning);
  4569. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4570. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4571. QSystemTrayIcon::Warning);
  4572. }
  4573. if (api)
  4574. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  4575. if (diskFullTimer->isActive())
  4576. diskFullTimer->stop();
  4577. if (remuxAfterRecord)
  4578. AutoRemux();
  4579. OnDeactivate();
  4580. UpdatePause(false);
  4581. }
  4582. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  4583. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  4584. void OBSBasic::ShowReplayBufferPauseWarning()
  4585. {
  4586. auto msgBox = []() {
  4587. QMessageBox msgbox(App()->GetMainWindow());
  4588. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  4589. "PauseWarning.Title"));
  4590. msgbox.setText(QTStr("Output.ReplayBuffer."
  4591. "PauseWarning.Text"));
  4592. msgbox.setIcon(QMessageBox::Icon::Information);
  4593. msgbox.addButton(QMessageBox::Ok);
  4594. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  4595. msgbox.setCheckBox(cb);
  4596. msgbox.exec();
  4597. if (cb->isChecked()) {
  4598. config_set_bool(App()->GlobalConfig(), "General",
  4599. "WarnedAboutReplayBufferPausing", true);
  4600. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  4601. }
  4602. };
  4603. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  4604. "WarnedAboutReplayBufferPausing");
  4605. if (!warned) {
  4606. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  4607. Q_ARG(VoidFunc, msgBox));
  4608. }
  4609. }
  4610. void OBSBasic::StartReplayBuffer()
  4611. {
  4612. if (!outputHandler || !outputHandler->replayBuffer)
  4613. return;
  4614. if (outputHandler->ReplayBufferActive())
  4615. return;
  4616. if (disableOutputsRef)
  4617. return;
  4618. if (!UIValidation::NoSourcesConfirmation(this)) {
  4619. replayBufferButton->setChecked(false);
  4620. return;
  4621. }
  4622. if (LowDiskSpace()) {
  4623. DiskSpaceMessage();
  4624. replayBufferButton->setChecked(false);
  4625. return;
  4626. }
  4627. obs_output_t *output = outputHandler->replayBuffer;
  4628. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  4629. obs_data_array_t *bindings =
  4630. obs_data_get_array(hotkeys, "ReplayBuffer.Save");
  4631. size_t count = obs_data_array_count(bindings);
  4632. obs_data_array_release(bindings);
  4633. obs_data_release(hotkeys);
  4634. if (!count) {
  4635. OBSMessageBox::information(this, RP_NO_HOTKEY_TITLE,
  4636. RP_NO_HOTKEY_TEXT);
  4637. replayBufferButton->setChecked(false);
  4638. return;
  4639. }
  4640. if (api)
  4641. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  4642. SaveProject();
  4643. if (!outputHandler->StartReplayBuffer()) {
  4644. replayBufferButton->setChecked(false);
  4645. } else if (os_atomic_load_bool(&recording_paused)) {
  4646. ShowReplayBufferPauseWarning();
  4647. }
  4648. }
  4649. void OBSBasic::ReplayBufferStopping()
  4650. {
  4651. if (!outputHandler || !outputHandler->replayBuffer)
  4652. return;
  4653. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  4654. if (sysTrayReplayBuffer)
  4655. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4656. replayBufferStopping = true;
  4657. if (api)
  4658. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  4659. }
  4660. void OBSBasic::StopReplayBuffer()
  4661. {
  4662. if (!outputHandler || !outputHandler->replayBuffer)
  4663. return;
  4664. SaveProject();
  4665. if (outputHandler->ReplayBufferActive())
  4666. outputHandler->StopReplayBuffer(replayBufferStopping);
  4667. OnDeactivate();
  4668. }
  4669. void OBSBasic::ReplayBufferStart()
  4670. {
  4671. if (!outputHandler || !outputHandler->replayBuffer)
  4672. return;
  4673. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  4674. replayBufferButton->setChecked(true);
  4675. if (sysTrayReplayBuffer)
  4676. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4677. replayBufferStopping = false;
  4678. if (api)
  4679. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  4680. OnActivate();
  4681. UpdateReplayBuffer();
  4682. blog(LOG_INFO, REPLAY_BUFFER_START);
  4683. }
  4684. void OBSBasic::ReplayBufferSave()
  4685. {
  4686. if (!outputHandler || !outputHandler->replayBuffer)
  4687. return;
  4688. if (!outputHandler->ReplayBufferActive())
  4689. return;
  4690. calldata_t cd = {0};
  4691. proc_handler_t *ph =
  4692. obs_output_get_proc_handler(outputHandler->replayBuffer);
  4693. proc_handler_call(ph, "save", &cd);
  4694. calldata_free(&cd);
  4695. }
  4696. void OBSBasic::ReplayBufferStop(int code)
  4697. {
  4698. if (!outputHandler || !outputHandler->replayBuffer)
  4699. return;
  4700. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  4701. replayBufferButton->setChecked(false);
  4702. if (sysTrayReplayBuffer)
  4703. sysTrayReplayBuffer->setText(replayBufferButton->text());
  4704. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  4705. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  4706. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  4707. QTStr("Output.RecordFail.Unsupported"));
  4708. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  4709. OBSMessageBox::warning(this,
  4710. QTStr("Output.RecordNoSpace.Title"),
  4711. QTStr("Output.RecordNoSpace.Msg"));
  4712. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  4713. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  4714. QTStr("Output.RecordError.Msg"));
  4715. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  4716. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  4717. QSystemTrayIcon::Warning);
  4718. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  4719. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  4720. QSystemTrayIcon::Warning);
  4721. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  4722. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  4723. QSystemTrayIcon::Warning);
  4724. }
  4725. if (api)
  4726. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  4727. OnDeactivate();
  4728. UpdateReplayBuffer(false);
  4729. }
  4730. void OBSBasic::on_streamButton_clicked()
  4731. {
  4732. if (outputHandler->StreamingActive()) {
  4733. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4734. "WarnBeforeStoppingStream");
  4735. if (confirm && isVisible()) {
  4736. QMessageBox::StandardButton button =
  4737. OBSMessageBox::question(
  4738. this, QTStr("ConfirmStop.Title"),
  4739. QTStr("ConfirmStop.Text"),
  4740. QMessageBox::Yes | QMessageBox::No,
  4741. QMessageBox::No);
  4742. if (button == QMessageBox::No) {
  4743. ui->streamButton->setChecked(true);
  4744. return;
  4745. }
  4746. }
  4747. StopStreaming();
  4748. } else {
  4749. if (!UIValidation::NoSourcesConfirmation(this)) {
  4750. ui->streamButton->setChecked(false);
  4751. return;
  4752. }
  4753. auto action =
  4754. UIValidation::StreamSettingsConfirmation(this, service);
  4755. switch (action) {
  4756. case StreamSettingsAction::ContinueStream:
  4757. break;
  4758. case StreamSettingsAction::OpenSettings:
  4759. on_action_Settings_triggered();
  4760. ui->streamButton->setChecked(false);
  4761. return;
  4762. case StreamSettingsAction::Cancel:
  4763. ui->streamButton->setChecked(false);
  4764. return;
  4765. }
  4766. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4767. "WarnBeforeStartingStream");
  4768. obs_data_t *settings = obs_service_get_settings(service);
  4769. bool bwtest = obs_data_get_bool(settings, "bwtest");
  4770. obs_data_release(settings);
  4771. if (bwtest && isVisible()) {
  4772. QMessageBox::StandardButton button =
  4773. OBSMessageBox::question(
  4774. this, QTStr("ConfirmBWTest.Title"),
  4775. QTStr("ConfirmBWTest.Text"));
  4776. if (button == QMessageBox::No) {
  4777. ui->streamButton->setChecked(false);
  4778. return;
  4779. }
  4780. } else if (confirm && isVisible()) {
  4781. QMessageBox::StandardButton button =
  4782. OBSMessageBox::question(
  4783. this, QTStr("ConfirmStart.Title"),
  4784. QTStr("ConfirmStart.Text"),
  4785. QMessageBox::Yes | QMessageBox::No,
  4786. QMessageBox::No);
  4787. if (button == QMessageBox::No) {
  4788. ui->streamButton->setChecked(false);
  4789. return;
  4790. }
  4791. }
  4792. StartStreaming();
  4793. }
  4794. }
  4795. void OBSBasic::on_recordButton_clicked()
  4796. {
  4797. if (outputHandler->RecordingActive()) {
  4798. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  4799. "WarnBeforeStoppingRecord");
  4800. if (confirm && isVisible()) {
  4801. QMessageBox::StandardButton button =
  4802. OBSMessageBox::question(
  4803. this, QTStr("ConfirmStopRecord.Title"),
  4804. QTStr("ConfirmStopRecord.Text"),
  4805. QMessageBox::Yes | QMessageBox::No,
  4806. QMessageBox::No);
  4807. if (button == QMessageBox::No) {
  4808. ui->recordButton->setChecked(true);
  4809. return;
  4810. }
  4811. }
  4812. StopRecording();
  4813. } else {
  4814. if (!UIValidation::NoSourcesConfirmation(this)) {
  4815. ui->recordButton->setChecked(false);
  4816. return;
  4817. }
  4818. StartRecording();
  4819. }
  4820. }
  4821. void OBSBasic::on_settingsButton_clicked()
  4822. {
  4823. on_action_Settings_triggered();
  4824. }
  4825. void OBSBasic::on_actionHelpPortal_triggered()
  4826. {
  4827. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4828. QDesktopServices::openUrl(url);
  4829. }
  4830. void OBSBasic::on_actionWebsite_triggered()
  4831. {
  4832. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4833. QDesktopServices::openUrl(url);
  4834. }
  4835. void OBSBasic::on_actionDiscord_triggered()
  4836. {
  4837. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  4838. QDesktopServices::openUrl(url);
  4839. }
  4840. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4841. {
  4842. char path[512];
  4843. int ret = GetConfigPath(path, 512, "obs-studio");
  4844. if (ret <= 0)
  4845. return;
  4846. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4847. }
  4848. void OBSBasic::on_actionShowProfileFolder_triggered()
  4849. {
  4850. char path[512];
  4851. int ret = GetProfilePath(path, 512, "");
  4852. if (ret <= 0)
  4853. return;
  4854. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4855. }
  4856. int OBSBasic::GetTopSelectedSourceItem()
  4857. {
  4858. QModelIndexList selectedItems =
  4859. ui->sources->selectionModel()->selectedIndexes();
  4860. return selectedItems.count() ? selectedItems[0].row() : -1;
  4861. }
  4862. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  4863. {
  4864. return ui->sources->selectionModel()->selectedIndexes();
  4865. }
  4866. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4867. {
  4868. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4869. UNUSED_PARAMETER(pos);
  4870. }
  4871. void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
  4872. {
  4873. QMenu popup(this);
  4874. QPointer<QMenu> studioProgramProjector;
  4875. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  4876. AddProjectorMenuMonitors(studioProgramProjector, this,
  4877. SLOT(OpenStudioProgramProjector()));
  4878. popup.addMenu(studioProgramProjector);
  4879. QAction *studioProgramWindow =
  4880. popup.addAction(QTStr("StudioProgramWindow"), this,
  4881. SLOT(OpenStudioProgramWindow()));
  4882. popup.addAction(studioProgramWindow);
  4883. popup.exec(QCursor::pos());
  4884. }
  4885. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  4886. {
  4887. QMenu popup(this);
  4888. delete previewProjectorMain;
  4889. QAction *action =
  4890. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4891. this, SLOT(TogglePreview()));
  4892. action->setCheckable(true);
  4893. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4894. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  4895. AddProjectorMenuMonitors(previewProjectorMain, this,
  4896. SLOT(OpenPreviewProjector()));
  4897. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  4898. SLOT(OpenPreviewWindow()));
  4899. popup.addMenu(previewProjectorMain);
  4900. popup.addAction(previewWindow);
  4901. popup.exec(QCursor::pos());
  4902. UNUSED_PARAMETER(pos);
  4903. }
  4904. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4905. {
  4906. #ifndef _WIN32
  4907. /* Make sure all dialogs are safely and successfully closed before
  4908. * switching the always on top mode due to the fact that windows all
  4909. * have to be recreated, so queue the actual toggle to happen after
  4910. * all events related to closing the dialogs have finished */
  4911. CloseDialogs();
  4912. #endif
  4913. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4914. Qt::QueuedConnection);
  4915. }
  4916. void OBSBasic::ToggleAlwaysOnTop()
  4917. {
  4918. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4919. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4920. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4921. show();
  4922. }
  4923. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4924. {
  4925. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4926. if (strcmp(val, "10") == 0) {
  4927. num = 10;
  4928. den = 1;
  4929. } else if (strcmp(val, "20") == 0) {
  4930. num = 20;
  4931. den = 1;
  4932. } else if (strcmp(val, "24 NTSC") == 0) {
  4933. num = 24000;
  4934. den = 1001;
  4935. } else if (strcmp(val, "25 PAL") == 0) {
  4936. num = 25;
  4937. den = 1;
  4938. } else if (strcmp(val, "29.97") == 0) {
  4939. num = 30000;
  4940. den = 1001;
  4941. } else if (strcmp(val, "48") == 0) {
  4942. num = 48;
  4943. den = 1;
  4944. } else if (strcmp(val, "50 PAL") == 0) {
  4945. num = 50;
  4946. den = 1;
  4947. } else if (strcmp(val, "59.94") == 0) {
  4948. num = 60000;
  4949. den = 1001;
  4950. } else if (strcmp(val, "60") == 0) {
  4951. num = 60;
  4952. den = 1;
  4953. } else {
  4954. num = 30;
  4955. den = 1;
  4956. }
  4957. }
  4958. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4959. {
  4960. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4961. den = 1;
  4962. }
  4963. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4964. {
  4965. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4966. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4967. }
  4968. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4969. {
  4970. num = 1000000000;
  4971. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4972. }
  4973. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4974. {
  4975. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4976. if (type == 1) //"Integer"
  4977. GetFPSInteger(num, den);
  4978. else if (type == 2) //"Fraction"
  4979. GetFPSFraction(num, den);
  4980. else if (false) //"Nanoseconds", currently not implemented
  4981. GetFPSNanoseconds(num, den);
  4982. else
  4983. GetFPSCommon(num, den);
  4984. }
  4985. config_t *OBSBasic::Config() const
  4986. {
  4987. return basicConfig;
  4988. }
  4989. void OBSBasic::on_actionEditTransform_triggered()
  4990. {
  4991. if (transformWindow)
  4992. transformWindow->close();
  4993. transformWindow = new OBSBasicTransform(this);
  4994. transformWindow->show();
  4995. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4996. }
  4997. static obs_transform_info copiedTransformInfo;
  4998. static obs_sceneitem_crop copiedCropInfo;
  4999. void OBSBasic::on_actionCopyTransform_triggered()
  5000. {
  5001. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5002. if (!obs_sceneitem_selected(item))
  5003. return true;
  5004. obs_sceneitem_defer_update_begin(item);
  5005. obs_sceneitem_get_info(item, &copiedTransformInfo);
  5006. obs_sceneitem_get_crop(item, &copiedCropInfo);
  5007. obs_sceneitem_defer_update_end(item);
  5008. UNUSED_PARAMETER(scene);
  5009. UNUSED_PARAMETER(param);
  5010. return true;
  5011. };
  5012. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5013. ui->actionPasteTransform->setEnabled(true);
  5014. }
  5015. void OBSBasic::on_actionPasteTransform_triggered()
  5016. {
  5017. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  5018. if (!obs_sceneitem_selected(item))
  5019. return true;
  5020. obs_sceneitem_defer_update_begin(item);
  5021. obs_sceneitem_set_info(item, &copiedTransformInfo);
  5022. obs_sceneitem_set_crop(item, &copiedCropInfo);
  5023. obs_sceneitem_defer_update_end(item);
  5024. UNUSED_PARAMETER(scene);
  5025. UNUSED_PARAMETER(param);
  5026. return true;
  5027. };
  5028. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  5029. }
  5030. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  5031. {
  5032. if (obs_sceneitem_is_group(item))
  5033. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  5034. if (!obs_sceneitem_selected(item))
  5035. return true;
  5036. if (obs_sceneitem_locked(item))
  5037. return true;
  5038. obs_sceneitem_defer_update_begin(item);
  5039. obs_transform_info info;
  5040. vec2_set(&info.pos, 0.0f, 0.0f);
  5041. vec2_set(&info.scale, 1.0f, 1.0f);
  5042. info.rot = 0.0f;
  5043. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  5044. info.bounds_type = OBS_BOUNDS_NONE;
  5045. info.bounds_alignment = OBS_ALIGN_CENTER;
  5046. vec2_set(&info.bounds, 0.0f, 0.0f);
  5047. obs_sceneitem_set_info(item, &info);
  5048. obs_sceneitem_crop crop = {};
  5049. obs_sceneitem_set_crop(item, &crop);
  5050. obs_sceneitem_defer_update_end(item);
  5051. UNUSED_PARAMETER(scene);
  5052. UNUSED_PARAMETER(param);
  5053. return true;
  5054. }
  5055. void OBSBasic::on_actionResetTransform_triggered()
  5056. {
  5057. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  5058. }
  5059. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  5060. {
  5061. matrix4 boxTransform;
  5062. obs_sceneitem_get_box_transform(item, &boxTransform);
  5063. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  5064. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  5065. auto GetMinPos = [&](float x, float y) {
  5066. vec3 pos;
  5067. vec3_set(&pos, x, y, 0.0f);
  5068. vec3_transform(&pos, &pos, &boxTransform);
  5069. vec3_min(&tl, &tl, &pos);
  5070. vec3_max(&br, &br, &pos);
  5071. };
  5072. GetMinPos(0.0f, 0.0f);
  5073. GetMinPos(1.0f, 0.0f);
  5074. GetMinPos(0.0f, 1.0f);
  5075. GetMinPos(1.0f, 1.0f);
  5076. }
  5077. static vec3 GetItemTL(obs_sceneitem_t *item)
  5078. {
  5079. vec3 tl, br;
  5080. GetItemBox(item, tl, br);
  5081. return tl;
  5082. }
  5083. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  5084. {
  5085. vec3 newTL;
  5086. vec2 pos;
  5087. obs_sceneitem_get_pos(item, &pos);
  5088. newTL = GetItemTL(item);
  5089. pos.x += tl.x - newTL.x;
  5090. pos.y += tl.y - newTL.y;
  5091. obs_sceneitem_set_pos(item, &pos);
  5092. }
  5093. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  5094. void *param)
  5095. {
  5096. if (obs_sceneitem_is_group(item))
  5097. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  5098. param);
  5099. if (!obs_sceneitem_selected(item))
  5100. return true;
  5101. if (obs_sceneitem_locked(item))
  5102. return true;
  5103. float rot = *reinterpret_cast<float *>(param);
  5104. vec3 tl = GetItemTL(item);
  5105. rot += obs_sceneitem_get_rot(item);
  5106. if (rot >= 360.0f)
  5107. rot -= 360.0f;
  5108. else if (rot <= -360.0f)
  5109. rot += 360.0f;
  5110. obs_sceneitem_set_rot(item, rot);
  5111. obs_sceneitem_force_update_transform(item);
  5112. SetItemTL(item, tl);
  5113. UNUSED_PARAMETER(scene);
  5114. return true;
  5115. };
  5116. void OBSBasic::on_actionRotate90CW_triggered()
  5117. {
  5118. float f90CW = 90.0f;
  5119. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  5120. }
  5121. void OBSBasic::on_actionRotate90CCW_triggered()
  5122. {
  5123. float f90CCW = -90.0f;
  5124. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  5125. }
  5126. void OBSBasic::on_actionRotate180_triggered()
  5127. {
  5128. float f180 = 180.0f;
  5129. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  5130. }
  5131. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  5132. void *param)
  5133. {
  5134. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  5135. if (obs_sceneitem_is_group(item))
  5136. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  5137. param);
  5138. if (!obs_sceneitem_selected(item))
  5139. return true;
  5140. if (obs_sceneitem_locked(item))
  5141. return true;
  5142. vec3 tl = GetItemTL(item);
  5143. vec2 scale;
  5144. obs_sceneitem_get_scale(item, &scale);
  5145. vec2_mul(&scale, &scale, &mul);
  5146. obs_sceneitem_set_scale(item, &scale);
  5147. obs_sceneitem_force_update_transform(item);
  5148. SetItemTL(item, tl);
  5149. UNUSED_PARAMETER(scene);
  5150. return true;
  5151. }
  5152. void OBSBasic::on_actionFlipHorizontal_triggered()
  5153. {
  5154. vec2 scale;
  5155. vec2_set(&scale, -1.0f, 1.0f);
  5156. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5157. &scale);
  5158. }
  5159. void OBSBasic::on_actionFlipVertical_triggered()
  5160. {
  5161. vec2 scale;
  5162. vec2_set(&scale, 1.0f, -1.0f);
  5163. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  5164. &scale);
  5165. }
  5166. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  5167. void *param)
  5168. {
  5169. obs_bounds_type boundsType =
  5170. *reinterpret_cast<obs_bounds_type *>(param);
  5171. if (obs_sceneitem_is_group(item))
  5172. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  5173. param);
  5174. if (!obs_sceneitem_selected(item))
  5175. return true;
  5176. if (obs_sceneitem_locked(item))
  5177. return true;
  5178. obs_video_info ovi;
  5179. obs_get_video_info(&ovi);
  5180. obs_transform_info itemInfo;
  5181. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  5182. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  5183. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  5184. itemInfo.rot = 0.0f;
  5185. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  5186. float(ovi.base_height));
  5187. itemInfo.bounds_type = boundsType;
  5188. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  5189. obs_sceneitem_set_info(item, &itemInfo);
  5190. UNUSED_PARAMETER(scene);
  5191. return true;
  5192. }
  5193. void OBSBasic::on_actionFitToScreen_triggered()
  5194. {
  5195. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  5196. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5197. &boundsType);
  5198. }
  5199. void OBSBasic::on_actionStretchToScreen_triggered()
  5200. {
  5201. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  5202. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  5203. &boundsType);
  5204. }
  5205. enum class CenterType {
  5206. Scene,
  5207. Vertical,
  5208. Horizontal,
  5209. };
  5210. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5211. {
  5212. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  5213. vec3 tl, br, itemCenter, screenCenter, offset;
  5214. obs_video_info ovi;
  5215. obs_transform_info oti;
  5216. if (obs_sceneitem_is_group(item))
  5217. obs_sceneitem_group_enum_items(item, center_to_scene,
  5218. &centerType);
  5219. if (!obs_sceneitem_selected(item))
  5220. return true;
  5221. if (obs_sceneitem_locked(item))
  5222. return true;
  5223. obs_get_video_info(&ovi);
  5224. obs_sceneitem_get_info(item, &oti);
  5225. if (centerType == CenterType::Scene)
  5226. vec3_set(&screenCenter, float(ovi.base_width),
  5227. float(ovi.base_height), 0.0f);
  5228. else if (centerType == CenterType::Vertical)
  5229. vec3_set(&screenCenter, float(oti.bounds.x),
  5230. float(ovi.base_height), 0.0f);
  5231. else if (centerType == CenterType::Horizontal)
  5232. vec3_set(&screenCenter, float(ovi.base_width),
  5233. float(oti.bounds.y), 0.0f);
  5234. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  5235. GetItemBox(item, tl, br);
  5236. vec3_sub(&itemCenter, &br, &tl);
  5237. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  5238. vec3_add(&itemCenter, &itemCenter, &tl);
  5239. vec3_sub(&offset, &screenCenter, &itemCenter);
  5240. vec3_add(&tl, &tl, &offset);
  5241. if (centerType == CenterType::Vertical)
  5242. tl.x = oti.pos.x;
  5243. else if (centerType == CenterType::Horizontal)
  5244. tl.y = oti.pos.y;
  5245. SetItemTL(item, tl);
  5246. return true;
  5247. };
  5248. void OBSBasic::on_actionCenterToScreen_triggered()
  5249. {
  5250. CenterType centerType = CenterType::Scene;
  5251. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5252. }
  5253. void OBSBasic::on_actionVerticalCenter_triggered()
  5254. {
  5255. CenterType centerType = CenterType::Vertical;
  5256. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5257. }
  5258. void OBSBasic::on_actionHorizontalCenter_triggered()
  5259. {
  5260. CenterType centerType = CenterType::Horizontal;
  5261. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  5262. }
  5263. void OBSBasic::EnablePreviewDisplay(bool enable)
  5264. {
  5265. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  5266. ui->preview->setVisible(enable);
  5267. ui->previewDisabledWidget->setVisible(!enable);
  5268. }
  5269. void OBSBasic::TogglePreview()
  5270. {
  5271. previewEnabled = !previewEnabled;
  5272. EnablePreviewDisplay(previewEnabled);
  5273. }
  5274. void OBSBasic::EnablePreview()
  5275. {
  5276. if (previewProgramMode)
  5277. return;
  5278. previewEnabled = true;
  5279. EnablePreviewDisplay(true);
  5280. }
  5281. void OBSBasic::DisablePreview()
  5282. {
  5283. if (previewProgramMode)
  5284. return;
  5285. previewEnabled = false;
  5286. EnablePreviewDisplay(false);
  5287. }
  5288. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5289. {
  5290. if (obs_sceneitem_locked(item))
  5291. return true;
  5292. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  5293. struct vec2 pos;
  5294. if (!obs_sceneitem_selected(item)) {
  5295. if (obs_sceneitem_is_group(item)) {
  5296. struct vec3 offset3;
  5297. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  5298. struct matrix4 matrix;
  5299. obs_sceneitem_get_draw_transform(item, &matrix);
  5300. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  5301. matrix4_inv(&matrix, &matrix);
  5302. vec3_transform(&offset3, &offset3, &matrix);
  5303. struct vec2 new_offset;
  5304. vec2_set(&new_offset, offset3.x, offset3.y);
  5305. obs_sceneitem_group_enum_items(item, nudge_callback,
  5306. &new_offset);
  5307. }
  5308. return true;
  5309. }
  5310. obs_sceneitem_get_pos(item, &pos);
  5311. vec2_add(&pos, &pos, &offset);
  5312. obs_sceneitem_set_pos(item, &pos);
  5313. return true;
  5314. }
  5315. void OBSBasic::Nudge(int dist, MoveDir dir)
  5316. {
  5317. if (ui->preview->Locked())
  5318. return;
  5319. struct vec2 offset;
  5320. vec2_set(&offset, 0.0f, 0.0f);
  5321. switch (dir) {
  5322. case MoveDir::Up:
  5323. offset.y = (float)-dist;
  5324. break;
  5325. case MoveDir::Down:
  5326. offset.y = (float)dist;
  5327. break;
  5328. case MoveDir::Left:
  5329. offset.x = (float)-dist;
  5330. break;
  5331. case MoveDir::Right:
  5332. offset.x = (float)dist;
  5333. break;
  5334. }
  5335. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  5336. }
  5337. void OBSBasic::NudgeUp()
  5338. {
  5339. Nudge(1, MoveDir::Up);
  5340. }
  5341. void OBSBasic::NudgeDown()
  5342. {
  5343. Nudge(1, MoveDir::Down);
  5344. }
  5345. void OBSBasic::NudgeLeft()
  5346. {
  5347. Nudge(1, MoveDir::Left);
  5348. }
  5349. void OBSBasic::NudgeRight()
  5350. {
  5351. Nudge(1, MoveDir::Right);
  5352. }
  5353. void OBSBasic::DeleteProjector(OBSProjector *projector)
  5354. {
  5355. for (size_t i = 0; i < projectors.size(); i++) {
  5356. if (projectors[i] == projector) {
  5357. projectors[i]->deleteLater();
  5358. projectors.erase(projectors.begin() + i);
  5359. break;
  5360. }
  5361. }
  5362. }
  5363. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  5364. ProjectorType type)
  5365. {
  5366. /* seriously? 10 monitors? */
  5367. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  5368. return nullptr;
  5369. OBSProjector *projector =
  5370. new OBSProjector(nullptr, source, monitor, type);
  5371. if (projector)
  5372. projectors.emplace_back(projector);
  5373. return projector;
  5374. }
  5375. void OBSBasic::OpenStudioProgramProjector()
  5376. {
  5377. int monitor = sender()->property("monitor").toInt();
  5378. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  5379. }
  5380. void OBSBasic::OpenPreviewProjector()
  5381. {
  5382. int monitor = sender()->property("monitor").toInt();
  5383. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  5384. }
  5385. void OBSBasic::OpenSourceProjector()
  5386. {
  5387. int monitor = sender()->property("monitor").toInt();
  5388. OBSSceneItem item = GetCurrentSceneItem();
  5389. if (!item)
  5390. return;
  5391. OpenProjector(obs_sceneitem_get_source(item), monitor,
  5392. ProjectorType::Source);
  5393. }
  5394. void OBSBasic::OpenMultiviewProjector()
  5395. {
  5396. int monitor = sender()->property("monitor").toInt();
  5397. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  5398. }
  5399. void OBSBasic::OpenSceneProjector()
  5400. {
  5401. int monitor = sender()->property("monitor").toInt();
  5402. OBSScene scene = GetCurrentScene();
  5403. if (!scene)
  5404. return;
  5405. OpenProjector(obs_scene_get_source(scene), monitor,
  5406. ProjectorType::Scene);
  5407. }
  5408. void OBSBasic::OpenStudioProgramWindow()
  5409. {
  5410. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  5411. }
  5412. void OBSBasic::OpenPreviewWindow()
  5413. {
  5414. OpenProjector(nullptr, -1, ProjectorType::Preview);
  5415. }
  5416. void OBSBasic::OpenSourceWindow()
  5417. {
  5418. OBSSceneItem item = GetCurrentSceneItem();
  5419. if (!item)
  5420. return;
  5421. OBSSource source = obs_sceneitem_get_source(item);
  5422. OpenProjector(obs_sceneitem_get_source(item), -1,
  5423. ProjectorType::Source);
  5424. }
  5425. void OBSBasic::OpenMultiviewWindow()
  5426. {
  5427. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  5428. }
  5429. void OBSBasic::OpenSceneWindow()
  5430. {
  5431. OBSScene scene = GetCurrentScene();
  5432. if (!scene)
  5433. return;
  5434. OBSSource source = obs_scene_get_source(scene);
  5435. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  5436. }
  5437. void OBSBasic::OpenSavedProjectors()
  5438. {
  5439. for (SavedProjectorInfo *info : savedProjectorsArray) {
  5440. OpenSavedProjector(info);
  5441. }
  5442. }
  5443. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  5444. {
  5445. if (info) {
  5446. OBSProjector *projector = nullptr;
  5447. switch (info->type) {
  5448. case ProjectorType::Source:
  5449. case ProjectorType::Scene: {
  5450. OBSSource source =
  5451. obs_get_source_by_name(info->name.c_str());
  5452. if (!source)
  5453. return;
  5454. projector = OpenProjector(source, info->monitor,
  5455. info->type);
  5456. obs_source_release(source);
  5457. break;
  5458. }
  5459. default: {
  5460. projector = OpenProjector(nullptr, info->monitor,
  5461. info->type);
  5462. break;
  5463. }
  5464. }
  5465. if (projector && !info->geometry.empty() && info->monitor < 0) {
  5466. QByteArray byteArray = QByteArray::fromBase64(
  5467. QByteArray(info->geometry.c_str()));
  5468. projector->restoreGeometry(byteArray);
  5469. if (!WindowPositionValid(projector->normalGeometry())) {
  5470. QRect rect = App()->desktop()->geometry();
  5471. projector->setGeometry(QStyle::alignedRect(
  5472. Qt::LeftToRight, Qt::AlignCenter,
  5473. size(), rect));
  5474. }
  5475. }
  5476. }
  5477. }
  5478. void OBSBasic::on_actionFullscreenInterface_triggered()
  5479. {
  5480. if (!isFullScreen())
  5481. showFullScreen();
  5482. else
  5483. showNormal();
  5484. }
  5485. void OBSBasic::UpdateTitleBar()
  5486. {
  5487. stringstream name;
  5488. const char *profile =
  5489. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  5490. const char *sceneCollection = config_get_string(
  5491. App()->GlobalConfig(), "Basic", "SceneCollection");
  5492. name << "OBS ";
  5493. if (previewProgramMode)
  5494. name << "Studio ";
  5495. name << App()->GetVersionString();
  5496. if (App()->IsPortableMode())
  5497. name << " - Portable Mode";
  5498. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  5499. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  5500. setWindowTitle(QT_UTF8(name.str().c_str()));
  5501. }
  5502. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  5503. {
  5504. char profiles_path[512];
  5505. const char *profile =
  5506. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  5507. int ret;
  5508. if (!profile)
  5509. return -1;
  5510. if (!path)
  5511. return -1;
  5512. if (!file)
  5513. file = "";
  5514. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  5515. if (ret <= 0)
  5516. return ret;
  5517. if (!*file)
  5518. return snprintf(path, size, "%s/%s", profiles_path, profile);
  5519. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  5520. }
  5521. void OBSBasic::on_resetUI_triggered()
  5522. {
  5523. /* prune deleted extra docks */
  5524. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5525. if (!extraDocks[i]) {
  5526. extraDocks.removeAt(i);
  5527. }
  5528. }
  5529. if (extraDocks.size()) {
  5530. QMessageBox::StandardButton button = QMessageBox::question(
  5531. this, QTStr("ResetUIWarning.Title"),
  5532. QTStr("ResetUIWarning.Text"));
  5533. if (button == QMessageBox::No)
  5534. return;
  5535. }
  5536. /* undock/hide/center extra docks */
  5537. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5538. if (extraDocks[i]) {
  5539. extraDocks[i]->setVisible(true);
  5540. extraDocks[i]->setFloating(true);
  5541. extraDocks[i]->move(frameGeometry().topLeft() +
  5542. rect().center() -
  5543. extraDocks[i]->rect().center());
  5544. extraDocks[i]->setVisible(false);
  5545. }
  5546. }
  5547. restoreState(startingDockLayout);
  5548. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  5549. int cx = width();
  5550. int cy = height();
  5551. int cx22_5 = cx * 225 / 1000;
  5552. int cx5 = cx * 5 / 100;
  5553. cy = cy * 225 / 1000;
  5554. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  5555. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  5556. ui->mixerDock, ui->transitionsDock,
  5557. ui->controlsDock};
  5558. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  5559. ui->scenesDock->setVisible(true);
  5560. ui->sourcesDock->setVisible(true);
  5561. ui->mixerDock->setVisible(true);
  5562. ui->transitionsDock->setVisible(true);
  5563. ui->controlsDock->setVisible(true);
  5564. statsDock->setVisible(false);
  5565. statsDock->setFloating(true);
  5566. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  5567. resizeDocks(docks, sizes, Qt::Horizontal);
  5568. #endif
  5569. }
  5570. void OBSBasic::on_lockUI_toggled(bool lock)
  5571. {
  5572. QDockWidget::DockWidgetFeatures features =
  5573. lock ? QDockWidget::NoDockWidgetFeatures
  5574. : QDockWidget::AllDockWidgetFeatures;
  5575. QDockWidget::DockWidgetFeatures mainFeatures = features;
  5576. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  5577. ui->scenesDock->setFeatures(mainFeatures);
  5578. ui->sourcesDock->setFeatures(mainFeatures);
  5579. ui->mixerDock->setFeatures(mainFeatures);
  5580. ui->transitionsDock->setFeatures(mainFeatures);
  5581. ui->controlsDock->setFeatures(mainFeatures);
  5582. statsDock->setFeatures(features);
  5583. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  5584. if (!extraDocks[i]) {
  5585. extraDocks.removeAt(i);
  5586. } else {
  5587. extraDocks[i]->setFeatures(features);
  5588. }
  5589. }
  5590. }
  5591. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  5592. {
  5593. ui->sourcesToolbar->setVisible(visible);
  5594. ui->scenesToolbar->setVisible(visible);
  5595. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  5596. "ShowListboxToolbars", visible);
  5597. }
  5598. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  5599. {
  5600. ui->statusbar->setVisible(visible);
  5601. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  5602. visible);
  5603. }
  5604. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  5605. {
  5606. ui->sources->SetIconsVisible(visible);
  5607. if (advAudioWindow != nullptr)
  5608. advAudioWindow->SetIconsVisible(visible);
  5609. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  5610. visible);
  5611. }
  5612. void OBSBasic::on_actionLockPreview_triggered()
  5613. {
  5614. ui->preview->ToggleLocked();
  5615. ui->actionLockPreview->setChecked(ui->preview->Locked());
  5616. }
  5617. void OBSBasic::on_scalingMenu_aboutToShow()
  5618. {
  5619. obs_video_info ovi;
  5620. obs_get_video_info(&ovi);
  5621. QAction *action = ui->actionScaleCanvas;
  5622. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  5623. text = text.arg(QString::number(ovi.base_width),
  5624. QString::number(ovi.base_height));
  5625. action->setText(text);
  5626. action = ui->actionScaleOutput;
  5627. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  5628. text = text.arg(QString::number(ovi.output_width),
  5629. QString::number(ovi.output_height));
  5630. action->setText(text);
  5631. action->setVisible(!(ovi.output_width == ovi.base_width &&
  5632. ovi.output_height == ovi.base_height));
  5633. UpdatePreviewScalingMenu();
  5634. }
  5635. void OBSBasic::on_actionScaleWindow_triggered()
  5636. {
  5637. ui->preview->SetFixedScaling(false);
  5638. ui->preview->ResetScrollingOffset();
  5639. emit ui->preview->DisplayResized();
  5640. }
  5641. void OBSBasic::on_actionScaleCanvas_triggered()
  5642. {
  5643. ui->preview->SetFixedScaling(true);
  5644. ui->preview->SetScalingLevel(0);
  5645. emit ui->preview->DisplayResized();
  5646. }
  5647. void OBSBasic::on_actionScaleOutput_triggered()
  5648. {
  5649. obs_video_info ovi;
  5650. obs_get_video_info(&ovi);
  5651. ui->preview->SetFixedScaling(true);
  5652. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  5653. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  5654. int32_t approxScalingLevel =
  5655. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  5656. ui->preview->SetScalingLevel(approxScalingLevel);
  5657. ui->preview->SetScalingAmount(scalingAmount);
  5658. emit ui->preview->DisplayResized();
  5659. }
  5660. void OBSBasic::SetShowing(bool showing)
  5661. {
  5662. if (!showing && isVisible()) {
  5663. config_set_string(App()->GlobalConfig(), "BasicWindow",
  5664. "geometry",
  5665. saveGeometry().toBase64().constData());
  5666. /* hide all visible child dialogs */
  5667. visDlgPositions.clear();
  5668. if (!visDialogs.isEmpty()) {
  5669. for (QDialog *dlg : visDialogs) {
  5670. visDlgPositions.append(dlg->pos());
  5671. dlg->hide();
  5672. }
  5673. }
  5674. if (showHide)
  5675. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5676. QTimer::singleShot(250, this, SLOT(hide()));
  5677. setVisible(false);
  5678. #ifdef __APPLE__
  5679. EnableOSXDockIcon(false);
  5680. #endif
  5681. } else if (showing && !isVisible()) {
  5682. if (showHide)
  5683. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5684. QTimer::singleShot(250, this, SLOT(show()));
  5685. setVisible(true);
  5686. #ifdef __APPLE__
  5687. EnableOSXDockIcon(true);
  5688. #endif
  5689. /* raise and activate window to ensure it is on top */
  5690. raise();
  5691. activateWindow();
  5692. /* show all child dialogs that was visible earlier */
  5693. if (!visDialogs.isEmpty()) {
  5694. for (int i = 0; i < visDialogs.size(); ++i) {
  5695. QDialog *dlg = visDialogs[i];
  5696. dlg->move(visDlgPositions[i]);
  5697. dlg->show();
  5698. }
  5699. }
  5700. /* Unminimize window if it was hidden to tray instead of task
  5701. * bar. */
  5702. if (sysTrayMinimizeToTray()) {
  5703. Qt::WindowStates state;
  5704. state = windowState() & ~Qt::WindowMinimized;
  5705. state |= Qt::WindowActive;
  5706. setWindowState(state);
  5707. }
  5708. }
  5709. }
  5710. void OBSBasic::ToggleShowHide()
  5711. {
  5712. bool showing = isVisible();
  5713. if (showing) {
  5714. /* check for modal dialogs */
  5715. EnumDialogs();
  5716. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  5717. return;
  5718. }
  5719. SetShowing(!showing);
  5720. }
  5721. void OBSBasic::SystemTrayInit()
  5722. {
  5723. trayIcon.reset(new QSystemTrayIcon(
  5724. QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
  5725. this));
  5726. trayIcon->setToolTip("OBS Studio");
  5727. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  5728. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  5729. trayIcon.data());
  5730. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  5731. trayIcon.data());
  5732. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  5733. trayIcon.data());
  5734. exit = new QAction(QTStr("Exit"), trayIcon.data());
  5735. trayMenu = new QMenu;
  5736. previewProjector = new QMenu(QTStr("PreviewProjector"));
  5737. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  5738. AddProjectorMenuMonitors(previewProjector, this,
  5739. SLOT(OpenPreviewProjector()));
  5740. AddProjectorMenuMonitors(studioProgramProjector, this,
  5741. SLOT(OpenStudioProgramProjector()));
  5742. trayMenu->addAction(showHide);
  5743. trayMenu->addMenu(previewProjector);
  5744. trayMenu->addMenu(studioProgramProjector);
  5745. trayMenu->addAction(sysTrayStream);
  5746. trayMenu->addAction(sysTrayRecord);
  5747. trayMenu->addAction(sysTrayReplayBuffer);
  5748. trayMenu->addAction(exit);
  5749. trayIcon->setContextMenu(trayMenu);
  5750. trayIcon->show();
  5751. if (outputHandler && !outputHandler->replayBuffer)
  5752. sysTrayReplayBuffer->setEnabled(false);
  5753. connect(trayIcon.data(),
  5754. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  5755. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  5756. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  5757. connect(sysTrayStream, SIGNAL(triggered()), this,
  5758. SLOT(on_streamButton_clicked()));
  5759. connect(sysTrayRecord, SIGNAL(triggered()), this,
  5760. SLOT(on_recordButton_clicked()));
  5761. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  5762. &OBSBasic::ReplayBufferClicked);
  5763. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  5764. }
  5765. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  5766. {
  5767. // Refresh projector list
  5768. previewProjector->clear();
  5769. studioProgramProjector->clear();
  5770. AddProjectorMenuMonitors(previewProjector, this,
  5771. SLOT(OpenPreviewProjector()));
  5772. AddProjectorMenuMonitors(studioProgramProjector, this,
  5773. SLOT(OpenStudioProgramProjector()));
  5774. if (reason == QSystemTrayIcon::Trigger)
  5775. ToggleShowHide();
  5776. }
  5777. void OBSBasic::SysTrayNotify(const QString &text,
  5778. QSystemTrayIcon::MessageIcon n)
  5779. {
  5780. if (trayIcon && QSystemTrayIcon::supportsMessages()) {
  5781. QSystemTrayIcon::MessageIcon icon =
  5782. QSystemTrayIcon::MessageIcon(n);
  5783. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  5784. }
  5785. }
  5786. void OBSBasic::SystemTray(bool firstStarted)
  5787. {
  5788. if (!QSystemTrayIcon::isSystemTrayAvailable())
  5789. return;
  5790. if (!trayIcon && !firstStarted)
  5791. return;
  5792. bool sysTrayWhenStarted = config_get_bool(
  5793. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  5794. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5795. "SysTrayEnabled");
  5796. if (firstStarted)
  5797. SystemTrayInit();
  5798. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  5799. trayIcon->hide();
  5800. } else if ((sysTrayWhenStarted && sysTrayEnabled) ||
  5801. opt_minimize_tray) {
  5802. trayIcon->show();
  5803. if (firstStarted) {
  5804. QTimer::singleShot(50, this, SLOT(hide()));
  5805. EnablePreviewDisplay(false);
  5806. setVisible(false);
  5807. #ifdef __APPLE__
  5808. EnableOSXDockIcon(false);
  5809. #endif
  5810. opt_minimize_tray = false;
  5811. }
  5812. } else if (sysTrayEnabled) {
  5813. trayIcon->show();
  5814. } else if (!sysTrayEnabled) {
  5815. trayIcon->hide();
  5816. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  5817. trayIcon->hide();
  5818. }
  5819. if (isVisible())
  5820. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  5821. else
  5822. showHide->setText(QTStr("Basic.SystemTray.Show"));
  5823. }
  5824. bool OBSBasic::sysTrayMinimizeToTray()
  5825. {
  5826. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  5827. "SysTrayMinimizeToTray");
  5828. }
  5829. void OBSBasic::on_actionCopySource_triggered()
  5830. {
  5831. copyStrings.clear();
  5832. bool allowPastingDuplicate = true;
  5833. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  5834. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  5835. if (!item)
  5836. continue;
  5837. on_actionCopyTransform_triggered();
  5838. OBSSource source = obs_sceneitem_get_source(item);
  5839. copyStrings.push_front(obs_source_get_name(source));
  5840. copyVisible = obs_sceneitem_visible(item);
  5841. uint32_t output_flags = obs_source_get_output_flags(source);
  5842. if (!(output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  5843. allowPastingDuplicate = false;
  5844. }
  5845. ui->actionPasteRef->setEnabled(true);
  5846. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  5847. }
  5848. void OBSBasic::on_actionPasteRef_triggered()
  5849. {
  5850. for (auto &copyString : copyStrings) {
  5851. /* do not allow duplicate refs of the same group in the same scene */
  5852. OBSScene scene = GetCurrentScene();
  5853. if (!!obs_scene_get_group(scene, copyString))
  5854. continue;
  5855. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5856. false);
  5857. on_actionPasteTransform_triggered();
  5858. }
  5859. }
  5860. void OBSBasic::on_actionPasteDup_triggered()
  5861. {
  5862. for (auto &copyString : copyStrings) {
  5863. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  5864. true);
  5865. on_actionPasteTransform_triggered();
  5866. }
  5867. }
  5868. void OBSBasic::AudioMixerCopyFilters()
  5869. {
  5870. QAction *action = reinterpret_cast<QAction *>(sender());
  5871. VolControl *vol = action->property("volControl").value<VolControl *>();
  5872. obs_source_t *source = vol->GetSource();
  5873. copyFiltersString = obs_source_get_name(source);
  5874. }
  5875. void OBSBasic::AudioMixerPasteFilters()
  5876. {
  5877. QAction *action = reinterpret_cast<QAction *>(sender());
  5878. VolControl *vol = action->property("volControl").value<VolControl *>();
  5879. obs_source_t *dstSource = vol->GetSource();
  5880. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5881. obs_source_release(source);
  5882. if (source == dstSource)
  5883. return;
  5884. obs_source_copy_filters(dstSource, source);
  5885. }
  5886. void OBSBasic::SceneCopyFilters()
  5887. {
  5888. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  5889. }
  5890. void OBSBasic::ScenePasteFilters()
  5891. {
  5892. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5893. obs_source_release(source);
  5894. OBSSource dstSource = GetCurrentSceneSource();
  5895. if (source == dstSource)
  5896. return;
  5897. obs_source_copy_filters(dstSource, source);
  5898. }
  5899. void OBSBasic::on_actionCopyFilters_triggered()
  5900. {
  5901. OBSSceneItem item = GetCurrentSceneItem();
  5902. if (!item)
  5903. return;
  5904. OBSSource source = obs_sceneitem_get_source(item);
  5905. copyFiltersString = obs_source_get_name(source);
  5906. ui->actionPasteFilters->setEnabled(true);
  5907. }
  5908. void OBSBasic::on_actionPasteFilters_triggered()
  5909. {
  5910. OBSSource source = obs_get_source_by_name(copyFiltersString);
  5911. obs_source_release(source);
  5912. OBSSceneItem sceneItem = GetCurrentSceneItem();
  5913. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  5914. if (source == dstSource)
  5915. return;
  5916. obs_source_copy_filters(dstSource, source);
  5917. }
  5918. static void ConfirmColor(SourceTree *sources, const QColor &color,
  5919. QModelIndexList selectedItems)
  5920. {
  5921. for (int x = 0; x < selectedItems.count(); x++) {
  5922. SourceTreeItem *treeItem =
  5923. sources->GetItemWidget(selectedItems[x].row());
  5924. treeItem->setStyleSheet("background: " +
  5925. color.name(QColor::HexArgb));
  5926. treeItem->style()->unpolish(treeItem);
  5927. treeItem->style()->polish(treeItem);
  5928. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  5929. obs_data_t *privData =
  5930. obs_sceneitem_get_private_settings(sceneItem);
  5931. obs_data_set_int(privData, "color-preset", 1);
  5932. obs_data_set_string(privData, "color",
  5933. QT_TO_UTF8(color.name(QColor::HexArgb)));
  5934. obs_data_release(privData);
  5935. }
  5936. }
  5937. void OBSBasic::ColorChange()
  5938. {
  5939. QModelIndexList selectedItems =
  5940. ui->sources->selectionModel()->selectedIndexes();
  5941. QAction *action = qobject_cast<QAction *>(sender());
  5942. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  5943. if (selectedItems.count() == 0)
  5944. return;
  5945. if (colorButton) {
  5946. int preset = colorButton->property("bgColor").value<int>();
  5947. for (int x = 0; x < selectedItems.count(); x++) {
  5948. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  5949. selectedItems[x].row());
  5950. treeItem->setStyleSheet("");
  5951. treeItem->setProperty("bgColor", preset);
  5952. treeItem->style()->unpolish(treeItem);
  5953. treeItem->style()->polish(treeItem);
  5954. OBSSceneItem sceneItem =
  5955. ui->sources->Get(selectedItems[x].row());
  5956. obs_data_t *privData =
  5957. obs_sceneitem_get_private_settings(sceneItem);
  5958. obs_data_set_int(privData, "color-preset", preset + 1);
  5959. obs_data_set_string(privData, "color", "");
  5960. obs_data_release(privData);
  5961. }
  5962. for (int i = 1; i < 9; i++) {
  5963. stringstream button;
  5964. button << "preset" << i;
  5965. QPushButton *cButton =
  5966. colorButton->parentWidget()
  5967. ->findChild<QPushButton *>(
  5968. button.str().c_str());
  5969. cButton->setStyleSheet("border: 1px solid black");
  5970. }
  5971. colorButton->setStyleSheet("border: 2px solid black");
  5972. } else if (action) {
  5973. int preset = action->property("bgColor").value<int>();
  5974. if (preset == 1) {
  5975. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  5976. SourceTreeItem *curTreeItem =
  5977. GetItemWidgetFromSceneItem(curSceneItem);
  5978. obs_data_t *curPrivData =
  5979. obs_sceneitem_get_private_settings(
  5980. curSceneItem);
  5981. int oldPreset =
  5982. obs_data_get_int(curPrivData, "color-preset");
  5983. const QString oldSheet = curTreeItem->styleSheet();
  5984. auto liveChangeColor = [=](const QColor &color) {
  5985. if (color.isValid()) {
  5986. curTreeItem->setStyleSheet(
  5987. "background: " +
  5988. color.name(QColor::HexArgb));
  5989. }
  5990. };
  5991. auto changedColor = [=](const QColor &color) {
  5992. if (color.isValid()) {
  5993. ConfirmColor(ui->sources, color,
  5994. selectedItems);
  5995. }
  5996. };
  5997. auto rejected = [=]() {
  5998. if (oldPreset == 1) {
  5999. curTreeItem->setStyleSheet(oldSheet);
  6000. curTreeItem->setProperty("bgColor", 0);
  6001. } else if (oldPreset == 0) {
  6002. curTreeItem->setStyleSheet(
  6003. "background: none");
  6004. curTreeItem->setProperty("bgColor", 0);
  6005. } else {
  6006. curTreeItem->setStyleSheet("");
  6007. curTreeItem->setProperty("bgColor",
  6008. oldPreset - 1);
  6009. }
  6010. curTreeItem->style()->unpolish(curTreeItem);
  6011. curTreeItem->style()->polish(curTreeItem);
  6012. };
  6013. QColorDialog::ColorDialogOptions options =
  6014. QColorDialog::ShowAlphaChannel;
  6015. const char *oldColor =
  6016. obs_data_get_string(curPrivData, "color");
  6017. const char *customColor = *oldColor != 0 ? oldColor
  6018. : "#55FF0000";
  6019. #ifdef __APPLE__
  6020. options |= QColorDialog::DontUseNativeDialog;
  6021. #endif
  6022. QColorDialog *colorDialog = new QColorDialog(this);
  6023. colorDialog->setOptions(options);
  6024. colorDialog->setCurrentColor(QColor(customColor));
  6025. connect(colorDialog, &QColorDialog::currentColorChanged,
  6026. liveChangeColor);
  6027. connect(colorDialog, &QColorDialog::colorSelected,
  6028. changedColor);
  6029. connect(colorDialog, &QColorDialog::rejected, rejected);
  6030. colorDialog->open();
  6031. obs_data_release(curPrivData);
  6032. } else {
  6033. for (int x = 0; x < selectedItems.count(); x++) {
  6034. SourceTreeItem *treeItem =
  6035. ui->sources->GetItemWidget(
  6036. selectedItems[x].row());
  6037. treeItem->setStyleSheet("background: none");
  6038. treeItem->setProperty("bgColor", preset);
  6039. treeItem->style()->unpolish(treeItem);
  6040. treeItem->style()->polish(treeItem);
  6041. OBSSceneItem sceneItem = ui->sources->Get(
  6042. selectedItems[x].row());
  6043. obs_data_t *privData =
  6044. obs_sceneitem_get_private_settings(
  6045. sceneItem);
  6046. obs_data_set_int(privData, "color-preset",
  6047. preset);
  6048. obs_data_set_string(privData, "color", "");
  6049. obs_data_release(privData);
  6050. }
  6051. }
  6052. }
  6053. }
  6054. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  6055. {
  6056. int i = 0;
  6057. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  6058. OBSSceneItem item = ui->sources->Get(i);
  6059. int64_t id = obs_sceneitem_get_id(sceneItem);
  6060. while (treeItem && obs_sceneitem_get_id(item) != id) {
  6061. i++;
  6062. treeItem = ui->sources->GetItemWidget(i);
  6063. item = ui->sources->Get(i);
  6064. }
  6065. if (treeItem)
  6066. return treeItem;
  6067. return nullptr;
  6068. }
  6069. void OBSBasic::on_autoConfigure_triggered()
  6070. {
  6071. AutoConfig test(this);
  6072. test.setModal(true);
  6073. test.show();
  6074. test.exec();
  6075. }
  6076. void OBSBasic::on_stats_triggered()
  6077. {
  6078. if (!stats.isNull()) {
  6079. stats->show();
  6080. stats->raise();
  6081. return;
  6082. }
  6083. OBSBasicStats *statsDlg;
  6084. statsDlg = new OBSBasicStats(nullptr);
  6085. statsDlg->show();
  6086. stats = statsDlg;
  6087. }
  6088. void OBSBasic::on_actionShowAbout_triggered()
  6089. {
  6090. if (about)
  6091. about->close();
  6092. about = new OBSAbout(this);
  6093. about->show();
  6094. about->setAttribute(Qt::WA_DeleteOnClose, true);
  6095. }
  6096. void OBSBasic::ResizeOutputSizeOfSource()
  6097. {
  6098. if (obs_video_active())
  6099. return;
  6100. QMessageBox resize_output(this);
  6101. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  6102. QTStr("ResizeOutputSizeOfSource.Continue"));
  6103. QAbstractButton *Yes =
  6104. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  6105. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  6106. resize_output.setIcon(QMessageBox::Warning);
  6107. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  6108. resize_output.exec();
  6109. if (resize_output.clickedButton() != Yes)
  6110. return;
  6111. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  6112. int width = obs_source_get_width(source);
  6113. int height = obs_source_get_height(source);
  6114. config_set_uint(basicConfig, "Video", "BaseCX", width);
  6115. config_set_uint(basicConfig, "Video", "BaseCY", height);
  6116. config_set_uint(basicConfig, "Video", "OutputCX", width);
  6117. config_set_uint(basicConfig, "Video", "OutputCY", height);
  6118. ResetVideo();
  6119. on_actionFitToScreen_triggered();
  6120. }
  6121. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  6122. {
  6123. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  6124. action->setCheckable(true);
  6125. assignDockToggle(dock, action);
  6126. extraDocks.push_back(dock);
  6127. bool lock = ui->lockUI->isChecked();
  6128. QDockWidget::DockWidgetFeatures features =
  6129. lock ? QDockWidget::NoDockWidgetFeatures
  6130. : QDockWidget::AllDockWidgetFeatures;
  6131. dock->setFeatures(features);
  6132. /* prune deleted docks */
  6133. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6134. if (!extraDocks[i]) {
  6135. extraDocks.removeAt(i);
  6136. }
  6137. }
  6138. return action;
  6139. }
  6140. OBSBasic *OBSBasic::Get()
  6141. {
  6142. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  6143. }
  6144. bool OBSBasic::StreamingActive()
  6145. {
  6146. if (!outputHandler)
  6147. return false;
  6148. return outputHandler->StreamingActive();
  6149. }
  6150. bool OBSBasic::RecordingActive()
  6151. {
  6152. if (!outputHandler)
  6153. return false;
  6154. return outputHandler->RecordingActive();
  6155. }
  6156. bool OBSBasic::ReplayBufferActive()
  6157. {
  6158. if (!outputHandler)
  6159. return false;
  6160. return outputHandler->ReplayBufferActive();
  6161. }
  6162. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  6163. : QStyledItemDelegate(parent)
  6164. {
  6165. }
  6166. void SceneRenameDelegate::setEditorData(QWidget *editor,
  6167. const QModelIndex &index) const
  6168. {
  6169. QStyledItemDelegate::setEditorData(editor, index);
  6170. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6171. if (lineEdit)
  6172. lineEdit->selectAll();
  6173. }
  6174. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  6175. {
  6176. if (event->type() == QEvent::KeyPress) {
  6177. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  6178. if (keyEvent->key() == Qt::Key_Escape) {
  6179. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  6180. if (lineEdit)
  6181. lineEdit->undo();
  6182. }
  6183. }
  6184. return QStyledItemDelegate::eventFilter(editor, event);
  6185. }
  6186. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  6187. {
  6188. if (!error.isEmpty())
  6189. return;
  6190. patronJson = QT_TO_UTF8(text);
  6191. }
  6192. void OBSBasic::PauseRecording()
  6193. {
  6194. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6195. return;
  6196. obs_output_t *output = outputHandler->fileOutput;
  6197. if (obs_output_pause(output, true)) {
  6198. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  6199. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  6200. pause->blockSignals(true);
  6201. pause->setChecked(true);
  6202. pause->blockSignals(false);
  6203. if (trayIcon)
  6204. trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
  6205. os_atomic_set_bool(&recording_paused, true);
  6206. if (api)
  6207. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  6208. if (os_atomic_load_bool(&replaybuf_active))
  6209. ShowReplayBufferPauseWarning();
  6210. }
  6211. }
  6212. void OBSBasic::UnpauseRecording()
  6213. {
  6214. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6215. return;
  6216. obs_output_t *output = outputHandler->fileOutput;
  6217. if (obs_output_pause(output, false)) {
  6218. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6219. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6220. pause->blockSignals(true);
  6221. pause->setChecked(false);
  6222. pause->blockSignals(false);
  6223. if (trayIcon)
  6224. trayIcon->setIcon(
  6225. QIcon(":/res/images/tray_active.png"));
  6226. os_atomic_set_bool(&recording_paused, false);
  6227. if (api)
  6228. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  6229. }
  6230. }
  6231. void OBSBasic::PauseToggled()
  6232. {
  6233. if (!pause || !outputHandler || !outputHandler->fileOutput)
  6234. return;
  6235. obs_output_t *output = outputHandler->fileOutput;
  6236. bool enable = !obs_output_paused(output);
  6237. if (enable)
  6238. PauseRecording();
  6239. else
  6240. UnpauseRecording();
  6241. }
  6242. void OBSBasic::UpdatePause(bool activate)
  6243. {
  6244. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  6245. pause.reset();
  6246. return;
  6247. }
  6248. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  6249. bool adv = astrcmpi(mode, "Advanced") == 0;
  6250. bool shared;
  6251. if (adv) {
  6252. const char *recType =
  6253. config_get_string(basicConfig, "AdvOut", "RecType");
  6254. if (astrcmpi(recType, "FFmpeg") == 0) {
  6255. shared = config_get_bool(basicConfig, "AdvOut",
  6256. "FFOutputToFile");
  6257. } else {
  6258. const char *recordEncoder = config_get_string(
  6259. basicConfig, "AdvOut", "RecEncoder");
  6260. shared = astrcmpi(recordEncoder, "none") == 0;
  6261. }
  6262. } else {
  6263. const char *quality = config_get_string(
  6264. basicConfig, "SimpleOutput", "RecQuality");
  6265. shared = strcmp(quality, "Stream") == 0;
  6266. }
  6267. if (!shared) {
  6268. pause.reset(new QPushButton());
  6269. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  6270. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  6271. pause->setCheckable(true);
  6272. pause->setChecked(false);
  6273. pause->setProperty("themeID",
  6274. QVariant(QStringLiteral("pauseIconSmall")));
  6275. connect(pause.data(), &QAbstractButton::clicked, this,
  6276. &OBSBasic::PauseToggled);
  6277. ui->recordingLayout->addWidget(pause.data());
  6278. } else {
  6279. pause.reset();
  6280. }
  6281. }
  6282. void OBSBasic::UpdateReplayBuffer(bool activate)
  6283. {
  6284. if (!activate || !outputHandler ||
  6285. !outputHandler->ReplayBufferActive()) {
  6286. replay.reset();
  6287. return;
  6288. }
  6289. replay.reset(new QPushButton());
  6290. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  6291. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  6292. replay->setCheckable(true);
  6293. replay->setChecked(false);
  6294. replay->setProperty("themeID",
  6295. QVariant(QStringLiteral("replayIconSmall")));
  6296. connect(replay.data(), &QAbstractButton::clicked, this,
  6297. &OBSBasic::ReplayBufferSave);
  6298. replayLayout->addWidget(replay.data());
  6299. }
  6300. #define MBYTE (1024ULL * 1024ULL)
  6301. #define MBYTES_LEFT_STOP_REC 50ULL
  6302. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  6303. const char *OBSBasic::GetCurrentOutputPath()
  6304. {
  6305. const char *path = nullptr;
  6306. const char *mode = config_get_string(Config(), "Output", "Mode");
  6307. if (strcmp(mode, "Advanced") == 0) {
  6308. const char *advanced_mode =
  6309. config_get_string(Config(), "AdvOut", "RecType");
  6310. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  6311. path = config_get_string(Config(), "AdvOut",
  6312. "FFFilePath");
  6313. } else {
  6314. path = config_get_string(Config(), "AdvOut",
  6315. "RecFilePath");
  6316. }
  6317. } else {
  6318. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  6319. }
  6320. return path;
  6321. }
  6322. void OBSBasic::OutputPathInvalidMessage()
  6323. {
  6324. blog(LOG_ERROR, "Recording stopped because of bad output path");
  6325. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  6326. QTStr("Output.BadPath.Text"));
  6327. }
  6328. bool OBSBasic::OutputPathValid()
  6329. {
  6330. const char *path = GetCurrentOutputPath();
  6331. return path && *path && QDir(path).exists();
  6332. }
  6333. void OBSBasic::DiskSpaceMessage()
  6334. {
  6335. blog(LOG_ERROR, "Recording stopped because of low disk space");
  6336. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  6337. QTStr("Output.RecordNoSpace.Msg"));
  6338. }
  6339. bool OBSBasic::LowDiskSpace()
  6340. {
  6341. const char *path;
  6342. path = GetCurrentOutputPath();
  6343. if (!path)
  6344. return false;
  6345. uint64_t num_bytes = os_get_free_disk_space(path);
  6346. if (num_bytes < (MAX_BYTES_LEFT))
  6347. return true;
  6348. else
  6349. return false;
  6350. }
  6351. void OBSBasic::CheckDiskSpaceRemaining()
  6352. {
  6353. if (LowDiskSpace()) {
  6354. StopRecording();
  6355. StopReplayBuffer();
  6356. DiskSpaceMessage();
  6357. }
  6358. }
  6359. void OBSBasic::ScenesReordered(const QModelIndex &parent, int start, int end,
  6360. const QModelIndex &destination, int row)
  6361. {
  6362. UNUSED_PARAMETER(parent);
  6363. UNUSED_PARAMETER(start);
  6364. UNUSED_PARAMETER(end);
  6365. UNUSED_PARAMETER(destination);
  6366. UNUSED_PARAMETER(row);
  6367. OBSProjector::UpdateMultiviewProjectors();
  6368. }
  6369. void OBSBasic::ResetStatsHotkey()
  6370. {
  6371. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  6372. foreach(OBSBasicStats * s, list) s->Reset();
  6373. }
  6374. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  6375. {
  6376. QWidget *widget = childAt(pos);
  6377. const char *className = nullptr;
  6378. if (widget != nullptr)
  6379. className = widget->metaObject()->className();
  6380. if (!className || strstr(className, "Dock") != nullptr)
  6381. ui->viewMenuDocks->exec(mapToGlobal(pos));
  6382. }