window-basic-main.cpp 161 KB

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