window-basic-main.cpp 161 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170
  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 <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  32. #include "obs-app.hpp"
  33. #include "platform.hpp"
  34. #include "visibility-item-widget.hpp"
  35. #include "item-widget-helpers.hpp"
  36. #include "window-basic-settings.hpp"
  37. #include "window-namedialog.hpp"
  38. #include "window-basic-auto-config.hpp"
  39. #include "window-basic-source-select.hpp"
  40. #include "window-basic-main.hpp"
  41. #include "window-basic-stats.hpp"
  42. #include "window-basic-main-outputs.hpp"
  43. #include "window-basic-properties.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 "source-tree.hpp"
  52. #ifdef _WIN32
  53. #include "win-update/win-update.hpp"
  54. #endif
  55. #include "ui_OBSBasic.h"
  56. #include <fstream>
  57. #include <sstream>
  58. #include <QScreen>
  59. #include <QWindow>
  60. using namespace std;
  61. namespace {
  62. template <typename OBSRef>
  63. struct SignalContainer {
  64. OBSRef ref;
  65. vector<shared_ptr<OBSSignal>> handlers;
  66. };
  67. }
  68. Q_DECLARE_METATYPE(OBSScene);
  69. Q_DECLARE_METATYPE(OBSSceneItem);
  70. Q_DECLARE_METATYPE(OBSSource);
  71. Q_DECLARE_METATYPE(obs_order_movement);
  72. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  73. template <typename T>
  74. static T GetOBSRef(QListWidgetItem *item)
  75. {
  76. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  77. }
  78. template <typename T>
  79. static void SetOBSRef(QListWidgetItem *item, T &&val)
  80. {
  81. item->setData(static_cast<int>(QtDataRole::OBSRef),
  82. QVariant::fromValue(val));
  83. }
  84. static void AddExtraModulePaths()
  85. {
  86. char base_module_dir[512];
  87. #if defined(_WIN32) || defined(__APPLE__)
  88. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  89. "obs-studio/plugins/%module%");
  90. #else
  91. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  92. "obs-studio/plugins/%module%");
  93. #endif
  94. if (ret <= 0)
  95. return;
  96. string path = (char*)base_module_dir;
  97. #if defined(__APPLE__)
  98. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  99. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  100. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  101. obs_add_module_path(config_bin, config_data);
  102. #elif ARCH_BITS == 64
  103. obs_add_module_path((path + "/bin/64bit").c_str(),
  104. (path + "/data").c_str());
  105. #else
  106. obs_add_module_path((path + "/bin/32bit").c_str(),
  107. (path + "/data").c_str());
  108. #endif
  109. }
  110. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  111. OBSBasic::OBSBasic(QWidget *parent)
  112. : OBSMainWindow (parent),
  113. ui (new Ui::OBSBasic)
  114. {
  115. setAttribute(Qt::WA_NativeWindow);
  116. setAcceptDrops(true);
  117. api = InitializeAPIInterface(this);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. char styleSheetPath[512];
  123. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  124. "stylesheet.qss");
  125. if (ret > 0) {
  126. if (QFile::exists(styleSheetPath)) {
  127. QString path = QString("file:///") +
  128. QT_UTF8(styleSheetPath);
  129. App()->setStyleSheet(path);
  130. }
  131. }
  132. qRegisterMetaType<OBSScene> ("OBSScene");
  133. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  134. qRegisterMetaType<OBSSource> ("OBSSource");
  135. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  136. qRegisterMetaTypeStreamOperators<
  137. std::vector<std::shared_ptr<OBSSignal>>>(
  138. "std::vector<std::shared_ptr<OBSSignal>>");
  139. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  140. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  141. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  142. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  143. auto displayResize = [this]() {
  144. struct obs_video_info ovi;
  145. if (obs_get_video_info(&ovi))
  146. ResizePreview(ovi.base_width, ovi.base_height);
  147. };
  148. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  149. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  150. installEventFilter(CreateShortcutFilter());
  151. stringstream name;
  152. name << "OBS " << App()->GetVersionString();
  153. blog(LOG_INFO, "%s", name.str().c_str());
  154. blog(LOG_INFO, "---------------------------------");
  155. UpdateTitleBar();
  156. connect(ui->scenes->itemDelegate(),
  157. SIGNAL(closeEditor(QWidget*,
  158. QAbstractItemDelegate::EndEditHint)),
  159. this,
  160. SLOT(SceneNameEdited(QWidget*,
  161. QAbstractItemDelegate::EndEditHint)));
  162. cpuUsageInfo = os_cpu_usage_info_start();
  163. cpuUsageTimer = new QTimer(this);
  164. connect(cpuUsageTimer, SIGNAL(timeout()),
  165. ui->statusbar, SLOT(UpdateCPUUsage()));
  166. cpuUsageTimer->start(3000);
  167. #ifdef __APPLE__
  168. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  169. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  170. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  171. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  172. #endif
  173. auto addNudge = [this](const QKeySequence &seq, const char *s)
  174. {
  175. QAction *nudge = new QAction(ui->preview);
  176. nudge->setShortcut(seq);
  177. nudge->setShortcutContext(Qt::WidgetShortcut);
  178. ui->preview->addAction(nudge);
  179. connect(nudge, SIGNAL(triggered()), this, s);
  180. };
  181. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  182. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  183. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  184. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  185. auto assignDockToggle = [] (QDockWidget *dock, QAction *action)
  186. {
  187. auto handleWindowToggle = [action] (bool vis)
  188. {
  189. action->blockSignals(true);
  190. action->setChecked(vis);
  191. action->blockSignals(false);
  192. };
  193. auto handleMenuToggle = [dock] (bool check)
  194. {
  195. dock->blockSignals(true);
  196. dock->setVisible(check);
  197. dock->blockSignals(false);
  198. };
  199. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  200. handleWindowToggle);
  201. dock->connect(action, &QAction::toggled,
  202. handleMenuToggle);
  203. };
  204. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  205. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  206. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  207. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  208. assignDockToggle(ui->controlsDock, ui->toggleControls);
  209. //hide all docking panes
  210. ui->toggleScenes->setChecked(false);
  211. ui->toggleSources->setChecked(false);
  212. ui->toggleMixer->setChecked(false);
  213. ui->toggleTransitions->setChecked(false);
  214. ui->toggleControls->setChecked(false);
  215. //restore parent window geometry
  216. const char *geometry = config_get_string(App()->GlobalConfig(),
  217. "BasicWindow", "geometry");
  218. if (geometry != NULL) {
  219. QByteArray byteArray = QByteArray::fromBase64(
  220. QByteArray(geometry));
  221. restoreGeometry(byteArray);
  222. QRect windowGeometry = normalGeometry();
  223. if (!WindowPositionValid(windowGeometry)) {
  224. QRect rect = App()->desktop()->geometry();
  225. setGeometry(QStyle::alignedRect(
  226. Qt::LeftToRight,
  227. Qt::AlignCenter,
  228. size(), rect));
  229. }
  230. }
  231. }
  232. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  233. vector<OBSSource> &audioSources)
  234. {
  235. obs_source_t *source = obs_get_output_source(channel);
  236. if (!source)
  237. return;
  238. audioSources.push_back(source);
  239. obs_data_t *data = obs_save_source(source);
  240. obs_data_set_obj(parent, name, data);
  241. obs_data_release(data);
  242. obs_source_release(source);
  243. }
  244. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  245. obs_data_array_t *quickTransitionData, int transitionDuration,
  246. obs_data_array_t *transitions,
  247. OBSScene &scene, OBSSource &curProgramScene,
  248. obs_data_array_t *savedProjectorList)
  249. {
  250. obs_data_t *saveData = obs_data_create();
  251. vector<OBSSource> audioSources;
  252. audioSources.reserve(5);
  253. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  254. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  255. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  256. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  257. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  258. /* -------------------------------- */
  259. /* save non-group sources */
  260. auto FilterAudioSources = [&](obs_source_t *source)
  261. {
  262. if (obs_source_is_group(source))
  263. return false;
  264. return find(begin(audioSources), end(audioSources), source) ==
  265. end(audioSources);
  266. };
  267. using FilterAudioSources_t = decltype(FilterAudioSources);
  268. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  269. [](void *data, obs_source_t *source)
  270. {
  271. return (*static_cast<FilterAudioSources_t*>(data))(source);
  272. }, static_cast<void*>(&FilterAudioSources));
  273. /* -------------------------------- */
  274. /* save group sources separately */
  275. /* saving separately ensures they won't be loaded in older versions */
  276. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  277. [](void*, obs_source_t *source)
  278. {
  279. return obs_source_is_group(source);
  280. }, nullptr);
  281. /* -------------------------------- */
  282. obs_source_t *transition = obs_get_output_source(0);
  283. obs_source_t *currentScene = obs_scene_get_source(scene);
  284. const char *sceneName = obs_source_get_name(currentScene);
  285. const char *programName = obs_source_get_name(curProgramScene);
  286. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  287. "Basic", "SceneCollection");
  288. obs_data_set_string(saveData, "current_scene", sceneName);
  289. obs_data_set_string(saveData, "current_program_scene", programName);
  290. obs_data_set_array(saveData, "scene_order", sceneOrder);
  291. obs_data_set_string(saveData, "name", sceneCollection);
  292. obs_data_set_array(saveData, "sources", sourcesArray);
  293. obs_data_set_array(saveData, "groups", groupsArray);
  294. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  295. obs_data_set_array(saveData, "transitions", transitions);
  296. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  297. obs_data_array_release(sourcesArray);
  298. obs_data_array_release(groupsArray);
  299. obs_data_set_string(saveData, "current_transition",
  300. obs_source_get_name(transition));
  301. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  302. obs_source_release(transition);
  303. return saveData;
  304. }
  305. void OBSBasic::copyActionsDynamicProperties()
  306. {
  307. // Themes need the QAction dynamic properties
  308. for (QAction *x : ui->scenesToolbar->actions()) {
  309. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  310. for (QByteArray &y : x->dynamicPropertyNames()) {
  311. temp->setProperty(y, x->property(y));
  312. }
  313. }
  314. for (QAction *x : ui->sourcesToolbar->actions()) {
  315. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  316. for (QByteArray &y : x->dynamicPropertyNames()) {
  317. temp->setProperty(y, x->property(y));
  318. }
  319. }
  320. }
  321. void OBSBasic::UpdateVolumeControlsDecayRate()
  322. {
  323. double meterDecayRate = config_get_double(basicConfig, "Audio",
  324. "MeterDecayRate");
  325. for (size_t i = 0; i < volumes.size(); i++) {
  326. volumes[i]->SetMeterDecayRate(meterDecayRate);
  327. }
  328. }
  329. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  330. {
  331. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  332. "PeakMeterType");
  333. enum obs_peak_meter_type peakMeterType;
  334. switch (peakMeterTypeIdx) {
  335. case 0:
  336. peakMeterType = SAMPLE_PEAK_METER;
  337. break;
  338. case 1:
  339. peakMeterType = TRUE_PEAK_METER;
  340. break;
  341. default:
  342. peakMeterType = SAMPLE_PEAK_METER;
  343. break;
  344. }
  345. for (size_t i = 0; i < volumes.size(); i++) {
  346. volumes[i]->setPeakMeterType(peakMeterType);
  347. }
  348. }
  349. void OBSBasic::ClearVolumeControls()
  350. {
  351. for (VolControl *vol : volumes)
  352. delete vol;
  353. volumes.clear();
  354. }
  355. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  356. {
  357. obs_data_array_t *sceneOrder = obs_data_array_create();
  358. for (int i = 0; i < ui->scenes->count(); i++) {
  359. obs_data_t *data = obs_data_create();
  360. obs_data_set_string(data, "name",
  361. QT_TO_UTF8(ui->scenes->item(i)->text()));
  362. obs_data_array_push_back(sceneOrder, data);
  363. obs_data_release(data);
  364. }
  365. return sceneOrder;
  366. }
  367. obs_data_array_t *OBSBasic::SaveProjectors()
  368. {
  369. obs_data_array_t *savedProjectors = obs_data_array_create();
  370. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  371. if (!projector)
  372. return;
  373. obs_data_t *data = obs_data_create();
  374. ProjectorType type = projector->GetProjectorType();
  375. switch (type) {
  376. case ProjectorType::Scene:
  377. case ProjectorType::Source: {
  378. obs_source_t *source = projector->GetSource();
  379. const char *name = obs_source_get_name(source);
  380. obs_data_set_string(data, "name", name);
  381. break;
  382. }
  383. default:
  384. break;
  385. }
  386. obs_data_set_int(data, "monitor", projector->GetMonitor());
  387. obs_data_set_int(data, "type", static_cast<int>(type));
  388. obs_data_set_string(data, "geometry",
  389. projector->saveGeometry().toBase64()
  390. .constData());
  391. obs_data_array_push_back(savedProjectors, data);
  392. obs_data_release(data);
  393. };
  394. for (QPointer<QWidget> &proj : projectors)
  395. saveProjector(static_cast<OBSProjector *>(proj.data()));
  396. for (QPointer<QWidget> &proj : windowProjectors)
  397. saveProjector(static_cast<OBSProjector *>(proj.data()));
  398. return savedProjectors;
  399. }
  400. void OBSBasic::Save(const char *file)
  401. {
  402. OBSScene scene = GetCurrentScene();
  403. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  404. if (!curProgramScene)
  405. curProgramScene = obs_scene_get_source(scene);
  406. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  407. obs_data_array_t *transitions = SaveTransitions();
  408. obs_data_array_t *quickTrData = SaveQuickTransitions();
  409. obs_data_array_t *savedProjectorList = SaveProjectors();
  410. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  411. ui->transitionDuration->value(), transitions,
  412. scene, curProgramScene, savedProjectorList);
  413. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  414. obs_data_set_bool(saveData, "scaling_enabled",
  415. ui->preview->IsFixedScaling());
  416. obs_data_set_int(saveData, "scaling_level",
  417. ui->preview->GetScalingLevel());
  418. obs_data_set_double(saveData, "scaling_off_x",
  419. ui->preview->GetScrollX());
  420. obs_data_set_double(saveData, "scaling_off_y",
  421. ui->preview->GetScrollY());
  422. if (api) {
  423. obs_data_t *moduleObj = obs_data_create();
  424. api->on_save(moduleObj);
  425. obs_data_set_obj(saveData, "modules", moduleObj);
  426. obs_data_release(moduleObj);
  427. }
  428. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  429. blog(LOG_ERROR, "Could not save scene data to %s", file);
  430. obs_data_release(saveData);
  431. obs_data_array_release(sceneOrder);
  432. obs_data_array_release(quickTrData);
  433. obs_data_array_release(transitions);
  434. obs_data_array_release(savedProjectorList);
  435. }
  436. void OBSBasic::DeferSaveBegin()
  437. {
  438. os_atomic_inc_long(&disableSaving);
  439. }
  440. void OBSBasic::DeferSaveEnd()
  441. {
  442. long result = os_atomic_dec_long(&disableSaving);
  443. if (result == 0) {
  444. SaveProject();
  445. }
  446. }
  447. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  448. {
  449. obs_data_t *data = obs_data_get_obj(parent, name);
  450. if (!data)
  451. return;
  452. obs_source_t *source = obs_load_source(data);
  453. if (source) {
  454. obs_set_output_source(channel, source);
  455. obs_source_release(source);
  456. }
  457. obs_data_release(data);
  458. }
  459. static inline bool HasAudioDevices(const char *source_id)
  460. {
  461. const char *output_id = source_id;
  462. obs_properties_t *props = obs_get_source_properties(output_id);
  463. size_t count = 0;
  464. if (!props)
  465. return false;
  466. obs_property_t *devices = obs_properties_get(props, "device_id");
  467. if (devices)
  468. count = obs_property_list_item_count(devices);
  469. obs_properties_destroy(props);
  470. return count != 0;
  471. }
  472. void OBSBasic::CreateFirstRunSources()
  473. {
  474. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  475. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  476. if (hasDesktopAudio)
  477. ResetAudioDevice(App()->OutputAudioSource(), "default",
  478. Str("Basic.DesktopDevice1"), 1);
  479. if (hasInputAudio)
  480. ResetAudioDevice(App()->InputAudioSource(), "default",
  481. Str("Basic.AuxDevice1"), 3);
  482. }
  483. void OBSBasic::CreateDefaultScene(bool firstStart)
  484. {
  485. disableSaving++;
  486. ClearSceneData();
  487. InitDefaultTransitions();
  488. CreateDefaultQuickTransitions();
  489. ui->transitionDuration->setValue(300);
  490. SetTransition(fadeTransition);
  491. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  492. if (firstStart)
  493. CreateFirstRunSources();
  494. SetCurrentScene(scene, true);
  495. obs_scene_release(scene);
  496. disableSaving--;
  497. }
  498. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  499. {
  500. for (int i = 0; i < lw->count(); i++) {
  501. QListWidgetItem *item = lw->item(i);
  502. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  503. if (newIndex != i) {
  504. item = lw->takeItem(i);
  505. lw->insertItem(newIndex, item);
  506. }
  507. break;
  508. }
  509. }
  510. }
  511. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  512. {
  513. size_t num = obs_data_array_count(array);
  514. for (size_t i = 0; i < num; i++) {
  515. obs_data_t *data = obs_data_array_item(array, i);
  516. const char *name = obs_data_get_string(data, "name");
  517. ReorderItemByName(ui->scenes, name, (int)i);
  518. obs_data_release(data);
  519. }
  520. }
  521. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  522. {
  523. size_t num = obs_data_array_count(array);
  524. for (size_t i = 0; i < num; i++) {
  525. obs_data_t *data = obs_data_array_item(array, i);
  526. SavedProjectorInfo *info = new SavedProjectorInfo();
  527. info->monitor = obs_data_get_int(data, "monitor");
  528. info->type = static_cast<ProjectorType>(obs_data_get_int(data,
  529. "type"));
  530. info->geometry = std::string(
  531. obs_data_get_string(data, "geometry"));
  532. info->name = std::string(obs_data_get_string(data, "name"));
  533. savedProjectorsArray.emplace_back(info);
  534. obs_data_release(data);
  535. }
  536. }
  537. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  538. {
  539. const char *name = obs_source_get_name(filter);
  540. const char *id = obs_source_get_id(filter);
  541. int val = (int)(intptr_t)v_val;
  542. string indent;
  543. for (int i = 0; i < val; i++)
  544. indent += " ";
  545. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  546. }
  547. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  548. {
  549. obs_source_t *source = obs_sceneitem_get_source(item);
  550. const char *name = obs_source_get_name(source);
  551. const char *id = obs_source_get_id(source);
  552. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  553. obs_monitoring_type monitoring_type =
  554. obs_source_get_monitoring_type(source);
  555. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  556. const char *type =
  557. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  558. ? "monitor only"
  559. : "monitor and output";
  560. blog(LOG_INFO, " - monitoring: %s", type);
  561. }
  562. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  563. return true;
  564. }
  565. void OBSBasic::LogScenes()
  566. {
  567. blog(LOG_INFO, "------------------------------------------------");
  568. blog(LOG_INFO, "Loaded scenes:");
  569. for (int i = 0; i < ui->scenes->count(); i++) {
  570. QListWidgetItem *item = ui->scenes->item(i);
  571. OBSScene scene = GetOBSRef<OBSScene>(item);
  572. obs_source_t *source = obs_scene_get_source(scene);
  573. const char *name = obs_source_get_name(source);
  574. blog(LOG_INFO, "- scene '%s':", name);
  575. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  576. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  577. }
  578. blog(LOG_INFO, "------------------------------------------------");
  579. }
  580. void OBSBasic::Load(const char *file)
  581. {
  582. disableSaving++;
  583. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  584. if (!data) {
  585. disableSaving--;
  586. blog(LOG_INFO, "No scene file found, creating default scene");
  587. CreateDefaultScene(true);
  588. SaveProject();
  589. return;
  590. }
  591. ClearSceneData();
  592. InitDefaultTransitions();
  593. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  594. if (api)
  595. api->on_preload(modulesObj);
  596. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  597. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  598. obs_data_array_t *groups = obs_data_get_array(data, "groups");
  599. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  600. const char *sceneName = obs_data_get_string(data,
  601. "current_scene");
  602. const char *programSceneName = obs_data_get_string(data,
  603. "current_program_scene");
  604. const char *transitionName = obs_data_get_string(data,
  605. "current_transition");
  606. if (!opt_starting_scene.empty()) {
  607. programSceneName = opt_starting_scene.c_str();
  608. if (!IsPreviewProgramMode())
  609. sceneName = opt_starting_scene.c_str();
  610. }
  611. int newDuration = obs_data_get_int(data, "transition_duration");
  612. if (!newDuration)
  613. newDuration = 300;
  614. if (!transitionName)
  615. transitionName = obs_source_get_name(fadeTransition);
  616. const char *curSceneCollection = config_get_string(
  617. App()->GlobalConfig(), "Basic", "SceneCollection");
  618. obs_data_set_default_string(data, "name", curSceneCollection);
  619. const char *name = obs_data_get_string(data, "name");
  620. obs_source_t *curScene;
  621. obs_source_t *curProgramScene;
  622. obs_source_t *curTransition;
  623. if (!name || !*name)
  624. name = curSceneCollection;
  625. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  626. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  627. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  628. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  629. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  630. if (!sources) {
  631. sources = groups;
  632. groups = nullptr;
  633. } else {
  634. obs_data_array_push_back_array(sources, groups);
  635. }
  636. obs_load_sources(sources, nullptr, nullptr);
  637. if (transitions)
  638. LoadTransitions(transitions);
  639. if (sceneOrder)
  640. LoadSceneListOrder(sceneOrder);
  641. obs_data_array_release(transitions);
  642. curTransition = FindTransition(transitionName);
  643. if (!curTransition)
  644. curTransition = fadeTransition;
  645. ui->transitionDuration->setValue(newDuration);
  646. SetTransition(curTransition);
  647. retryScene:
  648. curScene = obs_get_source_by_name(sceneName);
  649. curProgramScene = obs_get_source_by_name(programSceneName);
  650. /* if the starting scene command line parameter is bad at all,
  651. * fall back to original settings */
  652. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  653. sceneName = obs_data_get_string(data, "current_scene");
  654. programSceneName = obs_data_get_string(data,
  655. "current_program_scene");
  656. obs_source_release(curScene);
  657. obs_source_release(curProgramScene);
  658. opt_starting_scene.clear();
  659. goto retryScene;
  660. }
  661. if (!curProgramScene) {
  662. curProgramScene = curScene;
  663. obs_source_addref(curScene);
  664. }
  665. SetCurrentScene(curScene, true);
  666. if (IsPreviewProgramMode())
  667. TransitionToScene(curProgramScene, true);
  668. obs_source_release(curScene);
  669. obs_source_release(curProgramScene);
  670. obs_data_array_release(sources);
  671. obs_data_array_release(groups);
  672. obs_data_array_release(sceneOrder);
  673. /* ------------------- */
  674. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  675. "SaveProjectors");
  676. if (projectorSave) {
  677. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  678. "saved_projectors");
  679. if (savedProjectors) {
  680. LoadSavedProjectors(savedProjectors);
  681. OpenSavedProjectors();
  682. activateWindow();
  683. }
  684. obs_data_array_release(savedProjectors);
  685. }
  686. /* ------------------- */
  687. std::string file_base = strrchr(file, '/') + 1;
  688. file_base.erase(file_base.size() - 5, 5);
  689. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  690. name);
  691. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  692. file_base.c_str());
  693. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  694. "quick_transitions");
  695. LoadQuickTransitions(quickTransitionData);
  696. obs_data_array_release(quickTransitionData);
  697. RefreshQuickTransitions();
  698. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  699. ui->preview->SetLocked(previewLocked);
  700. ui->actionLockPreview->setChecked(previewLocked);
  701. /* ---------------------- */
  702. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  703. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  704. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  705. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  706. if (fixedScaling) {
  707. ui->preview->SetScalingLevel(scalingLevel);
  708. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  709. }
  710. ui->preview->SetFixedScaling(fixedScaling);
  711. /* ---------------------- */
  712. if (api)
  713. api->on_load(modulesObj);
  714. obs_data_release(modulesObj);
  715. obs_data_release(data);
  716. if (!opt_starting_scene.empty())
  717. opt_starting_scene.clear();
  718. if (opt_start_streaming) {
  719. blog(LOG_INFO, "Starting stream due to command line parameter");
  720. QMetaObject::invokeMethod(this, "StartStreaming",
  721. Qt::QueuedConnection);
  722. opt_start_streaming = false;
  723. }
  724. if (opt_start_recording) {
  725. blog(LOG_INFO, "Starting recording due to command line parameter");
  726. QMetaObject::invokeMethod(this, "StartRecording",
  727. Qt::QueuedConnection);
  728. opt_start_recording = false;
  729. }
  730. if (opt_start_replaybuffer) {
  731. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  732. Qt::QueuedConnection);
  733. opt_start_replaybuffer = false;
  734. }
  735. LogScenes();
  736. disableSaving--;
  737. if (api) {
  738. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  739. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  740. }
  741. }
  742. #define SERVICE_PATH "service.json"
  743. void OBSBasic::SaveService()
  744. {
  745. if (!service)
  746. return;
  747. char serviceJsonPath[512];
  748. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  749. SERVICE_PATH);
  750. if (ret <= 0)
  751. return;
  752. obs_data_t *data = obs_data_create();
  753. obs_data_t *settings = obs_service_get_settings(service);
  754. obs_data_set_string(data, "type", obs_service_get_type(service));
  755. obs_data_set_obj(data, "settings", settings);
  756. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  757. blog(LOG_WARNING, "Failed to save service");
  758. obs_data_release(settings);
  759. obs_data_release(data);
  760. }
  761. bool OBSBasic::LoadService()
  762. {
  763. const char *type;
  764. char serviceJsonPath[512];
  765. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  766. SERVICE_PATH);
  767. if (ret <= 0)
  768. return false;
  769. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  770. "bak");
  771. obs_data_set_default_string(data, "type", "rtmp_common");
  772. type = obs_data_get_string(data, "type");
  773. obs_data_t *settings = obs_data_get_obj(data, "settings");
  774. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  775. service = obs_service_create(type, "default_service", settings,
  776. hotkey_data);
  777. obs_service_release(service);
  778. obs_data_release(hotkey_data);
  779. obs_data_release(settings);
  780. obs_data_release(data);
  781. return !!service;
  782. }
  783. bool OBSBasic::InitService()
  784. {
  785. ProfileScope("OBSBasic::InitService");
  786. if (LoadService())
  787. return true;
  788. service = obs_service_create("rtmp_common", "default_service", nullptr,
  789. nullptr);
  790. if (!service)
  791. return false;
  792. obs_service_release(service);
  793. return true;
  794. }
  795. static const double scaled_vals[] =
  796. {
  797. 1.0,
  798. 1.25,
  799. (1.0/0.75),
  800. 1.5,
  801. (1.0/0.6),
  802. 1.75,
  803. 2.0,
  804. 2.25,
  805. 2.5,
  806. 2.75,
  807. 3.0,
  808. 0.0
  809. };
  810. bool OBSBasic::InitBasicConfigDefaults()
  811. {
  812. QList<QScreen*> screens = QGuiApplication::screens();
  813. if (!screens.size()) {
  814. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  815. "technically shouldn't be possible.");
  816. return false;
  817. }
  818. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  819. uint32_t cx = primaryScreen->size().width();
  820. uint32_t cy = primaryScreen->size().height();
  821. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  822. "General", "Pre19Defaults");
  823. /* use 1920x1080 for new default base res if main monitor is above
  824. * 1920x1080, but don't apply for people from older builds -- only to
  825. * new users */
  826. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  827. cx = 1920;
  828. cy = 1080;
  829. }
  830. /* ----------------------------------------------------- */
  831. /* move over mixer values in advanced if older config */
  832. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  833. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  834. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  835. "RecTrackIndex");
  836. track = 1ULL << (track - 1);
  837. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  838. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  839. config_save_safe(basicConfig, "tmp", nullptr);
  840. }
  841. /* ----------------------------------------------------- */
  842. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  843. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  844. GetDefaultVideoSavePath().c_str());
  845. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  846. "flv");
  847. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  848. 2500);
  849. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  850. SIMPLE_ENCODER_X264);
  851. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  852. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  853. false);
  854. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  855. true);
  856. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  857. "veryfast");
  858. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  859. "Stream");
  860. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  861. SIMPLE_ENCODER_X264);
  862. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  863. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  864. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  865. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  866. "Replay");
  867. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  868. true);
  869. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  870. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  871. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  872. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  873. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  874. GetDefaultVideoSavePath().c_str());
  875. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  876. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  877. false);
  878. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  879. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  880. "none");
  881. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  882. true);
  883. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  884. GetDefaultVideoSavePath().c_str());
  885. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  886. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  887. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  888. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  889. false);
  890. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  891. false);
  892. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  893. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  894. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  895. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  896. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  897. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  898. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  899. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  900. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  901. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  902. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  903. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  904. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  905. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  906. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  907. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  908. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  909. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  910. config_save_safe(basicConfig, "tmp", nullptr);
  911. }
  912. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  913. "%CCYY-%MM-%DD %hh-%mm-%ss");
  914. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  915. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  916. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  917. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  918. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  919. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  920. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  921. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  922. false);
  923. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  924. false);
  925. int i = 0;
  926. uint32_t scale_cx = cx;
  927. uint32_t scale_cy = cy;
  928. /* use a default scaled resolution that has a pixel count no higher
  929. * than 1280x720 */
  930. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  931. double scale = scaled_vals[i++];
  932. scale_cx = uint32_t(double(cx) / scale);
  933. scale_cy = uint32_t(double(cy) / scale);
  934. }
  935. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  936. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  937. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  938. * changing */
  939. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  940. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  941. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  942. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  943. config_save_safe(basicConfig, "tmp", nullptr);
  944. }
  945. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  946. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  947. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  948. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  949. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  950. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  951. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  952. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  953. config_set_default_string(basicConfig, "Video", "ColorRange",
  954. "Partial");
  955. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  956. "default");
  957. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  958. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  959. ".Default"));
  960. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  961. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  962. "Stereo");
  963. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  964. VOLUME_METER_DECAY_FAST);
  965. config_set_default_uint (basicConfig, "Audio", "PeakMeterType", 0);
  966. return true;
  967. }
  968. bool OBSBasic::InitBasicConfig()
  969. {
  970. ProfileScope("OBSBasic::InitBasicConfig");
  971. char configPath[512];
  972. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  973. if (ret <= 0) {
  974. OBSErrorBox(nullptr, "Failed to get profile path");
  975. return false;
  976. }
  977. if (os_mkdir(configPath) == MKDIR_ERROR) {
  978. OBSErrorBox(nullptr, "Failed to create profile path");
  979. return false;
  980. }
  981. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  982. if (ret <= 0) {
  983. OBSErrorBox(nullptr, "Failed to get base.ini path");
  984. return false;
  985. }
  986. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  987. if (code != CONFIG_SUCCESS) {
  988. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  989. return false;
  990. }
  991. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  992. const char *curName = config_get_string(App()->GlobalConfig(),
  993. "Basic", "Profile");
  994. config_set_string(basicConfig, "General", "Name", curName);
  995. basicConfig.SaveSafe("tmp");
  996. }
  997. return InitBasicConfigDefaults();
  998. }
  999. void OBSBasic::InitOBSCallbacks()
  1000. {
  1001. ProfileScope("OBSBasic::InitOBSCallbacks");
  1002. signalHandlers.reserve(signalHandlers.size() + 6);
  1003. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1004. OBSBasic::SourceCreated, this);
  1005. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1006. OBSBasic::SourceRemoved, this);
  1007. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1008. OBSBasic::SourceActivated, this);
  1009. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  1010. OBSBasic::SourceDeactivated, this);
  1011. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1012. OBSBasic::SourceRenamed, this);
  1013. }
  1014. void OBSBasic::InitPrimitives()
  1015. {
  1016. ProfileScope("OBSBasic::InitPrimitives");
  1017. obs_enter_graphics();
  1018. gs_render_start(true);
  1019. gs_vertex2f(0.0f, 0.0f);
  1020. gs_vertex2f(0.0f, 1.0f);
  1021. gs_vertex2f(1.0f, 1.0f);
  1022. gs_vertex2f(1.0f, 0.0f);
  1023. gs_vertex2f(0.0f, 0.0f);
  1024. box = gs_render_save();
  1025. gs_render_start(true);
  1026. gs_vertex2f(0.0f, 0.0f);
  1027. gs_vertex2f(0.0f, 1.0f);
  1028. boxLeft = gs_render_save();
  1029. gs_render_start(true);
  1030. gs_vertex2f(0.0f, 0.0f);
  1031. gs_vertex2f(1.0f, 0.0f);
  1032. boxTop = gs_render_save();
  1033. gs_render_start(true);
  1034. gs_vertex2f(1.0f, 0.0f);
  1035. gs_vertex2f(1.0f, 1.0f);
  1036. boxRight = gs_render_save();
  1037. gs_render_start(true);
  1038. gs_vertex2f(0.0f, 1.0f);
  1039. gs_vertex2f(1.0f, 1.0f);
  1040. boxBottom = gs_render_save();
  1041. gs_render_start(true);
  1042. for (int i = 0; i <= 360; i += (360/20)) {
  1043. float pos = RAD(float(i));
  1044. gs_vertex2f(cosf(pos), sinf(pos));
  1045. }
  1046. circle = gs_render_save();
  1047. obs_leave_graphics();
  1048. }
  1049. void OBSBasic::ReplayBufferClicked()
  1050. {
  1051. if (outputHandler->ReplayBufferActive())
  1052. StopReplayBuffer();
  1053. else
  1054. StartReplayBuffer();
  1055. };
  1056. void OBSBasic::ResetOutputs()
  1057. {
  1058. ProfileScope("OBSBasic::ResetOutputs");
  1059. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1060. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1061. if (!outputHandler || !outputHandler->Active()) {
  1062. outputHandler.reset();
  1063. outputHandler.reset(advOut ?
  1064. CreateAdvancedOutputHandler(this) :
  1065. CreateSimpleOutputHandler(this));
  1066. delete replayBufferButton;
  1067. if (outputHandler->replayBuffer) {
  1068. replayBufferButton = new QPushButton(
  1069. QTStr("Basic.Main.StartReplayBuffer"),
  1070. this);
  1071. connect(replayBufferButton.data(),
  1072. &QPushButton::clicked,
  1073. this,
  1074. &OBSBasic::ReplayBufferClicked);
  1075. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1076. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1077. }
  1078. if (sysTrayReplayBuffer)
  1079. sysTrayReplayBuffer->setEnabled(
  1080. !!outputHandler->replayBuffer);
  1081. } else {
  1082. outputHandler->Update();
  1083. }
  1084. }
  1085. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1086. const char *slot);
  1087. #define STARTUP_SEPARATOR \
  1088. "==== Startup complete ==============================================="
  1089. #define SHUTDOWN_SEPARATOR \
  1090. "==== Shutting down =================================================="
  1091. #define UNSUPPORTED_ERROR \
  1092. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1093. "not found. Your GPU may not be supported."
  1094. #define UNKNOWN_ERROR \
  1095. "Failed to initialize video. Your GPU may not be supported, " \
  1096. "or your graphics drivers may need to be updated."
  1097. void OBSBasic::OBSInit()
  1098. {
  1099. ProfileScope("OBSBasic::OBSInit");
  1100. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1101. "Basic", "SceneCollectionFile");
  1102. char savePath[512];
  1103. char fileName[512];
  1104. int ret;
  1105. if (!sceneCollection)
  1106. throw "Failed to get scene collection name";
  1107. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1108. sceneCollection);
  1109. if (ret <= 0)
  1110. throw "Failed to create scene collection file name";
  1111. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1112. if (ret <= 0)
  1113. throw "Failed to get scene collection json file path";
  1114. if (!InitBasicConfig())
  1115. throw "Failed to load basic.ini";
  1116. if (!ResetAudio())
  1117. throw "Failed to initialize audio";
  1118. ret = ResetVideo();
  1119. switch (ret) {
  1120. case OBS_VIDEO_MODULE_NOT_FOUND:
  1121. throw "Failed to initialize video: Graphics module not found";
  1122. case OBS_VIDEO_NOT_SUPPORTED:
  1123. throw UNSUPPORTED_ERROR;
  1124. case OBS_VIDEO_INVALID_PARAM:
  1125. throw "Failed to initialize video: Invalid parameters";
  1126. default:
  1127. if (ret != OBS_VIDEO_SUCCESS)
  1128. throw UNKNOWN_ERROR;
  1129. }
  1130. /* load audio monitoring */
  1131. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1132. const char *device_name = config_get_string(basicConfig, "Audio",
  1133. "MonitoringDeviceName");
  1134. const char *device_id = config_get_string(basicConfig, "Audio",
  1135. "MonitoringDeviceId");
  1136. obs_set_audio_monitoring_device(device_name, device_id);
  1137. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1138. device_name, device_id);
  1139. #endif
  1140. InitOBSCallbacks();
  1141. InitHotkeys();
  1142. AddExtraModulePaths();
  1143. blog(LOG_INFO, "---------------------------------");
  1144. obs_load_all_modules();
  1145. blog(LOG_INFO, "---------------------------------");
  1146. obs_log_loaded_modules();
  1147. blog(LOG_INFO, "---------------------------------");
  1148. obs_post_load_modules();
  1149. CheckForSimpleModeX264Fallback();
  1150. blog(LOG_INFO, STARTUP_SEPARATOR);
  1151. ResetOutputs();
  1152. CreateHotkeys();
  1153. if (!InitService())
  1154. throw "Failed to initialize service";
  1155. InitPrimitives();
  1156. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1157. "BasicWindow", "SceneDuplicationMode");
  1158. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1159. "BasicWindow", "SwapScenesMode");
  1160. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1161. "BasicWindow", "EditPropertiesMode");
  1162. if (!opt_studio_mode) {
  1163. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1164. "BasicWindow", "PreviewProgramMode"));
  1165. } else {
  1166. SetPreviewProgramMode(true);
  1167. opt_studio_mode = false;
  1168. }
  1169. #define SET_VISIBILITY(name, control) \
  1170. do { \
  1171. if (config_has_user_value(App()->GlobalConfig(), \
  1172. "BasicWindow", name)) { \
  1173. bool visible = config_get_bool(App()->GlobalConfig(), \
  1174. "BasicWindow", name); \
  1175. ui->control->setChecked(visible); \
  1176. } \
  1177. } while (false)
  1178. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1179. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1180. #undef SET_VISIBILITY
  1181. #ifndef __APPLE__
  1182. {
  1183. ProfileScope("OBSBasic::Load");
  1184. disableSaving--;
  1185. Load(savePath);
  1186. disableSaving++;
  1187. }
  1188. #endif
  1189. TimedCheckForUpdates();
  1190. loaded = true;
  1191. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1192. "BasicWindow", "PreviewEnabled");
  1193. if (!previewEnabled && !IsPreviewProgramMode())
  1194. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1195. Qt::QueuedConnection,
  1196. Q_ARG(bool, previewEnabled));
  1197. #ifdef _WIN32
  1198. uint32_t winVer = GetWindowsVersion();
  1199. if (winVer > 0 && winVer < 0x602) {
  1200. bool disableAero = config_get_bool(basicConfig, "Video",
  1201. "DisableAero");
  1202. SetAeroEnabled(!disableAero);
  1203. }
  1204. #endif
  1205. #ifndef __APPLE__
  1206. RefreshSceneCollections();
  1207. #endif
  1208. RefreshProfiles();
  1209. disableSaving--;
  1210. auto addDisplay = [this] (OBSQTDisplay *window)
  1211. {
  1212. obs_display_add_draw_callback(window->GetDisplay(),
  1213. OBSBasic::RenderMain, this);
  1214. struct obs_video_info ovi;
  1215. if (obs_get_video_info(&ovi))
  1216. ResizePreview(ovi.base_width, ovi.base_height);
  1217. };
  1218. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1219. #ifdef _WIN32
  1220. SetWin32DropStyle(this);
  1221. show();
  1222. #endif
  1223. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1224. "AlwaysOnTop");
  1225. if (alwaysOnTop || opt_always_on_top) {
  1226. SetAlwaysOnTop(this, true);
  1227. ui->actionAlwaysOnTop->setChecked(true);
  1228. }
  1229. #ifndef _WIN32
  1230. show();
  1231. #endif
  1232. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1233. "BasicWindow", "DockState");
  1234. if (!dockStateStr) {
  1235. on_resetUI_triggered();
  1236. } else {
  1237. QByteArray dockState =
  1238. QByteArray::fromBase64(QByteArray(dockStateStr));
  1239. if (!restoreState(dockState))
  1240. on_resetUI_triggered();
  1241. }
  1242. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1243. "DocksLocked", true);
  1244. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1245. "BasicWindow", "DocksLocked");
  1246. on_lockUI_toggled(docksLocked);
  1247. ui->lockUI->blockSignals(true);
  1248. ui->lockUI->setChecked(docksLocked);
  1249. ui->lockUI->blockSignals(false);
  1250. SystemTray(true);
  1251. if (windowState().testFlag(Qt::WindowFullScreen))
  1252. fullscreenInterface = true;
  1253. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1254. "General", "LastVersion");
  1255. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1256. "FirstRun");
  1257. if (!first_run) {
  1258. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1259. true);
  1260. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1261. }
  1262. if (!first_run && !has_last_version && !Active()) {
  1263. QString msg;
  1264. msg = QTStr("Basic.FirstStartup.RunWizard");
  1265. msg += "\n\n";
  1266. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1267. QMessageBox::StandardButton button =
  1268. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1269. msg);
  1270. if (button == QMessageBox::Yes) {
  1271. on_autoConfigure_triggered();
  1272. } else {
  1273. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1274. OBSMessageBox::information(this,
  1275. QTStr("Basic.AutoConfig"), msg);
  1276. }
  1277. }
  1278. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1279. "VerticalVolControl"));
  1280. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1281. on_stats_triggered();
  1282. OBSBasicStats::InitializeValues();
  1283. /* ----------------------- */
  1284. /* Add multiview menu */
  1285. ui->viewMenu->addSeparator();
  1286. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1287. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1288. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1289. &OBSBasic::UpdateMultiviewProjectorMenu);
  1290. ui->viewMenu->addAction(QTStr("MultiviewWindowed"),
  1291. this, SLOT(OpenMultiviewWindow()));
  1292. #if !defined(_WIN32) && !defined(__APPLE__)
  1293. delete ui->actionShowCrashLogs;
  1294. delete ui->actionUploadLastCrashLog;
  1295. delete ui->menuCrashLogs;
  1296. delete ui->actionCheckForUpdates;
  1297. ui->actionShowCrashLogs = nullptr;
  1298. ui->actionUploadLastCrashLog = nullptr;
  1299. ui->menuCrashLogs = nullptr;
  1300. ui->actionCheckForUpdates = nullptr;
  1301. #endif
  1302. #ifdef __APPLE__
  1303. /* This is an incredibly unpleasant hack for macOS to isolate CEF
  1304. * initialization until after all tasks related to Qt startup and main
  1305. * window initialization have completed. There is a macOS-specific bug
  1306. * within either CEF and/or Qt that can cause a crash if both Qt and
  1307. * CEF are loading at the same time.
  1308. *
  1309. * CEF will typically load fine after about two iterations from this
  1310. * point, and all Qt tasks are typically fully completed after about
  1311. * four or five iterations, but to be "ultra" safe, an arbitrarily
  1312. * large number such as 10 is used. This hack is extremely unpleasant,
  1313. * but is worth doing instead of being forced to isolate the entire
  1314. * browser plugin in to a separate process as before.
  1315. *
  1316. * Again, this hack is specific to macOS only. Fortunately, on other
  1317. * operating systems, such issues do not occur. */
  1318. QMetaObject::invokeMethod(this, "DeferredLoad",
  1319. Qt::QueuedConnection,
  1320. Q_ARG(QString, QT_UTF8(savePath)),
  1321. Q_ARG(int, 10));
  1322. #else
  1323. OnFirstLoad();
  1324. #endif
  1325. }
  1326. void OBSBasic::OnFirstLoad()
  1327. {
  1328. if (api)
  1329. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1330. }
  1331. void OBSBasic::DeferredLoad(const QString &file, int requeueCount)
  1332. {
  1333. if (--requeueCount > 0) {
  1334. QMetaObject::invokeMethod(this, "DeferredLoad",
  1335. Qt::QueuedConnection,
  1336. Q_ARG(QString, file),
  1337. Q_ARG(int, requeueCount));
  1338. return;
  1339. }
  1340. Load(QT_TO_UTF8(file));
  1341. RefreshSceneCollections();
  1342. OnFirstLoad();
  1343. }
  1344. void OBSBasic::UpdateMultiviewProjectorMenu()
  1345. {
  1346. multiviewProjectorMenu->clear();
  1347. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1348. SLOT(OpenMultiviewProjector()));
  1349. }
  1350. void OBSBasic::InitHotkeys()
  1351. {
  1352. ProfileScope("OBSBasic::InitHotkeys");
  1353. struct obs_hotkeys_translations t = {};
  1354. t.insert = Str("Hotkeys.Insert");
  1355. t.del = Str("Hotkeys.Delete");
  1356. t.home = Str("Hotkeys.Home");
  1357. t.end = Str("Hotkeys.End");
  1358. t.page_up = Str("Hotkeys.PageUp");
  1359. t.page_down = Str("Hotkeys.PageDown");
  1360. t.num_lock = Str("Hotkeys.NumLock");
  1361. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1362. t.caps_lock = Str("Hotkeys.CapsLock");
  1363. t.backspace = Str("Hotkeys.Backspace");
  1364. t.tab = Str("Hotkeys.Tab");
  1365. t.print = Str("Hotkeys.Print");
  1366. t.pause = Str("Hotkeys.Pause");
  1367. t.left = Str("Hotkeys.Left");
  1368. t.right = Str("Hotkeys.Right");
  1369. t.up = Str("Hotkeys.Up");
  1370. t.down = Str("Hotkeys.Down");
  1371. #ifdef _WIN32
  1372. t.meta = Str("Hotkeys.Windows");
  1373. #else
  1374. t.meta = Str("Hotkeys.Super");
  1375. #endif
  1376. t.menu = Str("Hotkeys.Menu");
  1377. t.space = Str("Hotkeys.Space");
  1378. t.numpad_num = Str("Hotkeys.NumpadNum");
  1379. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1380. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1381. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1382. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1383. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1384. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1385. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1386. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1387. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1388. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1389. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1390. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1391. t.mouse_num = Str("Hotkeys.MouseButton");
  1392. obs_hotkeys_set_translations(&t);
  1393. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1394. Str("Push-to-mute"), Str("Push-to-talk"));
  1395. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1396. Str("SceneItemShow"), Str("SceneItemHide"));
  1397. obs_hotkey_enable_callback_rerouting(true);
  1398. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1399. }
  1400. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1401. {
  1402. obs_hotkey_trigger_routed_callback(id, pressed);
  1403. }
  1404. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1405. {
  1406. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1407. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1408. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1409. }
  1410. void OBSBasic::CreateHotkeys()
  1411. {
  1412. ProfileScope("OBSBasic::CreateHotkeys");
  1413. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1414. {
  1415. const char *info = config_get_string(basicConfig,
  1416. "Hotkeys", name);
  1417. if (!info)
  1418. return {};
  1419. obs_data_t *data = obs_data_create_from_json(info);
  1420. if (!data)
  1421. return {};
  1422. OBSData res = data;
  1423. obs_data_release(data);
  1424. return res;
  1425. };
  1426. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1427. {
  1428. obs_data_array_t *array =
  1429. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1430. obs_hotkey_load(id, array);
  1431. obs_data_array_release(array);
  1432. };
  1433. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1434. const char *name1)
  1435. {
  1436. obs_data_array_t *array0 =
  1437. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1438. obs_data_array_t *array1 =
  1439. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1440. obs_hotkey_pair_load(id, array0, array1);
  1441. obs_data_array_release(array0);
  1442. obs_data_array_release(array1);
  1443. };
  1444. #define MAKE_CALLBACK(pred, method, log_action) \
  1445. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1446. { \
  1447. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1448. if ((pred) && pressed) { \
  1449. blog(LOG_INFO, log_action " due to hotkey"); \
  1450. method(); \
  1451. return true; \
  1452. } \
  1453. return false; \
  1454. }
  1455. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1456. "OBSBasic.StartStreaming",
  1457. Str("Basic.Main.StartStreaming"),
  1458. "OBSBasic.StopStreaming",
  1459. Str("Basic.Main.StopStreaming"),
  1460. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1461. basic.ui->streamButton->isEnabled(),
  1462. basic.StartStreaming, "Starting stream"),
  1463. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1464. basic.ui->streamButton->isEnabled(),
  1465. basic.StopStreaming, "Stopping stream"),
  1466. this, this);
  1467. LoadHotkeyPair(streamingHotkeys,
  1468. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1469. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1470. {
  1471. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1472. if (basic.outputHandler->StreamingActive() && pressed) {
  1473. basic.ForceStopStreaming();
  1474. }
  1475. };
  1476. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1477. "OBSBasic.ForceStopStreaming",
  1478. Str("Basic.Main.ForceStopStreaming"),
  1479. cb, this);
  1480. LoadHotkey(forceStreamingStopHotkey,
  1481. "OBSBasic.ForceStopStreaming");
  1482. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1483. "OBSBasic.StartRecording",
  1484. Str("Basic.Main.StartRecording"),
  1485. "OBSBasic.StopRecording",
  1486. Str("Basic.Main.StopRecording"),
  1487. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1488. !basic.ui->recordButton->isChecked(),
  1489. basic.StartRecording, "Starting recording"),
  1490. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1491. basic.ui->recordButton->isChecked(),
  1492. basic.StopRecording, "Stopping recording"),
  1493. this, this);
  1494. LoadHotkeyPair(recordingHotkeys,
  1495. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1496. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1497. "OBSBasic.StartReplayBuffer",
  1498. Str("Basic.Main.StartReplayBuffer"),
  1499. "OBSBasic.StopReplayBuffer",
  1500. Str("Basic.Main.StopReplayBuffer"),
  1501. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1502. basic.StartReplayBuffer, "Starting replay buffer"),
  1503. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1504. basic.StopReplayBuffer, "Stopping replay buffer"),
  1505. this, this);
  1506. LoadHotkeyPair(replayBufHotkeys,
  1507. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1508. #undef MAKE_CALLBACK
  1509. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1510. obs_hotkey_t*, bool pressed)
  1511. {
  1512. if (pressed)
  1513. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1514. "on_modeSwitch_clicked",
  1515. Qt::QueuedConnection);
  1516. };
  1517. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1518. "OBSBasic.TogglePreviewProgram",
  1519. Str("Basic.TogglePreviewProgramMode"),
  1520. togglePreviewProgram, this);
  1521. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1522. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1523. bool pressed)
  1524. {
  1525. if (pressed)
  1526. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1527. "TransitionClicked",
  1528. Qt::QueuedConnection);
  1529. };
  1530. transitionHotkey = obs_hotkey_register_frontend(
  1531. "OBSBasic.Transition",
  1532. Str("Transition"), transition, this);
  1533. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1534. }
  1535. void OBSBasic::ClearHotkeys()
  1536. {
  1537. obs_hotkey_pair_unregister(streamingHotkeys);
  1538. obs_hotkey_pair_unregister(recordingHotkeys);
  1539. obs_hotkey_pair_unregister(replayBufHotkeys);
  1540. obs_hotkey_unregister(forceStreamingStopHotkey);
  1541. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1542. obs_hotkey_unregister(transitionHotkey);
  1543. }
  1544. OBSBasic::~OBSBasic()
  1545. {
  1546. if (updateCheckThread && updateCheckThread->isRunning())
  1547. updateCheckThread->wait();
  1548. delete multiviewProjectorMenu;
  1549. delete trayMenu;
  1550. delete programOptions;
  1551. delete program;
  1552. /* XXX: any obs data must be released before calling obs_shutdown.
  1553. * currently, we can't automate this with C++ RAII because of the
  1554. * delicate nature of obs_shutdown needing to be freed before the UI
  1555. * can be freed, and we have no control over the destruction order of
  1556. * the Qt UI stuff, so we have to manually clear any references to
  1557. * libobs. */
  1558. delete cpuUsageTimer;
  1559. os_cpu_usage_info_destroy(cpuUsageInfo);
  1560. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1561. ClearHotkeys();
  1562. service = nullptr;
  1563. outputHandler.reset();
  1564. if (interaction)
  1565. delete interaction;
  1566. if (properties)
  1567. delete properties;
  1568. if (filters)
  1569. delete filters;
  1570. if (transformWindow)
  1571. delete transformWindow;
  1572. if (advAudioWindow)
  1573. delete advAudioWindow;
  1574. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1575. OBSBasic::RenderMain, this);
  1576. obs_enter_graphics();
  1577. gs_vertexbuffer_destroy(box);
  1578. gs_vertexbuffer_destroy(boxLeft);
  1579. gs_vertexbuffer_destroy(boxTop);
  1580. gs_vertexbuffer_destroy(boxRight);
  1581. gs_vertexbuffer_destroy(boxBottom);
  1582. gs_vertexbuffer_destroy(circle);
  1583. obs_leave_graphics();
  1584. /* When shutting down, sometimes source references can get in to the
  1585. * event queue, and if we don't forcibly process those events they
  1586. * won't get processed until after obs_shutdown has been called. I
  1587. * really wish there were a more elegant way to deal with this via C++,
  1588. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1589. * normal C++ behavior for your data to be freed in the order that you
  1590. * expect or want it to. */
  1591. QApplication::sendPostedEvents(this);
  1592. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1593. LIBOBS_API_VER);
  1594. bool alwaysOnTop = IsAlwaysOnTop(this);
  1595. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1596. previewEnabled);
  1597. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1598. alwaysOnTop);
  1599. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1600. "SceneDuplicationMode", sceneDuplicationMode);
  1601. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1602. "SwapScenesMode", swapScenesMode);
  1603. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1604. "EditPropertiesMode", editPropertiesMode);
  1605. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1606. "PreviewProgramMode", IsPreviewProgramMode());
  1607. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1608. "DocksLocked", ui->lockUI->isChecked());
  1609. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1610. #ifdef _WIN32
  1611. uint32_t winVer = GetWindowsVersion();
  1612. if (winVer > 0 && winVer < 0x602) {
  1613. bool disableAero = config_get_bool(basicConfig, "Video",
  1614. "DisableAero");
  1615. if (disableAero) {
  1616. SetAeroEnabled(true);
  1617. }
  1618. }
  1619. #endif
  1620. }
  1621. void OBSBasic::SaveProjectNow()
  1622. {
  1623. if (disableSaving)
  1624. return;
  1625. projectChanged = true;
  1626. SaveProjectDeferred();
  1627. }
  1628. void OBSBasic::SaveProject()
  1629. {
  1630. if (disableSaving)
  1631. return;
  1632. projectChanged = true;
  1633. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1634. Qt::QueuedConnection);
  1635. }
  1636. void OBSBasic::SaveProjectDeferred()
  1637. {
  1638. if (disableSaving)
  1639. return;
  1640. if (!projectChanged)
  1641. return;
  1642. projectChanged = false;
  1643. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1644. "Basic", "SceneCollectionFile");
  1645. char savePath[512];
  1646. char fileName[512];
  1647. int ret;
  1648. if (!sceneCollection)
  1649. return;
  1650. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1651. sceneCollection);
  1652. if (ret <= 0)
  1653. return;
  1654. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1655. if (ret <= 0)
  1656. return;
  1657. Save(savePath);
  1658. }
  1659. OBSSource OBSBasic::GetProgramSource()
  1660. {
  1661. return OBSGetStrongRef(programScene);
  1662. }
  1663. OBSScene OBSBasic::GetCurrentScene()
  1664. {
  1665. QListWidgetItem *item = ui->scenes->currentItem();
  1666. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1667. }
  1668. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1669. {
  1670. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1671. }
  1672. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1673. {
  1674. return ui->sources->Get(GetTopSelectedSourceItem());
  1675. }
  1676. void OBSBasic::UpdatePreviewScalingMenu()
  1677. {
  1678. bool fixedScaling = ui->preview->IsFixedScaling();
  1679. float scalingAmount = ui->preview->GetScalingAmount();
  1680. if (!fixedScaling) {
  1681. ui->actionScaleWindow->setChecked(true);
  1682. ui->actionScaleCanvas->setChecked(false);
  1683. ui->actionScaleOutput->setChecked(false);
  1684. return;
  1685. }
  1686. obs_video_info ovi;
  1687. obs_get_video_info(&ovi);
  1688. ui->actionScaleWindow->setChecked(false);
  1689. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1690. ui->actionScaleOutput->setChecked(
  1691. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1692. }
  1693. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1694. {
  1695. if (interaction)
  1696. interaction->close();
  1697. interaction = new OBSBasicInteraction(this, source);
  1698. interaction->Init();
  1699. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1700. }
  1701. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1702. {
  1703. if (properties)
  1704. properties->close();
  1705. properties = new OBSBasicProperties(this, source);
  1706. properties->Init();
  1707. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1708. }
  1709. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1710. {
  1711. if (filters)
  1712. filters->close();
  1713. filters = new OBSBasicFilters(this, source);
  1714. filters->Init();
  1715. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1716. }
  1717. /* Qt callbacks for invokeMethod */
  1718. void OBSBasic::AddScene(OBSSource source)
  1719. {
  1720. const char *name = obs_source_get_name(source);
  1721. obs_scene_t *scene = obs_scene_from_source(source);
  1722. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1723. SetOBSRef(item, OBSScene(scene));
  1724. ui->scenes->addItem(item);
  1725. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1726. Str("Basic.Hotkeys.SelectScene"),
  1727. [](void *data,
  1728. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1729. {
  1730. OBSBasic *main =
  1731. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1732. auto potential_source = static_cast<obs_source_t*>(data);
  1733. auto source = obs_source_get_ref(potential_source);
  1734. if (source && pressed)
  1735. main->SetCurrentScene(source);
  1736. obs_source_release(source);
  1737. }, static_cast<obs_source_t*>(source));
  1738. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1739. SignalContainer<OBSScene> container;
  1740. container.ref = scene;
  1741. container.handlers.assign({
  1742. std::make_shared<OBSSignal>(handler, "item_add",
  1743. OBSBasic::SceneItemAdded, this),
  1744. std::make_shared<OBSSignal>(handler, "item_select",
  1745. OBSBasic::SceneItemSelected, this),
  1746. std::make_shared<OBSSignal>(handler, "item_deselect",
  1747. OBSBasic::SceneItemDeselected, this),
  1748. std::make_shared<OBSSignal>(handler, "reorder",
  1749. OBSBasic::SceneReordered, this),
  1750. });
  1751. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1752. QVariant::fromValue(container));
  1753. /* if the scene already has items (a duplicated scene) add them */
  1754. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1755. {
  1756. AddSceneItem(item);
  1757. };
  1758. using addSceneItem_t = decltype(addSceneItem);
  1759. obs_scene_enum_items(scene,
  1760. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1761. {
  1762. addSceneItem_t *func;
  1763. func = reinterpret_cast<addSceneItem_t*>(param);
  1764. (*func)(item);
  1765. return true;
  1766. }, &addSceneItem);
  1767. SaveProject();
  1768. if (!disableSaving) {
  1769. obs_source_t *source = obs_scene_get_source(scene);
  1770. blog(LOG_INFO, "User added scene '%s'",
  1771. obs_source_get_name(source));
  1772. OBSProjector::UpdateMultiviewProjectors();
  1773. }
  1774. if (api)
  1775. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1776. }
  1777. void OBSBasic::RemoveScene(OBSSource source)
  1778. {
  1779. obs_scene_t *scene = obs_scene_from_source(source);
  1780. QListWidgetItem *sel = nullptr;
  1781. int count = ui->scenes->count();
  1782. for (int i = 0; i < count; i++) {
  1783. auto item = ui->scenes->item(i);
  1784. auto cur_scene = GetOBSRef<OBSScene>(item);
  1785. if (cur_scene != scene)
  1786. continue;
  1787. sel = item;
  1788. break;
  1789. }
  1790. if (sel != nullptr) {
  1791. if (sel == ui->scenes->currentItem())
  1792. ui->sources->Clear();
  1793. delete sel;
  1794. }
  1795. SaveProject();
  1796. if (!disableSaving) {
  1797. blog(LOG_INFO, "User Removed scene '%s'",
  1798. obs_source_get_name(source));
  1799. OBSProjector::UpdateMultiviewProjectors();
  1800. }
  1801. if (api)
  1802. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1803. }
  1804. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1805. {
  1806. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1807. if (GetCurrentScene() == scene)
  1808. ui->sources->Add(item);
  1809. SaveProject();
  1810. if (!disableSaving) {
  1811. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1812. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1813. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1814. obs_source_get_name(itemSource),
  1815. obs_source_get_id(itemSource),
  1816. obs_source_get_name(sceneSource));
  1817. }
  1818. }
  1819. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1820. {
  1821. if (source) {
  1822. obs_scene_t *scene = obs_scene_from_source(source);
  1823. const char *name = obs_source_get_name(source);
  1824. if (!scene)
  1825. return;
  1826. QList<QListWidgetItem*> items =
  1827. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1828. if (items.count()) {
  1829. sceneChanging = true;
  1830. ui->scenes->setCurrentItem(items.first());
  1831. sceneChanging = false;
  1832. OBSScene curScene =
  1833. GetOBSRef<OBSScene>(ui->scenes->currentItem());
  1834. if (api && scene != curScene)
  1835. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1836. }
  1837. }
  1838. }
  1839. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1840. const QString &prevName)
  1841. {
  1842. QList<QListWidgetItem*> items =
  1843. listWidget->findItems(prevName, Qt::MatchExactly);
  1844. for (int i = 0; i < items.count(); i++)
  1845. items[i]->setText(newName);
  1846. }
  1847. void OBSBasic::RenameSources(OBSSource source, QString newName,
  1848. QString prevName)
  1849. {
  1850. RenameListValues(ui->scenes, newName, prevName);
  1851. for (size_t i = 0; i < volumes.size(); i++) {
  1852. if (volumes[i]->GetName().compare(prevName) == 0)
  1853. volumes[i]->SetName(newName);
  1854. }
  1855. OBSProjector::RenameProjector(prevName, newName);
  1856. SaveProject();
  1857. obs_scene_t *scene = obs_scene_from_source(source);
  1858. if (scene)
  1859. OBSProjector::UpdateMultiviewProjectors();
  1860. }
  1861. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1862. {
  1863. SignalBlocker sourcesSignalBlocker(ui->sources);
  1864. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1865. return;
  1866. ui->sources->SelectItem(item, select);
  1867. }
  1868. static inline bool SourceMixerHidden(obs_source_t *source)
  1869. {
  1870. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1871. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  1872. obs_data_release(priv_settings);
  1873. return hidden;
  1874. }
  1875. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  1876. {
  1877. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1878. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  1879. obs_data_release(priv_settings);
  1880. }
  1881. void OBSBasic::GetAudioSourceFilters()
  1882. {
  1883. QAction *action = reinterpret_cast<QAction*>(sender());
  1884. VolControl *vol = action->property("volControl").value<VolControl*>();
  1885. obs_source_t *source = vol->GetSource();
  1886. CreateFiltersWindow(source);
  1887. }
  1888. void OBSBasic::GetAudioSourceProperties()
  1889. {
  1890. QAction *action = reinterpret_cast<QAction*>(sender());
  1891. VolControl *vol = action->property("volControl").value<VolControl*>();
  1892. obs_source_t *source = vol->GetSource();
  1893. CreatePropertiesWindow(source);
  1894. }
  1895. void OBSBasic::HideAudioControl()
  1896. {
  1897. QAction *action = reinterpret_cast<QAction*>(sender());
  1898. VolControl *vol = action->property("volControl").value<VolControl*>();
  1899. obs_source_t *source = vol->GetSource();
  1900. if (!SourceMixerHidden(source)) {
  1901. SetSourceMixerHidden(source, true);
  1902. DeactivateAudioSource(source);
  1903. }
  1904. }
  1905. void OBSBasic::UnhideAllAudioControls()
  1906. {
  1907. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  1908. {
  1909. if (!obs_source_active(source))
  1910. return true;
  1911. if (!SourceMixerHidden(source))
  1912. return true;
  1913. SetSourceMixerHidden(source, false);
  1914. ActivateAudioSource(source);
  1915. return true;
  1916. };
  1917. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  1918. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  1919. {
  1920. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  1921. };
  1922. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  1923. }
  1924. void OBSBasic::ToggleHideMixer()
  1925. {
  1926. OBSSceneItem item = GetCurrentSceneItem();
  1927. OBSSource source = obs_sceneitem_get_source(item);
  1928. if (!SourceMixerHidden(source)) {
  1929. SetSourceMixerHidden(source, true);
  1930. DeactivateAudioSource(source);
  1931. } else {
  1932. SetSourceMixerHidden(source, false);
  1933. ActivateAudioSource(source);
  1934. }
  1935. }
  1936. void OBSBasic::MixerRenameSource()
  1937. {
  1938. QAction *action = reinterpret_cast<QAction*>(sender());
  1939. VolControl *vol = action->property("volControl").value<VolControl*>();
  1940. OBSSource source = vol->GetSource();
  1941. const char *prevName = obs_source_get_name(source);
  1942. for (;;) {
  1943. string name;
  1944. bool accepted = NameDialog::AskForName(this,
  1945. QTStr("Basic.Main.MixerRename.Title"),
  1946. QTStr("Basic.Main.MixerRename.Text"),
  1947. name,
  1948. QT_UTF8(prevName));
  1949. if (!accepted)
  1950. return;
  1951. if (name.empty()) {
  1952. OBSMessageBox::information(this,
  1953. QTStr("NoNameEntered.Title"),
  1954. QTStr("NoNameEntered.Text"));
  1955. continue;
  1956. }
  1957. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  1958. obs_source_release(sourceTest);
  1959. if (sourceTest) {
  1960. OBSMessageBox::information(this,
  1961. QTStr("NameExists.Title"),
  1962. QTStr("NameExists.Text"));
  1963. continue;
  1964. }
  1965. obs_source_set_name(source, name.c_str());
  1966. break;
  1967. }
  1968. }
  1969. void OBSBasic::VolControlContextMenu()
  1970. {
  1971. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1972. /* ------------------- */
  1973. QAction hideAction(QTStr("Hide"), this);
  1974. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1975. QAction mixerRenameAction(QTStr("Rename"), this);
  1976. QAction filtersAction(QTStr("Filters"), this);
  1977. QAction propertiesAction(QTStr("Properties"), this);
  1978. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1979. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  1980. toggleControlLayoutAction.setCheckable(true);
  1981. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  1982. "BasicWindow", "VerticalVolControl"));
  1983. /* ------------------- */
  1984. connect(&hideAction, &QAction::triggered,
  1985. this, &OBSBasic::HideAudioControl,
  1986. Qt::DirectConnection);
  1987. connect(&unhideAllAction, &QAction::triggered,
  1988. this, &OBSBasic::UnhideAllAudioControls,
  1989. Qt::DirectConnection);
  1990. connect(&mixerRenameAction, &QAction::triggered,
  1991. this, &OBSBasic::MixerRenameSource,
  1992. Qt::DirectConnection);
  1993. connect(&filtersAction, &QAction::triggered,
  1994. this, &OBSBasic::GetAudioSourceFilters,
  1995. Qt::DirectConnection);
  1996. connect(&propertiesAction, &QAction::triggered,
  1997. this, &OBSBasic::GetAudioSourceProperties,
  1998. Qt::DirectConnection);
  1999. connect(&advPropAction, &QAction::triggered,
  2000. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2001. Qt::DirectConnection);
  2002. /* ------------------- */
  2003. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2004. &OBSBasic::ToggleVolControlLayout,
  2005. Qt::DirectConnection);
  2006. /* ------------------- */
  2007. hideAction.setProperty("volControl",
  2008. QVariant::fromValue<VolControl*>(vol));
  2009. mixerRenameAction.setProperty("volControl",
  2010. QVariant::fromValue<VolControl*>(vol));
  2011. filtersAction.setProperty("volControl",
  2012. QVariant::fromValue<VolControl*>(vol));
  2013. propertiesAction.setProperty("volControl",
  2014. QVariant::fromValue<VolControl*>(vol));
  2015. /* ------------------- */
  2016. QMenu popup(this);
  2017. popup.addAction(&unhideAllAction);
  2018. popup.addAction(&hideAction);
  2019. popup.addAction(&mixerRenameAction);
  2020. popup.addSeparator();
  2021. popup.addAction(&toggleControlLayoutAction);
  2022. popup.addSeparator();
  2023. popup.addAction(&filtersAction);
  2024. popup.addAction(&propertiesAction);
  2025. popup.addAction(&advPropAction);
  2026. popup.exec(QCursor::pos());
  2027. }
  2028. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2029. {
  2030. StackedMixerAreaContextMenuRequested();
  2031. }
  2032. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2033. {
  2034. StackedMixerAreaContextMenuRequested();
  2035. }
  2036. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2037. {
  2038. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2039. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2040. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2041. toggleControlLayoutAction.setCheckable(true);
  2042. toggleControlLayoutAction.setChecked(config_get_bool(GetGlobalConfig(),
  2043. "BasicWindow", "VerticalVolControl"));
  2044. /* ------------------- */
  2045. connect(&unhideAllAction, &QAction::triggered,
  2046. this, &OBSBasic::UnhideAllAudioControls,
  2047. Qt::DirectConnection);
  2048. connect(&advPropAction, &QAction::triggered,
  2049. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  2050. Qt::DirectConnection);
  2051. /* ------------------- */
  2052. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2053. &OBSBasic::ToggleVolControlLayout,
  2054. Qt::DirectConnection);
  2055. /* ------------------- */
  2056. QMenu popup(this);
  2057. popup.addAction(&unhideAllAction);
  2058. popup.addSeparator();
  2059. popup.addAction(&toggleControlLayoutAction);
  2060. popup.addSeparator();
  2061. popup.addAction(&advPropAction);
  2062. popup.exec(QCursor::pos());
  2063. }
  2064. void OBSBasic::ToggleMixerLayout(bool vertical)
  2065. {
  2066. if (vertical) {
  2067. ui->stackedMixerArea->setMinimumSize(180, 220);
  2068. ui->stackedMixerArea->setCurrentIndex(1);
  2069. } else {
  2070. ui->stackedMixerArea->setMinimumSize(220, 0);
  2071. ui->stackedMixerArea->setCurrentIndex(0);
  2072. }
  2073. }
  2074. void OBSBasic::ToggleVolControlLayout()
  2075. {
  2076. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2077. "VerticalVolControl");
  2078. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2079. vertical);
  2080. ToggleMixerLayout(vertical);
  2081. // We need to store it so we can delete current and then add
  2082. // at the right order
  2083. vector<OBSSource> sources;
  2084. for (size_t i = 0; i != volumes.size(); i++)
  2085. sources.emplace_back(volumes[i]->GetSource());
  2086. ClearVolumeControls();
  2087. for (const auto &source : sources)
  2088. ActivateAudioSource(source);
  2089. }
  2090. void OBSBasic::ActivateAudioSource(OBSSource source)
  2091. {
  2092. if (SourceMixerHidden(source))
  2093. return;
  2094. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2095. "VerticalVolControl");
  2096. VolControl *vol = new VolControl(source, true, vertical);
  2097. double meterDecayRate = config_get_double(basicConfig, "Audio",
  2098. "MeterDecayRate");
  2099. vol->SetMeterDecayRate(meterDecayRate);
  2100. uint32_t peakMeterTypeIdx = config_get_uint(basicConfig, "Audio",
  2101. "PeakMeterType");
  2102. enum obs_peak_meter_type peakMeterType;
  2103. switch (peakMeterTypeIdx) {
  2104. case 0:
  2105. peakMeterType = SAMPLE_PEAK_METER;
  2106. break;
  2107. case 1:
  2108. peakMeterType = TRUE_PEAK_METER;
  2109. break;
  2110. default:
  2111. peakMeterType = SAMPLE_PEAK_METER;
  2112. break;
  2113. }
  2114. vol->setPeakMeterType(peakMeterType);
  2115. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2116. connect(vol, &QWidget::customContextMenuRequested,
  2117. this, &OBSBasic::VolControlContextMenu);
  2118. connect(vol, &VolControl::ConfigClicked,
  2119. this, &OBSBasic::VolControlContextMenu);
  2120. InsertQObjectByName(volumes, vol);
  2121. for (auto volume : volumes) {
  2122. if (vertical)
  2123. ui->vVolControlLayout->addWidget(volume);
  2124. else
  2125. ui->hVolControlLayout->addWidget(volume);
  2126. }
  2127. }
  2128. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2129. {
  2130. for (size_t i = 0; i < volumes.size(); i++) {
  2131. if (volumes[i]->GetSource() == source) {
  2132. delete volumes[i];
  2133. volumes.erase(volumes.begin() + i);
  2134. break;
  2135. }
  2136. }
  2137. }
  2138. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2139. {
  2140. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2141. !obs_source_is_group(source)) {
  2142. int count = ui->scenes->count();
  2143. if (count == 1) {
  2144. OBSMessageBox::information(this,
  2145. QTStr("FinalScene.Title"),
  2146. QTStr("FinalScene.Text"));
  2147. return false;
  2148. }
  2149. }
  2150. const char *name = obs_source_get_name(source);
  2151. QString text = QTStr("ConfirmRemove.Text");
  2152. text.replace("$1", QT_UTF8(name));
  2153. QMessageBox remove_source(this);
  2154. remove_source.setText(text);
  2155. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  2156. QMessageBox::YesRole);
  2157. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2158. remove_source.setIcon(QMessageBox::Question);
  2159. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2160. remove_source.exec();
  2161. return Yes == remove_source.clickedButton();
  2162. }
  2163. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  2164. #ifdef UPDATE_SPARKLE
  2165. void init_sparkle_updater(bool update_to_undeployed);
  2166. void trigger_sparkle_update();
  2167. #endif
  2168. void OBSBasic::TimedCheckForUpdates()
  2169. {
  2170. if (!config_get_bool(App()->GlobalConfig(), "General",
  2171. "EnableAutoUpdates"))
  2172. return;
  2173. #ifdef UPDATE_SPARKLE
  2174. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2175. "UpdateToUndeployed"));
  2176. #elif _WIN32
  2177. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2178. "LastUpdateCheck");
  2179. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  2180. "LastVersion");
  2181. if (lastVersion < LIBOBS_API_VER) {
  2182. lastUpdate = 0;
  2183. config_set_int(App()->GlobalConfig(), "General",
  2184. "LastUpdateCheck", 0);
  2185. }
  2186. long long t = (long long)time(nullptr);
  2187. long long secs = t - lastUpdate;
  2188. if (secs > UPDATE_CHECK_INTERVAL)
  2189. CheckForUpdates(false);
  2190. #endif
  2191. }
  2192. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2193. {
  2194. #ifdef UPDATE_SPARKLE
  2195. trigger_sparkle_update();
  2196. #elif _WIN32
  2197. ui->actionCheckForUpdates->setEnabled(false);
  2198. if (updateCheckThread && updateCheckThread->isRunning())
  2199. return;
  2200. updateCheckThread = new AutoUpdateThread(manualUpdate);
  2201. updateCheckThread->start();
  2202. #endif
  2203. UNUSED_PARAMETER(manualUpdate);
  2204. }
  2205. void OBSBasic::updateCheckFinished()
  2206. {
  2207. ui->actionCheckForUpdates->setEnabled(true);
  2208. }
  2209. void OBSBasic::DuplicateSelectedScene()
  2210. {
  2211. OBSScene curScene = GetCurrentScene();
  2212. if (!curScene)
  2213. return;
  2214. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2215. QString format{obs_source_get_name(curSceneSource)};
  2216. format += " %1";
  2217. int i = 2;
  2218. QString placeHolderText = format.arg(i);
  2219. obs_source_t *source = nullptr;
  2220. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2221. obs_source_release(source);
  2222. placeHolderText = format.arg(++i);
  2223. }
  2224. for (;;) {
  2225. string name;
  2226. bool accepted = NameDialog::AskForName(this,
  2227. QTStr("Basic.Main.AddSceneDlg.Title"),
  2228. QTStr("Basic.Main.AddSceneDlg.Text"),
  2229. name,
  2230. placeHolderText);
  2231. if (!accepted)
  2232. return;
  2233. if (name.empty()) {
  2234. OBSMessageBox::information(this,
  2235. QTStr("NoNameEntered.Title"),
  2236. QTStr("NoNameEntered.Text"));
  2237. continue;
  2238. }
  2239. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2240. if (source) {
  2241. OBSMessageBox::information(this,
  2242. QTStr("NameExists.Title"),
  2243. QTStr("NameExists.Text"));
  2244. obs_source_release(source);
  2245. continue;
  2246. }
  2247. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2248. name.c_str(), OBS_SCENE_DUP_REFS);
  2249. source = obs_scene_get_source(scene);
  2250. SetCurrentScene(source, true);
  2251. obs_scene_release(scene);
  2252. break;
  2253. }
  2254. }
  2255. void OBSBasic::RemoveSelectedScene()
  2256. {
  2257. OBSScene scene = GetCurrentScene();
  2258. if (scene) {
  2259. obs_source_t *source = obs_scene_get_source(scene);
  2260. if (QueryRemoveSource(source)) {
  2261. obs_source_remove(source);
  2262. if (api)
  2263. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2264. }
  2265. }
  2266. }
  2267. void OBSBasic::RemoveSelectedSceneItem()
  2268. {
  2269. OBSSceneItem item = GetCurrentSceneItem();
  2270. if (item) {
  2271. obs_source_t *source = obs_sceneitem_get_source(item);
  2272. if (QueryRemoveSource(source))
  2273. obs_sceneitem_remove(item);
  2274. }
  2275. }
  2276. void OBSBasic::ReorderSources(OBSScene scene)
  2277. {
  2278. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2279. return;
  2280. ui->sources->ReorderItems();
  2281. SaveProject();
  2282. }
  2283. /* OBS Callbacks */
  2284. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2285. {
  2286. OBSBasic *window = static_cast<OBSBasic*>(data);
  2287. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2288. QMetaObject::invokeMethod(window, "ReorderSources",
  2289. Q_ARG(OBSScene, OBSScene(scene)));
  2290. }
  2291. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2292. {
  2293. OBSBasic *window = static_cast<OBSBasic*>(data);
  2294. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2295. QMetaObject::invokeMethod(window, "AddSceneItem",
  2296. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2297. }
  2298. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2299. {
  2300. OBSBasic *window = static_cast<OBSBasic*>(data);
  2301. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2302. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2303. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2304. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2305. Q_ARG(bool, true));
  2306. }
  2307. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2308. {
  2309. OBSBasic *window = static_cast<OBSBasic*>(data);
  2310. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2311. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2312. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2313. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2314. Q_ARG(bool, false));
  2315. }
  2316. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  2317. {
  2318. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2319. if (obs_scene_from_source(source) != NULL)
  2320. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2321. "AddScene", WaitConnection(),
  2322. Q_ARG(OBSSource, OBSSource(source)));
  2323. }
  2324. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2325. {
  2326. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2327. if (obs_scene_from_source(source) != NULL)
  2328. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2329. "RemoveScene",
  2330. Q_ARG(OBSSource, OBSSource(source)));
  2331. }
  2332. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2333. {
  2334. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2335. uint32_t flags = obs_source_get_output_flags(source);
  2336. if (flags & OBS_SOURCE_AUDIO)
  2337. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2338. "ActivateAudioSource",
  2339. Q_ARG(OBSSource, OBSSource(source)));
  2340. }
  2341. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2342. {
  2343. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2344. uint32_t flags = obs_source_get_output_flags(source);
  2345. if (flags & OBS_SOURCE_AUDIO)
  2346. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2347. "DeactivateAudioSource",
  2348. Q_ARG(OBSSource, OBSSource(source)));
  2349. }
  2350. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2351. {
  2352. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2353. const char *newName = calldata_string(params, "new_name");
  2354. const char *prevName = calldata_string(params, "prev_name");
  2355. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2356. "RenameSources",
  2357. Q_ARG(OBSSource, source),
  2358. Q_ARG(QString, QT_UTF8(newName)),
  2359. Q_ARG(QString, QT_UTF8(prevName)));
  2360. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2361. }
  2362. void OBSBasic::DrawBackdrop(float cx, float cy)
  2363. {
  2364. if (!box)
  2365. return;
  2366. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2367. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2368. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2369. vec4 colorVal;
  2370. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2371. gs_effect_set_vec4(color, &colorVal);
  2372. gs_technique_begin(tech);
  2373. gs_technique_begin_pass(tech, 0);
  2374. gs_matrix_push();
  2375. gs_matrix_identity();
  2376. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2377. gs_load_vertexbuffer(box);
  2378. gs_draw(GS_TRISTRIP, 0, 0);
  2379. gs_matrix_pop();
  2380. gs_technique_end_pass(tech);
  2381. gs_technique_end(tech);
  2382. gs_load_vertexbuffer(nullptr);
  2383. }
  2384. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2385. {
  2386. OBSBasic *window = static_cast<OBSBasic*>(data);
  2387. obs_video_info ovi;
  2388. obs_get_video_info(&ovi);
  2389. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2390. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2391. gs_viewport_push();
  2392. gs_projection_push();
  2393. /* --------------------------------------- */
  2394. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2395. -100.0f, 100.0f);
  2396. gs_set_viewport(window->previewX, window->previewY,
  2397. window->previewCX, window->previewCY);
  2398. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2399. if (window->IsPreviewProgramMode()) {
  2400. OBSScene scene = window->GetCurrentScene();
  2401. obs_source_t *source = obs_scene_get_source(scene);
  2402. if (source)
  2403. obs_source_video_render(source);
  2404. } else {
  2405. obs_render_main_texture();
  2406. }
  2407. gs_load_vertexbuffer(nullptr);
  2408. /* --------------------------------------- */
  2409. QSize previewSize = GetPixelSize(window->ui->preview);
  2410. float right = float(previewSize.width()) - window->previewX;
  2411. float bottom = float(previewSize.height()) - window->previewY;
  2412. gs_ortho(-window->previewX, right,
  2413. -window->previewY, bottom,
  2414. -100.0f, 100.0f);
  2415. gs_reset_viewport();
  2416. window->ui->preview->DrawSceneEditing();
  2417. /* --------------------------------------- */
  2418. gs_projection_pop();
  2419. gs_viewport_pop();
  2420. UNUSED_PARAMETER(cx);
  2421. UNUSED_PARAMETER(cy);
  2422. }
  2423. /* Main class functions */
  2424. obs_service_t *OBSBasic::GetService()
  2425. {
  2426. if (!service) {
  2427. service = obs_service_create("rtmp_common", NULL, NULL,
  2428. nullptr);
  2429. obs_service_release(service);
  2430. }
  2431. return service;
  2432. }
  2433. void OBSBasic::SetService(obs_service_t *newService)
  2434. {
  2435. if (newService)
  2436. service = newService;
  2437. }
  2438. bool OBSBasic::StreamingActive() const
  2439. {
  2440. if (!outputHandler)
  2441. return false;
  2442. return outputHandler->StreamingActive();
  2443. }
  2444. bool OBSBasic::Active() const
  2445. {
  2446. if (!outputHandler)
  2447. return false;
  2448. return outputHandler->Active();
  2449. }
  2450. #ifdef _WIN32
  2451. #define IS_WIN32 1
  2452. #else
  2453. #define IS_WIN32 0
  2454. #endif
  2455. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2456. {
  2457. return obs_reset_video(ovi);
  2458. }
  2459. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2460. {
  2461. const char *scaleTypeStr = config_get_string(basicConfig,
  2462. "Video", "ScaleType");
  2463. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2464. return OBS_SCALE_BILINEAR;
  2465. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2466. return OBS_SCALE_LANCZOS;
  2467. else
  2468. return OBS_SCALE_BICUBIC;
  2469. }
  2470. static inline enum video_format GetVideoFormatFromName(const char *name)
  2471. {
  2472. if (astrcmpi(name, "I420") == 0)
  2473. return VIDEO_FORMAT_I420;
  2474. else if (astrcmpi(name, "NV12") == 0)
  2475. return VIDEO_FORMAT_NV12;
  2476. else if (astrcmpi(name, "I444") == 0)
  2477. return VIDEO_FORMAT_I444;
  2478. #if 0 //currently unsupported
  2479. else if (astrcmpi(name, "YVYU") == 0)
  2480. return VIDEO_FORMAT_YVYU;
  2481. else if (astrcmpi(name, "YUY2") == 0)
  2482. return VIDEO_FORMAT_YUY2;
  2483. else if (astrcmpi(name, "UYVY") == 0)
  2484. return VIDEO_FORMAT_UYVY;
  2485. #endif
  2486. else
  2487. return VIDEO_FORMAT_RGBA;
  2488. }
  2489. void OBSBasic::ResetUI()
  2490. {
  2491. bool studioPortraitLayout = config_get_bool(GetGlobalConfig(),
  2492. "BasicWindow", "StudioPortraitLayout");
  2493. if (studioPortraitLayout)
  2494. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  2495. else
  2496. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  2497. }
  2498. int OBSBasic::ResetVideo()
  2499. {
  2500. if (outputHandler && outputHandler->Active())
  2501. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2502. ProfileScope("OBSBasic::ResetVideo");
  2503. struct obs_video_info ovi;
  2504. int ret;
  2505. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2506. const char *colorFormat = config_get_string(basicConfig, "Video",
  2507. "ColorFormat");
  2508. const char *colorSpace = config_get_string(basicConfig, "Video",
  2509. "ColorSpace");
  2510. const char *colorRange = config_get_string(basicConfig, "Video",
  2511. "ColorRange");
  2512. ovi.graphics_module = App()->GetRenderModule();
  2513. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2514. "Video", "BaseCX");
  2515. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2516. "Video", "BaseCY");
  2517. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2518. "Video", "OutputCX");
  2519. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2520. "Video", "OutputCY");
  2521. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2522. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2523. VIDEO_CS_601 : VIDEO_CS_709;
  2524. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2525. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2526. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2527. "Video", "AdapterIdx");
  2528. ovi.gpu_conversion = true;
  2529. ovi.scale_type = GetScaleType(basicConfig);
  2530. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2531. ovi.base_width = 1920;
  2532. ovi.base_height = 1080;
  2533. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2534. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2535. }
  2536. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2537. ovi.output_width = ovi.base_width;
  2538. ovi.output_height = ovi.base_height;
  2539. config_set_uint(basicConfig, "Video", "OutputCX",
  2540. ovi.base_width);
  2541. config_set_uint(basicConfig, "Video", "OutputCY",
  2542. ovi.base_height);
  2543. }
  2544. ret = AttemptToResetVideo(&ovi);
  2545. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2546. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2547. blog(LOG_WARNING, "Tried to reset when "
  2548. "already active");
  2549. return ret;
  2550. }
  2551. /* Try OpenGL if DirectX fails on windows */
  2552. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2553. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2554. "with graphics_module='%s', retrying "
  2555. "with graphics_module='%s'",
  2556. ret, ovi.graphics_module,
  2557. DL_OPENGL);
  2558. ovi.graphics_module = DL_OPENGL;
  2559. ret = AttemptToResetVideo(&ovi);
  2560. }
  2561. } else if (ret == OBS_VIDEO_SUCCESS) {
  2562. ResizePreview(ovi.base_width, ovi.base_height);
  2563. if (program)
  2564. ResizeProgram(ovi.base_width, ovi.base_height);
  2565. }
  2566. if (ret == OBS_VIDEO_SUCCESS) {
  2567. OBSBasicStats::InitializeValues();
  2568. OBSProjector::UpdateMultiviewProjectors();
  2569. }
  2570. return ret;
  2571. }
  2572. bool OBSBasic::ResetAudio()
  2573. {
  2574. ProfileScope("OBSBasic::ResetAudio");
  2575. struct obs_audio_info ai;
  2576. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2577. "SampleRate");
  2578. const char *channelSetupStr = config_get_string(basicConfig,
  2579. "Audio", "ChannelSetup");
  2580. if (strcmp(channelSetupStr, "Mono") == 0)
  2581. ai.speakers = SPEAKERS_MONO;
  2582. else if (strcmp(channelSetupStr, "2.1") == 0)
  2583. ai.speakers = SPEAKERS_2POINT1;
  2584. else if (strcmp(channelSetupStr, "4.0") == 0)
  2585. ai.speakers = SPEAKERS_4POINT0;
  2586. else if (strcmp(channelSetupStr, "4.1") == 0)
  2587. ai.speakers = SPEAKERS_4POINT1;
  2588. else if (strcmp(channelSetupStr, "5.1") == 0)
  2589. ai.speakers = SPEAKERS_5POINT1;
  2590. else if (strcmp(channelSetupStr, "7.1") == 0)
  2591. ai.speakers = SPEAKERS_7POINT1;
  2592. else
  2593. ai.speakers = SPEAKERS_STEREO;
  2594. return obs_reset_audio(&ai);
  2595. }
  2596. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2597. const char *deviceDesc, int channel)
  2598. {
  2599. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2600. obs_source_t *source;
  2601. obs_data_t *settings;
  2602. source = obs_get_output_source(channel);
  2603. if (source) {
  2604. if (disable) {
  2605. obs_set_output_source(channel, nullptr);
  2606. } else {
  2607. settings = obs_source_get_settings(source);
  2608. const char *oldId = obs_data_get_string(settings,
  2609. "device_id");
  2610. if (strcmp(oldId, deviceId) != 0) {
  2611. obs_data_set_string(settings, "device_id",
  2612. deviceId);
  2613. obs_source_update(source, settings);
  2614. }
  2615. obs_data_release(settings);
  2616. }
  2617. obs_source_release(source);
  2618. } else if (!disable) {
  2619. settings = obs_data_create();
  2620. obs_data_set_string(settings, "device_id", deviceId);
  2621. source = obs_source_create(sourceId, deviceDesc, settings,
  2622. nullptr);
  2623. obs_data_release(settings);
  2624. obs_set_output_source(channel, source);
  2625. obs_source_release(source);
  2626. }
  2627. }
  2628. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2629. {
  2630. QSize targetSize;
  2631. bool isFixedScaling;
  2632. obs_video_info ovi;
  2633. /* resize preview panel to fix to the top section of the window */
  2634. targetSize = GetPixelSize(ui->preview);
  2635. isFixedScaling = ui->preview->IsFixedScaling();
  2636. obs_get_video_info(&ovi);
  2637. if (isFixedScaling) {
  2638. previewScale = ui->preview->GetScalingAmount();
  2639. GetCenterPosFromFixedScale(int(cx), int(cy),
  2640. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2641. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2642. previewX, previewY, previewScale);
  2643. previewX += ui->preview->GetScrollX();
  2644. previewY += ui->preview->GetScrollY();
  2645. } else {
  2646. GetScaleAndCenterPos(int(cx), int(cy),
  2647. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2648. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2649. previewX, previewY, previewScale);
  2650. }
  2651. previewX += float(PREVIEW_EDGE_SIZE);
  2652. previewY += float(PREVIEW_EDGE_SIZE);
  2653. }
  2654. void OBSBasic::CloseDialogs()
  2655. {
  2656. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2657. if (!childDialogs.isEmpty()) {
  2658. for (int i = 0; i < childDialogs.size(); ++i) {
  2659. childDialogs.at(i)->close();
  2660. }
  2661. }
  2662. for (QPointer<QWidget> &projector : windowProjectors) {
  2663. delete projector;
  2664. projector.clear();
  2665. }
  2666. for (QPointer<QWidget> &projector : projectors) {
  2667. delete projector;
  2668. projector.clear();
  2669. }
  2670. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2671. if (!remux.isNull()) remux->close();
  2672. }
  2673. void OBSBasic::EnumDialogs()
  2674. {
  2675. visDialogs.clear();
  2676. modalDialogs.clear();
  2677. visMsgBoxes.clear();
  2678. /* fill list of Visible dialogs and Modal dialogs */
  2679. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2680. for (QDialog *dialog : dialogs) {
  2681. if (dialog->isVisible())
  2682. visDialogs.append(dialog);
  2683. if (dialog->isModal())
  2684. modalDialogs.append(dialog);
  2685. }
  2686. /* fill list of Visible message boxes */
  2687. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2688. for (QMessageBox *msgbox : msgBoxes) {
  2689. if (msgbox->isVisible())
  2690. visMsgBoxes.append(msgbox);
  2691. }
  2692. }
  2693. void OBSBasic::ClearSceneData()
  2694. {
  2695. disableSaving++;
  2696. CloseDialogs();
  2697. ClearVolumeControls();
  2698. ClearListItems(ui->scenes);
  2699. ui->sources->Clear();
  2700. ClearQuickTransitions();
  2701. ui->transitions->clear();
  2702. obs_set_output_source(0, nullptr);
  2703. obs_set_output_source(1, nullptr);
  2704. obs_set_output_source(2, nullptr);
  2705. obs_set_output_source(3, nullptr);
  2706. obs_set_output_source(4, nullptr);
  2707. obs_set_output_source(5, nullptr);
  2708. lastScene = nullptr;
  2709. swapScene = nullptr;
  2710. programScene = nullptr;
  2711. auto cb = [](void *unused, obs_source_t *source)
  2712. {
  2713. obs_source_remove(source);
  2714. UNUSED_PARAMETER(unused);
  2715. return true;
  2716. };
  2717. obs_enum_sources(cb, nullptr);
  2718. if (api)
  2719. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  2720. disableSaving--;
  2721. blog(LOG_INFO, "All scene data cleared");
  2722. blog(LOG_INFO, "------------------------------------------------");
  2723. }
  2724. void OBSBasic::closeEvent(QCloseEvent *event)
  2725. {
  2726. if (isVisible())
  2727. config_set_string(App()->GlobalConfig(),
  2728. "BasicWindow", "geometry",
  2729. saveGeometry().toBase64().constData());
  2730. config_set_string(App()->GlobalConfig(),
  2731. "BasicWindow", "DockState",
  2732. saveState().toBase64().constData());
  2733. if (outputHandler && outputHandler->Active()) {
  2734. SetShowing(true);
  2735. QMessageBox::StandardButton button = OBSMessageBox::question(
  2736. this, QTStr("ConfirmExit.Title"),
  2737. QTStr("ConfirmExit.Text"));
  2738. if (button == QMessageBox::No) {
  2739. event->ignore();
  2740. return;
  2741. }
  2742. }
  2743. QWidget::closeEvent(event);
  2744. if (!event->isAccepted())
  2745. return;
  2746. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2747. if (updateCheckThread)
  2748. updateCheckThread->wait();
  2749. if (logUploadThread)
  2750. logUploadThread->wait();
  2751. signalHandlers.clear();
  2752. SaveProjectNow();
  2753. if (api)
  2754. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2755. disableSaving++;
  2756. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2757. * sources, etc) so that all references are released before shutdown */
  2758. ClearSceneData();
  2759. App()->quit();
  2760. }
  2761. void OBSBasic::changeEvent(QEvent *event)
  2762. {
  2763. if (event->type() == QEvent::WindowStateChange &&
  2764. isMinimized() &&
  2765. trayIcon &&
  2766. trayIcon->isVisible() &&
  2767. sysTrayMinimizeToTray()) {
  2768. ToggleShowHide();
  2769. }
  2770. }
  2771. void OBSBasic::on_actionShow_Recordings_triggered()
  2772. {
  2773. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2774. const char *path = strcmp(mode, "Advanced") ?
  2775. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2776. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2777. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2778. }
  2779. void OBSBasic::on_actionRemux_triggered()
  2780. {
  2781. if (!remux.isNull()) {
  2782. remux->show();
  2783. remux->raise();
  2784. return;
  2785. }
  2786. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2787. const char *path = strcmp(mode, "Advanced") ?
  2788. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2789. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2790. OBSRemux *remuxDlg;
  2791. remuxDlg = new OBSRemux(path, this);
  2792. remuxDlg->show();
  2793. remux = remuxDlg;
  2794. }
  2795. void OBSBasic::on_action_Settings_triggered()
  2796. {
  2797. OBSBasicSettings settings(this);
  2798. settings.exec();
  2799. SystemTray(false);
  2800. }
  2801. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2802. {
  2803. if (advAudioWindow != nullptr) {
  2804. advAudioWindow->raise();
  2805. return;
  2806. }
  2807. advAudioWindow = new OBSBasicAdvAudio(this);
  2808. advAudioWindow->show();
  2809. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2810. connect(advAudioWindow, SIGNAL(destroyed()),
  2811. this, SLOT(on_advAudioProps_destroyed()));
  2812. }
  2813. void OBSBasic::on_advAudioProps_clicked()
  2814. {
  2815. on_actionAdvAudioProperties_triggered();
  2816. }
  2817. void OBSBasic::on_advAudioProps_destroyed()
  2818. {
  2819. advAudioWindow = nullptr;
  2820. }
  2821. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2822. QListWidgetItem *prev)
  2823. {
  2824. obs_source_t *source = NULL;
  2825. if (sceneChanging)
  2826. return;
  2827. if (current) {
  2828. obs_scene_t *scene;
  2829. scene = GetOBSRef<OBSScene>(current);
  2830. source = obs_scene_get_source(scene);
  2831. }
  2832. SetCurrentScene(source);
  2833. if (api)
  2834. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  2835. UNUSED_PARAMETER(prev);
  2836. }
  2837. void OBSBasic::EditSceneName()
  2838. {
  2839. QListWidgetItem *item = ui->scenes->currentItem();
  2840. Qt::ItemFlags flags = item->flags();
  2841. item->setFlags(flags | Qt::ItemIsEditable);
  2842. ui->scenes->editItem(item);
  2843. item->setFlags(flags);
  2844. }
  2845. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2846. const char *slot)
  2847. {
  2848. QAction *action;
  2849. QList<QScreen*> screens = QGuiApplication::screens();
  2850. for (int i = 0; i < screens.size(); i++) {
  2851. QRect screenGeometry = screens[i]->geometry();
  2852. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2853. arg(QTStr("Display"),
  2854. QString::number(i),
  2855. QString::number(screenGeometry.width()),
  2856. QString::number(screenGeometry.height()),
  2857. QString::number(screenGeometry.x()),
  2858. QString::number(screenGeometry.y()));
  2859. action = parent->addAction(str, target, slot);
  2860. action->setProperty("monitor", i);
  2861. }
  2862. }
  2863. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2864. {
  2865. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2866. QPointer<QMenu> sceneProjectorMenu;
  2867. QMenu popup(this);
  2868. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2869. popup.addAction(QTStr("Add"),
  2870. this, SLOT(on_actionAddScene_triggered()));
  2871. if (item) {
  2872. popup.addSeparator();
  2873. popup.addAction(QTStr("Duplicate"),
  2874. this, SLOT(DuplicateSelectedScene()));
  2875. popup.addAction(QTStr("Rename"),
  2876. this, SLOT(EditSceneName()));
  2877. popup.addAction(QTStr("Remove"),
  2878. this, SLOT(RemoveSelectedScene()));
  2879. popup.addSeparator();
  2880. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2881. this, SLOT(on_actionSceneUp_triggered()));
  2882. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2883. this, SLOT(on_actionSceneDown_triggered()));
  2884. order.addSeparator();
  2885. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2886. this, SLOT(MoveSceneToTop()));
  2887. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2888. this, SLOT(MoveSceneToBottom()));
  2889. popup.addMenu(&order);
  2890. popup.addSeparator();
  2891. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2892. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2893. SLOT(OpenSceneProjector()));
  2894. popup.addMenu(sceneProjectorMenu);
  2895. QAction *sceneWindow = popup.addAction(
  2896. QTStr("SceneWindow"),
  2897. this, SLOT(OpenSceneWindow()));
  2898. popup.addAction(sceneWindow);
  2899. popup.addSeparator();
  2900. popup.addAction(QTStr("Filters"), this,
  2901. SLOT(OpenSceneFilters()));
  2902. popup.addSeparator();
  2903. QMenu *transitionMenu = CreatePerSceneTransitionMenu();
  2904. popup.addMenu(transitionMenu);
  2905. /* ---------------------- */
  2906. QAction *multiviewAction = popup.addAction(
  2907. QTStr("ShowInMultiview"));
  2908. OBSSource source = GetCurrentSceneSource();
  2909. OBSData data = obs_source_get_private_settings(source);
  2910. obs_data_release(data);
  2911. obs_data_set_default_bool(data, "show_in_multiview",
  2912. true);
  2913. bool show = obs_data_get_bool(data, "show_in_multiview");
  2914. multiviewAction->setCheckable(true);
  2915. multiviewAction->setChecked(show);
  2916. auto showInMultiview = [] (OBSData data)
  2917. {
  2918. bool show = obs_data_get_bool(data,
  2919. "show_in_multiview");
  2920. obs_data_set_bool(data, "show_in_multiview",
  2921. !show);
  2922. OBSProjector::UpdateMultiviewProjectors();
  2923. };
  2924. connect(multiviewAction, &QAction::triggered,
  2925. std::bind(showInMultiview, data));
  2926. }
  2927. popup.exec(QCursor::pos());
  2928. }
  2929. void OBSBasic::on_actionAddScene_triggered()
  2930. {
  2931. string name;
  2932. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2933. int i = 2;
  2934. QString placeHolderText = format.arg(i);
  2935. obs_source_t *source = nullptr;
  2936. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2937. obs_source_release(source);
  2938. placeHolderText = format.arg(++i);
  2939. }
  2940. bool accepted = NameDialog::AskForName(this,
  2941. QTStr("Basic.Main.AddSceneDlg.Title"),
  2942. QTStr("Basic.Main.AddSceneDlg.Text"),
  2943. name,
  2944. placeHolderText);
  2945. if (accepted) {
  2946. if (name.empty()) {
  2947. OBSMessageBox::information(this,
  2948. QTStr("NoNameEntered.Title"),
  2949. QTStr("NoNameEntered.Text"));
  2950. on_actionAddScene_triggered();
  2951. return;
  2952. }
  2953. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2954. if (source) {
  2955. OBSMessageBox::information(this,
  2956. QTStr("NameExists.Title"),
  2957. QTStr("NameExists.Text"));
  2958. obs_source_release(source);
  2959. on_actionAddScene_triggered();
  2960. return;
  2961. }
  2962. obs_scene_t *scene = obs_scene_create(name.c_str());
  2963. source = obs_scene_get_source(scene);
  2964. SetCurrentScene(source);
  2965. obs_scene_release(scene);
  2966. }
  2967. }
  2968. void OBSBasic::on_actionRemoveScene_triggered()
  2969. {
  2970. OBSScene scene = GetCurrentScene();
  2971. obs_source_t *source = obs_scene_get_source(scene);
  2972. if (source && QueryRemoveSource(source))
  2973. obs_source_remove(source);
  2974. }
  2975. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2976. {
  2977. int idx = ui->scenes->currentRow();
  2978. if (idx == -1 || idx == invalidIdx)
  2979. return;
  2980. sceneChanging = true;
  2981. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2982. if (!relative)
  2983. idx = 0;
  2984. ui->scenes->insertItem(idx + offset, item);
  2985. ui->scenes->setCurrentRow(idx + offset);
  2986. item->setSelected(true);
  2987. sceneChanging = false;
  2988. OBSProjector::UpdateMultiviewProjectors();
  2989. }
  2990. void OBSBasic::on_actionSceneUp_triggered()
  2991. {
  2992. ChangeSceneIndex(true, -1, 0);
  2993. }
  2994. void OBSBasic::on_actionSceneDown_triggered()
  2995. {
  2996. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2997. }
  2998. void OBSBasic::MoveSceneToTop()
  2999. {
  3000. ChangeSceneIndex(false, 0, 0);
  3001. }
  3002. void OBSBasic::MoveSceneToBottom()
  3003. {
  3004. ChangeSceneIndex(false, ui->scenes->count() - 1,
  3005. ui->scenes->count() - 1);
  3006. }
  3007. void OBSBasic::EditSceneItemName()
  3008. {
  3009. int idx = GetTopSelectedSourceItem();
  3010. ui->sources->Edit(idx);
  3011. }
  3012. void OBSBasic::SetDeinterlacingMode()
  3013. {
  3014. QAction *action = reinterpret_cast<QAction*>(sender());
  3015. obs_deinterlace_mode mode =
  3016. (obs_deinterlace_mode)action->property("mode").toInt();
  3017. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3018. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3019. obs_source_set_deinterlace_mode(source, mode);
  3020. }
  3021. void OBSBasic::SetDeinterlacingOrder()
  3022. {
  3023. QAction *action = reinterpret_cast<QAction*>(sender());
  3024. obs_deinterlace_field_order order =
  3025. (obs_deinterlace_field_order)action->property("order").toInt();
  3026. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3027. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3028. obs_source_set_deinterlace_field_order(source, order);
  3029. }
  3030. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  3031. {
  3032. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  3033. obs_deinterlace_mode deinterlaceMode =
  3034. obs_source_get_deinterlace_mode(source);
  3035. obs_deinterlace_field_order deinterlaceOrder =
  3036. obs_source_get_deinterlace_field_order(source);
  3037. QAction *action;
  3038. #define ADD_MODE(name, mode) \
  3039. action = menu->addAction(QTStr("" name), this, \
  3040. SLOT(SetDeinterlacingMode())); \
  3041. action->setProperty("mode", (int)mode); \
  3042. action->setCheckable(true); \
  3043. action->setChecked(deinterlaceMode == mode);
  3044. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  3045. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  3046. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  3047. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  3048. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  3049. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  3050. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  3051. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  3052. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  3053. #undef ADD_MODE
  3054. menu->addSeparator();
  3055. #define ADD_ORDER(name, order) \
  3056. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  3057. SLOT(SetDeinterlacingOrder())); \
  3058. action->setProperty("order", (int)order); \
  3059. action->setCheckable(true); \
  3060. action->setChecked(deinterlaceOrder == order);
  3061. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  3062. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  3063. #undef ADD_ORDER
  3064. return menu;
  3065. }
  3066. void OBSBasic::SetScaleFilter()
  3067. {
  3068. QAction *action = reinterpret_cast<QAction*>(sender());
  3069. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  3070. OBSSceneItem sceneItem = GetCurrentSceneItem();
  3071. obs_sceneitem_set_scale_filter(sceneItem, mode);
  3072. }
  3073. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  3074. {
  3075. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  3076. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  3077. QAction *action;
  3078. #define ADD_MODE(name, mode) \
  3079. action = menu->addAction(QTStr("" name), this, \
  3080. SLOT(SetScaleFilter())); \
  3081. action->setProperty("mode", (int)mode); \
  3082. action->setCheckable(true); \
  3083. action->setChecked(scaleFilter == mode);
  3084. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  3085. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  3086. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  3087. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  3088. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  3089. #undef ADD_MODE
  3090. return menu;
  3091. }
  3092. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  3093. {
  3094. QMenu popup(this);
  3095. QPointer<QMenu> previewProjector;
  3096. QPointer<QMenu> sourceProjector;
  3097. if (preview) {
  3098. QAction *action = popup.addAction(
  3099. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3100. this, SLOT(TogglePreview()));
  3101. action->setCheckable(true);
  3102. action->setChecked(
  3103. obs_display_enabled(ui->preview->GetDisplay()));
  3104. if (IsPreviewProgramMode())
  3105. action->setEnabled(false);
  3106. popup.addAction(ui->actionLockPreview);
  3107. popup.addMenu(ui->scalingMenu);
  3108. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3109. AddProjectorMenuMonitors(previewProjector, this,
  3110. SLOT(OpenPreviewProjector()));
  3111. popup.addMenu(previewProjector);
  3112. QAction *previewWindow = popup.addAction(
  3113. QTStr("PreviewWindow"),
  3114. this, SLOT(OpenPreviewWindow()));
  3115. popup.addAction(previewWindow);
  3116. popup.addSeparator();
  3117. }
  3118. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  3119. if (addSourceMenu)
  3120. popup.addMenu(addSourceMenu);
  3121. ui->actionCopyFilters->setEnabled(false);
  3122. ui->actionCopySource->setEnabled(false);
  3123. if (ui->sources->MultipleBaseSelected()) {
  3124. popup.addSeparator();
  3125. popup.addAction(QTStr("Basic.Main.GroupItems"),
  3126. ui->sources, SLOT(GroupSelectedItems()));
  3127. } else if (ui->sources->GroupsSelected()) {
  3128. popup.addSeparator();
  3129. popup.addAction(QTStr("Basic.Main.Ungroup"),
  3130. ui->sources, SLOT(UngroupSelectedGroups()));
  3131. }
  3132. popup.addSeparator();
  3133. popup.addAction(ui->actionCopySource);
  3134. popup.addAction(ui->actionPasteRef);
  3135. popup.addAction(ui->actionPasteDup);
  3136. popup.addSeparator();
  3137. popup.addSeparator();
  3138. popup.addAction(ui->actionCopyFilters);
  3139. popup.addAction(ui->actionPasteFilters);
  3140. popup.addSeparator();
  3141. if (idx != -1) {
  3142. if (addSourceMenu)
  3143. popup.addSeparator();
  3144. OBSSceneItem sceneItem = ui->sources->Get(idx);
  3145. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  3146. uint32_t flags = obs_source_get_output_flags(source);
  3147. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  3148. OBS_SOURCE_ASYNC_VIDEO;
  3149. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  3150. OBS_SOURCE_AUDIO;
  3151. QAction *action;
  3152. popup.addAction(QTStr("Rename"), this,
  3153. SLOT(EditSceneItemName()));
  3154. popup.addAction(QTStr("Remove"), this,
  3155. SLOT(on_actionRemoveSource_triggered()));
  3156. popup.addSeparator();
  3157. popup.addMenu(ui->orderMenu);
  3158. popup.addMenu(ui->transformMenu);
  3159. sourceProjector = new QMenu(QTStr("SourceProjector"));
  3160. AddProjectorMenuMonitors(sourceProjector, this,
  3161. SLOT(OpenSourceProjector()));
  3162. QAction *sourceWindow = popup.addAction(
  3163. QTStr("SourceWindow"),
  3164. this, SLOT(OpenSourceWindow()));
  3165. popup.addAction(sourceWindow);
  3166. popup.addSeparator();
  3167. if (hasAudio) {
  3168. QAction *actionHideMixer = popup.addAction(
  3169. QTStr("HideMixer"),
  3170. this, SLOT(ToggleHideMixer()));
  3171. actionHideMixer->setCheckable(true);
  3172. actionHideMixer->setChecked(SourceMixerHidden(source));
  3173. }
  3174. if (isAsyncVideo) {
  3175. popup.addMenu(AddDeinterlacingMenu(source));
  3176. popup.addSeparator();
  3177. }
  3178. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  3179. popup.addSeparator();
  3180. popup.addMenu(sourceProjector);
  3181. popup.addAction(sourceWindow);
  3182. popup.addSeparator();
  3183. action = popup.addAction(QTStr("Interact"), this,
  3184. SLOT(on_actionInteract_triggered()));
  3185. action->setEnabled(obs_source_get_output_flags(source) &
  3186. OBS_SOURCE_INTERACTION);
  3187. popup.addAction(QTStr("Filters"), this,
  3188. SLOT(OpenFilters()));
  3189. popup.addAction(QTStr("Properties"), this,
  3190. SLOT(on_actionSourceProperties_triggered()));
  3191. ui->actionCopyFilters->setEnabled(true);
  3192. ui->actionCopySource->setEnabled(true);
  3193. } else {
  3194. ui->actionPasteFilters->setEnabled(false);
  3195. }
  3196. popup.exec(QCursor::pos());
  3197. }
  3198. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  3199. {
  3200. if (ui->scenes->count()) {
  3201. QModelIndex idx = ui->sources->indexAt(pos);
  3202. CreateSourcePopupMenu(idx.row(), false);
  3203. }
  3204. }
  3205. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  3206. {
  3207. if (!witem)
  3208. return;
  3209. if (IsPreviewProgramMode()) {
  3210. bool doubleClickSwitch = config_get_bool(App()->GlobalConfig(),
  3211. "BasicWindow", "TransitionOnDoubleClick");
  3212. if (doubleClickSwitch) {
  3213. OBSScene scene = GetCurrentScene();
  3214. if (scene)
  3215. SetCurrentScene(scene, false, true);
  3216. }
  3217. }
  3218. }
  3219. void OBSBasic::AddSource(const char *id)
  3220. {
  3221. if (id && *id) {
  3222. OBSBasicSourceSelect sourceSelect(this, id);
  3223. sourceSelect.exec();
  3224. if (sourceSelect.newSource && strcmp(id, "group") != 0)
  3225. CreatePropertiesWindow(sourceSelect.newSource);
  3226. }
  3227. }
  3228. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3229. {
  3230. const char *type;
  3231. bool foundValues = false;
  3232. bool foundDeprecated = false;
  3233. size_t idx = 0;
  3234. QMenu *popup = new QMenu(QTStr("Add"), this);
  3235. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3236. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3237. {
  3238. QList<QAction*> actions = menu->actions();
  3239. for (QAction *menuAction : actions) {
  3240. if (menuAction->text().compare(name) >= 0)
  3241. return menuAction;
  3242. }
  3243. return (QAction*)nullptr;
  3244. };
  3245. auto addSource = [this, getActionAfter] (QMenu *popup,
  3246. const char *type, const char *name)
  3247. {
  3248. QString qname = QT_UTF8(name);
  3249. QAction *popupItem = new QAction(qname, this);
  3250. popupItem->setData(QT_UTF8(type));
  3251. connect(popupItem, SIGNAL(triggered(bool)),
  3252. this, SLOT(AddSourceFromAction()));
  3253. QAction *after = getActionAfter(popup, qname);
  3254. popup->insertAction(after, popupItem);
  3255. };
  3256. while (obs_enum_input_types(idx++, &type)) {
  3257. const char *name = obs_source_get_display_name(type);
  3258. uint32_t caps = obs_get_source_output_flags(type);
  3259. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  3260. continue;
  3261. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3262. addSource(popup, type, name);
  3263. } else {
  3264. addSource(deprecated, type, name);
  3265. foundDeprecated = true;
  3266. }
  3267. foundValues = true;
  3268. }
  3269. addSource(popup, "scene", Str("Basic.Scene"));
  3270. popup->addSeparator();
  3271. QAction *addGroup = new QAction(QTStr("Group"), this);
  3272. addGroup->setData(QT_UTF8("group"));
  3273. connect(addGroup, SIGNAL(triggered(bool)),
  3274. this, SLOT(AddSourceFromAction()));
  3275. popup->addAction(addGroup);
  3276. if (!foundDeprecated) {
  3277. delete deprecated;
  3278. deprecated = nullptr;
  3279. }
  3280. if (!foundValues) {
  3281. delete popup;
  3282. popup = nullptr;
  3283. } else if (foundDeprecated) {
  3284. popup->addSeparator();
  3285. popup->addMenu(deprecated);
  3286. }
  3287. return popup;
  3288. }
  3289. void OBSBasic::AddSourceFromAction()
  3290. {
  3291. QAction *action = qobject_cast<QAction*>(sender());
  3292. if (!action)
  3293. return;
  3294. AddSource(QT_TO_UTF8(action->data().toString()));
  3295. }
  3296. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3297. {
  3298. if (!GetCurrentScene()) {
  3299. // Tell the user he needs a scene first (help beginners).
  3300. OBSMessageBox::information(this,
  3301. QTStr("Basic.Main.AddSourceHelp.Title"),
  3302. QTStr("Basic.Main.AddSourceHelp.Text"));
  3303. return;
  3304. }
  3305. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3306. if (popup)
  3307. popup->exec(pos);
  3308. }
  3309. void OBSBasic::on_actionAddSource_triggered()
  3310. {
  3311. AddSourcePopupMenu(QCursor::pos());
  3312. }
  3313. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  3314. {
  3315. vector<OBSSceneItem> &items =
  3316. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3317. if (obs_sceneitem_selected(item)) {
  3318. items.emplace_back(item);
  3319. } else if (obs_sceneitem_is_group(item)) {
  3320. obs_sceneitem_group_enum_items(item, remove_items, &items);
  3321. }
  3322. return true;
  3323. };
  3324. void OBSBasic::on_actionRemoveSource_triggered()
  3325. {
  3326. vector<OBSSceneItem> items;
  3327. obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
  3328. if (!items.size())
  3329. return;
  3330. auto removeMultiple = [this] (size_t count)
  3331. {
  3332. QString text = QTStr("ConfirmRemove.TextMultiple")
  3333. .arg(QString::number(count));
  3334. QMessageBox remove_items(this);
  3335. remove_items.setText(text);
  3336. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3337. QMessageBox::YesRole);
  3338. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3339. remove_items.setIcon(QMessageBox::Question);
  3340. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3341. remove_items.exec();
  3342. return Yes == remove_items.clickedButton();
  3343. };
  3344. if (items.size() == 1) {
  3345. OBSSceneItem &item = items[0];
  3346. obs_source_t *source = obs_sceneitem_get_source(item);
  3347. if (source && QueryRemoveSource(source))
  3348. obs_sceneitem_remove(item);
  3349. } else {
  3350. if (removeMultiple(items.size())) {
  3351. for (auto &item : items)
  3352. obs_sceneitem_remove(item);
  3353. }
  3354. }
  3355. }
  3356. void OBSBasic::on_actionInteract_triggered()
  3357. {
  3358. OBSSceneItem item = GetCurrentSceneItem();
  3359. OBSSource source = obs_sceneitem_get_source(item);
  3360. if (source)
  3361. CreateInteractionWindow(source);
  3362. }
  3363. void OBSBasic::on_actionSourceProperties_triggered()
  3364. {
  3365. OBSSceneItem item = GetCurrentSceneItem();
  3366. OBSSource source = obs_sceneitem_get_source(item);
  3367. if (source)
  3368. CreatePropertiesWindow(source);
  3369. }
  3370. void OBSBasic::on_actionSourceUp_triggered()
  3371. {
  3372. OBSSceneItem item = GetCurrentSceneItem();
  3373. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3374. }
  3375. void OBSBasic::on_actionSourceDown_triggered()
  3376. {
  3377. OBSSceneItem item = GetCurrentSceneItem();
  3378. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3379. }
  3380. void OBSBasic::on_actionMoveUp_triggered()
  3381. {
  3382. OBSSceneItem item = GetCurrentSceneItem();
  3383. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3384. }
  3385. void OBSBasic::on_actionMoveDown_triggered()
  3386. {
  3387. OBSSceneItem item = GetCurrentSceneItem();
  3388. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3389. }
  3390. void OBSBasic::on_actionMoveToTop_triggered()
  3391. {
  3392. OBSSceneItem item = GetCurrentSceneItem();
  3393. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3394. }
  3395. void OBSBasic::on_actionMoveToBottom_triggered()
  3396. {
  3397. OBSSceneItem item = GetCurrentSceneItem();
  3398. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3399. }
  3400. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  3401. {
  3402. char logDir[512];
  3403. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  3404. return nullptr;
  3405. string path = (char*)logDir;
  3406. path += "/";
  3407. path += log;
  3408. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3409. if (!file)
  3410. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3411. return file;
  3412. }
  3413. void OBSBasic::UploadLog(const char *subdir, const char *file)
  3414. {
  3415. BPtr<char> fileString{ReadLogFile(subdir, file)};
  3416. if (!fileString)
  3417. return;
  3418. if (!*fileString)
  3419. return;
  3420. ui->menuLogFiles->setEnabled(false);
  3421. stringstream ss;
  3422. ss << "OBS " << App()->GetVersionString()
  3423. << " log file uploaded at " << CurrentDateTimeString()
  3424. << "\n\n" << fileString;
  3425. if (logUploadThread) {
  3426. logUploadThread->wait();
  3427. delete logUploadThread;
  3428. }
  3429. RemoteTextThread *thread = new RemoteTextThread(
  3430. "https://obsproject.com/logs/upload",
  3431. "text/plain", ss.str().c_str());
  3432. logUploadThread = thread;
  3433. connect(thread, &RemoteTextThread::Result,
  3434. this, &OBSBasic::logUploadFinished);
  3435. logUploadThread->start();
  3436. }
  3437. void OBSBasic::on_actionShowLogs_triggered()
  3438. {
  3439. char logDir[512];
  3440. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3441. return;
  3442. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3443. QDesktopServices::openUrl(url);
  3444. }
  3445. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3446. {
  3447. UploadLog("obs-studio/logs", App()->GetCurrentLog());
  3448. }
  3449. void OBSBasic::on_actionUploadLastLog_triggered()
  3450. {
  3451. UploadLog("obs-studio/logs", App()->GetLastLog());
  3452. }
  3453. void OBSBasic::on_actionViewCurrentLog_triggered()
  3454. {
  3455. char logDir[512];
  3456. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3457. return;
  3458. const char* log = App()->GetCurrentLog();
  3459. string path = (char*)logDir;
  3460. path += "/";
  3461. path += log;
  3462. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3463. QDesktopServices::openUrl(url);
  3464. }
  3465. void OBSBasic::on_actionShowCrashLogs_triggered()
  3466. {
  3467. char logDir[512];
  3468. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  3469. return;
  3470. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3471. QDesktopServices::openUrl(url);
  3472. }
  3473. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  3474. {
  3475. UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
  3476. }
  3477. void OBSBasic::on_actionCheckForUpdates_triggered()
  3478. {
  3479. CheckForUpdates(true);
  3480. }
  3481. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3482. {
  3483. ui->menuLogFiles->setEnabled(true);
  3484. if (text.isEmpty()) {
  3485. OBSMessageBox::information(this,
  3486. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3487. error);
  3488. return;
  3489. }
  3490. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3491. string resURL = obs_data_get_string(returnData, "url");
  3492. QString logURL = resURL.c_str();
  3493. obs_data_release(returnData);
  3494. OBSLogReply logDialog(this, logURL);
  3495. logDialog.exec();
  3496. }
  3497. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3498. obs_source_t *source, const string &name)
  3499. {
  3500. const char *prevName = obs_source_get_name(source);
  3501. if (name == prevName)
  3502. return;
  3503. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3504. QListWidgetItem *listItem = listWidget->currentItem();
  3505. if (foundSource || name.empty()) {
  3506. listItem->setText(QT_UTF8(prevName));
  3507. if (foundSource) {
  3508. OBSMessageBox::information(parent,
  3509. QTStr("NameExists.Title"),
  3510. QTStr("NameExists.Text"));
  3511. } else if (name.empty()) {
  3512. OBSMessageBox::information(parent,
  3513. QTStr("NoNameEntered.Title"),
  3514. QTStr("NoNameEntered.Text"));
  3515. }
  3516. obs_source_release(foundSource);
  3517. } else {
  3518. listItem->setText(QT_UTF8(name.c_str()));
  3519. obs_source_set_name(source, name.c_str());
  3520. }
  3521. }
  3522. void OBSBasic::SceneNameEdited(QWidget *editor,
  3523. QAbstractItemDelegate::EndEditHint endHint)
  3524. {
  3525. OBSScene scene = GetCurrentScene();
  3526. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3527. string text = QT_TO_UTF8(edit->text().trimmed());
  3528. if (!scene)
  3529. return;
  3530. obs_source_t *source = obs_scene_get_source(scene);
  3531. RenameListItem(this, ui->scenes, source, text);
  3532. if (api)
  3533. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3534. UNUSED_PARAMETER(endHint);
  3535. }
  3536. void OBSBasic::OpenFilters()
  3537. {
  3538. OBSSceneItem item = GetCurrentSceneItem();
  3539. OBSSource source = obs_sceneitem_get_source(item);
  3540. CreateFiltersWindow(source);
  3541. }
  3542. void OBSBasic::OpenSceneFilters()
  3543. {
  3544. OBSScene scene = GetCurrentScene();
  3545. OBSSource source = obs_scene_get_source(scene);
  3546. CreateFiltersWindow(source);
  3547. }
  3548. #define RECORDING_START \
  3549. "==== Recording Start ==============================================="
  3550. #define RECORDING_STOP \
  3551. "==== Recording Stop ================================================"
  3552. #define REPLAY_BUFFER_START \
  3553. "==== Replay Buffer Start ==========================================="
  3554. #define REPLAY_BUFFER_STOP \
  3555. "==== Replay Buffer Stop ============================================"
  3556. #define STREAMING_START \
  3557. "==== Streaming Start ==============================================="
  3558. #define STREAMING_STOP \
  3559. "==== Streaming Stop ================================================"
  3560. void OBSBasic::StartStreaming()
  3561. {
  3562. if (outputHandler->StreamingActive())
  3563. return;
  3564. if (disableOutputsRef)
  3565. return;
  3566. if (api)
  3567. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3568. SaveProject();
  3569. ui->streamButton->setEnabled(false);
  3570. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3571. if (sysTrayStream) {
  3572. sysTrayStream->setEnabled(false);
  3573. sysTrayStream->setText(ui->streamButton->text());
  3574. }
  3575. if (!outputHandler->StartStreaming(service)) {
  3576. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3577. ui->streamButton->setEnabled(true);
  3578. ui->streamButton->setChecked(false);
  3579. if (sysTrayStream) {
  3580. sysTrayStream->setText(ui->streamButton->text());
  3581. sysTrayStream->setEnabled(true);
  3582. }
  3583. QMessageBox::critical(this,
  3584. QTStr("Output.StartStreamFailed"),
  3585. QTStr("Output.StartFailedGeneric"));
  3586. return;
  3587. }
  3588. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3589. "BasicWindow", "RecordWhenStreaming");
  3590. if (recordWhenStreaming)
  3591. StartRecording();
  3592. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3593. "BasicWindow", "ReplayBufferWhileStreaming");
  3594. if (replayBufferWhileStreaming)
  3595. StartReplayBuffer();
  3596. }
  3597. #ifdef _WIN32
  3598. static inline void UpdateProcessPriority()
  3599. {
  3600. const char *priority = config_get_string(App()->GlobalConfig(),
  3601. "General", "ProcessPriority");
  3602. if (priority && strcmp(priority, "Normal") != 0)
  3603. SetProcessPriority(priority);
  3604. }
  3605. static inline void ClearProcessPriority()
  3606. {
  3607. const char *priority = config_get_string(App()->GlobalConfig(),
  3608. "General", "ProcessPriority");
  3609. if (priority && strcmp(priority, "Normal") != 0)
  3610. SetProcessPriority("Normal");
  3611. }
  3612. #else
  3613. #define UpdateProcessPriority() do {} while(false)
  3614. #define ClearProcessPriority() do {} while(false)
  3615. #endif
  3616. inline void OBSBasic::OnActivate()
  3617. {
  3618. if (ui->profileMenu->isEnabled()) {
  3619. ui->profileMenu->setEnabled(false);
  3620. ui->autoConfigure->setEnabled(false);
  3621. App()->IncrementSleepInhibition();
  3622. UpdateProcessPriority();
  3623. if (trayIcon)
  3624. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3625. }
  3626. }
  3627. inline void OBSBasic::OnDeactivate()
  3628. {
  3629. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3630. ui->profileMenu->setEnabled(true);
  3631. ui->autoConfigure->setEnabled(true);
  3632. App()->DecrementSleepInhibition();
  3633. ClearProcessPriority();
  3634. if (trayIcon)
  3635. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3636. }
  3637. }
  3638. void OBSBasic::StopStreaming()
  3639. {
  3640. SaveProject();
  3641. if (outputHandler->StreamingActive())
  3642. outputHandler->StopStreaming(streamingStopping);
  3643. OnDeactivate();
  3644. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3645. "BasicWindow", "RecordWhenStreaming");
  3646. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3647. "BasicWindow", "KeepRecordingWhenStreamStops");
  3648. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3649. StopRecording();
  3650. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3651. "BasicWindow", "ReplayBufferWhileStreaming");
  3652. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3653. "BasicWindow", "KeepReplayBufferStreamStops");
  3654. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3655. StopReplayBuffer();
  3656. }
  3657. void OBSBasic::ForceStopStreaming()
  3658. {
  3659. SaveProject();
  3660. if (outputHandler->StreamingActive())
  3661. outputHandler->StopStreaming(true);
  3662. OnDeactivate();
  3663. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3664. "BasicWindow", "RecordWhenStreaming");
  3665. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3666. "BasicWindow", "KeepRecordingWhenStreamStops");
  3667. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3668. StopRecording();
  3669. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3670. "BasicWindow", "ReplayBufferWhileStreaming");
  3671. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3672. "BasicWindow", "KeepReplayBufferStreamStops");
  3673. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3674. StopReplayBuffer();
  3675. }
  3676. void OBSBasic::StreamDelayStarting(int sec)
  3677. {
  3678. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3679. ui->streamButton->setEnabled(true);
  3680. ui->streamButton->setChecked(true);
  3681. if (sysTrayStream) {
  3682. sysTrayStream->setText(ui->streamButton->text());
  3683. sysTrayStream->setEnabled(true);
  3684. }
  3685. if (!startStreamMenu.isNull())
  3686. startStreamMenu->deleteLater();
  3687. startStreamMenu = new QMenu();
  3688. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3689. this, SLOT(StopStreaming()));
  3690. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3691. this, SLOT(ForceStopStreaming()));
  3692. ui->streamButton->setMenu(startStreamMenu);
  3693. ui->statusbar->StreamDelayStarting(sec);
  3694. OnActivate();
  3695. }
  3696. void OBSBasic::StreamDelayStopping(int sec)
  3697. {
  3698. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3699. ui->streamButton->setEnabled(true);
  3700. ui->streamButton->setChecked(false);
  3701. if (sysTrayStream) {
  3702. sysTrayStream->setText(ui->streamButton->text());
  3703. sysTrayStream->setEnabled(true);
  3704. }
  3705. if (!startStreamMenu.isNull())
  3706. startStreamMenu->deleteLater();
  3707. startStreamMenu = new QMenu();
  3708. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3709. this, SLOT(StartStreaming()));
  3710. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3711. this, SLOT(ForceStopStreaming()));
  3712. ui->streamButton->setMenu(startStreamMenu);
  3713. ui->statusbar->StreamDelayStopping(sec);
  3714. }
  3715. void OBSBasic::StreamingStart()
  3716. {
  3717. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3718. ui->streamButton->setEnabled(true);
  3719. ui->streamButton->setChecked(true);
  3720. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3721. if (sysTrayStream) {
  3722. sysTrayStream->setText(ui->streamButton->text());
  3723. sysTrayStream->setEnabled(true);
  3724. }
  3725. if (api)
  3726. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3727. OnActivate();
  3728. blog(LOG_INFO, STREAMING_START);
  3729. }
  3730. void OBSBasic::StreamStopping()
  3731. {
  3732. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3733. if (sysTrayStream)
  3734. sysTrayStream->setText(ui->streamButton->text());
  3735. streamingStopping = true;
  3736. if (api)
  3737. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3738. }
  3739. void OBSBasic::StreamingStop(int code, QString last_error)
  3740. {
  3741. const char *errorDescription;
  3742. DStr errorMessage;
  3743. bool use_last_error = false;
  3744. switch (code) {
  3745. case OBS_OUTPUT_BAD_PATH:
  3746. errorDescription = Str("Output.ConnectFail.BadPath");
  3747. break;
  3748. case OBS_OUTPUT_CONNECT_FAILED:
  3749. use_last_error = true;
  3750. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3751. break;
  3752. case OBS_OUTPUT_INVALID_STREAM:
  3753. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3754. break;
  3755. default:
  3756. case OBS_OUTPUT_ERROR:
  3757. use_last_error = true;
  3758. errorDescription = Str("Output.ConnectFail.Error");
  3759. break;
  3760. case OBS_OUTPUT_DISCONNECTED:
  3761. /* doesn't happen if output is set to reconnect. note that
  3762. * reconnects are handled in the output, not in the UI */
  3763. use_last_error = true;
  3764. errorDescription = Str("Output.ConnectFail.Disconnected");
  3765. }
  3766. if (use_last_error && !last_error.isEmpty())
  3767. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3768. QT_TO_UTF8(last_error));
  3769. else
  3770. dstr_copy(errorMessage, errorDescription);
  3771. ui->statusbar->StreamStopped();
  3772. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3773. ui->streamButton->setEnabled(true);
  3774. ui->streamButton->setChecked(false);
  3775. if (sysTrayStream) {
  3776. sysTrayStream->setText(ui->streamButton->text());
  3777. sysTrayStream->setEnabled(true);
  3778. }
  3779. streamingStopping = false;
  3780. if (api)
  3781. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3782. OnDeactivate();
  3783. blog(LOG_INFO, STREAMING_STOP);
  3784. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3785. OBSMessageBox::information(this,
  3786. QTStr("Output.ConnectFail.Title"),
  3787. QT_UTF8(errorMessage));
  3788. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3789. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3790. }
  3791. if (!startStreamMenu.isNull()) {
  3792. ui->streamButton->setMenu(nullptr);
  3793. startStreamMenu->deleteLater();
  3794. startStreamMenu = nullptr;
  3795. }
  3796. }
  3797. void OBSBasic::StartRecording()
  3798. {
  3799. if (outputHandler->RecordingActive())
  3800. return;
  3801. if (disableOutputsRef)
  3802. return;
  3803. if (api)
  3804. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3805. SaveProject();
  3806. outputHandler->StartRecording();
  3807. }
  3808. void OBSBasic::RecordStopping()
  3809. {
  3810. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3811. if (sysTrayRecord)
  3812. sysTrayRecord->setText(ui->recordButton->text());
  3813. recordingStopping = true;
  3814. if (api)
  3815. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3816. }
  3817. void OBSBasic::StopRecording()
  3818. {
  3819. SaveProject();
  3820. if (outputHandler->RecordingActive())
  3821. outputHandler->StopRecording(recordingStopping);
  3822. OnDeactivate();
  3823. }
  3824. void OBSBasic::RecordingStart()
  3825. {
  3826. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3827. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3828. ui->recordButton->setChecked(true);
  3829. if (sysTrayRecord)
  3830. sysTrayRecord->setText(ui->recordButton->text());
  3831. recordingStopping = false;
  3832. if (api)
  3833. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3834. OnActivate();
  3835. blog(LOG_INFO, RECORDING_START);
  3836. }
  3837. void OBSBasic::RecordingStop(int code)
  3838. {
  3839. ui->statusbar->RecordingStopped();
  3840. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3841. ui->recordButton->setChecked(false);
  3842. if (sysTrayRecord)
  3843. sysTrayRecord->setText(ui->recordButton->text());
  3844. blog(LOG_INFO, RECORDING_STOP);
  3845. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3846. OBSMessageBox::information(this,
  3847. QTStr("Output.RecordFail.Title"),
  3848. QTStr("Output.RecordFail.Unsupported"));
  3849. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3850. OBSMessageBox::information(this,
  3851. QTStr("Output.RecordNoSpace.Title"),
  3852. QTStr("Output.RecordNoSpace.Msg"));
  3853. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3854. OBSMessageBox::information(this,
  3855. QTStr("Output.RecordError.Title"),
  3856. QTStr("Output.RecordError.Msg"));
  3857. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3858. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3859. QSystemTrayIcon::Warning);
  3860. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3861. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3862. QSystemTrayIcon::Warning);
  3863. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3864. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3865. QSystemTrayIcon::Warning);
  3866. }
  3867. if (api)
  3868. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3869. OnDeactivate();
  3870. }
  3871. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3872. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3873. void OBSBasic::StartReplayBuffer()
  3874. {
  3875. if (!outputHandler || !outputHandler->replayBuffer)
  3876. return;
  3877. if (outputHandler->ReplayBufferActive())
  3878. return;
  3879. if (disableOutputsRef)
  3880. return;
  3881. obs_output_t *output = outputHandler->replayBuffer;
  3882. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3883. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3884. "ReplayBuffer.Save");
  3885. size_t count = obs_data_array_count(bindings);
  3886. obs_data_array_release(bindings);
  3887. obs_data_release(hotkeys);
  3888. if (!count) {
  3889. OBSMessageBox::information(this,
  3890. RP_NO_HOTKEY_TITLE,
  3891. RP_NO_HOTKEY_TEXT);
  3892. return;
  3893. }
  3894. if (api)
  3895. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3896. SaveProject();
  3897. outputHandler->StartReplayBuffer();
  3898. }
  3899. void OBSBasic::ReplayBufferStopping()
  3900. {
  3901. if (!outputHandler || !outputHandler->replayBuffer)
  3902. return;
  3903. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3904. if (sysTrayReplayBuffer)
  3905. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3906. replayBufferStopping = true;
  3907. if (api)
  3908. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3909. }
  3910. void OBSBasic::StopReplayBuffer()
  3911. {
  3912. if (!outputHandler || !outputHandler->replayBuffer)
  3913. return;
  3914. SaveProject();
  3915. if (outputHandler->ReplayBufferActive())
  3916. outputHandler->StopReplayBuffer(replayBufferStopping);
  3917. OnDeactivate();
  3918. }
  3919. void OBSBasic::ReplayBufferStart()
  3920. {
  3921. if (!outputHandler || !outputHandler->replayBuffer)
  3922. return;
  3923. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3924. if (sysTrayReplayBuffer)
  3925. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3926. replayBufferStopping = false;
  3927. if (api)
  3928. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3929. OnActivate();
  3930. blog(LOG_INFO, REPLAY_BUFFER_START);
  3931. }
  3932. void OBSBasic::ReplayBufferSave()
  3933. {
  3934. if (!outputHandler || !outputHandler->replayBuffer)
  3935. return;
  3936. if (!outputHandler->ReplayBufferActive())
  3937. return;
  3938. calldata_t cd = {0};
  3939. proc_handler_t *ph = obs_output_get_proc_handler(
  3940. outputHandler->replayBuffer);
  3941. proc_handler_call(ph, "save", &cd);
  3942. calldata_free(&cd);
  3943. }
  3944. void OBSBasic::ReplayBufferStop(int code)
  3945. {
  3946. if (!outputHandler || !outputHandler->replayBuffer)
  3947. return;
  3948. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3949. if (sysTrayReplayBuffer)
  3950. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3951. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3952. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3953. OBSMessageBox::information(this,
  3954. QTStr("Output.RecordFail.Title"),
  3955. QTStr("Output.RecordFail.Unsupported"));
  3956. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3957. OBSMessageBox::information(this,
  3958. QTStr("Output.RecordNoSpace.Title"),
  3959. QTStr("Output.RecordNoSpace.Msg"));
  3960. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3961. OBSMessageBox::information(this,
  3962. QTStr("Output.RecordError.Title"),
  3963. QTStr("Output.RecordError.Msg"));
  3964. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3965. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3966. QSystemTrayIcon::Warning);
  3967. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3968. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3969. QSystemTrayIcon::Warning);
  3970. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3971. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3972. QSystemTrayIcon::Warning);
  3973. }
  3974. if (api)
  3975. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3976. OnDeactivate();
  3977. }
  3978. void OBSBasic::on_streamButton_clicked()
  3979. {
  3980. if (outputHandler->StreamingActive()) {
  3981. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3982. "WarnBeforeStoppingStream");
  3983. if (confirm && isVisible()) {
  3984. QMessageBox::StandardButton button =
  3985. OBSMessageBox::question(this,
  3986. QTStr("ConfirmStop.Title"),
  3987. QTStr("ConfirmStop.Text"));
  3988. if (button == QMessageBox::No) {
  3989. ui->streamButton->setChecked(true);
  3990. return;
  3991. }
  3992. }
  3993. StopStreaming();
  3994. } else {
  3995. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3996. "WarnBeforeStartingStream");
  3997. if (confirm && isVisible()) {
  3998. QMessageBox::StandardButton button =
  3999. OBSMessageBox::question(this,
  4000. QTStr("ConfirmStart.Title"),
  4001. QTStr("ConfirmStart.Text"));
  4002. if (button == QMessageBox::No) {
  4003. ui->streamButton->setChecked(false);
  4004. return;
  4005. }
  4006. }
  4007. StartStreaming();
  4008. }
  4009. }
  4010. void OBSBasic::on_recordButton_clicked()
  4011. {
  4012. if (outputHandler->RecordingActive())
  4013. StopRecording();
  4014. else
  4015. StartRecording();
  4016. }
  4017. void OBSBasic::on_settingsButton_clicked()
  4018. {
  4019. on_action_Settings_triggered();
  4020. }
  4021. void OBSBasic::on_actionHelpPortal_triggered()
  4022. {
  4023. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  4024. QDesktopServices::openUrl(url);
  4025. }
  4026. void OBSBasic::on_actionWebsite_triggered()
  4027. {
  4028. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  4029. QDesktopServices::openUrl(url);
  4030. }
  4031. void OBSBasic::on_actionShowSettingsFolder_triggered()
  4032. {
  4033. char path[512];
  4034. int ret = GetConfigPath(path, 512, "obs-studio");
  4035. if (ret <= 0)
  4036. return;
  4037. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4038. }
  4039. void OBSBasic::on_actionShowProfileFolder_triggered()
  4040. {
  4041. char path[512];
  4042. int ret = GetProfilePath(path, 512, "");
  4043. if (ret <= 0)
  4044. return;
  4045. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4046. }
  4047. int OBSBasic::GetTopSelectedSourceItem()
  4048. {
  4049. QModelIndexList selectedItems =
  4050. ui->sources->selectionModel()->selectedIndexes();
  4051. return selectedItems.count() ? selectedItems[0].row() : -1;
  4052. }
  4053. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  4054. {
  4055. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  4056. UNUSED_PARAMETER(pos);
  4057. }
  4058. void OBSBasic::on_program_customContextMenuRequested(const QPoint&)
  4059. {
  4060. QMenu popup(this);
  4061. QPointer<QMenu> studioProgramProjector;
  4062. studioProgramProjector = new QMenu(
  4063. QTStr("StudioProgramProjector"));
  4064. AddProjectorMenuMonitors(studioProgramProjector, this,
  4065. SLOT(OpenStudioProgramProjector()));
  4066. popup.addMenu(studioProgramProjector);
  4067. QAction *studioProgramWindow = popup.addAction(
  4068. QTStr("StudioProgramWindow"),
  4069. this, SLOT(OpenStudioProgramWindow()));
  4070. popup.addAction(studioProgramWindow);
  4071. popup.exec(QCursor::pos());
  4072. }
  4073. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  4074. const QPoint &pos)
  4075. {
  4076. QMenu popup(this);
  4077. QPointer<QMenu> previewProjector;
  4078. QAction *action = popup.addAction(
  4079. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  4080. this, SLOT(TogglePreview()));
  4081. action->setCheckable(true);
  4082. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  4083. previewProjector = new QMenu(QTStr("PreviewProjector"));
  4084. AddProjectorMenuMonitors(previewProjector, this,
  4085. SLOT(OpenPreviewProjector()));
  4086. QAction *previewWindow = popup.addAction(
  4087. QTStr("PreviewWindow"),
  4088. this, SLOT(OpenPreviewWindow()));
  4089. popup.addMenu(previewProjector);
  4090. popup.addAction(previewWindow);
  4091. popup.exec(QCursor::pos());
  4092. UNUSED_PARAMETER(pos);
  4093. }
  4094. void OBSBasic::on_actionAlwaysOnTop_triggered()
  4095. {
  4096. #ifndef _WIN32
  4097. /* Make sure all dialogs are safely and successfully closed before
  4098. * switching the always on top mode due to the fact that windows all
  4099. * have to be recreated, so queue the actual toggle to happen after
  4100. * all events related to closing the dialogs have finished */
  4101. CloseDialogs();
  4102. #endif
  4103. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  4104. Qt::QueuedConnection);
  4105. }
  4106. void OBSBasic::ToggleAlwaysOnTop()
  4107. {
  4108. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  4109. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  4110. SetAlwaysOnTop(this, !isAlwaysOnTop);
  4111. show();
  4112. }
  4113. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  4114. {
  4115. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  4116. if (strcmp(val, "10") == 0) {
  4117. num = 10;
  4118. den = 1;
  4119. } else if (strcmp(val, "20") == 0) {
  4120. num = 20;
  4121. den = 1;
  4122. } else if (strcmp(val, "24 NTSC") == 0) {
  4123. num = 24000;
  4124. den = 1001;
  4125. } else if (strcmp(val, "25") == 0) {
  4126. num = 25;
  4127. den = 1;
  4128. } else if (strcmp(val, "29.97") == 0) {
  4129. num = 30000;
  4130. den = 1001;
  4131. } else if (strcmp(val, "48") == 0) {
  4132. num = 48;
  4133. den = 1;
  4134. } else if (strcmp(val, "59.94") == 0) {
  4135. num = 60000;
  4136. den = 1001;
  4137. } else if (strcmp(val, "60") == 0) {
  4138. num = 60;
  4139. den = 1;
  4140. } else {
  4141. num = 30;
  4142. den = 1;
  4143. }
  4144. }
  4145. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  4146. {
  4147. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  4148. den = 1;
  4149. }
  4150. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  4151. {
  4152. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  4153. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  4154. }
  4155. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  4156. {
  4157. num = 1000000000;
  4158. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  4159. }
  4160. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  4161. {
  4162. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  4163. if (type == 1) //"Integer"
  4164. GetFPSInteger(num, den);
  4165. else if (type == 2) //"Fraction"
  4166. GetFPSFraction(num, den);
  4167. else if (false) //"Nanoseconds", currently not implemented
  4168. GetFPSNanoseconds(num, den);
  4169. else
  4170. GetFPSCommon(num, den);
  4171. }
  4172. config_t *OBSBasic::Config() const
  4173. {
  4174. return basicConfig;
  4175. }
  4176. void OBSBasic::on_actionEditTransform_triggered()
  4177. {
  4178. if (transformWindow)
  4179. transformWindow->close();
  4180. transformWindow = new OBSBasicTransform(this);
  4181. transformWindow->show();
  4182. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4183. }
  4184. static obs_transform_info copiedTransformInfo;
  4185. static obs_sceneitem_crop copiedCropInfo;
  4186. void OBSBasic::on_actionCopyTransform_triggered()
  4187. {
  4188. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4189. {
  4190. if (!obs_sceneitem_selected(item))
  4191. return true;
  4192. obs_sceneitem_defer_update_begin(item);
  4193. obs_sceneitem_get_info(item, &copiedTransformInfo);
  4194. obs_sceneitem_get_crop(item, &copiedCropInfo);
  4195. obs_sceneitem_defer_update_end(item);
  4196. UNUSED_PARAMETER(scene);
  4197. UNUSED_PARAMETER(param);
  4198. return true;
  4199. };
  4200. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4201. ui->actionPasteTransform->setEnabled(true);
  4202. }
  4203. void OBSBasic::on_actionPasteTransform_triggered()
  4204. {
  4205. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4206. {
  4207. if (!obs_sceneitem_selected(item))
  4208. return true;
  4209. obs_sceneitem_defer_update_begin(item);
  4210. obs_sceneitem_set_info(item, &copiedTransformInfo);
  4211. obs_sceneitem_set_crop(item, &copiedCropInfo);
  4212. obs_sceneitem_defer_update_end(item);
  4213. UNUSED_PARAMETER(scene);
  4214. UNUSED_PARAMETER(param);
  4215. return true;
  4216. };
  4217. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4218. }
  4219. void OBSBasic::on_actionResetTransform_triggered()
  4220. {
  4221. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4222. {
  4223. if (!obs_sceneitem_selected(item))
  4224. return true;
  4225. obs_sceneitem_defer_update_begin(item);
  4226. obs_transform_info info;
  4227. vec2_set(&info.pos, 0.0f, 0.0f);
  4228. vec2_set(&info.scale, 1.0f, 1.0f);
  4229. info.rot = 0.0f;
  4230. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  4231. info.bounds_type = OBS_BOUNDS_NONE;
  4232. info.bounds_alignment = OBS_ALIGN_CENTER;
  4233. vec2_set(&info.bounds, 0.0f, 0.0f);
  4234. obs_sceneitem_set_info(item, &info);
  4235. obs_sceneitem_crop crop = {};
  4236. obs_sceneitem_set_crop(item, &crop);
  4237. obs_sceneitem_defer_update_end(item);
  4238. UNUSED_PARAMETER(scene);
  4239. UNUSED_PARAMETER(param);
  4240. return true;
  4241. };
  4242. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4243. }
  4244. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  4245. {
  4246. matrix4 boxTransform;
  4247. obs_sceneitem_get_box_transform(item, &boxTransform);
  4248. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  4249. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  4250. auto GetMinPos = [&] (float x, float y)
  4251. {
  4252. vec3 pos;
  4253. vec3_set(&pos, x, y, 0.0f);
  4254. vec3_transform(&pos, &pos, &boxTransform);
  4255. vec3_min(&tl, &tl, &pos);
  4256. vec3_max(&br, &br, &pos);
  4257. };
  4258. GetMinPos(0.0f, 0.0f);
  4259. GetMinPos(1.0f, 0.0f);
  4260. GetMinPos(0.0f, 1.0f);
  4261. GetMinPos(1.0f, 1.0f);
  4262. }
  4263. static vec3 GetItemTL(obs_sceneitem_t *item)
  4264. {
  4265. vec3 tl, br;
  4266. GetItemBox(item, tl, br);
  4267. return tl;
  4268. }
  4269. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4270. {
  4271. vec3 newTL;
  4272. vec2 pos;
  4273. obs_sceneitem_get_pos(item, &pos);
  4274. newTL = GetItemTL(item);
  4275. pos.x += tl.x - newTL.x;
  4276. pos.y += tl.y - newTL.y;
  4277. obs_sceneitem_set_pos(item, &pos);
  4278. }
  4279. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4280. void *param)
  4281. {
  4282. if (!obs_sceneitem_selected(item))
  4283. return true;
  4284. float rot = *reinterpret_cast<float*>(param);
  4285. vec3 tl = GetItemTL(item);
  4286. rot += obs_sceneitem_get_rot(item);
  4287. if (rot >= 360.0f) rot -= 360.0f;
  4288. else if (rot <= -360.0f) rot += 360.0f;
  4289. obs_sceneitem_set_rot(item, rot);
  4290. SetItemTL(item, tl);
  4291. UNUSED_PARAMETER(scene);
  4292. UNUSED_PARAMETER(param);
  4293. return true;
  4294. };
  4295. void OBSBasic::on_actionRotate90CW_triggered()
  4296. {
  4297. float f90CW = 90.0f;
  4298. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4299. }
  4300. void OBSBasic::on_actionRotate90CCW_triggered()
  4301. {
  4302. float f90CCW = -90.0f;
  4303. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4304. }
  4305. void OBSBasic::on_actionRotate180_triggered()
  4306. {
  4307. float f180 = 180.0f;
  4308. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4309. }
  4310. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4311. void *param)
  4312. {
  4313. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4314. if (!obs_sceneitem_selected(item))
  4315. return true;
  4316. vec3 tl = GetItemTL(item);
  4317. vec2 scale;
  4318. obs_sceneitem_get_scale(item, &scale);
  4319. vec2_mul(&scale, &scale, &mul);
  4320. obs_sceneitem_set_scale(item, &scale);
  4321. SetItemTL(item, tl);
  4322. UNUSED_PARAMETER(scene);
  4323. return true;
  4324. }
  4325. void OBSBasic::on_actionFlipHorizontal_triggered()
  4326. {
  4327. vec2 scale;
  4328. vec2_set(&scale, -1.0f, 1.0f);
  4329. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4330. &scale);
  4331. }
  4332. void OBSBasic::on_actionFlipVertical_triggered()
  4333. {
  4334. vec2 scale;
  4335. vec2_set(&scale, 1.0f, -1.0f);
  4336. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4337. &scale);
  4338. }
  4339. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4340. void *param)
  4341. {
  4342. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4343. if (!obs_sceneitem_selected(item))
  4344. return true;
  4345. obs_video_info ovi;
  4346. obs_get_video_info(&ovi);
  4347. obs_transform_info itemInfo;
  4348. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4349. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4350. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4351. itemInfo.rot = 0.0f;
  4352. vec2_set(&itemInfo.bounds,
  4353. float(ovi.base_width), float(ovi.base_height));
  4354. itemInfo.bounds_type = boundsType;
  4355. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4356. obs_sceneitem_set_info(item, &itemInfo);
  4357. UNUSED_PARAMETER(scene);
  4358. return true;
  4359. }
  4360. void OBSBasic::on_actionFitToScreen_triggered()
  4361. {
  4362. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4363. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4364. &boundsType);
  4365. }
  4366. void OBSBasic::on_actionStretchToScreen_triggered()
  4367. {
  4368. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4369. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4370. &boundsType);
  4371. }
  4372. void OBSBasic::on_actionCenterToScreen_triggered()
  4373. {
  4374. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4375. {
  4376. vec3 tl, br, itemCenter, screenCenter, offset;
  4377. obs_video_info ovi;
  4378. if (!obs_sceneitem_selected(item))
  4379. return true;
  4380. obs_get_video_info(&ovi);
  4381. vec3_set(&screenCenter, float(ovi.base_width),
  4382. float(ovi.base_height), 0.0f);
  4383. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4384. GetItemBox(item, tl, br);
  4385. vec3_sub(&itemCenter, &br, &tl);
  4386. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4387. vec3_add(&itemCenter, &itemCenter, &tl);
  4388. vec3_sub(&offset, &screenCenter, &itemCenter);
  4389. vec3_add(&tl, &tl, &offset);
  4390. SetItemTL(item, tl);
  4391. UNUSED_PARAMETER(scene);
  4392. UNUSED_PARAMETER(param);
  4393. return true;
  4394. };
  4395. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4396. }
  4397. void OBSBasic::EnablePreviewDisplay(bool enable)
  4398. {
  4399. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4400. ui->preview->setVisible(enable);
  4401. ui->previewDisabledLabel->setVisible(!enable);
  4402. }
  4403. void OBSBasic::TogglePreview()
  4404. {
  4405. previewEnabled = !previewEnabled;
  4406. EnablePreviewDisplay(previewEnabled);
  4407. }
  4408. static bool nudge_callback(obs_scene_t*, obs_sceneitem_t *item, void *param)
  4409. {
  4410. if (obs_sceneitem_locked(item))
  4411. return true;
  4412. struct vec2 &offset = *reinterpret_cast<struct vec2*>(param);
  4413. struct vec2 pos;
  4414. if (!obs_sceneitem_selected(item)) {
  4415. if (obs_sceneitem_is_group(item)) {
  4416. struct vec3 offset3;
  4417. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  4418. struct matrix4 matrix;
  4419. obs_sceneitem_get_draw_transform(item, &matrix);
  4420. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  4421. matrix4_inv(&matrix, &matrix);
  4422. vec3_transform(&offset3, &offset3, &matrix);
  4423. struct vec2 new_offset;
  4424. vec2_set(&new_offset, offset3.x, offset3.y);
  4425. obs_sceneitem_group_enum_items(item, nudge_callback,
  4426. &new_offset);
  4427. }
  4428. return true;
  4429. }
  4430. obs_sceneitem_get_pos(item, &pos);
  4431. vec2_add(&pos, &pos, &offset);
  4432. obs_sceneitem_set_pos(item, &pos);
  4433. return true;
  4434. }
  4435. void OBSBasic::Nudge(int dist, MoveDir dir)
  4436. {
  4437. if (ui->preview->Locked())
  4438. return;
  4439. struct vec2 offset;
  4440. vec2_set(&offset, 0.0f, 0.0f);
  4441. switch (dir) {
  4442. case MoveDir::Up: offset.y = (float)-dist; break;
  4443. case MoveDir::Down: offset.y = (float) dist; break;
  4444. case MoveDir::Left: offset.x = (float)-dist; break;
  4445. case MoveDir::Right: offset.x = (float) dist; break;
  4446. }
  4447. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  4448. }
  4449. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4450. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4451. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4452. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4453. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  4454. QString title, ProjectorType type)
  4455. {
  4456. /* seriously? 10 monitors? */
  4457. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4458. return nullptr;
  4459. OBSProjector *projector = new OBSProjector(nullptr, source, monitor,
  4460. title, type);
  4461. if (monitor < 0) {
  4462. for (auto &projPtr : windowProjectors) {
  4463. if (!projPtr) {
  4464. projPtr = projector;
  4465. projector = nullptr;
  4466. }
  4467. }
  4468. if (projector)
  4469. windowProjectors.push_back(projector);
  4470. } else {
  4471. delete projectors[monitor];
  4472. projectors[monitor].clear();
  4473. projectors[monitor] = projector;
  4474. }
  4475. return projector;
  4476. }
  4477. void OBSBasic::OpenStudioProgramProjector()
  4478. {
  4479. int monitor = sender()->property("monitor").toInt();
  4480. OpenProjector(nullptr, monitor, nullptr, ProjectorType::StudioProgram);
  4481. }
  4482. void OBSBasic::OpenPreviewProjector()
  4483. {
  4484. int monitor = sender()->property("monitor").toInt();
  4485. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Preview);
  4486. }
  4487. void OBSBasic::OpenSourceProjector()
  4488. {
  4489. int monitor = sender()->property("monitor").toInt();
  4490. OBSSceneItem item = GetCurrentSceneItem();
  4491. if (!item)
  4492. return;
  4493. OpenProjector(obs_sceneitem_get_source(item), monitor, nullptr,
  4494. ProjectorType::Source);
  4495. }
  4496. void OBSBasic::OpenMultiviewProjector()
  4497. {
  4498. int monitor = sender()->property("monitor").toInt();
  4499. OpenProjector(nullptr, monitor, nullptr, ProjectorType::Multiview);
  4500. }
  4501. void OBSBasic::OpenSceneProjector()
  4502. {
  4503. int monitor = sender()->property("monitor").toInt();
  4504. OBSScene scene = GetCurrentScene();
  4505. if (!scene)
  4506. return;
  4507. OpenProjector(obs_scene_get_source(scene), monitor, nullptr,
  4508. ProjectorType::Scene);
  4509. }
  4510. void OBSBasic::OpenStudioProgramWindow()
  4511. {
  4512. OpenProjector(nullptr, -1, QTStr("StudioProgramWindow"),
  4513. ProjectorType::StudioProgram);
  4514. }
  4515. void OBSBasic::OpenPreviewWindow()
  4516. {
  4517. OpenProjector(nullptr, -1, QTStr("PreviewWindow"),
  4518. ProjectorType::Preview);
  4519. }
  4520. void OBSBasic::OpenSourceWindow()
  4521. {
  4522. OBSSceneItem item = GetCurrentSceneItem();
  4523. if (!item)
  4524. return;
  4525. OBSSource source = obs_sceneitem_get_source(item);
  4526. QString title = QString::fromUtf8(obs_source_get_name(source));
  4527. OpenProjector(obs_sceneitem_get_source(item), -1, title,
  4528. ProjectorType::Source);
  4529. }
  4530. void OBSBasic::OpenMultiviewWindow()
  4531. {
  4532. OpenProjector(nullptr, -1, QTStr("MultiviewWindowed"),
  4533. ProjectorType::Multiview);
  4534. }
  4535. void OBSBasic::OpenSceneWindow()
  4536. {
  4537. OBSScene scene = GetCurrentScene();
  4538. if (!scene)
  4539. return;
  4540. OBSSource source = obs_scene_get_source(scene);
  4541. QString title = QString::fromUtf8(obs_source_get_name(source));
  4542. OpenProjector(obs_scene_get_source(scene), -1, title,
  4543. ProjectorType::Scene);
  4544. }
  4545. void OBSBasic::OpenSavedProjectors()
  4546. {
  4547. for (SavedProjectorInfo *info : savedProjectorsArray) {
  4548. OBSProjector *projector = nullptr;
  4549. switch (info->type) {
  4550. case ProjectorType::Source:
  4551. case ProjectorType::Scene: {
  4552. OBSSource source = obs_get_source_by_name(
  4553. info->name.c_str());
  4554. if (!source)
  4555. continue;
  4556. QString title = nullptr;
  4557. if (info->monitor < 0)
  4558. title = QString::fromUtf8(
  4559. obs_source_get_name(source));
  4560. projector = OpenProjector(source, info->monitor, title,
  4561. info->type);
  4562. obs_source_release(source);
  4563. break;
  4564. }
  4565. case ProjectorType::Preview: {
  4566. projector = OpenProjector(nullptr, info->monitor,
  4567. QTStr("PreviewWindow"),
  4568. ProjectorType::Preview);
  4569. break;
  4570. }
  4571. case ProjectorType::StudioProgram: {
  4572. projector = OpenProjector(nullptr, info->monitor,
  4573. QTStr("StudioProgramWindow"),
  4574. ProjectorType::StudioProgram);
  4575. break;
  4576. }
  4577. case ProjectorType::Multiview: {
  4578. projector = OpenProjector(nullptr, info->monitor,
  4579. QTStr("MultiviewWindowed"),
  4580. ProjectorType::Multiview);
  4581. break;
  4582. }
  4583. }
  4584. if (projector && !info->geometry.empty()) {
  4585. QByteArray byteArray = QByteArray::fromBase64(
  4586. QByteArray(info->geometry.c_str()));
  4587. projector->restoreGeometry(byteArray);
  4588. if (!WindowPositionValid(projector->normalGeometry())) {
  4589. QRect rect = App()->desktop()->geometry();
  4590. projector->setGeometry(QStyle::alignedRect(
  4591. Qt::LeftToRight,
  4592. Qt::AlignCenter, size(), rect));
  4593. }
  4594. }
  4595. }
  4596. }
  4597. void OBSBasic::on_actionFullscreenInterface_triggered()
  4598. {
  4599. if (!fullscreenInterface)
  4600. showFullScreen();
  4601. else
  4602. showNormal();
  4603. fullscreenInterface = !fullscreenInterface;
  4604. }
  4605. void OBSBasic::UpdateTitleBar()
  4606. {
  4607. stringstream name;
  4608. const char *profile = config_get_string(App()->GlobalConfig(),
  4609. "Basic", "Profile");
  4610. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4611. "Basic", "SceneCollection");
  4612. name << "OBS ";
  4613. if (previewProgramMode)
  4614. name << "Studio ";
  4615. name << App()->GetVersionString();
  4616. if (App()->IsPortableMode())
  4617. name << " - Portable Mode";
  4618. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4619. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4620. setWindowTitle(QT_UTF8(name.str().c_str()));
  4621. }
  4622. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4623. {
  4624. char profiles_path[512];
  4625. const char *profile = config_get_string(App()->GlobalConfig(),
  4626. "Basic", "ProfileDir");
  4627. int ret;
  4628. if (!profile)
  4629. return -1;
  4630. if (!path)
  4631. return -1;
  4632. if (!file)
  4633. file = "";
  4634. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4635. if (ret <= 0)
  4636. return ret;
  4637. if (!*file)
  4638. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4639. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4640. }
  4641. void OBSBasic::on_resetUI_triggered()
  4642. {
  4643. restoreState(startingDockLayout);
  4644. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4645. int cx = width();
  4646. int cy = height();
  4647. int cx22_5 = cx * 225 / 1000;
  4648. int cx5 = cx * 5 / 100;
  4649. cy = cy * 225 / 1000;
  4650. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4651. QList<QDockWidget*> docks {
  4652. ui->scenesDock,
  4653. ui->sourcesDock,
  4654. ui->mixerDock,
  4655. ui->transitionsDock,
  4656. ui->controlsDock
  4657. };
  4658. QList<int> sizes {
  4659. cx22_5,
  4660. cx22_5,
  4661. mixerSize,
  4662. cx5,
  4663. cx5
  4664. };
  4665. ui->scenesDock->setVisible(true);
  4666. ui->sourcesDock->setVisible(true);
  4667. ui->mixerDock->setVisible(true);
  4668. ui->transitionsDock->setVisible(true);
  4669. ui->controlsDock->setVisible(true);
  4670. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4671. resizeDocks(docks, sizes, Qt::Horizontal);
  4672. #endif
  4673. }
  4674. void OBSBasic::on_lockUI_toggled(bool lock)
  4675. {
  4676. QDockWidget::DockWidgetFeatures features = lock
  4677. ? QDockWidget::NoDockWidgetFeatures
  4678. : QDockWidget::AllDockWidgetFeatures;
  4679. ui->scenesDock->setFeatures(features);
  4680. ui->sourcesDock->setFeatures(features);
  4681. ui->mixerDock->setFeatures(features);
  4682. ui->transitionsDock->setFeatures(features);
  4683. ui->controlsDock->setFeatures(features);
  4684. }
  4685. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4686. {
  4687. ui->sourcesToolbar->setVisible(visible);
  4688. ui->scenesToolbar->setVisible(visible);
  4689. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4690. "ShowListboxToolbars", visible);
  4691. }
  4692. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4693. {
  4694. ui->statusbar->setVisible(visible);
  4695. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4696. "ShowStatusBar", visible);
  4697. }
  4698. void OBSBasic::on_actionLockPreview_triggered()
  4699. {
  4700. ui->preview->ToggleLocked();
  4701. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4702. }
  4703. void OBSBasic::on_scalingMenu_aboutToShow()
  4704. {
  4705. obs_video_info ovi;
  4706. obs_get_video_info(&ovi);
  4707. QAction *action = ui->actionScaleCanvas;
  4708. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4709. text = text.arg(QString::number(ovi.base_width),
  4710. QString::number(ovi.base_height));
  4711. action->setText(text);
  4712. action = ui->actionScaleOutput;
  4713. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4714. text = text.arg(QString::number(ovi.output_width),
  4715. QString::number(ovi.output_height));
  4716. action->setText(text);
  4717. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4718. ovi.output_height == ovi.base_height));
  4719. UpdatePreviewScalingMenu();
  4720. }
  4721. void OBSBasic::on_actionScaleWindow_triggered()
  4722. {
  4723. ui->preview->SetFixedScaling(false);
  4724. ui->preview->ResetScrollingOffset();
  4725. emit ui->preview->DisplayResized();
  4726. }
  4727. void OBSBasic::on_actionScaleCanvas_triggered()
  4728. {
  4729. ui->preview->SetFixedScaling(true);
  4730. ui->preview->SetScalingLevel(0);
  4731. emit ui->preview->DisplayResized();
  4732. }
  4733. void OBSBasic::on_actionScaleOutput_triggered()
  4734. {
  4735. obs_video_info ovi;
  4736. obs_get_video_info(&ovi);
  4737. ui->preview->SetFixedScaling(true);
  4738. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4739. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4740. int32_t approxScalingLevel = int32_t(
  4741. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4742. ui->preview->SetScalingLevel(approxScalingLevel);
  4743. ui->preview->SetScalingAmount(scalingAmount);
  4744. emit ui->preview->DisplayResized();
  4745. }
  4746. void OBSBasic::SetShowing(bool showing)
  4747. {
  4748. if (!showing && isVisible()) {
  4749. config_set_string(App()->GlobalConfig(),
  4750. "BasicWindow", "geometry",
  4751. saveGeometry().toBase64().constData());
  4752. /* hide all visible child dialogs */
  4753. visDlgPositions.clear();
  4754. if (!visDialogs.isEmpty()) {
  4755. for (QDialog *dlg : visDialogs) {
  4756. visDlgPositions.append(dlg->pos());
  4757. dlg->hide();
  4758. }
  4759. }
  4760. if (showHide)
  4761. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4762. QTimer::singleShot(250, this, SLOT(hide()));
  4763. if (previewEnabled)
  4764. EnablePreviewDisplay(false);
  4765. setVisible(false);
  4766. } else if (showing && !isVisible()) {
  4767. if (showHide)
  4768. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4769. QTimer::singleShot(250, this, SLOT(show()));
  4770. if (previewEnabled)
  4771. EnablePreviewDisplay(true);
  4772. setVisible(true);
  4773. /* show all child dialogs that was visible earlier */
  4774. if (!visDialogs.isEmpty()) {
  4775. for (int i = 0; i < visDialogs.size(); ++i) {
  4776. QDialog *dlg = visDialogs[i];
  4777. dlg->move(visDlgPositions[i]);
  4778. dlg->show();
  4779. }
  4780. }
  4781. /* Unminimize window if it was hidden to tray instead of task
  4782. * bar. */
  4783. if (sysTrayMinimizeToTray()) {
  4784. Qt::WindowStates state;
  4785. state = windowState() & ~Qt::WindowMinimized;
  4786. state |= Qt::WindowActive;
  4787. setWindowState(state);
  4788. }
  4789. }
  4790. }
  4791. void OBSBasic::ToggleShowHide()
  4792. {
  4793. bool showing = isVisible();
  4794. if (showing) {
  4795. /* check for modal dialogs */
  4796. EnumDialogs();
  4797. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4798. return;
  4799. }
  4800. SetShowing(!showing);
  4801. }
  4802. void OBSBasic::SystemTrayInit()
  4803. {
  4804. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4805. this);
  4806. trayIcon->setToolTip("OBS Studio");
  4807. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4808. trayIcon);
  4809. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4810. trayIcon);
  4811. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4812. trayIcon);
  4813. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4814. trayIcon);
  4815. exit = new QAction(QTStr("Exit"),
  4816. trayIcon);
  4817. if (outputHandler && !outputHandler->replayBuffer)
  4818. sysTrayReplayBuffer->setEnabled(false);
  4819. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4820. this,
  4821. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4822. connect(showHide, SIGNAL(triggered()),
  4823. this, SLOT(ToggleShowHide()));
  4824. connect(sysTrayStream, SIGNAL(triggered()),
  4825. this, SLOT(on_streamButton_clicked()));
  4826. connect(sysTrayRecord, SIGNAL(triggered()),
  4827. this, SLOT(on_recordButton_clicked()));
  4828. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4829. this, &OBSBasic::ReplayBufferClicked);
  4830. connect(exit, SIGNAL(triggered()),
  4831. this, SLOT(close()));
  4832. trayMenu = new QMenu;
  4833. }
  4834. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4835. {
  4836. if (reason == QSystemTrayIcon::Trigger) {
  4837. ToggleShowHide();
  4838. } else if (reason == QSystemTrayIcon::Context) {
  4839. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4840. AddProjectorMenuMonitors(previewProjector, this,
  4841. SLOT(OpenPreviewProjector()));
  4842. QMenu *studioProgramProjector = new QMenu(
  4843. QTStr("StudioProgramProjector"));
  4844. AddProjectorMenuMonitors(studioProgramProjector, this,
  4845. SLOT(OpenStudioProgramProjector()));
  4846. trayMenu->clear();
  4847. trayMenu->addAction(showHide);
  4848. trayMenu->addMenu(previewProjector);
  4849. trayMenu->addMenu(studioProgramProjector);
  4850. trayMenu->addAction(sysTrayStream);
  4851. trayMenu->addAction(sysTrayRecord);
  4852. trayMenu->addAction(sysTrayReplayBuffer);
  4853. trayMenu->addAction(exit);
  4854. trayMenu->popup(QCursor::pos());
  4855. }
  4856. }
  4857. void OBSBasic::SysTrayNotify(const QString &text,
  4858. QSystemTrayIcon::MessageIcon n)
  4859. {
  4860. if (QSystemTrayIcon::supportsMessages()) {
  4861. QSystemTrayIcon::MessageIcon icon =
  4862. QSystemTrayIcon::MessageIcon(n);
  4863. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4864. }
  4865. }
  4866. void OBSBasic::SystemTray(bool firstStarted)
  4867. {
  4868. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4869. return;
  4870. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4871. "BasicWindow", "SysTrayWhenStarted");
  4872. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4873. "BasicWindow", "SysTrayEnabled");
  4874. if (firstStarted)
  4875. SystemTrayInit();
  4876. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4877. trayIcon->hide();
  4878. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4879. || opt_minimize_tray) {
  4880. trayIcon->show();
  4881. if (firstStarted) {
  4882. QTimer::singleShot(50, this, SLOT(hide()));
  4883. EnablePreviewDisplay(false);
  4884. setVisible(false);
  4885. opt_minimize_tray = false;
  4886. }
  4887. } else if (sysTrayEnabled) {
  4888. trayIcon->show();
  4889. } else if (!sysTrayEnabled) {
  4890. trayIcon->hide();
  4891. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4892. trayIcon->hide();
  4893. }
  4894. if (isVisible())
  4895. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4896. else
  4897. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4898. }
  4899. bool OBSBasic::sysTrayMinimizeToTray()
  4900. {
  4901. return config_get_bool(GetGlobalConfig(),
  4902. "BasicWindow", "SysTrayMinimizeToTray");
  4903. }
  4904. void OBSBasic::on_actionCopySource_triggered()
  4905. {
  4906. OBSSceneItem item = GetCurrentSceneItem();
  4907. if (!item)
  4908. return;
  4909. on_actionCopyTransform_triggered();
  4910. OBSSource source = obs_sceneitem_get_source(item);
  4911. copyString = obs_source_get_name(source);
  4912. copyVisible = obs_sceneitem_visible(item);
  4913. ui->actionPasteRef->setEnabled(true);
  4914. uint32_t output_flags = obs_source_get_output_flags(source);
  4915. if ((output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
  4916. ui->actionPasteDup->setEnabled(true);
  4917. else
  4918. ui->actionPasteDup->setEnabled(false);
  4919. }
  4920. void OBSBasic::on_actionPasteRef_triggered()
  4921. {
  4922. /* do not allow duplicate refs of the same group in the same scene */
  4923. OBSScene scene = GetCurrentScene();
  4924. if (!!obs_scene_get_group(scene, copyString))
  4925. return;
  4926. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4927. on_actionPasteTransform_triggered();
  4928. }
  4929. void OBSBasic::on_actionPasteDup_triggered()
  4930. {
  4931. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4932. on_actionPasteTransform_triggered();
  4933. }
  4934. void OBSBasic::on_actionCopyFilters_triggered()
  4935. {
  4936. OBSSceneItem item = GetCurrentSceneItem();
  4937. if (!item)
  4938. return;
  4939. OBSSource source = obs_sceneitem_get_source(item);
  4940. copyFiltersString = obs_source_get_name(source);
  4941. ui->actionPasteFilters->setEnabled(true);
  4942. }
  4943. void OBSBasic::on_actionPasteFilters_triggered()
  4944. {
  4945. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4946. obs_source_release(source);
  4947. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4948. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4949. if (source == dstSource)
  4950. return;
  4951. obs_source_copy_filters(dstSource, source);
  4952. }
  4953. void OBSBasic::on_autoConfigure_triggered()
  4954. {
  4955. AutoConfig test(this);
  4956. test.setModal(true);
  4957. test.show();
  4958. test.exec();
  4959. }
  4960. void OBSBasic::on_stats_triggered()
  4961. {
  4962. if (!stats.isNull()) {
  4963. stats->show();
  4964. stats->raise();
  4965. return;
  4966. }
  4967. OBSBasicStats *statsDlg;
  4968. statsDlg = new OBSBasicStats(nullptr);
  4969. statsDlg->show();
  4970. stats = statsDlg;
  4971. }