window-basic-main.cpp 162 KB

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