window-basic-main.cpp 160 KB

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