window-basic-main.cpp 152 KB

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