window-basic-main.cpp 162 KB

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