window-basic-main.cpp 160 KB

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