window-basic-main.cpp 161 KB

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