window-basic-main.cpp 162 KB

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