1
0

window-basic-main.cpp 161 KB

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