window-basic-main.cpp 160 KB

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