window-basic-main.cpp 208 KB

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