window-basic-main.cpp 208 KB

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