window-basic-main.cpp 206 KB

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