window-basic-main.cpp 161 KB

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