window-basic-main.cpp 161 KB

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