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