window-basic-main.cpp 260 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712
  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 "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <obs-data.h>
  21. #include <obs.h>
  22. #include <obs.hpp>
  23. #include <QGuiApplication>
  24. #include <QMessageBox>
  25. #include <QShowEvent>
  26. #include <QDesktopServices>
  27. #include <QFileDialog>
  28. #include <QScreen>
  29. #include <QColorDialog>
  30. #include <QSizePolicy>
  31. #include <QScrollBar>
  32. #include <QTextStream>
  33. #include <util/dstr.h>
  34. #include <util/util.hpp>
  35. #include <util/platform.h>
  36. #include <util/profiler.hpp>
  37. #include <util/dstr.hpp>
  38. #include "obs-app.hpp"
  39. #include "platform.hpp"
  40. #include "visibility-item-widget.hpp"
  41. #include "item-widget-helpers.hpp"
  42. #include "window-basic-settings.hpp"
  43. #include "window-namedialog.hpp"
  44. #include "window-basic-auto-config.hpp"
  45. #include "window-basic-source-select.hpp"
  46. #include "window-basic-main.hpp"
  47. #include "window-basic-stats.hpp"
  48. #include "window-basic-main-outputs.hpp"
  49. #include "window-log-reply.hpp"
  50. #include "window-projector.hpp"
  51. #include "window-remux.hpp"
  52. #if YOUTUBE_ENABLED
  53. #include "auth-youtube.hpp"
  54. #include "window-youtube-actions.hpp"
  55. #include "youtube-api-wrappers.hpp"
  56. #endif
  57. #include "qt-wrappers.hpp"
  58. #include "context-bar-controls.hpp"
  59. #include "obs-proxy-style.hpp"
  60. #include "display-helpers.hpp"
  61. #include "volume-control.hpp"
  62. #include "remote-text.hpp"
  63. #include "ui-validation.hpp"
  64. #include "media-controls.hpp"
  65. #include "undo-stack-obs.hpp"
  66. #include <fstream>
  67. #include <sstream>
  68. #ifdef _WIN32
  69. #include "win-update/win-update.hpp"
  70. #include "windows.h"
  71. #endif
  72. #include "ui_OBSBasic.h"
  73. #include "ui_ColorSelect.h"
  74. #include <QWindow>
  75. #include <json11.hpp>
  76. #ifdef ENABLE_WAYLAND
  77. #include <obs-nix-platform.h>
  78. #endif
  79. using namespace json11;
  80. using namespace std;
  81. #ifdef BROWSER_AVAILABLE
  82. #include <browser-panel.hpp>
  83. #endif
  84. #include "ui-config.h"
  85. struct QCef;
  86. struct QCefCookieManager;
  87. QCef *cef = nullptr;
  88. QCefCookieManager *panel_cookies = nullptr;
  89. void DestroyPanelCookieManager();
  90. namespace {
  91. template<typename OBSRef> struct SignalContainer {
  92. OBSRef ref;
  93. vector<shared_ptr<OBSSignal>> handlers;
  94. };
  95. }
  96. extern volatile long insideEventLoop;
  97. Q_DECLARE_METATYPE(OBSScene);
  98. Q_DECLARE_METATYPE(OBSSceneItem);
  99. Q_DECLARE_METATYPE(OBSSource);
  100. Q_DECLARE_METATYPE(obs_order_movement);
  101. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  102. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  103. {
  104. out << v.ref;
  105. return out;
  106. }
  107. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  108. {
  109. in >> v.ref;
  110. return in;
  111. }
  112. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  113. {
  114. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  115. }
  116. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  117. {
  118. item->setData(static_cast<int>(QtDataRole::OBSRef),
  119. QVariant::fromValue(val));
  120. }
  121. static void AddExtraModulePaths()
  122. {
  123. char *plugins_path = getenv("OBS_PLUGINS_PATH");
  124. char *plugins_data_path = getenv("OBS_PLUGINS_DATA_PATH");
  125. if (plugins_path && plugins_data_path) {
  126. string data_path_with_module_suffix;
  127. data_path_with_module_suffix += plugins_data_path;
  128. data_path_with_module_suffix += "/%module%";
  129. obs_add_module_path(plugins_path,
  130. data_path_with_module_suffix.c_str());
  131. }
  132. char base_module_dir[512];
  133. #if defined(_WIN32) || defined(__APPLE__)
  134. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  135. "obs-studio/plugins/%module%");
  136. #else
  137. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  138. "obs-studio/plugins/%module%");
  139. #endif
  140. if (ret <= 0)
  141. return;
  142. string path = base_module_dir;
  143. #if defined(__APPLE__)
  144. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  145. BPtr<char> config_bin =
  146. os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  147. BPtr<char> config_data =
  148. os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  149. obs_add_module_path(config_bin, config_data);
  150. #elif ARCH_BITS == 64
  151. obs_add_module_path((path + "/bin/64bit").c_str(),
  152. (path + "/data").c_str());
  153. #else
  154. obs_add_module_path((path + "/bin/32bit").c_str(),
  155. (path + "/data").c_str());
  156. #endif
  157. }
  158. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  159. void assignDockToggle(QDockWidget *dock, QAction *action)
  160. {
  161. auto handleWindowToggle = [action](bool vis) {
  162. action->blockSignals(true);
  163. action->setChecked(vis);
  164. action->blockSignals(false);
  165. };
  166. auto handleMenuToggle = [dock](bool check) {
  167. dock->blockSignals(true);
  168. dock->setVisible(check);
  169. dock->blockSignals(false);
  170. };
  171. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  172. handleWindowToggle);
  173. dock->connect(action, &QAction::toggled, handleMenuToggle);
  174. }
  175. extern void RegisterTwitchAuth();
  176. extern void RegisterRestreamAuth();
  177. #if YOUTUBE_ENABLED
  178. extern void RegisterYoutubeAuth();
  179. #endif
  180. OBSBasic::OBSBasic(QWidget *parent)
  181. : OBSMainWindow(parent), undo_s(ui), ui(new Ui::OBSBasic)
  182. {
  183. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  184. qRegisterMetaTypeStreamOperators<SignalContainer<OBSScene>>(
  185. "SignalContainer<OBSScene>");
  186. #endif
  187. setAttribute(Qt::WA_NativeWindow);
  188. #if TWITCH_ENABLED
  189. RegisterTwitchAuth();
  190. #endif
  191. #if RESTREAM_ENABLED
  192. RegisterRestreamAuth();
  193. #endif
  194. #if YOUTUBE_ENABLED
  195. RegisterYoutubeAuth();
  196. #endif
  197. setAcceptDrops(true);
  198. setContextMenuPolicy(Qt::CustomContextMenu);
  199. connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this,
  200. SLOT(on_customContextMenuRequested(const QPoint &)));
  201. api = InitializeAPIInterface(this);
  202. ui->setupUi(this);
  203. ui->previewDisabledWidget->setVisible(false);
  204. ui->contextContainer->setStyle(new OBSProxyStyle);
  205. ui->broadcastButton->setVisible(false);
  206. startingDockLayout = saveState();
  207. statsDock = new OBSDock();
  208. statsDock->setObjectName(QStringLiteral("statsDock"));
  209. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  210. QDockWidget::DockWidgetMovable |
  211. QDockWidget::DockWidgetFloatable);
  212. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  213. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  214. statsDock->setVisible(false);
  215. statsDock->setFloating(true);
  216. statsDock->resize(700, 200);
  217. copyActionsDynamicProperties();
  218. char styleSheetPath[512];
  219. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  220. "stylesheet.qss");
  221. if (ret > 0) {
  222. if (QFile::exists(styleSheetPath)) {
  223. QString path =
  224. QString("file:///") + QT_UTF8(styleSheetPath);
  225. App()->setStyleSheet(path);
  226. }
  227. }
  228. qRegisterMetaType<int64_t>("int64_t");
  229. qRegisterMetaType<uint32_t>("uint32_t");
  230. qRegisterMetaType<OBSScene>("OBSScene");
  231. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  232. qRegisterMetaType<OBSSource>("OBSSource");
  233. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  234. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  235. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  236. qRegisterMetaTypeStreamOperators<std::vector<std::shared_ptr<OBSSignal>>>(
  237. "std::vector<std::shared_ptr<OBSSignal>>");
  238. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  239. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  240. #endif
  241. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  242. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  243. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  244. "gridMode");
  245. ui->scenes->SetGridMode(sceneGrid);
  246. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  247. auto displayResize = [this]() {
  248. struct obs_video_info ovi;
  249. if (obs_get_video_info(&ovi))
  250. ResizePreview(ovi.base_width, ovi.base_height);
  251. };
  252. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  253. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  254. delete shortcutFilter;
  255. shortcutFilter = CreateShortcutFilter();
  256. installEventFilter(shortcutFilter);
  257. stringstream name;
  258. name << "OBS " << App()->GetVersionString();
  259. blog(LOG_INFO, "%s", name.str().c_str());
  260. blog(LOG_INFO, "---------------------------------");
  261. UpdateTitleBar();
  262. connect(ui->scenes->itemDelegate(),
  263. SIGNAL(closeEditor(QWidget *,
  264. QAbstractItemDelegate::EndEditHint)),
  265. this,
  266. SLOT(SceneNameEdited(QWidget *,
  267. QAbstractItemDelegate::EndEditHint)));
  268. cpuUsageInfo = os_cpu_usage_info_start();
  269. cpuUsageTimer = new QTimer(this);
  270. connect(cpuUsageTimer.data(), SIGNAL(timeout()), ui->statusbar,
  271. SLOT(UpdateCPUUsage()));
  272. cpuUsageTimer->start(3000);
  273. diskFullTimer = new QTimer(this);
  274. connect(diskFullTimer, SIGNAL(timeout()), this,
  275. SLOT(CheckDiskSpaceRemaining()));
  276. renameScene = new QAction(ui->scenesDock);
  277. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  278. connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
  279. ui->scenesDock->addAction(renameScene);
  280. renameSource = new QAction(ui->sourcesDock);
  281. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  282. connect(renameSource, SIGNAL(triggered()), this,
  283. SLOT(EditSceneItemName()));
  284. ui->sourcesDock->addAction(renameSource);
  285. #ifdef __APPLE__
  286. renameScene->setShortcut({Qt::Key_Return});
  287. renameSource->setShortcut({Qt::Key_Return});
  288. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  289. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  290. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  291. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  292. #else
  293. renameScene->setShortcut({Qt::Key_F2});
  294. renameSource->setShortcut({Qt::Key_F2});
  295. #endif
  296. #ifdef __linux__
  297. ui->actionE_xit->setShortcut(Qt::CTRL + Qt::Key_Q);
  298. #endif
  299. auto addNudge = [this](const QKeySequence &seq, const char *s) {
  300. QAction *nudge = new QAction(ui->preview);
  301. nudge->setShortcut(seq);
  302. nudge->setShortcutContext(Qt::WidgetShortcut);
  303. ui->preview->addAction(nudge);
  304. connect(nudge, SIGNAL(triggered()), this, s);
  305. };
  306. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  307. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  308. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  309. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  310. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  311. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  312. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  313. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  314. assignDockToggle(ui->controlsDock, ui->toggleControls);
  315. assignDockToggle(statsDock, ui->toggleStats);
  316. // Register shortcuts for Undo/Redo
  317. ui->actionMainUndo->setShortcut(Qt::CTRL + Qt::Key_Z);
  318. QList<QKeySequence> shrt;
  319. shrt << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z)
  320. << QKeySequence(Qt::CTRL + Qt::Key_Y);
  321. ui->actionMainRedo->setShortcuts(shrt);
  322. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  323. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  324. //hide all docking panes
  325. ui->toggleScenes->setChecked(false);
  326. ui->toggleSources->setChecked(false);
  327. ui->toggleMixer->setChecked(false);
  328. ui->toggleTransitions->setChecked(false);
  329. ui->toggleControls->setChecked(false);
  330. ui->toggleStats->setChecked(false);
  331. QPoint curPos;
  332. //restore parent window geometry
  333. const char *geometry = config_get_string(App()->GlobalConfig(),
  334. "BasicWindow", "geometry");
  335. if (geometry != NULL) {
  336. QByteArray byteArray =
  337. QByteArray::fromBase64(QByteArray(geometry));
  338. restoreGeometry(byteArray);
  339. QRect windowGeometry = normalGeometry();
  340. if (!WindowPositionValid(windowGeometry)) {
  341. QRect rect =
  342. QGuiApplication::primaryScreen()->geometry();
  343. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  344. Qt::AlignCenter, size(),
  345. rect));
  346. }
  347. curPos = pos();
  348. } else {
  349. QRect desktopRect =
  350. QGuiApplication::primaryScreen()->geometry();
  351. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  352. curPos = QPoint(adjSize.width(), adjSize.height());
  353. }
  354. QPoint curSize(width(), height());
  355. QPoint statsDockSize(statsDock->width(), statsDock->height());
  356. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  357. QPoint newPos = curPos + statsDockPos;
  358. statsDock->move(newPos);
  359. ui->previewLabel->setProperty("themeID", "previewProgramLabels");
  360. ui->previewLabel->style()->polish(ui->previewLabel);
  361. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  362. "StudioModeLabels");
  363. if (!previewProgramMode)
  364. ui->previewLabel->setHidden(true);
  365. else
  366. ui->previewLabel->setHidden(!labels);
  367. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  368. connect(ui->previewDisabledWidget,
  369. SIGNAL(customContextMenuRequested(const QPoint &)), this,
  370. SLOT(PreviewDisabledMenu(const QPoint &)));
  371. connect(ui->enablePreviewButton, SIGNAL(clicked()), this,
  372. SLOT(TogglePreview()));
  373. connect(ui->scenes, SIGNAL(scenesReordered()), this,
  374. SLOT(ScenesReordered()));
  375. connect(ui->broadcastButton, &QPushButton::clicked, this,
  376. &OBSBasic::BroadcastButtonClicked);
  377. UpdatePreviewSafeAreas();
  378. }
  379. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  380. vector<OBSSource> &audioSources)
  381. {
  382. obs_source_t *source = obs_get_output_source(channel);
  383. if (!source)
  384. return;
  385. audioSources.push_back(source);
  386. obs_data_t *data = obs_save_source(source);
  387. obs_data_set_obj(parent, name, data);
  388. obs_data_release(data);
  389. obs_source_release(source);
  390. }
  391. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  392. obs_data_array_t *quickTransitionData,
  393. int transitionDuration,
  394. obs_data_array_t *transitions,
  395. OBSScene &scene, OBSSource &curProgramScene,
  396. obs_data_array_t *savedProjectorList)
  397. {
  398. obs_data_t *saveData = obs_data_create();
  399. vector<OBSSource> audioSources;
  400. audioSources.reserve(6);
  401. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  402. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  403. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  404. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  405. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  406. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  407. /* -------------------------------- */
  408. /* save non-group sources */
  409. auto FilterAudioSources = [&](obs_source_t *source) {
  410. if (obs_source_is_group(source))
  411. return false;
  412. return find(begin(audioSources), end(audioSources), source) ==
  413. end(audioSources);
  414. };
  415. using FilterAudioSources_t = decltype(FilterAudioSources);
  416. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  417. [](void *data, obs_source_t *source) {
  418. return (*static_cast<FilterAudioSources_t *>(data))(
  419. source);
  420. },
  421. static_cast<void *>(&FilterAudioSources));
  422. /* -------------------------------- */
  423. /* save group sources separately */
  424. /* saving separately ensures they won't be loaded in older versions */
  425. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  426. [](void *, obs_source_t *source) {
  427. return obs_source_is_group(source);
  428. },
  429. nullptr);
  430. /* -------------------------------- */
  431. obs_source_t *transition = obs_get_output_source(0);
  432. obs_source_t *currentScene = obs_scene_get_source(scene);
  433. const char *sceneName = obs_source_get_name(currentScene);
  434. const char *programName = obs_source_get_name(curProgramScene);
  435. const char *sceneCollection = config_get_string(
  436. App()->GlobalConfig(), "Basic", "SceneCollection");
  437. obs_data_set_string(saveData, "current_scene", sceneName);
  438. obs_data_set_string(saveData, "current_program_scene", programName);
  439. obs_data_set_array(saveData, "scene_order", sceneOrder);
  440. obs_data_set_string(saveData, "name", sceneCollection);
  441. obs_data_set_array(saveData, "sources", sourcesArray);
  442. obs_data_set_array(saveData, "groups", groupsArray);
  443. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  444. obs_data_set_array(saveData, "transitions", transitions);
  445. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  446. obs_data_array_release(sourcesArray);
  447. obs_data_array_release(groupsArray);
  448. obs_data_set_string(saveData, "current_transition",
  449. obs_source_get_name(transition));
  450. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  451. obs_source_release(transition);
  452. return saveData;
  453. }
  454. void OBSBasic::copyActionsDynamicProperties()
  455. {
  456. // Themes need the QAction dynamic properties
  457. for (QAction *x : ui->scenesToolbar->actions()) {
  458. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  459. for (QByteArray &y : x->dynamicPropertyNames()) {
  460. temp->setProperty(y, x->property(y));
  461. }
  462. }
  463. for (QAction *x : ui->sourcesToolbar->actions()) {
  464. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  465. for (QByteArray &y : x->dynamicPropertyNames()) {
  466. temp->setProperty(y, x->property(y));
  467. }
  468. }
  469. }
  470. void OBSBasic::UpdateVolumeControlsDecayRate()
  471. {
  472. double meterDecayRate =
  473. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  474. for (size_t i = 0; i < volumes.size(); i++) {
  475. volumes[i]->SetMeterDecayRate(meterDecayRate);
  476. }
  477. }
  478. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  479. {
  480. uint32_t peakMeterTypeIdx =
  481. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  482. enum obs_peak_meter_type peakMeterType;
  483. switch (peakMeterTypeIdx) {
  484. case 0:
  485. peakMeterType = SAMPLE_PEAK_METER;
  486. break;
  487. case 1:
  488. peakMeterType = TRUE_PEAK_METER;
  489. break;
  490. default:
  491. peakMeterType = SAMPLE_PEAK_METER;
  492. break;
  493. }
  494. for (size_t i = 0; i < volumes.size(); i++) {
  495. volumes[i]->setPeakMeterType(peakMeterType);
  496. }
  497. }
  498. void OBSBasic::ClearVolumeControls()
  499. {
  500. for (VolControl *vol : volumes)
  501. delete vol;
  502. volumes.clear();
  503. }
  504. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  505. {
  506. obs_data_array_t *sceneOrder = obs_data_array_create();
  507. for (int i = 0; i < ui->scenes->count(); i++) {
  508. obs_data_t *data = obs_data_create();
  509. obs_data_set_string(data, "name",
  510. QT_TO_UTF8(ui->scenes->item(i)->text()));
  511. obs_data_array_push_back(sceneOrder, data);
  512. obs_data_release(data);
  513. }
  514. return sceneOrder;
  515. }
  516. obs_data_array_t *OBSBasic::SaveProjectors()
  517. {
  518. obs_data_array_t *savedProjectors = obs_data_array_create();
  519. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  520. if (!projector)
  521. return;
  522. obs_data_t *data = obs_data_create();
  523. ProjectorType type = projector->GetProjectorType();
  524. switch (type) {
  525. case ProjectorType::Scene:
  526. case ProjectorType::Source: {
  527. obs_source_t *source = projector->GetSource();
  528. const char *name = obs_source_get_name(source);
  529. obs_data_set_string(data, "name", name);
  530. break;
  531. }
  532. default:
  533. break;
  534. }
  535. obs_data_set_int(data, "monitor", projector->GetMonitor());
  536. obs_data_set_int(data, "type", static_cast<int>(type));
  537. obs_data_set_string(
  538. data, "geometry",
  539. projector->saveGeometry().toBase64().constData());
  540. if (projector->IsAlwaysOnTopOverridden())
  541. obs_data_set_bool(data, "alwaysOnTop",
  542. projector->IsAlwaysOnTop());
  543. obs_data_set_bool(data, "alwaysOnTopOverridden",
  544. projector->IsAlwaysOnTopOverridden());
  545. obs_data_array_push_back(savedProjectors, data);
  546. obs_data_release(data);
  547. };
  548. for (size_t i = 0; i < projectors.size(); i++)
  549. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  550. return savedProjectors;
  551. }
  552. void OBSBasic::Save(const char *file)
  553. {
  554. OBSScene scene = GetCurrentScene();
  555. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  556. if (!curProgramScene)
  557. curProgramScene = obs_scene_get_source(scene);
  558. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  559. obs_data_array_t *transitions = SaveTransitions();
  560. obs_data_array_t *quickTrData = SaveQuickTransitions();
  561. obs_data_array_t *savedProjectorList = SaveProjectors();
  562. obs_data_t *saveData = GenerateSaveData(
  563. sceneOrder, quickTrData, ui->transitionDuration->value(),
  564. transitions, scene, curProgramScene, savedProjectorList);
  565. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  566. obs_data_set_bool(saveData, "scaling_enabled",
  567. ui->preview->IsFixedScaling());
  568. obs_data_set_int(saveData, "scaling_level",
  569. ui->preview->GetScalingLevel());
  570. obs_data_set_double(saveData, "scaling_off_x",
  571. ui->preview->GetScrollX());
  572. obs_data_set_double(saveData, "scaling_off_y",
  573. ui->preview->GetScrollY());
  574. if (api) {
  575. obs_data_t *moduleObj = obs_data_create();
  576. api->on_save(moduleObj);
  577. obs_data_set_obj(saveData, "modules", moduleObj);
  578. obs_data_release(moduleObj);
  579. }
  580. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  581. blog(LOG_ERROR, "Could not save scene data to %s", file);
  582. obs_data_release(saveData);
  583. obs_data_array_release(sceneOrder);
  584. obs_data_array_release(quickTrData);
  585. obs_data_array_release(transitions);
  586. obs_data_array_release(savedProjectorList);
  587. }
  588. void OBSBasic::DeferSaveBegin()
  589. {
  590. os_atomic_inc_long(&disableSaving);
  591. }
  592. void OBSBasic::DeferSaveEnd()
  593. {
  594. long result = os_atomic_dec_long(&disableSaving);
  595. if (result == 0) {
  596. SaveProject();
  597. }
  598. }
  599. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  600. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  601. {
  602. obs_data_t *data = obs_data_get_obj(parent, name);
  603. if (!data)
  604. return;
  605. obs_source_t *source = obs_load_source(data);
  606. if (source) {
  607. obs_set_output_source(channel, source);
  608. const char *name = obs_source_get_name(source);
  609. blog(LOG_INFO, "[Loaded global audio device]: '%s'", name);
  610. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  611. obs_monitoring_type monitoring_type =
  612. obs_source_get_monitoring_type(source);
  613. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  614. const char *type = (monitoring_type ==
  615. OBS_MONITORING_TYPE_MONITOR_ONLY)
  616. ? "monitor only"
  617. : "monitor and output";
  618. blog(LOG_INFO, " - monitoring: %s", type);
  619. }
  620. obs_source_release(source);
  621. }
  622. obs_data_release(data);
  623. }
  624. static inline bool HasAudioDevices(const char *source_id)
  625. {
  626. const char *output_id = source_id;
  627. obs_properties_t *props = obs_get_source_properties(output_id);
  628. size_t count = 0;
  629. if (!props)
  630. return false;
  631. obs_property_t *devices = obs_properties_get(props, "device_id");
  632. if (devices)
  633. count = obs_property_list_item_count(devices);
  634. obs_properties_destroy(props);
  635. return count != 0;
  636. }
  637. void OBSBasic::CreateFirstRunSources()
  638. {
  639. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  640. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  641. if (hasDesktopAudio)
  642. ResetAudioDevice(App()->OutputAudioSource(), "default",
  643. Str("Basic.DesktopDevice1"), 1);
  644. if (hasInputAudio)
  645. ResetAudioDevice(App()->InputAudioSource(), "default",
  646. Str("Basic.AuxDevice1"), 3);
  647. }
  648. void OBSBasic::CreateDefaultScene(bool firstStart)
  649. {
  650. disableSaving++;
  651. ClearSceneData();
  652. InitDefaultTransitions();
  653. CreateDefaultQuickTransitions();
  654. ui->transitionDuration->setValue(300);
  655. SetTransition(fadeTransition);
  656. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  657. if (firstStart)
  658. CreateFirstRunSources();
  659. SetCurrentScene(scene, true);
  660. obs_scene_release(scene);
  661. disableSaving--;
  662. }
  663. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  664. {
  665. for (int i = 0; i < lw->count(); i++) {
  666. QListWidgetItem *item = lw->item(i);
  667. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  668. if (newIndex != i) {
  669. item = lw->takeItem(i);
  670. lw->insertItem(newIndex, item);
  671. }
  672. break;
  673. }
  674. }
  675. }
  676. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  677. {
  678. size_t num = obs_data_array_count(array);
  679. for (size_t i = 0; i < num; i++) {
  680. obs_data_t *data = obs_data_array_item(array, i);
  681. const char *name = obs_data_get_string(data, "name");
  682. ReorderItemByName(ui->scenes, name, (int)i);
  683. obs_data_release(data);
  684. }
  685. }
  686. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  687. {
  688. for (SavedProjectorInfo *info : savedProjectorsArray) {
  689. delete info;
  690. }
  691. savedProjectorsArray.clear();
  692. size_t num = obs_data_array_count(array);
  693. for (size_t i = 0; i < num; i++) {
  694. obs_data_t *data = obs_data_array_item(array, i);
  695. SavedProjectorInfo *info = new SavedProjectorInfo();
  696. info->monitor = obs_data_get_int(data, "monitor");
  697. info->type = static_cast<ProjectorType>(
  698. obs_data_get_int(data, "type"));
  699. info->geometry =
  700. std::string(obs_data_get_string(data, "geometry"));
  701. info->name = std::string(obs_data_get_string(data, "name"));
  702. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  703. info->alwaysOnTopOverridden =
  704. obs_data_get_bool(data, "alwaysOnTopOverridden");
  705. savedProjectorsArray.emplace_back(info);
  706. obs_data_release(data);
  707. }
  708. }
  709. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  710. {
  711. const char *name = obs_source_get_name(filter);
  712. const char *id = obs_source_get_id(filter);
  713. int val = (int)(intptr_t)v_val;
  714. string indent;
  715. for (int i = 0; i < val; i++)
  716. indent += " ";
  717. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  718. }
  719. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  720. {
  721. obs_source_t *source = obs_sceneitem_get_source(item);
  722. const char *name = obs_source_get_name(source);
  723. const char *id = obs_source_get_id(source);
  724. int indent_count = (int)(intptr_t)v_val;
  725. string indent;
  726. for (int i = 0; i < indent_count; i++)
  727. indent += " ";
  728. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  729. obs_monitoring_type monitoring_type =
  730. obs_source_get_monitoring_type(source);
  731. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  732. const char *type =
  733. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  734. ? "monitor only"
  735. : "monitor and output";
  736. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  737. }
  738. int child_indent = 1 + indent_count;
  739. obs_source_enum_filters(source, LogFilter,
  740. (void *)(intptr_t)child_indent);
  741. obs_source_t *show_tn = obs_sceneitem_get_show_transition(item);
  742. obs_source_t *hide_tn = obs_sceneitem_get_hide_transition(item);
  743. if (show_tn)
  744. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  745. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  746. if (hide_tn)
  747. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  748. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  749. if (obs_sceneitem_is_group(item))
  750. obs_sceneitem_group_enum_items(item, LogSceneItem,
  751. (void *)(intptr_t)child_indent);
  752. return true;
  753. }
  754. void OBSBasic::LogScenes()
  755. {
  756. blog(LOG_INFO, "------------------------------------------------");
  757. blog(LOG_INFO, "Loaded scenes:");
  758. for (int i = 0; i < ui->scenes->count(); i++) {
  759. QListWidgetItem *item = ui->scenes->item(i);
  760. OBSScene scene = GetOBSRef<OBSScene>(item);
  761. obs_source_t *source = obs_scene_get_source(scene);
  762. const char *name = obs_source_get_name(source);
  763. blog(LOG_INFO, "- scene '%s':", name);
  764. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  765. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  766. }
  767. blog(LOG_INFO, "------------------------------------------------");
  768. }
  769. void OBSBasic::Load(const char *file)
  770. {
  771. disableSaving++;
  772. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  773. if (!data) {
  774. disableSaving--;
  775. blog(LOG_INFO, "No scene file found, creating default scene");
  776. CreateDefaultScene(true);
  777. SaveProject();
  778. return;
  779. }
  780. LoadData(data, file);
  781. }
  782. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  783. {
  784. ClearSceneData();
  785. InitDefaultTransitions();
  786. ClearContextBar();
  787. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  788. devicePropertiesThread->wait();
  789. devicePropertiesThread.reset();
  790. }
  791. QApplication::sendPostedEvents(this);
  792. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  793. if (api)
  794. api->on_preload(modulesObj);
  795. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  796. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  797. obs_data_array_t *groups = obs_data_get_array(data, "groups");
  798. obs_data_array_t *transitions = obs_data_get_array(data, "transitions");
  799. const char *sceneName = obs_data_get_string(data, "current_scene");
  800. const char *programSceneName =
  801. obs_data_get_string(data, "current_program_scene");
  802. const char *transitionName =
  803. obs_data_get_string(data, "current_transition");
  804. if (!opt_starting_scene.empty()) {
  805. programSceneName = opt_starting_scene.c_str();
  806. if (!IsPreviewProgramMode())
  807. sceneName = opt_starting_scene.c_str();
  808. }
  809. int newDuration = obs_data_get_int(data, "transition_duration");
  810. if (!newDuration)
  811. newDuration = 300;
  812. if (!transitionName)
  813. transitionName = obs_source_get_name(fadeTransition);
  814. const char *curSceneCollection = config_get_string(
  815. App()->GlobalConfig(), "Basic", "SceneCollection");
  816. obs_data_set_default_string(data, "name", curSceneCollection);
  817. const char *name = obs_data_get_string(data, "name");
  818. obs_source_t *curScene;
  819. obs_source_t *curProgramScene;
  820. obs_source_t *curTransition;
  821. if (!name || !*name)
  822. name = curSceneCollection;
  823. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  824. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  825. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  826. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  827. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  828. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  829. if (!sources) {
  830. sources = groups;
  831. groups = nullptr;
  832. } else {
  833. obs_data_array_push_back_array(sources, groups);
  834. }
  835. obs_missing_files_t *files = obs_missing_files_create();
  836. auto cb = [](void *private_data, obs_source_t *source) {
  837. obs_missing_files_t *f = (obs_missing_files_t *)private_data;
  838. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  839. obs_missing_files_append(f, sf);
  840. obs_missing_files_destroy(sf);
  841. UNUSED_PARAMETER(source);
  842. };
  843. obs_load_sources(sources, cb, files);
  844. if (transitions)
  845. LoadTransitions(transitions, cb, files);
  846. if (sceneOrder)
  847. LoadSceneListOrder(sceneOrder);
  848. obs_data_array_release(transitions);
  849. curTransition = FindTransition(transitionName);
  850. if (!curTransition)
  851. curTransition = fadeTransition;
  852. ui->transitionDuration->setValue(newDuration);
  853. SetTransition(curTransition);
  854. retryScene:
  855. curScene = obs_get_source_by_name(sceneName);
  856. curProgramScene = obs_get_source_by_name(programSceneName);
  857. /* if the starting scene command line parameter is bad at all,
  858. * fall back to original settings */
  859. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  860. sceneName = obs_data_get_string(data, "current_scene");
  861. programSceneName =
  862. obs_data_get_string(data, "current_program_scene");
  863. obs_source_release(curScene);
  864. obs_source_release(curProgramScene);
  865. opt_starting_scene.clear();
  866. goto retryScene;
  867. }
  868. if (!curProgramScene) {
  869. curProgramScene = curScene;
  870. obs_source_addref(curScene);
  871. }
  872. SetCurrentScene(curScene, true);
  873. if (IsPreviewProgramMode())
  874. TransitionToScene(curProgramScene, true);
  875. obs_source_release(curScene);
  876. obs_source_release(curProgramScene);
  877. obs_data_array_release(sources);
  878. obs_data_array_release(groups);
  879. obs_data_array_release(sceneOrder);
  880. /* ------------------- */
  881. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  882. "SaveProjectors");
  883. if (projectorSave) {
  884. obs_data_array_t *savedProjectors =
  885. obs_data_get_array(data, "saved_projectors");
  886. if (savedProjectors) {
  887. LoadSavedProjectors(savedProjectors);
  888. OpenSavedProjectors();
  889. activateWindow();
  890. }
  891. obs_data_array_release(savedProjectors);
  892. }
  893. /* ------------------- */
  894. std::string file_base = strrchr(file, '/') + 1;
  895. file_base.erase(file_base.size() - 5, 5);
  896. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  897. name);
  898. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  899. file_base.c_str());
  900. obs_data_array_t *quickTransitionData =
  901. obs_data_get_array(data, "quick_transitions");
  902. LoadQuickTransitions(quickTransitionData);
  903. obs_data_array_release(quickTransitionData);
  904. RefreshQuickTransitions();
  905. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  906. ui->preview->SetLocked(previewLocked);
  907. ui->actionLockPreview->setChecked(previewLocked);
  908. /* ---------------------- */
  909. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  910. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  911. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  912. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  913. if (fixedScaling) {
  914. ui->preview->SetScalingLevel(scalingLevel);
  915. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  916. }
  917. ui->preview->SetFixedScaling(fixedScaling);
  918. emit ui->preview->DisplayResized();
  919. /* ---------------------- */
  920. if (api)
  921. api->on_load(modulesObj);
  922. obs_data_release(modulesObj);
  923. obs_data_release(data);
  924. if (!opt_starting_scene.empty())
  925. opt_starting_scene.clear();
  926. if (opt_start_streaming) {
  927. blog(LOG_INFO, "Starting stream due to command line parameter");
  928. QMetaObject::invokeMethod(this, "StartStreaming",
  929. Qt::QueuedConnection);
  930. opt_start_streaming = false;
  931. }
  932. if (opt_start_recording) {
  933. blog(LOG_INFO,
  934. "Starting recording due to command line parameter");
  935. QMetaObject::invokeMethod(this, "StartRecording",
  936. Qt::QueuedConnection);
  937. opt_start_recording = false;
  938. }
  939. if (opt_start_replaybuffer) {
  940. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  941. Qt::QueuedConnection);
  942. opt_start_replaybuffer = false;
  943. }
  944. if (opt_start_virtualcam) {
  945. QMetaObject::invokeMethod(this, "StartVirtualCam",
  946. Qt::QueuedConnection);
  947. opt_start_virtualcam = false;
  948. }
  949. LogScenes();
  950. if (obs_missing_files_count(files) > 0 &&
  951. !App()->IsMissingFilesCheckDisabled()) {
  952. /* the window hasn't fully initialized by this point on macOS,
  953. * so put this at the end of the current task queue. Fixes a
  954. * bug where the window be behind OBS on startup */
  955. QTimer::singleShot(0, [this, files] {
  956. missDialog = new OBSMissingFiles(files, this);
  957. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  958. missDialog->show();
  959. missDialog->raise();
  960. });
  961. } else {
  962. obs_missing_files_destroy(files);
  963. }
  964. disableSaving--;
  965. if (api) {
  966. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  967. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  968. }
  969. }
  970. #define SERVICE_PATH "service.json"
  971. void OBSBasic::SaveService()
  972. {
  973. if (!service)
  974. return;
  975. char serviceJsonPath[512];
  976. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  977. SERVICE_PATH);
  978. if (ret <= 0)
  979. return;
  980. obs_data_t *data = obs_data_create();
  981. obs_data_t *settings = obs_service_get_settings(service);
  982. obs_data_set_string(data, "type", obs_service_get_type(service));
  983. obs_data_set_obj(data, "settings", settings);
  984. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  985. blog(LOG_WARNING, "Failed to save service");
  986. obs_data_release(settings);
  987. obs_data_release(data);
  988. }
  989. bool OBSBasic::LoadService()
  990. {
  991. const char *type;
  992. char serviceJsonPath[512];
  993. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  994. SERVICE_PATH);
  995. if (ret <= 0)
  996. return false;
  997. obs_data_t *data =
  998. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  999. if (!data)
  1000. return false;
  1001. obs_data_set_default_string(data, "type", "rtmp_common");
  1002. type = obs_data_get_string(data, "type");
  1003. obs_data_t *settings = obs_data_get_obj(data, "settings");
  1004. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  1005. service = obs_service_create(type, "default_service", settings,
  1006. hotkey_data);
  1007. obs_service_release(service);
  1008. obs_data_release(hotkey_data);
  1009. obs_data_release(settings);
  1010. obs_data_release(data);
  1011. return !!service;
  1012. }
  1013. bool OBSBasic::InitService()
  1014. {
  1015. ProfileScope("OBSBasic::InitService");
  1016. if (LoadService())
  1017. return true;
  1018. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1019. nullptr);
  1020. if (!service)
  1021. return false;
  1022. obs_service_release(service);
  1023. return true;
  1024. }
  1025. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1026. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1027. 2.5, 2.75, 3.0, 0.0};
  1028. extern void CheckExistingCookieId();
  1029. bool OBSBasic::InitBasicConfigDefaults()
  1030. {
  1031. QList<QScreen *> screens = QGuiApplication::screens();
  1032. if (!screens.size()) {
  1033. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1034. "technically shouldn't be possible.");
  1035. return false;
  1036. }
  1037. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1038. uint32_t cx = primaryScreen->size().width();
  1039. uint32_t cy = primaryScreen->size().height();
  1040. cx *= devicePixelRatioF();
  1041. cy *= devicePixelRatioF();
  1042. bool oldResolutionDefaults = config_get_bool(
  1043. App()->GlobalConfig(), "General", "Pre19Defaults");
  1044. /* use 1920x1080 for new default base res if main monitor is above
  1045. * 1920x1080, but don't apply for people from older builds -- only to
  1046. * new users */
  1047. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1048. cx = 1920;
  1049. cy = 1080;
  1050. }
  1051. bool changed = false;
  1052. /* ----------------------------------------------------- */
  1053. /* move over old FFmpeg track settings */
  1054. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1055. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1056. int track = (int)config_get_int(basicConfig, "AdvOut",
  1057. "FFAudioTrack");
  1058. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1059. 1LL << (track - 1));
  1060. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1061. changed = true;
  1062. }
  1063. /* ----------------------------------------------------- */
  1064. /* move over mixer values in advanced if older config */
  1065. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1066. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1067. uint64_t track =
  1068. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1069. track = 1ULL << (track - 1);
  1070. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1071. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1072. changed = true;
  1073. }
  1074. /* ----------------------------------------------------- */
  1075. /* set twitch chat extensions to "both" if prev version */
  1076. /* is under 24.1 */
  1077. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1078. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1079. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1080. changed = true;
  1081. }
  1082. /* ----------------------------------------------------- */
  1083. /* move bitrate enforcement setting to new value */
  1084. if (config_has_user_value(basicConfig, "SimpleOutput",
  1085. "EnforceBitrate") &&
  1086. !config_has_user_value(basicConfig, "Stream1",
  1087. "IgnoreRecommended") &&
  1088. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1089. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1090. "EnforceBitrate");
  1091. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1092. !enforce);
  1093. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1094. true);
  1095. changed = true;
  1096. }
  1097. /* ----------------------------------------------------- */
  1098. if (changed)
  1099. config_save_safe(basicConfig, "tmp", nullptr);
  1100. /* ----------------------------------------------------- */
  1101. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1102. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1103. false);
  1104. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1105. GetDefaultVideoSavePath().c_str());
  1106. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  1107. "mkv");
  1108. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1109. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1110. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1111. false);
  1112. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1113. "veryfast");
  1114. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
  1115. "hq");
  1116. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1117. "Stream");
  1118. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1119. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1120. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1121. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1122. "Replay");
  1123. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1124. true);
  1125. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1126. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1127. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1128. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1129. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1130. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1131. GetDefaultVideoSavePath().c_str());
  1132. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "mkv");
  1133. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1134. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1135. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1136. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1137. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1138. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1139. GetDefaultVideoSavePath().c_str());
  1140. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1141. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1142. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1143. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1144. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1145. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1146. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1147. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1148. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1149. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1150. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1151. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1152. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1153. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1154. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1155. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1156. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1157. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1158. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1159. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1160. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1161. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1162. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1163. config_save_safe(basicConfig, "tmp", nullptr);
  1164. }
  1165. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1166. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1167. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1168. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1169. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1170. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1171. config_set_default_uint(basicConfig, "Output", "RetryDelay", 10);
  1172. config_set_default_uint(basicConfig, "Output", "MaxRetries", 20);
  1173. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1174. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1175. false);
  1176. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1177. false);
  1178. int i = 0;
  1179. uint32_t scale_cx = cx;
  1180. uint32_t scale_cy = cy;
  1181. /* use a default scaled resolution that has a pixel count no higher
  1182. * than 1280x720 */
  1183. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1184. double scale = scaled_vals[i++];
  1185. scale_cx = uint32_t(double(cx) / scale);
  1186. scale_cy = uint32_t(double(cy) / scale);
  1187. }
  1188. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1189. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1190. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1191. * changing */
  1192. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1193. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1194. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1195. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1196. config_save_safe(basicConfig, "tmp", nullptr);
  1197. }
  1198. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1199. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1200. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1201. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1202. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1203. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1204. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1205. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1206. config_set_default_string(basicConfig, "Video", "ColorRange",
  1207. "Partial");
  1208. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1209. "default");
  1210. config_set_default_string(
  1211. basicConfig, "Audio", "MonitoringDeviceName",
  1212. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1213. ".Default"));
  1214. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1215. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1216. "Stereo");
  1217. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1218. VOLUME_METER_DECAY_FAST);
  1219. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1220. CheckExistingCookieId();
  1221. return true;
  1222. }
  1223. extern bool EncoderAvailable(const char *encoder);
  1224. void OBSBasic::InitBasicConfigDefaults2()
  1225. {
  1226. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1227. "Pre23Defaults");
  1228. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1229. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1230. useNV ? SIMPLE_ENCODER_NVENC
  1231. : SIMPLE_ENCODER_X264);
  1232. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1233. useNV ? SIMPLE_ENCODER_NVENC
  1234. : SIMPLE_ENCODER_X264);
  1235. }
  1236. bool OBSBasic::InitBasicConfig()
  1237. {
  1238. ProfileScope("OBSBasic::InitBasicConfig");
  1239. char configPath[512];
  1240. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1241. if (ret <= 0) {
  1242. OBSErrorBox(nullptr, "Failed to get profile path");
  1243. return false;
  1244. }
  1245. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1246. OBSErrorBox(nullptr, "Failed to create profile path");
  1247. return false;
  1248. }
  1249. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1250. if (ret <= 0) {
  1251. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1252. return false;
  1253. }
  1254. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1255. if (code != CONFIG_SUCCESS) {
  1256. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1257. return false;
  1258. }
  1259. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1260. const char *curName = config_get_string(App()->GlobalConfig(),
  1261. "Basic", "Profile");
  1262. config_set_string(basicConfig, "General", "Name", curName);
  1263. basicConfig.SaveSafe("tmp");
  1264. }
  1265. return InitBasicConfigDefaults();
  1266. }
  1267. void OBSBasic::InitOBSCallbacks()
  1268. {
  1269. ProfileScope("OBSBasic::InitOBSCallbacks");
  1270. signalHandlers.reserve(signalHandlers.size() + 7);
  1271. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1272. OBSBasic::SourceCreated, this);
  1273. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1274. OBSBasic::SourceRemoved, this);
  1275. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1276. OBSBasic::SourceActivated, this);
  1277. signalHandlers.emplace_back(obs_get_signal_handler(),
  1278. "source_deactivate",
  1279. OBSBasic::SourceDeactivated, this);
  1280. signalHandlers.emplace_back(obs_get_signal_handler(),
  1281. "source_audio_activate",
  1282. OBSBasic::SourceAudioActivated, this);
  1283. signalHandlers.emplace_back(obs_get_signal_handler(),
  1284. "source_audio_deactivate",
  1285. OBSBasic::SourceAudioDeactivated, this);
  1286. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1287. OBSBasic::SourceRenamed, this);
  1288. }
  1289. void OBSBasic::InitPrimitives()
  1290. {
  1291. ProfileScope("OBSBasic::InitPrimitives");
  1292. obs_enter_graphics();
  1293. gs_render_start(true);
  1294. gs_vertex2f(0.0f, 0.0f);
  1295. gs_vertex2f(0.0f, 1.0f);
  1296. gs_vertex2f(1.0f, 0.0f);
  1297. gs_vertex2f(1.0f, 1.0f);
  1298. box = gs_render_save();
  1299. gs_render_start(true);
  1300. gs_vertex2f(0.0f, 0.0f);
  1301. gs_vertex2f(0.0f, 1.0f);
  1302. boxLeft = gs_render_save();
  1303. gs_render_start(true);
  1304. gs_vertex2f(0.0f, 0.0f);
  1305. gs_vertex2f(1.0f, 0.0f);
  1306. boxTop = gs_render_save();
  1307. gs_render_start(true);
  1308. gs_vertex2f(1.0f, 0.0f);
  1309. gs_vertex2f(1.0f, 1.0f);
  1310. boxRight = gs_render_save();
  1311. gs_render_start(true);
  1312. gs_vertex2f(0.0f, 1.0f);
  1313. gs_vertex2f(1.0f, 1.0f);
  1314. boxBottom = gs_render_save();
  1315. gs_render_start(true);
  1316. for (int i = 0; i <= 360; i += (360 / 20)) {
  1317. float pos = RAD(float(i));
  1318. gs_vertex2f(cosf(pos), sinf(pos));
  1319. }
  1320. circle = gs_render_save();
  1321. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1322. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1323. obs_leave_graphics();
  1324. }
  1325. void OBSBasic::ReplayBufferClicked()
  1326. {
  1327. if (outputHandler->ReplayBufferActive())
  1328. StopReplayBuffer();
  1329. else
  1330. StartReplayBuffer();
  1331. };
  1332. void OBSBasic::AddVCamButton()
  1333. {
  1334. vcamButton = new ReplayBufferButton(QTStr("Basic.Main.StartVirtualCam"),
  1335. this);
  1336. vcamButton->setCheckable(true);
  1337. connect(vcamButton.data(), &QPushButton::clicked, this,
  1338. &OBSBasic::VCamButtonClicked);
  1339. vcamButton->setProperty("themeID", "vcamButton");
  1340. ui->buttonsVLayout->insertWidget(2, vcamButton);
  1341. setTabOrder(ui->recordButton, vcamButton);
  1342. setTabOrder(vcamButton, ui->modeSwitch);
  1343. }
  1344. void OBSBasic::ResetOutputs()
  1345. {
  1346. ProfileScope("OBSBasic::ResetOutputs");
  1347. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1348. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1349. if (!outputHandler || !outputHandler->Active()) {
  1350. outputHandler.reset();
  1351. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1352. : CreateSimpleOutputHandler(this));
  1353. delete replayBufferButton;
  1354. delete replayLayout;
  1355. if (outputHandler->replayBuffer) {
  1356. replayBufferButton = new ReplayBufferButton(
  1357. QTStr("Basic.Main.StartReplayBuffer"), this);
  1358. replayBufferButton->setCheckable(true);
  1359. connect(replayBufferButton.data(),
  1360. &QPushButton::clicked, this,
  1361. &OBSBasic::ReplayBufferClicked);
  1362. replayBufferButton->setSizePolicy(QSizePolicy::Ignored,
  1363. QSizePolicy::Fixed);
  1364. replayLayout = new QHBoxLayout(this);
  1365. replayLayout->addWidget(replayBufferButton);
  1366. replayBufferButton->setProperty("themeID",
  1367. "replayBufferButton");
  1368. ui->buttonsVLayout->insertLayout(2, replayLayout);
  1369. setTabOrder(ui->recordButton, replayBufferButton);
  1370. setTabOrder(replayBufferButton,
  1371. ui->buttonsVLayout->itemAt(3)->widget());
  1372. }
  1373. if (sysTrayReplayBuffer)
  1374. sysTrayReplayBuffer->setEnabled(
  1375. !!outputHandler->replayBuffer);
  1376. } else {
  1377. outputHandler->Update();
  1378. }
  1379. }
  1380. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  1381. const char *slot);
  1382. #define STARTUP_SEPARATOR \
  1383. "==== Startup complete ==============================================="
  1384. #define SHUTDOWN_SEPARATOR \
  1385. "==== Shutting down =================================================="
  1386. #define UNSUPPORTED_ERROR \
  1387. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1388. "not found. Your GPU may not be supported."
  1389. #define UNKNOWN_ERROR \
  1390. "Failed to initialize video. Your GPU may not be supported, " \
  1391. "or your graphics drivers may need to be updated."
  1392. void OBSBasic::OBSInit()
  1393. {
  1394. ProfileScope("OBSBasic::OBSInit");
  1395. const char *sceneCollection = config_get_string(
  1396. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1397. char savePath[1024];
  1398. char fileName[1024];
  1399. int ret;
  1400. if (!sceneCollection)
  1401. throw "Failed to get scene collection name";
  1402. ret = snprintf(fileName, sizeof(fileName),
  1403. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1404. if (ret <= 0)
  1405. throw "Failed to create scene collection file name";
  1406. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1407. if (ret <= 0)
  1408. throw "Failed to get scene collection json file path";
  1409. if (!InitBasicConfig())
  1410. throw "Failed to load basic.ini";
  1411. if (!ResetAudio())
  1412. throw "Failed to initialize audio";
  1413. ret = ResetVideo();
  1414. switch (ret) {
  1415. case OBS_VIDEO_MODULE_NOT_FOUND:
  1416. throw "Failed to initialize video: Graphics module not found";
  1417. case OBS_VIDEO_NOT_SUPPORTED:
  1418. throw UNSUPPORTED_ERROR;
  1419. case OBS_VIDEO_INVALID_PARAM:
  1420. throw "Failed to initialize video: Invalid parameters";
  1421. default:
  1422. if (ret != OBS_VIDEO_SUCCESS)
  1423. throw UNKNOWN_ERROR;
  1424. }
  1425. /* load audio monitoring */
  1426. #if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
  1427. const char *device_name =
  1428. config_get_string(basicConfig, "Audio", "MonitoringDeviceName");
  1429. const char *device_id =
  1430. config_get_string(basicConfig, "Audio", "MonitoringDeviceId");
  1431. obs_set_audio_monitoring_device(device_name, device_id);
  1432. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1433. device_name, device_id);
  1434. #endif
  1435. InitOBSCallbacks();
  1436. InitHotkeys();
  1437. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1438. * to ship with */
  1439. #if defined(_WIN32) && !defined(_DEBUG)
  1440. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1441. LoadLibraryW(L"Qt5Network");
  1442. #else
  1443. LoadLibraryW(L"Qt6Network");
  1444. #endif
  1445. #endif
  1446. AddExtraModulePaths();
  1447. blog(LOG_INFO, "---------------------------------");
  1448. obs_load_all_modules();
  1449. blog(LOG_INFO, "---------------------------------");
  1450. obs_log_loaded_modules();
  1451. blog(LOG_INFO, "---------------------------------");
  1452. obs_post_load_modules();
  1453. #ifdef BROWSER_AVAILABLE
  1454. cef = obs_browser_init_panel();
  1455. #endif
  1456. obs_data_t *obsData = obs_get_private_data();
  1457. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1458. if (vcamEnabled) {
  1459. AddVCamButton();
  1460. }
  1461. obs_data_release(obsData);
  1462. InitBasicConfigDefaults2();
  1463. CheckForSimpleModeX264Fallback();
  1464. blog(LOG_INFO, STARTUP_SEPARATOR);
  1465. ResetOutputs();
  1466. CreateHotkeys();
  1467. if (!InitService())
  1468. throw "Failed to initialize service";
  1469. InitPrimitives();
  1470. sceneDuplicationMode = config_get_bool(
  1471. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1472. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1473. "SwapScenesMode");
  1474. editPropertiesMode = config_get_bool(
  1475. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1476. if (!opt_studio_mode) {
  1477. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1478. "BasicWindow",
  1479. "PreviewProgramMode"));
  1480. } else {
  1481. SetPreviewProgramMode(true);
  1482. opt_studio_mode = false;
  1483. }
  1484. #define SET_VISIBILITY(name, control) \
  1485. do { \
  1486. if (config_has_user_value(App()->GlobalConfig(), \
  1487. "BasicWindow", name)) { \
  1488. bool visible = config_get_bool(App()->GlobalConfig(), \
  1489. "BasicWindow", name); \
  1490. ui->control->setChecked(visible); \
  1491. } \
  1492. } while (false)
  1493. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1494. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1495. #undef SET_VISIBILITY
  1496. bool sourceIconsVisible = config_get_bool(
  1497. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1498. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1499. bool contextVisible = config_get_bool(
  1500. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1501. ui->toggleContextBar->setChecked(contextVisible);
  1502. ui->contextContainer->setVisible(contextVisible);
  1503. if (contextVisible)
  1504. UpdateContextBar(true);
  1505. {
  1506. ProfileScope("OBSBasic::Load");
  1507. disableSaving--;
  1508. Load(savePath);
  1509. disableSaving++;
  1510. }
  1511. TimedCheckForUpdates();
  1512. loaded = true;
  1513. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1514. "PreviewEnabled");
  1515. if (!previewEnabled && !IsPreviewProgramMode())
  1516. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1517. Qt::QueuedConnection,
  1518. Q_ARG(bool, previewEnabled));
  1519. #ifdef _WIN32
  1520. uint32_t winVer = GetWindowsVersion();
  1521. if (winVer > 0 && winVer < 0x602) {
  1522. bool disableAero =
  1523. config_get_bool(basicConfig, "Video", "DisableAero");
  1524. SetAeroEnabled(!disableAero);
  1525. }
  1526. #endif
  1527. RefreshSceneCollections();
  1528. RefreshProfiles();
  1529. disableSaving--;
  1530. auto addDisplay = [this](OBSQTDisplay *window) {
  1531. obs_display_add_draw_callback(window->GetDisplay(),
  1532. OBSBasic::RenderMain, this);
  1533. struct obs_video_info ovi;
  1534. if (obs_get_video_info(&ovi))
  1535. ResizePreview(ovi.base_width, ovi.base_height);
  1536. };
  1537. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1538. #ifdef _WIN32
  1539. SetWin32DropStyle(this);
  1540. show();
  1541. #endif
  1542. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1543. "AlwaysOnTop");
  1544. #ifdef ENABLE_WAYLAND
  1545. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1546. #else
  1547. bool isWayland = false;
  1548. #endif
  1549. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1550. SetAlwaysOnTop(this, true);
  1551. ui->actionAlwaysOnTop->setChecked(true);
  1552. } else if (isWayland) {
  1553. if (opt_always_on_top)
  1554. blog(LOG_INFO,
  1555. "Always On Top not available on Wayland, ignoring.");
  1556. ui->actionAlwaysOnTop->setEnabled(false);
  1557. ui->actionAlwaysOnTop->setVisible(false);
  1558. }
  1559. #ifndef _WIN32
  1560. show();
  1561. #endif
  1562. /* setup stats dock */
  1563. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1564. statsDock->setWidget(statsDlg);
  1565. /* ----------------------------- */
  1566. /* add custom browser docks */
  1567. #ifdef BROWSER_AVAILABLE
  1568. if (cef) {
  1569. QAction *action = new QAction(QTStr("Basic.MainMenu."
  1570. "View.Docks."
  1571. "CustomBrowserDocks"),
  1572. this);
  1573. ui->viewMenuDocks->insertAction(ui->toggleScenes, action);
  1574. connect(action, &QAction::triggered, this,
  1575. &OBSBasic::ManageExtraBrowserDocks);
  1576. ui->viewMenuDocks->insertSeparator(ui->toggleScenes);
  1577. LoadExtraBrowserDocks();
  1578. }
  1579. #endif
  1580. const char *dockStateStr = config_get_string(
  1581. App()->GlobalConfig(), "BasicWindow", "DockState");
  1582. if (!dockStateStr) {
  1583. on_resetUI_triggered();
  1584. } else {
  1585. QByteArray dockState =
  1586. QByteArray::fromBase64(QByteArray(dockStateStr));
  1587. if (!restoreState(dockState))
  1588. on_resetUI_triggered();
  1589. }
  1590. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1591. "Pre23Defaults");
  1592. if (pre23Defaults) {
  1593. bool resetDockLock23 = config_get_bool(
  1594. App()->GlobalConfig(), "General", "ResetDockLock23");
  1595. if (!resetDockLock23) {
  1596. config_set_bool(App()->GlobalConfig(), "General",
  1597. "ResetDockLock23", true);
  1598. config_remove_value(App()->GlobalConfig(),
  1599. "BasicWindow", "DocksLocked");
  1600. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1601. }
  1602. }
  1603. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1604. "DocksLocked");
  1605. on_lockUI_toggled(docksLocked);
  1606. ui->lockUI->blockSignals(true);
  1607. ui->lockUI->setChecked(docksLocked);
  1608. ui->lockUI->blockSignals(false);
  1609. #ifndef __APPLE__
  1610. SystemTray(true);
  1611. #endif
  1612. #ifdef __APPLE__
  1613. disableColorSpaceConversion(this);
  1614. #endif
  1615. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1616. "General", "LastVersion");
  1617. bool first_run =
  1618. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1619. if (!first_run) {
  1620. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1621. true);
  1622. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1623. }
  1624. if (!first_run && !has_last_version && !Active())
  1625. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1626. Qt::QueuedConnection);
  1627. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1628. "VerticalVolControl"));
  1629. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1630. on_stats_triggered();
  1631. OBSBasicStats::InitializeValues();
  1632. /* ----------------------- */
  1633. /* Add multiview menu */
  1634. ui->viewMenu->addSeparator();
  1635. multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
  1636. ui->viewMenu->addMenu(multiviewProjectorMenu);
  1637. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1638. SLOT(OpenMultiviewProjector()));
  1639. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1640. &OBSBasic::UpdateMultiviewProjectorMenu);
  1641. ui->viewMenu->addAction(QTStr("MultiviewWindowed"), this,
  1642. SLOT(OpenMultiviewWindow()));
  1643. ui->sources->UpdateIcons();
  1644. #if !defined(_WIN32)
  1645. delete ui->actionShowCrashLogs;
  1646. delete ui->actionUploadLastCrashLog;
  1647. delete ui->menuCrashLogs;
  1648. ui->actionShowCrashLogs = nullptr;
  1649. ui->actionUploadLastCrashLog = nullptr;
  1650. ui->menuCrashLogs = nullptr;
  1651. #if !defined(__APPLE__)
  1652. delete ui->actionCheckForUpdates;
  1653. ui->actionCheckForUpdates = nullptr;
  1654. #endif
  1655. #endif
  1656. #ifdef __APPLE__
  1657. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1658. delete ui->actionFullscreenInterface;
  1659. ui->actionFullscreenInterface = nullptr;
  1660. #endif
  1661. #if defined(_WIN32) || defined(__APPLE__)
  1662. if (App()->IsUpdaterDisabled())
  1663. ui->actionCheckForUpdates->setEnabled(false);
  1664. #endif
  1665. OnFirstLoad();
  1666. activateWindow();
  1667. #ifdef __APPLE__
  1668. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1669. Qt::QueuedConnection, Q_ARG(int, 10));
  1670. #endif
  1671. }
  1672. void OBSBasic::OnFirstLoad()
  1673. {
  1674. if (api)
  1675. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1676. #if defined(BROWSER_AVAILABLE) && defined(_WIN32)
  1677. /* Attempt to load init screen if available */
  1678. if (cef) {
  1679. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1680. connect(wnit, &WhatsNewInfoThread::Result, this,
  1681. &OBSBasic::ReceivedIntroJson);
  1682. introCheckThread.reset(wnit);
  1683. introCheckThread->start();
  1684. }
  1685. #endif
  1686. Auth::Load();
  1687. bool showLogViewerOnStartup = config_get_bool(
  1688. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1689. if (showLogViewerOnStartup)
  1690. on_actionViewCurrentLog_triggered();
  1691. }
  1692. void OBSBasic::DeferredSysTrayLoad(int requeueCount)
  1693. {
  1694. if (--requeueCount > 0) {
  1695. QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
  1696. Qt::QueuedConnection,
  1697. Q_ARG(int, requeueCount));
  1698. return;
  1699. }
  1700. /* Minimizng to tray on initial startup does not work on mac
  1701. * unless it is done in the deferred load */
  1702. SystemTray(true);
  1703. }
  1704. /* shows a "what's new" page on startup of new versions using CEF */
  1705. void OBSBasic::ReceivedIntroJson(const QString &text)
  1706. {
  1707. #ifdef BROWSER_AVAILABLE
  1708. #ifdef _WIN32
  1709. if (closing)
  1710. return;
  1711. std::string err;
  1712. Json json = Json::parse(QT_TO_UTF8(text), err);
  1713. if (!err.empty())
  1714. return;
  1715. std::string info_url;
  1716. int info_increment = -1;
  1717. /* check to see if there's an info page for this version */
  1718. const Json::array &items = json.array_items();
  1719. for (const Json &item : items) {
  1720. const std::string &version = item["version"].string_value();
  1721. const std::string &url = item["url"].string_value();
  1722. int increment = item["increment"].int_value();
  1723. int rc = item["RC"].int_value();
  1724. int major = 0;
  1725. int minor = 0;
  1726. sscanf(version.c_str(), "%d.%d", &major, &minor);
  1727. #if OBS_RELEASE_CANDIDATE > 0
  1728. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1729. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1730. rc == OBS_RELEASE_CANDIDATE) {
  1731. #else
  1732. if (major == LIBOBS_API_MAJOR_VER &&
  1733. minor == LIBOBS_API_MINOR_VER && rc == 0) {
  1734. #endif
  1735. info_url = url;
  1736. info_increment = increment;
  1737. }
  1738. }
  1739. /* this version was not found, or no info for this version */
  1740. if (info_increment == -1) {
  1741. return;
  1742. }
  1743. #if OBS_RELEASE_CANDIDATE > 0
  1744. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1745. "LastRCVersion");
  1746. #else
  1747. uint32_t lastVersion =
  1748. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  1749. #endif
  1750. int current_version_increment = -1;
  1751. #if OBS_RELEASE_CANDIDATE > 0
  1752. if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
  1753. #else
  1754. if ((lastVersion & ~0xFFFF) < (LIBOBS_API_VER & ~0xFFFF)) {
  1755. #endif
  1756. config_set_int(App()->GlobalConfig(), "General",
  1757. "InfoIncrement", -1);
  1758. } else {
  1759. current_version_increment = config_get_int(
  1760. App()->GlobalConfig(), "General", "InfoIncrement");
  1761. }
  1762. if (info_increment <= current_version_increment) {
  1763. return;
  1764. }
  1765. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  1766. info_increment);
  1767. /* Don't show What's New dialog for new users */
  1768. #if !defined(OBS_RELEASE_CANDIDATE) || OBS_RELEASE_CANDIDATE == 0
  1769. if (!lastVersion) {
  1770. return;
  1771. }
  1772. #endif
  1773. cef->init_browser();
  1774. WhatsNewBrowserInitThread *wnbit =
  1775. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  1776. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  1777. &OBSBasic::ShowWhatsNew);
  1778. whatsNewInitThread.reset(wnbit);
  1779. whatsNewInitThread->start();
  1780. #else
  1781. UNUSED_PARAMETER(text);
  1782. #endif
  1783. #else
  1784. UNUSED_PARAMETER(text);
  1785. #endif
  1786. }
  1787. void OBSBasic::ShowWhatsNew(const QString &url)
  1788. {
  1789. #ifdef BROWSER_AVAILABLE
  1790. #ifdef _WIN32
  1791. if (closing)
  1792. return;
  1793. std::string info_url = QT_TO_UTF8(url);
  1794. QDialog *dlg = new QDialog(this);
  1795. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  1796. dlg->setWindowTitle("What's New");
  1797. dlg->resize(700, 600);
  1798. Qt::WindowFlags flags = dlg->windowFlags();
  1799. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  1800. dlg->setWindowFlags(flags & (~helpFlag));
  1801. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  1802. if (!cefWidget) {
  1803. return;
  1804. }
  1805. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  1806. SLOT(setWindowTitle(const QString &)));
  1807. QPushButton *close = new QPushButton(QTStr("Close"));
  1808. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  1809. QHBoxLayout *bottomLayout = new QHBoxLayout();
  1810. bottomLayout->addStretch();
  1811. bottomLayout->addWidget(close);
  1812. bottomLayout->addStretch();
  1813. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  1814. topLayout->addWidget(cefWidget);
  1815. topLayout->addLayout(bottomLayout);
  1816. dlg->show();
  1817. #else
  1818. UNUSED_PARAMETER(url);
  1819. #endif
  1820. #else
  1821. UNUSED_PARAMETER(url);
  1822. #endif
  1823. }
  1824. void OBSBasic::UpdateMultiviewProjectorMenu()
  1825. {
  1826. multiviewProjectorMenu->clear();
  1827. AddProjectorMenuMonitors(multiviewProjectorMenu, this,
  1828. SLOT(OpenMultiviewProjector()));
  1829. }
  1830. void OBSBasic::InitHotkeys()
  1831. {
  1832. ProfileScope("OBSBasic::InitHotkeys");
  1833. struct obs_hotkeys_translations t = {};
  1834. t.insert = Str("Hotkeys.Insert");
  1835. t.del = Str("Hotkeys.Delete");
  1836. t.home = Str("Hotkeys.Home");
  1837. t.end = Str("Hotkeys.End");
  1838. t.page_up = Str("Hotkeys.PageUp");
  1839. t.page_down = Str("Hotkeys.PageDown");
  1840. t.num_lock = Str("Hotkeys.NumLock");
  1841. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1842. t.caps_lock = Str("Hotkeys.CapsLock");
  1843. t.backspace = Str("Hotkeys.Backspace");
  1844. t.tab = Str("Hotkeys.Tab");
  1845. t.print = Str("Hotkeys.Print");
  1846. t.pause = Str("Hotkeys.Pause");
  1847. t.left = Str("Hotkeys.Left");
  1848. t.right = Str("Hotkeys.Right");
  1849. t.up = Str("Hotkeys.Up");
  1850. t.down = Str("Hotkeys.Down");
  1851. #ifdef _WIN32
  1852. t.meta = Str("Hotkeys.Windows");
  1853. #else
  1854. t.meta = Str("Hotkeys.Super");
  1855. #endif
  1856. t.menu = Str("Hotkeys.Menu");
  1857. t.space = Str("Hotkeys.Space");
  1858. t.numpad_num = Str("Hotkeys.NumpadNum");
  1859. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1860. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1861. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1862. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1863. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1864. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1865. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1866. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1867. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1868. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1869. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1870. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1871. t.mouse_num = Str("Hotkeys.MouseButton");
  1872. t.escape = Str("Hotkeys.Escape");
  1873. obs_hotkeys_set_translations(&t);
  1874. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1875. Str("Push-to-mute"),
  1876. Str("Push-to-talk"));
  1877. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  1878. Str("SceneItemHide"));
  1879. obs_hotkey_enable_callback_rerouting(true);
  1880. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1881. }
  1882. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1883. {
  1884. obs_hotkey_trigger_routed_callback(id, pressed);
  1885. }
  1886. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1887. {
  1888. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1889. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1890. Q_ARG(obs_hotkey_id, id),
  1891. Q_ARG(bool, pressed));
  1892. }
  1893. void OBSBasic::CreateHotkeys()
  1894. {
  1895. ProfileScope("OBSBasic::CreateHotkeys");
  1896. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  1897. const char *info =
  1898. config_get_string(basicConfig, "Hotkeys", name);
  1899. if (!info)
  1900. return {};
  1901. obs_data_t *data = obs_data_create_from_json(info);
  1902. if (!data)
  1903. return {};
  1904. OBSData res = data;
  1905. obs_data_release(data);
  1906. return res;
  1907. };
  1908. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  1909. obs_data_array_t *array =
  1910. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1911. obs_hotkey_load(id, array);
  1912. obs_data_array_release(array);
  1913. };
  1914. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1915. const char *name1) {
  1916. obs_data_array_t *array0 =
  1917. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1918. obs_data_array_t *array1 =
  1919. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1920. obs_hotkey_pair_load(id, array0, array1);
  1921. obs_data_array_release(array0);
  1922. obs_data_array_release(array1);
  1923. };
  1924. #define MAKE_CALLBACK(pred, method, log_action) \
  1925. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  1926. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  1927. if ((pred) && pressed) { \
  1928. blog(LOG_INFO, log_action " due to hotkey"); \
  1929. method(); \
  1930. return true; \
  1931. } \
  1932. return false; \
  1933. }
  1934. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1935. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  1936. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  1937. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  1938. basic.ui->streamButton->isEnabled(),
  1939. basic.StartStreaming, "Starting stream"),
  1940. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  1941. basic.ui->streamButton->isEnabled(),
  1942. basic.StopStreaming, "Stopping stream"),
  1943. this, this);
  1944. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  1945. "OBSBasic.StopStreaming");
  1946. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  1947. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  1948. if (basic.outputHandler->StreamingActive() && pressed) {
  1949. basic.ForceStopStreaming();
  1950. }
  1951. };
  1952. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1953. "OBSBasic.ForceStopStreaming",
  1954. Str("Basic.Main.ForceStopStreaming"), cb, this);
  1955. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  1956. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1957. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  1958. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  1959. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  1960. !basic.ui->recordButton->isChecked(),
  1961. basic.StartRecording, "Starting recording"),
  1962. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  1963. basic.ui->recordButton->isChecked(),
  1964. basic.StopRecording, "Stopping recording"),
  1965. this, this);
  1966. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  1967. "OBSBasic.StopRecording");
  1968. pauseHotkeys = obs_hotkey_pair_register_frontend(
  1969. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  1970. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  1971. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  1972. basic.PauseRecording, "Pausing recording"),
  1973. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  1974. basic.UnpauseRecording, "Unpausing recording"),
  1975. this, this);
  1976. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  1977. "OBSBasic.UnpauseRecording");
  1978. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1979. "OBSBasic.StartReplayBuffer",
  1980. Str("Basic.Main.StartReplayBuffer"),
  1981. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  1982. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1983. basic.StartReplayBuffer,
  1984. "Starting replay buffer"),
  1985. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1986. basic.StopReplayBuffer, "Stopping replay buffer"),
  1987. this, this);
  1988. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  1989. "OBSBasic.StopReplayBuffer");
  1990. if (vcamEnabled) {
  1991. vcamHotkeys = obs_hotkey_pair_register_frontend(
  1992. "OBSBasic.StartVirtualCam",
  1993. Str("Basic.Main.StartVirtualCam"),
  1994. "OBSBasic.StopVirtualCam",
  1995. Str("Basic.Main.StopVirtualCam"),
  1996. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  1997. basic.StartVirtualCam,
  1998. "Starting virtual camera"),
  1999. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2000. basic.StopVirtualCam,
  2001. "Stopping virtual camera"),
  2002. this, this);
  2003. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2004. "OBSBasic.StopVirtualCam");
  2005. }
  2006. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2007. "OBSBasic.EnablePreview",
  2008. Str("Basic.Main.PreviewConextMenu.Enable"),
  2009. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2010. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2011. "Enabling preview"),
  2012. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2013. "Disabling preview"),
  2014. this, this);
  2015. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2016. "OBSBasic.DisablePreview");
  2017. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2018. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2019. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2020. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2021. basic.ShowContextBar, "Showing Context Bar"),
  2022. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2023. basic.HideContextBar, "Hiding Context Bar"),
  2024. this, this);
  2025. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2026. "OBSBasic.HideContextBar");
  2027. #undef MAKE_CALLBACK
  2028. auto togglePreviewProgram = [](void *data, obs_hotkey_id,
  2029. obs_hotkey_t *, bool pressed) {
  2030. if (pressed)
  2031. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2032. "on_modeSwitch_clicked",
  2033. Qt::QueuedConnection);
  2034. };
  2035. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  2036. "OBSBasic.TogglePreviewProgram",
  2037. Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
  2038. this);
  2039. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  2040. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2041. bool pressed) {
  2042. if (pressed)
  2043. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2044. "TransitionClicked",
  2045. Qt::QueuedConnection);
  2046. };
  2047. transitionHotkey = obs_hotkey_register_frontend(
  2048. "OBSBasic.Transition", Str("Transition"), transition, this);
  2049. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2050. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2051. bool pressed) {
  2052. if (pressed)
  2053. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2054. "ResetStatsHotkey",
  2055. Qt::QueuedConnection);
  2056. };
  2057. statsHotkey = obs_hotkey_register_frontend(
  2058. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2059. resetStats, this);
  2060. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2061. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2062. bool pressed) {
  2063. if (pressed)
  2064. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2065. "Screenshot",
  2066. Qt::QueuedConnection);
  2067. };
  2068. screenshotHotkey = obs_hotkey_register_frontend(
  2069. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2070. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2071. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2072. bool pressed) {
  2073. if (pressed)
  2074. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2075. "ScreenshotSelectedSource",
  2076. Qt::QueuedConnection);
  2077. };
  2078. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2079. "OBSBasic.SelectedSourceScreenshot",
  2080. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2081. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2082. }
  2083. void OBSBasic::ClearHotkeys()
  2084. {
  2085. obs_hotkey_pair_unregister(streamingHotkeys);
  2086. obs_hotkey_pair_unregister(recordingHotkeys);
  2087. obs_hotkey_pair_unregister(pauseHotkeys);
  2088. obs_hotkey_pair_unregister(replayBufHotkeys);
  2089. obs_hotkey_pair_unregister(vcamHotkeys);
  2090. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2091. obs_hotkey_pair_unregister(contextBarHotkeys);
  2092. obs_hotkey_unregister(forceStreamingStopHotkey);
  2093. obs_hotkey_unregister(togglePreviewProgramHotkey);
  2094. obs_hotkey_unregister(transitionHotkey);
  2095. obs_hotkey_unregister(statsHotkey);
  2096. obs_hotkey_unregister(screenshotHotkey);
  2097. obs_hotkey_unregister(sourceScreenshotHotkey);
  2098. }
  2099. OBSBasic::~OBSBasic()
  2100. {
  2101. /* clear out UI event queue */
  2102. QApplication::sendPostedEvents(App());
  2103. if (updateCheckThread && updateCheckThread->isRunning())
  2104. updateCheckThread->wait();
  2105. delete screenshotData;
  2106. delete multiviewProjectorMenu;
  2107. delete previewProjector;
  2108. delete studioProgramProjector;
  2109. delete previewProjectorSource;
  2110. delete previewProjectorMain;
  2111. delete sourceProjector;
  2112. delete sceneProjectorMenu;
  2113. delete scaleFilteringMenu;
  2114. delete colorMenu;
  2115. delete colorWidgetAction;
  2116. delete colorSelect;
  2117. delete deinterlaceMenu;
  2118. delete perSceneTransitionMenu;
  2119. delete shortcutFilter;
  2120. delete trayMenu;
  2121. delete programOptions;
  2122. delete program;
  2123. /* XXX: any obs data must be released before calling obs_shutdown.
  2124. * currently, we can't automate this with C++ RAII because of the
  2125. * delicate nature of obs_shutdown needing to be freed before the UI
  2126. * can be freed, and we have no control over the destruction order of
  2127. * the Qt UI stuff, so we have to manually clear any references to
  2128. * libobs. */
  2129. delete cpuUsageTimer;
  2130. os_cpu_usage_info_destroy(cpuUsageInfo);
  2131. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2132. ClearHotkeys();
  2133. service = nullptr;
  2134. outputHandler.reset();
  2135. if (interaction)
  2136. delete interaction;
  2137. if (properties)
  2138. delete properties;
  2139. if (filters)
  2140. delete filters;
  2141. if (transformWindow)
  2142. delete transformWindow;
  2143. if (advAudioWindow)
  2144. delete advAudioWindow;
  2145. if (about)
  2146. delete about;
  2147. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2148. OBSBasic::RenderMain, this);
  2149. obs_enter_graphics();
  2150. gs_vertexbuffer_destroy(box);
  2151. gs_vertexbuffer_destroy(boxLeft);
  2152. gs_vertexbuffer_destroy(boxTop);
  2153. gs_vertexbuffer_destroy(boxRight);
  2154. gs_vertexbuffer_destroy(boxBottom);
  2155. gs_vertexbuffer_destroy(circle);
  2156. gs_vertexbuffer_destroy(actionSafeMargin);
  2157. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2158. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2159. gs_vertexbuffer_destroy(leftLine);
  2160. gs_vertexbuffer_destroy(topLine);
  2161. gs_vertexbuffer_destroy(rightLine);
  2162. obs_leave_graphics();
  2163. /* When shutting down, sometimes source references can get in to the
  2164. * event queue, and if we don't forcibly process those events they
  2165. * won't get processed until after obs_shutdown has been called. I
  2166. * really wish there were a more elegant way to deal with this via C++,
  2167. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2168. * normal C++ behavior for your data to be freed in the order that you
  2169. * expect or want it to. */
  2170. QApplication::sendPostedEvents(this);
  2171. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2172. LIBOBS_API_VER);
  2173. #if OBS_RELEASE_CANDIDATE > 0
  2174. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2175. OBS_RELEASE_CANDIDATE_VER);
  2176. #endif
  2177. bool alwaysOnTop = IsAlwaysOnTop(this);
  2178. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2179. previewEnabled);
  2180. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2181. alwaysOnTop);
  2182. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2183. "SceneDuplicationMode", sceneDuplicationMode);
  2184. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2185. swapScenesMode);
  2186. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2187. "EditPropertiesMode", editPropertiesMode);
  2188. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2189. "PreviewProgramMode", IsPreviewProgramMode());
  2190. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2191. ui->lockUI->isChecked());
  2192. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2193. #ifdef _WIN32
  2194. uint32_t winVer = GetWindowsVersion();
  2195. if (winVer > 0 && winVer < 0x602) {
  2196. bool disableAero =
  2197. config_get_bool(basicConfig, "Video", "DisableAero");
  2198. if (disableAero) {
  2199. SetAeroEnabled(true);
  2200. }
  2201. }
  2202. #endif
  2203. #ifdef BROWSER_AVAILABLE
  2204. DestroyPanelCookieManager();
  2205. delete cef;
  2206. cef = nullptr;
  2207. #endif
  2208. }
  2209. void OBSBasic::SaveProjectNow()
  2210. {
  2211. if (disableSaving)
  2212. return;
  2213. projectChanged = true;
  2214. SaveProjectDeferred();
  2215. }
  2216. void OBSBasic::SaveProject()
  2217. {
  2218. if (disableSaving)
  2219. return;
  2220. projectChanged = true;
  2221. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2222. Qt::QueuedConnection);
  2223. }
  2224. void OBSBasic::SaveProjectDeferred()
  2225. {
  2226. if (disableSaving)
  2227. return;
  2228. if (!projectChanged)
  2229. return;
  2230. projectChanged = false;
  2231. const char *sceneCollection = config_get_string(
  2232. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2233. char savePath[1024];
  2234. char fileName[1024];
  2235. int ret;
  2236. if (!sceneCollection)
  2237. return;
  2238. ret = snprintf(fileName, sizeof(fileName),
  2239. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2240. if (ret <= 0)
  2241. return;
  2242. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2243. if (ret <= 0)
  2244. return;
  2245. Save(savePath);
  2246. }
  2247. OBSSource OBSBasic::GetProgramSource()
  2248. {
  2249. return OBSGetStrongRef(programScene);
  2250. }
  2251. OBSScene OBSBasic::GetCurrentScene()
  2252. {
  2253. QListWidgetItem *item = ui->scenes->currentItem();
  2254. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  2255. }
  2256. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2257. {
  2258. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2259. }
  2260. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2261. {
  2262. return ui->sources->Get(GetTopSelectedSourceItem());
  2263. }
  2264. void OBSBasic::UpdatePreviewScalingMenu()
  2265. {
  2266. bool fixedScaling = ui->preview->IsFixedScaling();
  2267. float scalingAmount = ui->preview->GetScalingAmount();
  2268. if (!fixedScaling) {
  2269. ui->actionScaleWindow->setChecked(true);
  2270. ui->actionScaleCanvas->setChecked(false);
  2271. ui->actionScaleOutput->setChecked(false);
  2272. return;
  2273. }
  2274. obs_video_info ovi;
  2275. obs_get_video_info(&ovi);
  2276. ui->actionScaleWindow->setChecked(false);
  2277. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2278. ui->actionScaleOutput->setChecked(scalingAmount ==
  2279. float(ovi.output_width) /
  2280. float(ovi.base_width));
  2281. }
  2282. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2283. {
  2284. bool closed = true;
  2285. if (interaction)
  2286. closed = interaction->close();
  2287. if (!closed)
  2288. return;
  2289. interaction = new OBSBasicInteraction(this, source);
  2290. interaction->Init();
  2291. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2292. }
  2293. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2294. {
  2295. bool closed = true;
  2296. if (properties)
  2297. closed = properties->close();
  2298. if (!closed)
  2299. return;
  2300. properties = new OBSBasicProperties(this, source);
  2301. properties->Init();
  2302. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2303. }
  2304. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2305. {
  2306. bool closed = true;
  2307. if (filters)
  2308. closed = filters->close();
  2309. if (!closed)
  2310. return;
  2311. filters = new OBSBasicFilters(this, source);
  2312. filters->Init();
  2313. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2314. }
  2315. /* Qt callbacks for invokeMethod */
  2316. void OBSBasic::AddScene(OBSSource source)
  2317. {
  2318. const char *name = obs_source_get_name(source);
  2319. obs_scene_t *scene = obs_scene_from_source(source);
  2320. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2321. SetOBSRef(item, OBSScene(scene));
  2322. ui->scenes->addItem(item);
  2323. obs_hotkey_register_source(
  2324. source, "OBSBasic.SelectScene",
  2325. Str("Basic.Hotkeys.SelectScene"),
  2326. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2327. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2328. App()->GetMainWindow());
  2329. auto potential_source =
  2330. static_cast<obs_source_t *>(data);
  2331. auto source = obs_source_get_ref(potential_source);
  2332. if (source && pressed)
  2333. main->SetCurrentScene(source);
  2334. obs_source_release(source);
  2335. },
  2336. static_cast<obs_source_t *>(source));
  2337. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2338. SignalContainer<OBSScene> container;
  2339. container.ref = scene;
  2340. container.handlers.assign({
  2341. std::make_shared<OBSSignal>(handler, "item_add",
  2342. OBSBasic::SceneItemAdded, this),
  2343. std::make_shared<OBSSignal>(handler, "reorder",
  2344. OBSBasic::SceneReordered, this),
  2345. std::make_shared<OBSSignal>(handler, "refresh",
  2346. OBSBasic::SceneRefreshed, this),
  2347. });
  2348. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2349. QVariant::fromValue(container));
  2350. /* if the scene already has items (a duplicated scene) add them */
  2351. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2352. AddSceneItem(item);
  2353. };
  2354. using addSceneItem_t = decltype(addSceneItem);
  2355. obs_scene_enum_items(
  2356. scene,
  2357. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2358. addSceneItem_t *func;
  2359. func = reinterpret_cast<addSceneItem_t *>(param);
  2360. (*func)(item);
  2361. return true;
  2362. },
  2363. &addSceneItem);
  2364. SaveProject();
  2365. if (!disableSaving) {
  2366. obs_source_t *source = obs_scene_get_source(scene);
  2367. blog(LOG_INFO, "User added scene '%s'",
  2368. obs_source_get_name(source));
  2369. OBSProjector::UpdateMultiviewProjectors();
  2370. }
  2371. if (api)
  2372. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2373. }
  2374. void OBSBasic::RemoveScene(OBSSource source)
  2375. {
  2376. obs_scene_t *scene = obs_scene_from_source(source);
  2377. QListWidgetItem *sel = nullptr;
  2378. int count = ui->scenes->count();
  2379. for (int i = 0; i < count; i++) {
  2380. auto item = ui->scenes->item(i);
  2381. auto cur_scene = GetOBSRef<OBSScene>(item);
  2382. if (cur_scene != scene)
  2383. continue;
  2384. sel = item;
  2385. break;
  2386. }
  2387. if (sel != nullptr) {
  2388. if (sel == ui->scenes->currentItem())
  2389. ui->sources->Clear();
  2390. delete sel;
  2391. }
  2392. SaveProject();
  2393. if (!disableSaving) {
  2394. blog(LOG_INFO, "User Removed scene '%s'",
  2395. obs_source_get_name(source));
  2396. OBSProjector::UpdateMultiviewProjectors();
  2397. }
  2398. if (api)
  2399. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2400. }
  2401. static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  2402. {
  2403. obs_sceneitem_t *selectedItem =
  2404. reinterpret_cast<obs_sceneitem_t *>(param);
  2405. if (obs_sceneitem_is_group(item))
  2406. obs_sceneitem_group_enum_items(item, select_one, param);
  2407. obs_sceneitem_select(item, (selectedItem == item));
  2408. UNUSED_PARAMETER(scene);
  2409. return true;
  2410. }
  2411. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2412. {
  2413. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2414. if (GetCurrentScene() == scene)
  2415. ui->sources->Add(item);
  2416. SaveProject();
  2417. if (!disableSaving) {
  2418. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2419. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2420. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2421. obs_source_get_name(itemSource),
  2422. obs_source_get_id(itemSource),
  2423. obs_source_get_name(sceneSource));
  2424. obs_scene_enum_items(scene, select_one,
  2425. (obs_sceneitem_t *)item);
  2426. }
  2427. }
  2428. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2429. const QString &prevName)
  2430. {
  2431. QList<QListWidgetItem *> items =
  2432. listWidget->findItems(prevName, Qt::MatchExactly);
  2433. for (int i = 0; i < items.count(); i++)
  2434. items[i]->setText(newName);
  2435. }
  2436. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2437. QString prevName)
  2438. {
  2439. RenameListValues(ui->scenes, newName, prevName);
  2440. for (size_t i = 0; i < volumes.size(); i++) {
  2441. if (volumes[i]->GetName().compare(prevName) == 0)
  2442. volumes[i]->SetName(newName);
  2443. }
  2444. for (size_t i = 0; i < projectors.size(); i++) {
  2445. if (projectors[i]->GetSource() == source)
  2446. projectors[i]->RenameProjector(prevName, newName);
  2447. }
  2448. SaveProject();
  2449. obs_scene_t *scene = obs_scene_from_source(source);
  2450. if (scene)
  2451. OBSProjector::UpdateMultiviewProjectors();
  2452. UpdateContextBar();
  2453. }
  2454. void OBSBasic::ClearContextBar()
  2455. {
  2456. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2457. if (la) {
  2458. delete la->widget();
  2459. ui->emptySpace->layout()->removeItem(la);
  2460. }
  2461. }
  2462. static bool is_network_media_source(obs_source_t *source, const char *id)
  2463. {
  2464. if (strcmp(id, "ffmpeg_source") != 0)
  2465. return false;
  2466. obs_data_t *s = obs_source_get_settings(source);
  2467. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2468. obs_data_release(s);
  2469. return !is_local_file;
  2470. }
  2471. void OBSBasic::UpdateContextBarDeferred(bool force)
  2472. {
  2473. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2474. Qt::QueuedConnection, Q_ARG(bool, force));
  2475. }
  2476. void OBSBasic::UpdateContextBar(bool force)
  2477. {
  2478. if (!ui->contextContainer->isVisible() && !force)
  2479. return;
  2480. OBSSceneItem item = GetCurrentSceneItem();
  2481. ClearContextBar();
  2482. if (item) {
  2483. obs_source_t *source = obs_sceneitem_get_source(item);
  2484. const char *id = obs_source_get_unversioned_id(source);
  2485. uint32_t flags = obs_source_get_output_flags(source);
  2486. ui->sourceInteractButton->setVisible(flags &
  2487. OBS_SOURCE_INTERACTION);
  2488. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2489. if (!is_network_media_source(source, id)) {
  2490. MediaControls *mediaControls =
  2491. new MediaControls(ui->emptySpace);
  2492. mediaControls->SetSource(source);
  2493. ui->emptySpace->layout()->addWidget(
  2494. mediaControls);
  2495. }
  2496. } else if (strcmp(id, "browser_source") == 0) {
  2497. BrowserToolbar *c =
  2498. new BrowserToolbar(ui->emptySpace, source);
  2499. ui->emptySpace->layout()->addWidget(c);
  2500. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2501. strcmp(id, "wasapi_output_capture") == 0 ||
  2502. strcmp(id, "coreaudio_input_capture") == 0 ||
  2503. strcmp(id, "coreaudio_output_capture") == 0 ||
  2504. strcmp(id, "pulse_input_capture") == 0 ||
  2505. strcmp(id, "pulse_output_capture") == 0 ||
  2506. strcmp(id, "alsa_input_capture") == 0) {
  2507. AudioCaptureToolbar *c =
  2508. new AudioCaptureToolbar(ui->emptySpace, source);
  2509. c->Init();
  2510. ui->emptySpace->layout()->addWidget(c);
  2511. } else if (strcmp(id, "window_capture") == 0 ||
  2512. strcmp(id, "xcomposite_input") == 0) {
  2513. WindowCaptureToolbar *c = new WindowCaptureToolbar(
  2514. ui->emptySpace, source);
  2515. c->Init();
  2516. ui->emptySpace->layout()->addWidget(c);
  2517. } else if (strcmp(id, "monitor_capture") == 0 ||
  2518. strcmp(id, "display_capture") == 0 ||
  2519. strcmp(id, "xshm_input") == 0) {
  2520. DisplayCaptureToolbar *c = new DisplayCaptureToolbar(
  2521. ui->emptySpace, source);
  2522. c->Init();
  2523. ui->emptySpace->layout()->addWidget(c);
  2524. } else if (strcmp(id, "dshow_input") == 0) {
  2525. DeviceCaptureToolbar *c = new DeviceCaptureToolbar(
  2526. ui->emptySpace, source);
  2527. ui->emptySpace->layout()->addWidget(c);
  2528. } else if (strcmp(id, "game_capture") == 0) {
  2529. GameCaptureToolbar *c =
  2530. new GameCaptureToolbar(ui->emptySpace, source);
  2531. ui->emptySpace->layout()->addWidget(c);
  2532. } else if (strcmp(id, "image_source") == 0) {
  2533. ImageSourceToolbar *c =
  2534. new ImageSourceToolbar(ui->emptySpace, source);
  2535. ui->emptySpace->layout()->addWidget(c);
  2536. } else if (strcmp(id, "color_source") == 0) {
  2537. ColorSourceToolbar *c =
  2538. new ColorSourceToolbar(ui->emptySpace, source);
  2539. ui->emptySpace->layout()->addWidget(c);
  2540. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2541. strcmp(id, "text_gdiplus") == 0) {
  2542. TextSourceToolbar *c =
  2543. new TextSourceToolbar(ui->emptySpace, source);
  2544. ui->emptySpace->layout()->addWidget(c);
  2545. }
  2546. QIcon icon;
  2547. if (strcmp(id, "scene") == 0)
  2548. icon = GetSceneIcon();
  2549. else if (strcmp(id, "group") == 0)
  2550. icon = GetGroupIcon();
  2551. else
  2552. icon = GetSourceIcon(id);
  2553. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2554. ui->contextSourceIcon->setPixmap(pixmap);
  2555. ui->contextSourceIconSpacer->hide();
  2556. ui->contextSourceIcon->show();
  2557. const char *name = obs_source_get_name(source);
  2558. ui->contextSourceLabel->setText(name);
  2559. ui->sourceFiltersButton->setEnabled(true);
  2560. ui->sourcePropertiesButton->setEnabled(
  2561. obs_source_configurable(source));
  2562. } else {
  2563. ui->contextSourceIcon->hide();
  2564. ui->contextSourceIconSpacer->show();
  2565. ui->contextSourceLabel->setText(
  2566. QTStr("ContextBar.NoSelectedSource"));
  2567. ui->sourceFiltersButton->setEnabled(false);
  2568. ui->sourcePropertiesButton->setEnabled(false);
  2569. ui->sourceInteractButton->setVisible(false);
  2570. }
  2571. }
  2572. static inline bool SourceMixerHidden(obs_source_t *source)
  2573. {
  2574. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2575. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2576. obs_data_release(priv_settings);
  2577. return hidden;
  2578. }
  2579. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2580. {
  2581. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2582. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2583. obs_data_release(priv_settings);
  2584. }
  2585. void OBSBasic::GetAudioSourceFilters()
  2586. {
  2587. QAction *action = reinterpret_cast<QAction *>(sender());
  2588. VolControl *vol = action->property("volControl").value<VolControl *>();
  2589. obs_source_t *source = vol->GetSource();
  2590. CreateFiltersWindow(source);
  2591. }
  2592. void OBSBasic::GetAudioSourceProperties()
  2593. {
  2594. QAction *action = reinterpret_cast<QAction *>(sender());
  2595. VolControl *vol = action->property("volControl").value<VolControl *>();
  2596. obs_source_t *source = vol->GetSource();
  2597. CreatePropertiesWindow(source);
  2598. }
  2599. void OBSBasic::HideAudioControl()
  2600. {
  2601. QAction *action = reinterpret_cast<QAction *>(sender());
  2602. VolControl *vol = action->property("volControl").value<VolControl *>();
  2603. obs_source_t *source = vol->GetSource();
  2604. if (!SourceMixerHidden(source)) {
  2605. SetSourceMixerHidden(source, true);
  2606. DeactivateAudioSource(source);
  2607. }
  2608. }
  2609. void OBSBasic::UnhideAllAudioControls()
  2610. {
  2611. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2612. {
  2613. if (!obs_source_active(source))
  2614. return true;
  2615. if (!SourceMixerHidden(source))
  2616. return true;
  2617. SetSourceMixerHidden(source, false);
  2618. ActivateAudioSource(source);
  2619. return true;
  2620. };
  2621. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2622. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2623. { return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
  2624. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2625. }
  2626. void OBSBasic::ToggleHideMixer()
  2627. {
  2628. OBSSceneItem item = GetCurrentSceneItem();
  2629. OBSSource source = obs_sceneitem_get_source(item);
  2630. if (!SourceMixerHidden(source)) {
  2631. SetSourceMixerHidden(source, true);
  2632. DeactivateAudioSource(source);
  2633. } else {
  2634. SetSourceMixerHidden(source, false);
  2635. ActivateAudioSource(source);
  2636. }
  2637. }
  2638. void OBSBasic::MixerRenameSource()
  2639. {
  2640. QAction *action = reinterpret_cast<QAction *>(sender());
  2641. VolControl *vol = action->property("volControl").value<VolControl *>();
  2642. OBSSource source = vol->GetSource();
  2643. const char *prevName = obs_source_get_name(source);
  2644. for (;;) {
  2645. string name;
  2646. bool accepted = NameDialog::AskForName(
  2647. this, QTStr("Basic.Main.MixerRename.Title"),
  2648. QTStr("Basic.Main.MixerRename.Text"), name,
  2649. QT_UTF8(prevName));
  2650. if (!accepted)
  2651. return;
  2652. if (name.empty()) {
  2653. OBSMessageBox::warning(this,
  2654. QTStr("NoNameEntered.Title"),
  2655. QTStr("NoNameEntered.Text"));
  2656. continue;
  2657. }
  2658. OBSSource sourceTest = obs_get_source_by_name(name.c_str());
  2659. obs_source_release(sourceTest);
  2660. if (sourceTest) {
  2661. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2662. QTStr("NameExists.Text"));
  2663. continue;
  2664. }
  2665. obs_source_set_name(source, name.c_str());
  2666. break;
  2667. }
  2668. }
  2669. static inline bool SourceVolumeLocked(obs_source_t *source)
  2670. {
  2671. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2672. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  2673. obs_data_release(priv_settings);
  2674. return lock;
  2675. }
  2676. void OBSBasic::LockVolumeControl(bool lock)
  2677. {
  2678. QAction *action = reinterpret_cast<QAction *>(sender());
  2679. VolControl *vol = action->property("volControl").value<VolControl *>();
  2680. obs_source_t *source = vol->GetSource();
  2681. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  2682. obs_data_set_bool(priv_settings, "volume_locked", lock);
  2683. obs_data_release(priv_settings);
  2684. vol->EnableSlider(!lock);
  2685. }
  2686. void OBSBasic::VolControlContextMenu()
  2687. {
  2688. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  2689. /* ------------------- */
  2690. QAction lockAction(QTStr("LockVolume"), this);
  2691. lockAction.setCheckable(true);
  2692. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  2693. QAction hideAction(QTStr("Hide"), this);
  2694. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2695. QAction mixerRenameAction(QTStr("Rename"), this);
  2696. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  2697. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  2698. QAction filtersAction(QTStr("Filters"), this);
  2699. QAction propertiesAction(QTStr("Properties"), this);
  2700. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2701. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2702. toggleControlLayoutAction.setCheckable(true);
  2703. toggleControlLayoutAction.setChecked(config_get_bool(
  2704. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2705. /* ------------------- */
  2706. connect(&hideAction, &QAction::triggered, this,
  2707. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  2708. connect(&unhideAllAction, &QAction::triggered, this,
  2709. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2710. connect(&lockAction, &QAction::toggled, this,
  2711. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  2712. connect(&mixerRenameAction, &QAction::triggered, this,
  2713. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  2714. connect(&copyFiltersAction, &QAction::triggered, this,
  2715. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  2716. connect(&pasteFiltersAction, &QAction::triggered, this,
  2717. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  2718. connect(&filtersAction, &QAction::triggered, this,
  2719. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  2720. connect(&propertiesAction, &QAction::triggered, this,
  2721. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  2722. connect(&advPropAction, &QAction::triggered, this,
  2723. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2724. Qt::DirectConnection);
  2725. /* ------------------- */
  2726. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2727. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2728. /* ------------------- */
  2729. hideAction.setProperty("volControl",
  2730. QVariant::fromValue<VolControl *>(vol));
  2731. lockAction.setProperty("volControl",
  2732. QVariant::fromValue<VolControl *>(vol));
  2733. mixerRenameAction.setProperty("volControl",
  2734. QVariant::fromValue<VolControl *>(vol));
  2735. copyFiltersAction.setProperty("volControl",
  2736. QVariant::fromValue<VolControl *>(vol));
  2737. pasteFiltersAction.setProperty("volControl",
  2738. QVariant::fromValue<VolControl *>(vol));
  2739. filtersAction.setProperty("volControl",
  2740. QVariant::fromValue<VolControl *>(vol));
  2741. propertiesAction.setProperty("volControl",
  2742. QVariant::fromValue<VolControl *>(vol));
  2743. /* ------------------- */
  2744. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  2745. 0);
  2746. if (copyFiltersString == nullptr)
  2747. pasteFiltersAction.setEnabled(false);
  2748. else
  2749. pasteFiltersAction.setEnabled(true);
  2750. QMenu popup;
  2751. vol->SetContextMenu(&popup);
  2752. popup.addAction(&lockAction);
  2753. popup.addSeparator();
  2754. popup.addAction(&unhideAllAction);
  2755. popup.addAction(&hideAction);
  2756. popup.addAction(&mixerRenameAction);
  2757. popup.addSeparator();
  2758. popup.addAction(&copyFiltersAction);
  2759. popup.addAction(&pasteFiltersAction);
  2760. popup.addSeparator();
  2761. popup.addAction(&toggleControlLayoutAction);
  2762. popup.addSeparator();
  2763. popup.addAction(&filtersAction);
  2764. popup.addAction(&propertiesAction);
  2765. popup.addAction(&advPropAction);
  2766. popup.exec(QCursor::pos());
  2767. vol->SetContextMenu(nullptr);
  2768. }
  2769. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  2770. {
  2771. StackedMixerAreaContextMenuRequested();
  2772. }
  2773. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  2774. {
  2775. StackedMixerAreaContextMenuRequested();
  2776. }
  2777. void OBSBasic::StackedMixerAreaContextMenuRequested()
  2778. {
  2779. QAction unhideAllAction(QTStr("UnhideAll"), this);
  2780. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  2781. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  2782. toggleControlLayoutAction.setCheckable(true);
  2783. toggleControlLayoutAction.setChecked(config_get_bool(
  2784. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  2785. /* ------------------- */
  2786. connect(&unhideAllAction, &QAction::triggered, this,
  2787. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  2788. connect(&advPropAction, &QAction::triggered, this,
  2789. &OBSBasic::on_actionAdvAudioProperties_triggered,
  2790. Qt::DirectConnection);
  2791. /* ------------------- */
  2792. connect(&toggleControlLayoutAction, &QAction::changed, this,
  2793. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  2794. /* ------------------- */
  2795. QMenu popup;
  2796. popup.addAction(&unhideAllAction);
  2797. popup.addSeparator();
  2798. popup.addAction(&toggleControlLayoutAction);
  2799. popup.addSeparator();
  2800. popup.addAction(&advPropAction);
  2801. popup.exec(QCursor::pos());
  2802. }
  2803. void OBSBasic::ToggleMixerLayout(bool vertical)
  2804. {
  2805. if (vertical) {
  2806. ui->stackedMixerArea->setMinimumSize(180, 220);
  2807. ui->stackedMixerArea->setCurrentIndex(1);
  2808. } else {
  2809. ui->stackedMixerArea->setMinimumSize(220, 0);
  2810. ui->stackedMixerArea->setCurrentIndex(0);
  2811. }
  2812. }
  2813. void OBSBasic::ToggleVolControlLayout()
  2814. {
  2815. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  2816. "VerticalVolControl");
  2817. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  2818. vertical);
  2819. ToggleMixerLayout(vertical);
  2820. // We need to store it so we can delete current and then add
  2821. // at the right order
  2822. vector<OBSSource> sources;
  2823. for (size_t i = 0; i != volumes.size(); i++)
  2824. sources.emplace_back(volumes[i]->GetSource());
  2825. ClearVolumeControls();
  2826. for (const auto &source : sources)
  2827. ActivateAudioSource(source);
  2828. }
  2829. void OBSBasic::ActivateAudioSource(OBSSource source)
  2830. {
  2831. if (SourceMixerHidden(source))
  2832. return;
  2833. if (!obs_source_audio_active(source))
  2834. return;
  2835. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  2836. "VerticalVolControl");
  2837. VolControl *vol = new VolControl(source, true, vertical);
  2838. vol->EnableSlider(!SourceVolumeLocked(source));
  2839. double meterDecayRate =
  2840. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  2841. vol->SetMeterDecayRate(meterDecayRate);
  2842. uint32_t peakMeterTypeIdx =
  2843. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  2844. enum obs_peak_meter_type peakMeterType;
  2845. switch (peakMeterTypeIdx) {
  2846. case 0:
  2847. peakMeterType = SAMPLE_PEAK_METER;
  2848. break;
  2849. case 1:
  2850. peakMeterType = TRUE_PEAK_METER;
  2851. break;
  2852. default:
  2853. peakMeterType = SAMPLE_PEAK_METER;
  2854. break;
  2855. }
  2856. vol->setPeakMeterType(peakMeterType);
  2857. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  2858. connect(vol, &QWidget::customContextMenuRequested, this,
  2859. &OBSBasic::VolControlContextMenu);
  2860. connect(vol, &VolControl::ConfigClicked, this,
  2861. &OBSBasic::VolControlContextMenu);
  2862. InsertQObjectByName(volumes, vol);
  2863. for (auto volume : volumes) {
  2864. if (vertical)
  2865. ui->vVolControlLayout->addWidget(volume);
  2866. else
  2867. ui->hVolControlLayout->addWidget(volume);
  2868. }
  2869. }
  2870. void OBSBasic::DeactivateAudioSource(OBSSource source)
  2871. {
  2872. for (size_t i = 0; i < volumes.size(); i++) {
  2873. if (volumes[i]->GetSource() == source) {
  2874. delete volumes[i];
  2875. volumes.erase(volumes.begin() + i);
  2876. break;
  2877. }
  2878. }
  2879. }
  2880. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  2881. {
  2882. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  2883. !obs_source_is_group(source)) {
  2884. int count = ui->scenes->count();
  2885. if (count == 1) {
  2886. OBSMessageBox::information(this,
  2887. QTStr("FinalScene.Title"),
  2888. QTStr("FinalScene.Text"));
  2889. return false;
  2890. }
  2891. }
  2892. const char *name = obs_source_get_name(source);
  2893. QString text = QTStr("ConfirmRemove.Text");
  2894. text.replace("$1", QT_UTF8(name));
  2895. QMessageBox remove_source(this);
  2896. remove_source.setText(text);
  2897. QPushButton *Yes =
  2898. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  2899. remove_source.setDefaultButton(Yes);
  2900. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  2901. remove_source.setIcon(QMessageBox::Question);
  2902. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  2903. remove_source.exec();
  2904. return Yes == remove_source.clickedButton();
  2905. }
  2906. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  2907. #ifdef UPDATE_SPARKLE
  2908. void init_sparkle_updater(bool update_to_undeployed);
  2909. void trigger_sparkle_update();
  2910. #endif
  2911. void OBSBasic::TimedCheckForUpdates()
  2912. {
  2913. if (App()->IsUpdaterDisabled())
  2914. return;
  2915. if (!config_get_bool(App()->GlobalConfig(), "General",
  2916. "EnableAutoUpdates"))
  2917. return;
  2918. #ifdef UPDATE_SPARKLE
  2919. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  2920. "UpdateToUndeployed"));
  2921. #elif _WIN32
  2922. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  2923. "LastUpdateCheck");
  2924. uint32_t lastVersion =
  2925. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  2926. if (lastVersion < LIBOBS_API_VER) {
  2927. lastUpdate = 0;
  2928. config_set_int(App()->GlobalConfig(), "General",
  2929. "LastUpdateCheck", 0);
  2930. }
  2931. long long t = (long long)time(nullptr);
  2932. long long secs = t - lastUpdate;
  2933. if (secs > UPDATE_CHECK_INTERVAL)
  2934. CheckForUpdates(false);
  2935. #endif
  2936. }
  2937. void OBSBasic::CheckForUpdates(bool manualUpdate)
  2938. {
  2939. #ifdef UPDATE_SPARKLE
  2940. trigger_sparkle_update();
  2941. #elif _WIN32
  2942. ui->actionCheckForUpdates->setEnabled(false);
  2943. if (updateCheckThread && updateCheckThread->isRunning())
  2944. return;
  2945. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  2946. updateCheckThread->start();
  2947. #endif
  2948. UNUSED_PARAMETER(manualUpdate);
  2949. }
  2950. void OBSBasic::updateCheckFinished()
  2951. {
  2952. ui->actionCheckForUpdates->setEnabled(true);
  2953. }
  2954. void OBSBasic::DuplicateSelectedScene()
  2955. {
  2956. OBSScene curScene = GetCurrentScene();
  2957. if (!curScene)
  2958. return;
  2959. OBSSource curSceneSource = obs_scene_get_source(curScene);
  2960. QString format{obs_source_get_name(curSceneSource)};
  2961. format += " %1";
  2962. int i = 2;
  2963. QString placeHolderText = format.arg(i);
  2964. obs_source_t *source = nullptr;
  2965. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2966. obs_source_release(source);
  2967. placeHolderText = format.arg(++i);
  2968. }
  2969. for (;;) {
  2970. string name;
  2971. bool accepted = NameDialog::AskForName(
  2972. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  2973. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  2974. placeHolderText);
  2975. if (!accepted)
  2976. return;
  2977. if (name.empty()) {
  2978. OBSMessageBox::warning(this,
  2979. QTStr("NoNameEntered.Title"),
  2980. QTStr("NoNameEntered.Text"));
  2981. continue;
  2982. }
  2983. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2984. if (source) {
  2985. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  2986. QTStr("NameExists.Text"));
  2987. obs_source_release(source);
  2988. continue;
  2989. }
  2990. obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
  2991. OBS_SCENE_DUP_REFS);
  2992. source = obs_scene_get_source(scene);
  2993. SetCurrentScene(source, true);
  2994. auto undo = [](const std::string &data) {
  2995. obs_source_t *source =
  2996. obs_get_source_by_name(data.c_str());
  2997. obs_source_remove(source);
  2998. obs_source_release(source);
  2999. };
  3000. auto redo = [this, name](const std::string &data) {
  3001. obs_source_t *source =
  3002. obs_get_source_by_name(data.c_str());
  3003. obs_scene_t *scene = obs_scene_from_source(source);
  3004. obs_source_release(source);
  3005. scene = obs_scene_duplicate(scene, name.c_str(),
  3006. OBS_SCENE_DUP_REFS);
  3007. source = obs_scene_get_source(scene);
  3008. SetCurrentScene(source, true);
  3009. obs_scene_release(scene);
  3010. };
  3011. undo_s.add_action(
  3012. QTStr("Undo.Scene.Duplicate")
  3013. .arg(obs_source_get_name(source)),
  3014. undo, redo, obs_source_get_name(source),
  3015. obs_source_get_name(obs_scene_get_source(curScene)));
  3016. obs_scene_release(scene);
  3017. break;
  3018. }
  3019. }
  3020. static bool save_undo_source_enum(obs_scene_t *scene, obs_sceneitem_t *item,
  3021. void *p)
  3022. {
  3023. UNUSED_PARAMETER(scene);
  3024. obs_source_t *source = obs_sceneitem_get_source(item);
  3025. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3026. return true;
  3027. obs_data_array_t *array = (obs_data_array_t *)p;
  3028. /* check if the source is already stored in the array */
  3029. const char *name = obs_source_get_name(source);
  3030. const size_t count = obs_data_array_count(array);
  3031. for (size_t i = 0; i < count; i++) {
  3032. obs_data_t *sourceData = obs_data_array_item(array, i);
  3033. if (strcmp(name, obs_data_get_string(sourceData, "name")) ==
  3034. 0) {
  3035. obs_data_release(sourceData);
  3036. return true;
  3037. }
  3038. obs_data_release(sourceData);
  3039. }
  3040. if (obs_source_is_group(source))
  3041. obs_scene_enum_items(obs_group_from_source(source),
  3042. save_undo_source_enum, p);
  3043. obs_data_t *source_data = obs_save_source(source);
  3044. obs_data_array_push_back(array, source_data);
  3045. obs_data_release(source_data);
  3046. return true;
  3047. }
  3048. void OBSBasic::RemoveSelectedScene()
  3049. {
  3050. OBSScene scene = GetCurrentScene();
  3051. obs_source_t *source = obs_scene_get_source(scene);
  3052. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  3053. if (!source || !QueryRemoveSource(source)) {
  3054. return;
  3055. }
  3056. /* ------------------------------ */
  3057. /* save all sources in scene */
  3058. obs_data_array_t *array = obs_data_array_create();
  3059. obs_scene_enum_items(scene, save_undo_source_enum, array);
  3060. obs_data_t *scene_data = obs_save_source(source);
  3061. obs_data_array_push_back(array, scene_data);
  3062. obs_data_release(scene_data);
  3063. /* ----------------------------------------------- */
  3064. /* save all scenes and groups the scene is used in */
  3065. for (int i = 0; i < ui->scenes->count(); i++) {
  3066. QListWidgetItem *widget_item = ui->scenes->item(i);
  3067. auto item_scene = GetOBSRef<OBSScene>(widget_item);
  3068. if (scene == item_scene)
  3069. continue;
  3070. auto *item = obs_scene_find_source_recursive(
  3071. item_scene, obs_source_get_name(source));
  3072. if (item) {
  3073. scene_data = obs_save_source(obs_scene_get_source(
  3074. obs_sceneitem_get_scene(item)));
  3075. obs_data_array_push_back(array, scene_data);
  3076. obs_data_release(scene_data);
  3077. }
  3078. }
  3079. /* --------------------------- */
  3080. /* undo/redo */
  3081. auto undo = [this](const std::string &json) {
  3082. obs_data_t *base = obs_data_create_from_json(json.c_str());
  3083. obs_data_array_t *array = obs_data_get_array(base, "array");
  3084. int savedIndex = (int)obs_data_get_int(base, "index");
  3085. std::vector<obs_source_t *> sources;
  3086. /* create missing sources */
  3087. size_t count = obs_data_array_count(array);
  3088. sources.reserve(count);
  3089. for (size_t i = 0; i < count; i++) {
  3090. obs_data_t *data = obs_data_array_item(array, i);
  3091. const char *name = obs_data_get_string(data, "name");
  3092. obs_source_t *source = obs_get_source_by_name(name);
  3093. if (!source)
  3094. source = obs_load_source(data);
  3095. sources.push_back(source);
  3096. obs_data_release(data);
  3097. }
  3098. /* actually load sources now */
  3099. for (obs_source_t *source : sources)
  3100. obs_source_load2(source);
  3101. obs_source_t *scene_source = sources.back();
  3102. OBSScene scene = obs_scene_from_source(scene_source);
  3103. SetCurrentScene(scene, true);
  3104. /* set original index in list box */
  3105. ui->scenes->blockSignals(true);
  3106. int curIndex = ui->scenes->currentRow();
  3107. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3108. ui->scenes->insertItem(savedIndex, item);
  3109. ui->scenes->setCurrentRow(savedIndex);
  3110. ui->scenes->blockSignals(false);
  3111. /* release sources */
  3112. for (obs_source_t *source : sources)
  3113. obs_source_release(source);
  3114. obs_data_array_release(array);
  3115. obs_data_release(base);
  3116. };
  3117. auto redo = [](const std::string &name) {
  3118. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3119. obs_source_remove(source);
  3120. obs_source_release(source);
  3121. };
  3122. obs_data_t *data = obs_data_create();
  3123. obs_data_set_array(data, "array", array);
  3124. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3125. const char *scene_name = obs_source_get_name(source);
  3126. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3127. obs_data_get_json(data), scene_name);
  3128. obs_data_array_release(array);
  3129. obs_data_release(data);
  3130. /* --------------------------- */
  3131. /* remove */
  3132. obs_source_remove(source);
  3133. if (api)
  3134. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3135. }
  3136. void OBSBasic::RemoveSelectedSceneItem()
  3137. {
  3138. OBSSceneItem item = GetCurrentSceneItem();
  3139. if (item) {
  3140. obs_source_t *source = obs_sceneitem_get_source(item);
  3141. if (QueryRemoveSource(source))
  3142. obs_sceneitem_remove(item);
  3143. }
  3144. }
  3145. void OBSBasic::ReorderSources(OBSScene scene)
  3146. {
  3147. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3148. return;
  3149. ui->sources->ReorderItems();
  3150. SaveProject();
  3151. }
  3152. void OBSBasic::RefreshSources(OBSScene scene)
  3153. {
  3154. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3155. return;
  3156. ui->sources->RefreshItems();
  3157. SaveProject();
  3158. }
  3159. /* OBS Callbacks */
  3160. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3161. {
  3162. OBSBasic *window = static_cast<OBSBasic *>(data);
  3163. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3164. QMetaObject::invokeMethod(window, "ReorderSources",
  3165. Q_ARG(OBSScene, OBSScene(scene)));
  3166. }
  3167. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3168. {
  3169. OBSBasic *window = static_cast<OBSBasic *>(data);
  3170. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3171. QMetaObject::invokeMethod(window, "RefreshSources",
  3172. Q_ARG(OBSScene, OBSScene(scene)));
  3173. }
  3174. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3175. {
  3176. OBSBasic *window = static_cast<OBSBasic *>(data);
  3177. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3178. QMetaObject::invokeMethod(window, "AddSceneItem",
  3179. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3180. }
  3181. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3182. {
  3183. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3184. if (obs_scene_from_source(source) != NULL)
  3185. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3186. "AddScene", WaitConnection(),
  3187. Q_ARG(OBSSource, OBSSource(source)));
  3188. }
  3189. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3190. {
  3191. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3192. if (obs_scene_from_source(source) != NULL)
  3193. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3194. "RemoveScene",
  3195. Q_ARG(OBSSource, OBSSource(source)));
  3196. }
  3197. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3198. {
  3199. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3200. uint32_t flags = obs_source_get_output_flags(source);
  3201. if (flags & OBS_SOURCE_AUDIO)
  3202. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3203. "ActivateAudioSource",
  3204. Q_ARG(OBSSource, OBSSource(source)));
  3205. }
  3206. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3207. {
  3208. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3209. uint32_t flags = obs_source_get_output_flags(source);
  3210. if (flags & OBS_SOURCE_AUDIO)
  3211. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3212. "DeactivateAudioSource",
  3213. Q_ARG(OBSSource, OBSSource(source)));
  3214. }
  3215. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3216. {
  3217. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3218. if (obs_source_active(source))
  3219. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3220. "ActivateAudioSource",
  3221. Q_ARG(OBSSource, OBSSource(source)));
  3222. }
  3223. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3224. {
  3225. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3226. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3227. "DeactivateAudioSource",
  3228. Q_ARG(OBSSource, OBSSource(source)));
  3229. }
  3230. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3231. {
  3232. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3233. const char *newName = calldata_string(params, "new_name");
  3234. const char *prevName = calldata_string(params, "prev_name");
  3235. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3236. "RenameSources", Q_ARG(OBSSource, source),
  3237. Q_ARG(QString, QT_UTF8(newName)),
  3238. Q_ARG(QString, QT_UTF8(prevName)));
  3239. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3240. }
  3241. void OBSBasic::DrawBackdrop(float cx, float cy)
  3242. {
  3243. if (!box)
  3244. return;
  3245. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3246. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3247. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3248. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3249. vec4 colorVal;
  3250. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3251. gs_effect_set_vec4(color, &colorVal);
  3252. gs_technique_begin(tech);
  3253. gs_technique_begin_pass(tech, 0);
  3254. gs_matrix_push();
  3255. gs_matrix_identity();
  3256. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3257. gs_load_vertexbuffer(box);
  3258. gs_draw(GS_TRISTRIP, 0, 0);
  3259. gs_matrix_pop();
  3260. gs_technique_end_pass(tech);
  3261. gs_technique_end(tech);
  3262. gs_load_vertexbuffer(nullptr);
  3263. GS_DEBUG_MARKER_END();
  3264. }
  3265. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  3266. {
  3267. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3268. OBSBasic *window = static_cast<OBSBasic *>(data);
  3269. obs_video_info ovi;
  3270. obs_get_video_info(&ovi);
  3271. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3272. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3273. gs_viewport_push();
  3274. gs_projection_push();
  3275. obs_display_t *display = window->ui->preview->GetDisplay();
  3276. uint32_t width, height;
  3277. obs_display_size(display, &width, &height);
  3278. float right = float(width) - window->previewX;
  3279. float bottom = float(height) - window->previewY;
  3280. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3281. 100.0f);
  3282. window->ui->preview->DrawOverflow();
  3283. /* --------------------------------------- */
  3284. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3285. -100.0f, 100.0f);
  3286. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3287. window->previewCY);
  3288. if (window->IsPreviewProgramMode()) {
  3289. window->DrawBackdrop(float(ovi.base_width),
  3290. float(ovi.base_height));
  3291. OBSScene scene = window->GetCurrentScene();
  3292. obs_source_t *source = obs_scene_get_source(scene);
  3293. if (source)
  3294. obs_source_video_render(source);
  3295. } else {
  3296. obs_render_main_texture_src_color_only();
  3297. }
  3298. gs_load_vertexbuffer(nullptr);
  3299. /* --------------------------------------- */
  3300. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3301. 100.0f);
  3302. gs_reset_viewport();
  3303. window->ui->preview->DrawSceneEditing();
  3304. uint32_t targetCX = window->previewCX;
  3305. uint32_t targetCY = window->previewCY;
  3306. if (window->drawSafeAreas) {
  3307. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3308. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3309. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3310. targetCY);
  3311. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3312. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3313. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3314. }
  3315. /* --------------------------------------- */
  3316. gs_projection_pop();
  3317. gs_viewport_pop();
  3318. GS_DEBUG_MARKER_END();
  3319. UNUSED_PARAMETER(cx);
  3320. UNUSED_PARAMETER(cy);
  3321. }
  3322. /* Main class functions */
  3323. obs_service_t *OBSBasic::GetService()
  3324. {
  3325. if (!service) {
  3326. service =
  3327. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3328. obs_service_release(service);
  3329. }
  3330. return service;
  3331. }
  3332. void OBSBasic::SetService(obs_service_t *newService)
  3333. {
  3334. if (newService)
  3335. service = newService;
  3336. }
  3337. int OBSBasic::GetTransitionDuration()
  3338. {
  3339. return ui->transitionDuration->value();
  3340. }
  3341. bool OBSBasic::StreamingActive() const
  3342. {
  3343. if (!outputHandler)
  3344. return false;
  3345. return outputHandler->StreamingActive();
  3346. }
  3347. bool OBSBasic::Active() const
  3348. {
  3349. if (!outputHandler)
  3350. return false;
  3351. return outputHandler->Active();
  3352. }
  3353. #ifdef _WIN32
  3354. #define IS_WIN32 1
  3355. #else
  3356. #define IS_WIN32 0
  3357. #endif
  3358. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3359. {
  3360. return obs_reset_video(ovi);
  3361. }
  3362. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3363. {
  3364. const char *scaleTypeStr =
  3365. config_get_string(basicConfig, "Video", "ScaleType");
  3366. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3367. return OBS_SCALE_BILINEAR;
  3368. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3369. return OBS_SCALE_LANCZOS;
  3370. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3371. return OBS_SCALE_AREA;
  3372. else
  3373. return OBS_SCALE_BICUBIC;
  3374. }
  3375. static inline enum video_format GetVideoFormatFromName(const char *name)
  3376. {
  3377. if (astrcmpi(name, "I420") == 0)
  3378. return VIDEO_FORMAT_I420;
  3379. else if (astrcmpi(name, "NV12") == 0)
  3380. return VIDEO_FORMAT_NV12;
  3381. else if (astrcmpi(name, "I444") == 0)
  3382. return VIDEO_FORMAT_I444;
  3383. #if 0 //currently unsupported
  3384. else if (astrcmpi(name, "YVYU") == 0)
  3385. return VIDEO_FORMAT_YVYU;
  3386. else if (astrcmpi(name, "YUY2") == 0)
  3387. return VIDEO_FORMAT_YUY2;
  3388. else if (astrcmpi(name, "UYVY") == 0)
  3389. return VIDEO_FORMAT_UYVY;
  3390. #endif
  3391. else
  3392. return VIDEO_FORMAT_RGBA;
  3393. }
  3394. void OBSBasic::ResetUI()
  3395. {
  3396. bool studioPortraitLayout = config_get_bool(
  3397. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3398. bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3399. "StudioModeLabels");
  3400. if (studioPortraitLayout)
  3401. ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
  3402. else
  3403. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3404. if (previewProgramMode)
  3405. ui->previewLabel->setHidden(!labels);
  3406. if (programLabel)
  3407. programLabel->setHidden(!labels);
  3408. }
  3409. int OBSBasic::ResetVideo()
  3410. {
  3411. if (outputHandler && outputHandler->Active())
  3412. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3413. ProfileScope("OBSBasic::ResetVideo");
  3414. struct obs_video_info ovi;
  3415. int ret;
  3416. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3417. const char *colorFormat =
  3418. config_get_string(basicConfig, "Video", "ColorFormat");
  3419. const char *colorSpace =
  3420. config_get_string(basicConfig, "Video", "ColorSpace");
  3421. const char *colorRange =
  3422. config_get_string(basicConfig, "Video", "ColorRange");
  3423. ovi.graphics_module = App()->GetRenderModule();
  3424. ovi.base_width =
  3425. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3426. ovi.base_height =
  3427. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3428. ovi.output_width =
  3429. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3430. ovi.output_height =
  3431. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3432. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3433. ovi.colorspace = astrcmpi(colorSpace, "601") == 0
  3434. ? VIDEO_CS_601
  3435. : (astrcmpi(colorSpace, "709") == 0
  3436. ? VIDEO_CS_709
  3437. : VIDEO_CS_SRGB);
  3438. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3439. : VIDEO_RANGE_PARTIAL;
  3440. ovi.adapter =
  3441. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3442. ovi.gpu_conversion = true;
  3443. ovi.scale_type = GetScaleType(basicConfig);
  3444. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3445. ovi.base_width = 1920;
  3446. ovi.base_height = 1080;
  3447. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3448. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3449. }
  3450. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3451. ovi.output_width = ovi.base_width;
  3452. ovi.output_height = ovi.base_height;
  3453. config_set_uint(basicConfig, "Video", "OutputCX",
  3454. ovi.base_width);
  3455. config_set_uint(basicConfig, "Video", "OutputCY",
  3456. ovi.base_height);
  3457. }
  3458. ret = AttemptToResetVideo(&ovi);
  3459. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3460. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3461. blog(LOG_WARNING, "Tried to reset when "
  3462. "already active");
  3463. return ret;
  3464. }
  3465. /* Try OpenGL if DirectX fails on windows */
  3466. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3467. blog(LOG_WARNING,
  3468. "Failed to initialize obs video (%d) "
  3469. "with graphics_module='%s', retrying "
  3470. "with graphics_module='%s'",
  3471. ret, ovi.graphics_module, DL_OPENGL);
  3472. ovi.graphics_module = DL_OPENGL;
  3473. ret = AttemptToResetVideo(&ovi);
  3474. }
  3475. } else if (ret == OBS_VIDEO_SUCCESS) {
  3476. ResizePreview(ovi.base_width, ovi.base_height);
  3477. if (program)
  3478. ResizeProgram(ovi.base_width, ovi.base_height);
  3479. }
  3480. if (ret == OBS_VIDEO_SUCCESS) {
  3481. OBSBasicStats::InitializeValues();
  3482. OBSProjector::UpdateMultiviewProjectors();
  3483. }
  3484. return ret;
  3485. }
  3486. bool OBSBasic::ResetAudio()
  3487. {
  3488. ProfileScope("OBSBasic::ResetAudio");
  3489. struct obs_audio_info ai;
  3490. ai.samples_per_sec =
  3491. config_get_uint(basicConfig, "Audio", "SampleRate");
  3492. const char *channelSetupStr =
  3493. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3494. if (strcmp(channelSetupStr, "Mono") == 0)
  3495. ai.speakers = SPEAKERS_MONO;
  3496. else if (strcmp(channelSetupStr, "2.1") == 0)
  3497. ai.speakers = SPEAKERS_2POINT1;
  3498. else if (strcmp(channelSetupStr, "4.0") == 0)
  3499. ai.speakers = SPEAKERS_4POINT0;
  3500. else if (strcmp(channelSetupStr, "4.1") == 0)
  3501. ai.speakers = SPEAKERS_4POINT1;
  3502. else if (strcmp(channelSetupStr, "5.1") == 0)
  3503. ai.speakers = SPEAKERS_5POINT1;
  3504. else if (strcmp(channelSetupStr, "7.1") == 0)
  3505. ai.speakers = SPEAKERS_7POINT1;
  3506. else
  3507. ai.speakers = SPEAKERS_STEREO;
  3508. return obs_reset_audio(&ai);
  3509. }
  3510. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3511. const char *deviceDesc, int channel)
  3512. {
  3513. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3514. obs_source_t *source;
  3515. obs_data_t *settings;
  3516. source = obs_get_output_source(channel);
  3517. if (source) {
  3518. if (disable) {
  3519. obs_set_output_source(channel, nullptr);
  3520. } else {
  3521. settings = obs_source_get_settings(source);
  3522. const char *oldId =
  3523. obs_data_get_string(settings, "device_id");
  3524. if (strcmp(oldId, deviceId) != 0) {
  3525. obs_data_set_string(settings, "device_id",
  3526. deviceId);
  3527. obs_source_update(source, settings);
  3528. }
  3529. obs_data_release(settings);
  3530. }
  3531. obs_source_release(source);
  3532. } else if (!disable) {
  3533. settings = obs_data_create();
  3534. obs_data_set_string(settings, "device_id", deviceId);
  3535. source = obs_source_create(sourceId, deviceDesc, settings,
  3536. nullptr);
  3537. obs_data_release(settings);
  3538. obs_set_output_source(channel, source);
  3539. obs_source_release(source);
  3540. }
  3541. }
  3542. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3543. {
  3544. QSize targetSize;
  3545. bool isFixedScaling;
  3546. obs_video_info ovi;
  3547. /* resize preview panel to fix to the top section of the window */
  3548. targetSize = GetPixelSize(ui->preview);
  3549. isFixedScaling = ui->preview->IsFixedScaling();
  3550. obs_get_video_info(&ovi);
  3551. if (isFixedScaling) {
  3552. previewScale = ui->preview->GetScalingAmount();
  3553. GetCenterPosFromFixedScale(
  3554. int(cx), int(cy),
  3555. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3556. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  3557. previewY, previewScale);
  3558. previewX += ui->preview->GetScrollX();
  3559. previewY += ui->preview->GetScrollY();
  3560. } else {
  3561. GetScaleAndCenterPos(int(cx), int(cy),
  3562. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  3563. targetSize.height() -
  3564. PREVIEW_EDGE_SIZE * 2,
  3565. previewX, previewY, previewScale);
  3566. }
  3567. previewX += float(PREVIEW_EDGE_SIZE);
  3568. previewY += float(PREVIEW_EDGE_SIZE);
  3569. }
  3570. void OBSBasic::CloseDialogs()
  3571. {
  3572. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  3573. if (!childDialogs.isEmpty()) {
  3574. for (int i = 0; i < childDialogs.size(); ++i) {
  3575. childDialogs.at(i)->close();
  3576. }
  3577. }
  3578. if (!stats.isNull())
  3579. stats->close(); //call close to save Stats geometry
  3580. if (!remux.isNull())
  3581. remux->close();
  3582. }
  3583. void OBSBasic::EnumDialogs()
  3584. {
  3585. visDialogs.clear();
  3586. modalDialogs.clear();
  3587. visMsgBoxes.clear();
  3588. /* fill list of Visible dialogs and Modal dialogs */
  3589. QList<QDialog *> dialogs = findChildren<QDialog *>();
  3590. for (QDialog *dialog : dialogs) {
  3591. if (dialog->isVisible())
  3592. visDialogs.append(dialog);
  3593. if (dialog->isModal())
  3594. modalDialogs.append(dialog);
  3595. }
  3596. /* fill list of Visible message boxes */
  3597. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  3598. for (QMessageBox *msgbox : msgBoxes) {
  3599. if (msgbox->isVisible())
  3600. visMsgBoxes.append(msgbox);
  3601. }
  3602. }
  3603. void OBSBasic::ClearProjectors()
  3604. {
  3605. for (size_t i = 0; i < projectors.size(); i++) {
  3606. if (projectors[i])
  3607. delete projectors[i];
  3608. }
  3609. projectors.clear();
  3610. }
  3611. void OBSBasic::ClearSceneData()
  3612. {
  3613. disableSaving++;
  3614. CloseDialogs();
  3615. ClearVolumeControls();
  3616. ClearListItems(ui->scenes);
  3617. ui->sources->Clear();
  3618. ClearQuickTransitions();
  3619. ui->transitions->clear();
  3620. ClearProjectors();
  3621. for (int i = 0; i < MAX_CHANNELS; i++)
  3622. obs_set_output_source(i, nullptr);
  3623. lastScene = nullptr;
  3624. swapScene = nullptr;
  3625. programScene = nullptr;
  3626. prevFTBSource = nullptr;
  3627. copyStrings.clear();
  3628. copyFiltersString = nullptr;
  3629. copyFilter = nullptr;
  3630. auto cb = [](void *unused, obs_source_t *source) {
  3631. obs_source_remove(source);
  3632. UNUSED_PARAMETER(unused);
  3633. return true;
  3634. };
  3635. obs_enum_scenes(cb, nullptr);
  3636. obs_enum_sources(cb, nullptr);
  3637. if (api)
  3638. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  3639. undo_s.clear();
  3640. disableSaving--;
  3641. blog(LOG_INFO, "All scene data cleared");
  3642. blog(LOG_INFO, "------------------------------------------------");
  3643. }
  3644. void OBSBasic::closeEvent(QCloseEvent *event)
  3645. {
  3646. /* Do not close window if inside of a temporary event loop because we
  3647. * could be inside of an Auth::LoadUI call. Keep trying once per
  3648. * second until we've exit any known sub-loops. */
  3649. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3650. QTimer::singleShot(1000, this, SLOT(close()));
  3651. event->ignore();
  3652. return;
  3653. }
  3654. #if YOUTUBE_ENABLED
  3655. /* Also don't close the window if the youtube stream check is active */
  3656. if (youtubeStreamCheckThread) {
  3657. QTimer::singleShot(1000, this, SLOT(close()));
  3658. event->ignore();
  3659. return;
  3660. }
  3661. #endif
  3662. if (isVisible())
  3663. config_set_string(App()->GlobalConfig(), "BasicWindow",
  3664. "geometry",
  3665. saveGeometry().toBase64().constData());
  3666. if (outputHandler && outputHandler->Active()) {
  3667. SetShowing(true);
  3668. QMessageBox::StandardButton button = OBSMessageBox::question(
  3669. this, QTStr("ConfirmExit.Title"),
  3670. QTStr("ConfirmExit.Text"));
  3671. if (button == QMessageBox::No) {
  3672. event->ignore();
  3673. restart = false;
  3674. return;
  3675. }
  3676. }
  3677. QWidget::closeEvent(event);
  3678. if (!event->isAccepted())
  3679. return;
  3680. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  3681. closing = true;
  3682. if (introCheckThread)
  3683. introCheckThread->wait();
  3684. if (whatsNewInitThread)
  3685. whatsNewInitThread->wait();
  3686. if (updateCheckThread)
  3687. updateCheckThread->wait();
  3688. if (logUploadThread)
  3689. logUploadThread->wait();
  3690. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  3691. devicePropertiesThread->wait();
  3692. devicePropertiesThread.reset();
  3693. }
  3694. QApplication::sendPostedEvents(this);
  3695. signalHandlers.clear();
  3696. Auth::Save();
  3697. SaveProjectNow();
  3698. auth.reset();
  3699. delete extraBrowsers;
  3700. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  3701. saveState().toBase64().constData());
  3702. #ifdef BROWSER_AVAILABLE
  3703. SaveExtraBrowserDocks();
  3704. ClearExtraBrowserDocks();
  3705. #endif
  3706. disableSaving++;
  3707. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  3708. * sources, etc) so that all references are released before shutdown */
  3709. ClearSceneData();
  3710. if (api)
  3711. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  3712. App()->quit();
  3713. }
  3714. void OBSBasic::changeEvent(QEvent *event)
  3715. {
  3716. if (event->type() == QEvent::WindowStateChange) {
  3717. QWindowStateChangeEvent *stateEvent =
  3718. (QWindowStateChangeEvent *)event;
  3719. if (isMinimized()) {
  3720. if (trayIcon && trayIcon->isVisible() &&
  3721. sysTrayMinimizeToTray()) {
  3722. ToggleShowHide();
  3723. }
  3724. if (previewEnabled)
  3725. EnablePreviewDisplay(false);
  3726. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  3727. isVisible()) {
  3728. if (previewEnabled)
  3729. EnablePreviewDisplay(true);
  3730. }
  3731. }
  3732. }
  3733. void OBSBasic::on_actionShow_Recordings_triggered()
  3734. {
  3735. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3736. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  3737. const char *adv_path =
  3738. strcmp(type, "Standard")
  3739. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  3740. : config_get_string(basicConfig, "AdvOut",
  3741. "RecFilePath");
  3742. const char *path = strcmp(mode, "Advanced")
  3743. ? config_get_string(basicConfig,
  3744. "SimpleOutput",
  3745. "FilePath")
  3746. : adv_path;
  3747. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3748. }
  3749. void OBSBasic::on_actionRemux_triggered()
  3750. {
  3751. if (!remux.isNull()) {
  3752. remux->show();
  3753. remux->raise();
  3754. return;
  3755. }
  3756. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  3757. const char *path = strcmp(mode, "Advanced")
  3758. ? config_get_string(basicConfig,
  3759. "SimpleOutput",
  3760. "FilePath")
  3761. : config_get_string(basicConfig, "AdvOut",
  3762. "RecFilePath");
  3763. OBSRemux *remuxDlg;
  3764. remuxDlg = new OBSRemux(path, this);
  3765. remuxDlg->show();
  3766. remux = remuxDlg;
  3767. }
  3768. void OBSBasic::on_action_Settings_triggered()
  3769. {
  3770. static bool settings_already_executing = false;
  3771. /* Do not load settings window if inside of a temporary event loop
  3772. * because we could be inside of an Auth::LoadUI call. Keep trying
  3773. * once per second until we've exit any known sub-loops. */
  3774. if (os_atomic_load_long(&insideEventLoop) != 0) {
  3775. QTimer::singleShot(1000, this,
  3776. SLOT(on_action_Settings_triggered()));
  3777. return;
  3778. }
  3779. if (settings_already_executing) {
  3780. return;
  3781. }
  3782. settings_already_executing = true;
  3783. {
  3784. OBSBasicSettings settings(this);
  3785. settings.exec();
  3786. }
  3787. SystemTray(false);
  3788. settings_already_executing = false;
  3789. if (restart) {
  3790. QMessageBox::StandardButton button = OBSMessageBox::question(
  3791. this, QTStr("Restart"), QTStr("NeedsRestart"));
  3792. if (button == QMessageBox::Yes)
  3793. close();
  3794. else
  3795. restart = false;
  3796. }
  3797. }
  3798. static inline void AddMissingFiles(void *data, obs_source_t *source)
  3799. {
  3800. obs_missing_files_t *f = (obs_missing_files_t *)data;
  3801. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  3802. obs_missing_files_append(f, sf);
  3803. obs_missing_files_destroy(sf);
  3804. }
  3805. void OBSBasic::on_actionShowMissingFiles_triggered()
  3806. {
  3807. obs_missing_files_t *files = obs_missing_files_create();
  3808. auto cb_sources = [](void *data, obs_source_t *source) {
  3809. AddMissingFiles(data, source);
  3810. return true;
  3811. };
  3812. obs_enum_sources(cb_sources, files);
  3813. auto cb_transitions = [](void *data, obs_source_t *source) {
  3814. if (obs_source_get_type(source) != OBS_SOURCE_TYPE_TRANSITION)
  3815. return true;
  3816. AddMissingFiles(data, source);
  3817. return true;
  3818. };
  3819. obs_enum_all_sources(cb_transitions, files);
  3820. if (obs_missing_files_count(files) > 0) {
  3821. missDialog = new OBSMissingFiles(files, this);
  3822. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  3823. missDialog->show();
  3824. missDialog->raise();
  3825. } else {
  3826. obs_missing_files_destroy(files);
  3827. OBSMessageBox::information(
  3828. this, QTStr("MissingFiles.NoMissing.Title"),
  3829. QTStr("MissingFiles.NoMissing.Text"));
  3830. }
  3831. }
  3832. void save_audio_source(int channel, obs_data_t *save)
  3833. {
  3834. obs_source_t *source = obs_get_output_source(channel);
  3835. if (!source)
  3836. return;
  3837. obs_data_t *obj = obs_data_create();
  3838. obs_data_set_double(obj, "vol", obs_source_get_volume(source));
  3839. obs_data_set_double(obj, "balance",
  3840. obs_source_get_balance_value(source));
  3841. obs_data_set_double(obj, "mixers", obs_source_get_audio_mixers(source));
  3842. obs_data_set_double(obj, "sync", obs_source_get_sync_offset(source));
  3843. obs_data_set_double(obj, "flags", obs_source_get_flags(source));
  3844. obs_data_set_obj(save, std::to_string(channel).c_str(), obj);
  3845. obs_data_release(obj);
  3846. obs_source_release(source);
  3847. }
  3848. void load_audio_source(int channel, obs_data_t *data)
  3849. {
  3850. obs_source_t *source = obs_get_output_source(channel);
  3851. if (!source)
  3852. return;
  3853. obs_data_t *save =
  3854. obs_data_get_obj(data, std::to_string(channel).c_str());
  3855. obs_source_set_volume(source, obs_data_get_double(save, "vol"));
  3856. obs_source_set_balance_value(source,
  3857. obs_data_get_double(save, "balance"));
  3858. obs_source_set_audio_mixers(source,
  3859. obs_data_get_double(save, "mixers"));
  3860. obs_source_set_sync_offset(source, obs_data_get_double(save, "sync"));
  3861. obs_source_set_flags(source, obs_data_get_double(save, "flags"));
  3862. obs_data_release(save);
  3863. obs_source_release(source);
  3864. }
  3865. void OBSBasic::on_actionAdvAudioProperties_triggered()
  3866. {
  3867. if (advAudioWindow != nullptr) {
  3868. advAudioWindow->raise();
  3869. return;
  3870. }
  3871. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  3872. "BasicWindow", "ShowSourceIcons");
  3873. advAudioWindow = new OBSBasicAdvAudio(this);
  3874. advAudioWindow->show();
  3875. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3876. advAudioWindow->SetIconsVisible(iconsVisible);
  3877. connect(advAudioWindow, SIGNAL(destroyed()), this,
  3878. SLOT(AdvAudioPropsDestroyed()));
  3879. }
  3880. void OBSBasic::AdvAudioPropsClicked()
  3881. {
  3882. on_actionAdvAudioProperties_triggered();
  3883. }
  3884. void OBSBasic::AdvAudioPropsDestroyed()
  3885. {
  3886. advAudioWindow = nullptr;
  3887. }
  3888. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  3889. QListWidgetItem *prev)
  3890. {
  3891. obs_source_t *source = NULL;
  3892. if (current) {
  3893. obs_scene_t *scene;
  3894. scene = GetOBSRef<OBSScene>(current);
  3895. source = obs_scene_get_source(scene);
  3896. }
  3897. SetCurrentScene(source);
  3898. if (api)
  3899. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  3900. UpdateContextBar();
  3901. UNUSED_PARAMETER(prev);
  3902. }
  3903. void OBSBasic::EditSceneName()
  3904. {
  3905. App()->DisableHotkeys();
  3906. ui->scenesDock->removeAction(renameScene);
  3907. QListWidgetItem *item = ui->scenes->currentItem();
  3908. Qt::ItemFlags flags = item->flags();
  3909. item->setFlags(flags | Qt::ItemIsEditable);
  3910. ui->scenes->editItem(item);
  3911. item->setFlags(flags);
  3912. }
  3913. void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  3914. const char *slot)
  3915. {
  3916. QAction *action;
  3917. QList<QScreen *> screens = QGuiApplication::screens();
  3918. for (int i = 0; i < screens.size(); i++) {
  3919. QScreen *screen = screens[i];
  3920. QRect screenGeometry = screen->geometry();
  3921. qreal ratio = screen->devicePixelRatio();
  3922. QString name = "";
  3923. #ifdef _WIN32
  3924. QTextStream fullname(&name);
  3925. fullname << GetMonitorName(screen->name());
  3926. fullname << " (";
  3927. fullname << (i + 1);
  3928. fullname << ")";
  3929. #elif defined(__APPLE__)
  3930. name = screen->name();
  3931. #else
  3932. name = screen->model().simplified();
  3933. if (name.length() > 1 && name.endsWith("-"))
  3934. name.chop(1);
  3935. #endif
  3936. name = name.simplified();
  3937. if (name.length() == 0) {
  3938. name = QString("%1 %2")
  3939. .arg(QTStr("Display"))
  3940. .arg(QString::number(i + 1));
  3941. }
  3942. QString str =
  3943. QString("%1: %2x%3 @ %4,%5")
  3944. .arg(name,
  3945. QString::number(screenGeometry.width() *
  3946. ratio),
  3947. QString::number(screenGeometry.height() *
  3948. ratio),
  3949. QString::number(screenGeometry.x()),
  3950. QString::number(screenGeometry.y()));
  3951. action = parent->addAction(str, target, slot);
  3952. action->setProperty("monitor", i);
  3953. }
  3954. }
  3955. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  3956. {
  3957. QListWidgetItem *item = ui->scenes->itemAt(pos);
  3958. QMenu popup(this);
  3959. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  3960. popup.addAction(QTStr("Add"), this,
  3961. SLOT(on_actionAddScene_triggered()));
  3962. if (item) {
  3963. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  3964. copyFilters->setEnabled(false);
  3965. connect(copyFilters, SIGNAL(triggered()), this,
  3966. SLOT(SceneCopyFilters()));
  3967. QAction *pasteFilters =
  3968. new QAction(QTStr("Paste.Filters"), this);
  3969. pasteFilters->setEnabled(copyFiltersString);
  3970. connect(pasteFilters, SIGNAL(triggered()), this,
  3971. SLOT(ScenePasteFilters()));
  3972. popup.addSeparator();
  3973. popup.addAction(QTStr("Duplicate"), this,
  3974. SLOT(DuplicateSelectedScene()));
  3975. popup.addAction(copyFilters);
  3976. popup.addAction(pasteFilters);
  3977. popup.addSeparator();
  3978. popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
  3979. popup.addAction(QTStr("Remove"), this,
  3980. SLOT(RemoveSelectedScene()));
  3981. popup.addSeparator();
  3982. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  3983. SLOT(on_actionSceneUp_triggered()));
  3984. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  3985. this, SLOT(on_actionSceneDown_triggered()));
  3986. order.addSeparator();
  3987. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  3988. this, SLOT(MoveSceneToTop()));
  3989. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  3990. this, SLOT(MoveSceneToBottom()));
  3991. popup.addMenu(&order);
  3992. popup.addSeparator();
  3993. delete sceneProjectorMenu;
  3994. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  3995. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  3996. SLOT(OpenSceneProjector()));
  3997. popup.addMenu(sceneProjectorMenu);
  3998. QAction *sceneWindow = popup.addAction(
  3999. QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
  4000. popup.addAction(sceneWindow);
  4001. popup.addAction(QTStr("Screenshot.Scene"), this,
  4002. SLOT(ScreenshotScene()));
  4003. popup.addSeparator();
  4004. popup.addAction(QTStr("Filters"), this,
  4005. SLOT(OpenSceneFilters()));
  4006. popup.addSeparator();
  4007. delete perSceneTransitionMenu;
  4008. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4009. popup.addMenu(perSceneTransitionMenu);
  4010. /* ---------------------- */
  4011. QAction *multiviewAction =
  4012. popup.addAction(QTStr("ShowInMultiview"));
  4013. OBSSource source = GetCurrentSceneSource();
  4014. OBSData data = obs_source_get_private_settings(source);
  4015. obs_data_release(data);
  4016. obs_data_set_default_bool(data, "show_in_multiview", true);
  4017. bool show = obs_data_get_bool(data, "show_in_multiview");
  4018. multiviewAction->setCheckable(true);
  4019. multiviewAction->setChecked(show);
  4020. auto showInMultiview = [](OBSData data) {
  4021. bool show =
  4022. obs_data_get_bool(data, "show_in_multiview");
  4023. obs_data_set_bool(data, "show_in_multiview", !show);
  4024. OBSProjector::UpdateMultiviewProjectors();
  4025. };
  4026. connect(multiviewAction, &QAction::triggered,
  4027. std::bind(showInMultiview, data));
  4028. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4029. }
  4030. popup.addSeparator();
  4031. bool grid = ui->scenes->GetGridMode();
  4032. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4033. : QTStr("Basic.Main.GridMode"),
  4034. this);
  4035. connect(gridAction, SIGNAL(triggered()), this,
  4036. SLOT(GridActionClicked()));
  4037. popup.addAction(gridAction);
  4038. popup.exec(QCursor::pos());
  4039. }
  4040. void OBSBasic::GridActionClicked()
  4041. {
  4042. bool gridMode = !ui->scenes->GetGridMode();
  4043. ui->scenes->SetGridMode(gridMode);
  4044. }
  4045. void OBSBasic::on_actionAddScene_triggered()
  4046. {
  4047. string name;
  4048. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4049. int i = 2;
  4050. QString placeHolderText = format.arg(i);
  4051. obs_source_t *source = nullptr;
  4052. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4053. obs_source_release(source);
  4054. placeHolderText = format.arg(++i);
  4055. }
  4056. bool accepted = NameDialog::AskForName(
  4057. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4058. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4059. if (accepted) {
  4060. if (name.empty()) {
  4061. OBSMessageBox::warning(this,
  4062. QTStr("NoNameEntered.Title"),
  4063. QTStr("NoNameEntered.Text"));
  4064. on_actionAddScene_triggered();
  4065. return;
  4066. }
  4067. obs_source_t *source = obs_get_source_by_name(name.c_str());
  4068. if (source) {
  4069. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4070. QTStr("NameExists.Text"));
  4071. obs_source_release(source);
  4072. on_actionAddScene_triggered();
  4073. return;
  4074. }
  4075. auto undo_fn = [](const std::string &data) {
  4076. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4077. if (t) {
  4078. obs_source_release(t);
  4079. obs_source_remove(t);
  4080. }
  4081. };
  4082. auto redo_fn = [this](const std::string &data) {
  4083. obs_scene_t *scene = obs_scene_create(data.c_str());
  4084. obs_source_t *source = obs_scene_get_source(scene);
  4085. SetCurrentScene(source, true);
  4086. obs_scene_release(scene);
  4087. };
  4088. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4089. undo_fn, redo_fn, name, name);
  4090. obs_scene_t *scene = obs_scene_create(name.c_str());
  4091. source = obs_scene_get_source(scene);
  4092. SetCurrentScene(source);
  4093. RefreshSources(scene);
  4094. obs_scene_release(scene);
  4095. }
  4096. }
  4097. void OBSBasic::on_actionRemoveScene_triggered()
  4098. {
  4099. App()->DisableHotkeys();
  4100. RemoveSelectedScene();
  4101. App()->UpdateHotkeyFocusSetting();
  4102. }
  4103. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4104. {
  4105. int idx = ui->scenes->currentRow();
  4106. if (idx == -1 || idx == invalidIdx)
  4107. return;
  4108. ui->scenes->blockSignals(true);
  4109. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4110. if (!relative)
  4111. idx = 0;
  4112. ui->scenes->insertItem(idx + offset, item);
  4113. ui->scenes->setCurrentRow(idx + offset);
  4114. item->setSelected(true);
  4115. ui->scenes->blockSignals(false);
  4116. OBSProjector::UpdateMultiviewProjectors();
  4117. }
  4118. void OBSBasic::on_actionSceneUp_triggered()
  4119. {
  4120. ChangeSceneIndex(true, -1, 0);
  4121. }
  4122. void OBSBasic::on_actionSceneDown_triggered()
  4123. {
  4124. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4125. }
  4126. void OBSBasic::MoveSceneToTop()
  4127. {
  4128. ChangeSceneIndex(false, 0, 0);
  4129. }
  4130. void OBSBasic::MoveSceneToBottom()
  4131. {
  4132. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4133. ui->scenes->count() - 1);
  4134. }
  4135. void OBSBasic::EditSceneItemName()
  4136. {
  4137. int idx = GetTopSelectedSourceItem();
  4138. ui->sources->Edit(idx);
  4139. }
  4140. void OBSBasic::SetDeinterlacingMode()
  4141. {
  4142. QAction *action = reinterpret_cast<QAction *>(sender());
  4143. obs_deinterlace_mode mode =
  4144. (obs_deinterlace_mode)action->property("mode").toInt();
  4145. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4146. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4147. obs_source_set_deinterlace_mode(source, mode);
  4148. }
  4149. void OBSBasic::SetDeinterlacingOrder()
  4150. {
  4151. QAction *action = reinterpret_cast<QAction *>(sender());
  4152. obs_deinterlace_field_order order =
  4153. (obs_deinterlace_field_order)action->property("order").toInt();
  4154. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4155. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4156. obs_source_set_deinterlace_field_order(source, order);
  4157. }
  4158. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4159. {
  4160. obs_deinterlace_mode deinterlaceMode =
  4161. obs_source_get_deinterlace_mode(source);
  4162. obs_deinterlace_field_order deinterlaceOrder =
  4163. obs_source_get_deinterlace_field_order(source);
  4164. QAction *action;
  4165. #define ADD_MODE(name, mode) \
  4166. action = menu->addAction(QTStr("" name), this, \
  4167. SLOT(SetDeinterlacingMode())); \
  4168. action->setProperty("mode", (int)mode); \
  4169. action->setCheckable(true); \
  4170. action->setChecked(deinterlaceMode == mode);
  4171. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4172. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4173. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4174. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4175. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4176. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4177. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4178. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4179. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4180. #undef ADD_MODE
  4181. menu->addSeparator();
  4182. #define ADD_ORDER(name, order) \
  4183. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4184. SLOT(SetDeinterlacingOrder())); \
  4185. action->setProperty("order", (int)order); \
  4186. action->setCheckable(true); \
  4187. action->setChecked(deinterlaceOrder == order);
  4188. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4189. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4190. #undef ADD_ORDER
  4191. return menu;
  4192. }
  4193. void OBSBasic::SetScaleFilter()
  4194. {
  4195. QAction *action = reinterpret_cast<QAction *>(sender());
  4196. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4197. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4198. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4199. }
  4200. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4201. {
  4202. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4203. QAction *action;
  4204. #define ADD_MODE(name, mode) \
  4205. action = \
  4206. menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
  4207. action->setProperty("mode", (int)mode); \
  4208. action->setCheckable(true); \
  4209. action->setChecked(scaleFilter == mode);
  4210. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4211. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4212. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4213. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4214. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4215. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4216. #undef ADD_MODE
  4217. return menu;
  4218. }
  4219. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4220. QWidgetAction *widgetAction,
  4221. ColorSelect *select,
  4222. obs_sceneitem_t *item)
  4223. {
  4224. QAction *action;
  4225. menu->setStyleSheet(QString(
  4226. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4227. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4228. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4229. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4230. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4231. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4232. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4233. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4234. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4235. obs_data_release(privData);
  4236. obs_data_set_default_int(privData, "color-preset", 0);
  4237. int preset = obs_data_get_int(privData, "color-preset");
  4238. action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
  4239. action->setCheckable(true);
  4240. action->setProperty("bgColor", 0);
  4241. action->setChecked(preset == 0);
  4242. action = menu->addAction(QTStr("CustomColor"), this,
  4243. +SLOT(ColorChange()));
  4244. action->setCheckable(true);
  4245. action->setProperty("bgColor", 1);
  4246. action->setChecked(preset == 1);
  4247. menu->addSeparator();
  4248. widgetAction->setDefaultWidget(select);
  4249. for (int i = 1; i < 9; i++) {
  4250. stringstream button;
  4251. button << "preset" << i;
  4252. QPushButton *colorButton =
  4253. select->findChild<QPushButton *>(button.str().c_str());
  4254. if (preset == i + 1)
  4255. colorButton->setStyleSheet("border: 2px solid black");
  4256. colorButton->setProperty("bgColor", i);
  4257. select->connect(colorButton, SIGNAL(released()), this,
  4258. SLOT(ColorChange()));
  4259. }
  4260. menu->addAction(widgetAction);
  4261. return menu;
  4262. }
  4263. ColorSelect::ColorSelect(QWidget *parent)
  4264. : QWidget(parent), ui(new Ui::ColorSelect)
  4265. {
  4266. ui->setupUi(this);
  4267. }
  4268. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4269. {
  4270. QMenu popup(this);
  4271. delete previewProjectorSource;
  4272. delete sourceProjector;
  4273. delete scaleFilteringMenu;
  4274. delete colorMenu;
  4275. delete colorWidgetAction;
  4276. delete colorSelect;
  4277. delete deinterlaceMenu;
  4278. if (preview) {
  4279. QAction *action = popup.addAction(
  4280. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4281. SLOT(TogglePreview()));
  4282. action->setCheckable(true);
  4283. action->setChecked(
  4284. obs_display_enabled(ui->preview->GetDisplay()));
  4285. if (IsPreviewProgramMode())
  4286. action->setEnabled(false);
  4287. popup.addAction(ui->actionLockPreview);
  4288. popup.addMenu(ui->scalingMenu);
  4289. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4290. AddProjectorMenuMonitors(previewProjectorSource, this,
  4291. SLOT(OpenPreviewProjector()));
  4292. popup.addMenu(previewProjectorSource);
  4293. QAction *previewWindow =
  4294. popup.addAction(QTStr("PreviewWindow"), this,
  4295. SLOT(OpenPreviewWindow()));
  4296. popup.addAction(previewWindow);
  4297. popup.addAction(QTStr("Screenshot.Preview"), this,
  4298. SLOT(ScreenshotScene()));
  4299. popup.addSeparator();
  4300. }
  4301. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4302. if (addSourceMenu)
  4303. popup.addMenu(addSourceMenu);
  4304. ui->actionCopyFilters->setEnabled(false);
  4305. ui->actionCopySource->setEnabled(false);
  4306. if (ui->sources->MultipleBaseSelected()) {
  4307. popup.addSeparator();
  4308. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4309. SLOT(GroupSelectedItems()));
  4310. } else if (ui->sources->GroupsSelected()) {
  4311. popup.addSeparator();
  4312. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4313. SLOT(UngroupSelectedGroups()));
  4314. }
  4315. popup.addSeparator();
  4316. popup.addAction(ui->actionCopySource);
  4317. popup.addAction(ui->actionPasteRef);
  4318. popup.addAction(ui->actionPasteDup);
  4319. popup.addSeparator();
  4320. popup.addSeparator();
  4321. popup.addAction(ui->actionCopyFilters);
  4322. popup.addAction(ui->actionPasteFilters);
  4323. popup.addSeparator();
  4324. if (idx != -1) {
  4325. if (addSourceMenu)
  4326. popup.addSeparator();
  4327. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4328. bool lock = obs_sceneitem_locked(sceneItem);
  4329. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4330. uint32_t flags = obs_source_get_output_flags(source);
  4331. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4332. OBS_SOURCE_ASYNC_VIDEO;
  4333. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4334. QAction *action;
  4335. colorMenu = new QMenu(QTStr("ChangeBG"));
  4336. colorWidgetAction = new QWidgetAction(colorMenu);
  4337. colorSelect = new ColorSelect(colorMenu);
  4338. popup.addMenu(AddBackgroundColorMenu(
  4339. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4340. popup.addAction(QTStr("Rename"), this,
  4341. SLOT(EditSceneItemName()));
  4342. popup.addAction(QTStr("Remove"), this,
  4343. SLOT(on_actionRemoveSource_triggered()));
  4344. popup.addSeparator();
  4345. popup.addMenu(ui->orderMenu);
  4346. popup.addMenu(ui->transformMenu);
  4347. ui->actionResetTransform->setEnabled(!lock);
  4348. ui->actionRotate90CW->setEnabled(!lock);
  4349. ui->actionRotate90CCW->setEnabled(!lock);
  4350. ui->actionRotate180->setEnabled(!lock);
  4351. ui->actionFlipHorizontal->setEnabled(!lock);
  4352. ui->actionFlipVertical->setEnabled(!lock);
  4353. ui->actionFitToScreen->setEnabled(!lock);
  4354. ui->actionStretchToScreen->setEnabled(!lock);
  4355. ui->actionCenterToScreen->setEnabled(!lock);
  4356. ui->actionVerticalCenter->setEnabled(!lock);
  4357. ui->actionHorizontalCenter->setEnabled(!lock);
  4358. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4359. AddProjectorMenuMonitors(sourceProjector, this,
  4360. SLOT(OpenSourceProjector()));
  4361. QAction *sourceWindow = popup.addAction(
  4362. QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
  4363. popup.addAction(sourceWindow);
  4364. popup.addSeparator();
  4365. if (hasAudio) {
  4366. QAction *actionHideMixer =
  4367. popup.addAction(QTStr("HideMixer"), this,
  4368. SLOT(ToggleHideMixer()));
  4369. actionHideMixer->setCheckable(true);
  4370. actionHideMixer->setChecked(SourceMixerHidden(source));
  4371. }
  4372. if (isAsyncVideo) {
  4373. deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
  4374. popup.addMenu(
  4375. AddDeinterlacingMenu(deinterlaceMenu, source));
  4376. popup.addSeparator();
  4377. }
  4378. QAction *resizeOutput =
  4379. popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
  4380. SLOT(ResizeOutputSizeOfSource()));
  4381. int width = obs_source_get_width(source);
  4382. int height = obs_source_get_height(source);
  4383. resizeOutput->setEnabled(!obs_video_active());
  4384. if (width < 8 || height < 8)
  4385. resizeOutput->setEnabled(false);
  4386. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4387. popup.addMenu(
  4388. AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
  4389. popup.addSeparator();
  4390. popup.addMenu(sourceProjector);
  4391. popup.addAction(sourceWindow);
  4392. popup.addAction(QTStr("Screenshot.Source"), this,
  4393. SLOT(ScreenshotSelectedSource()));
  4394. popup.addSeparator();
  4395. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4396. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4397. popup.addSeparator();
  4398. action = popup.addAction(QTStr("Interact"), this,
  4399. SLOT(on_actionInteract_triggered()));
  4400. action->setEnabled(obs_source_get_output_flags(source) &
  4401. OBS_SOURCE_INTERACTION);
  4402. popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
  4403. popup.addAction(QTStr("Properties"), this,
  4404. SLOT(on_actionSourceProperties_triggered()));
  4405. ui->actionCopyFilters->setEnabled(
  4406. obs_source_filter_count(source) > 0);
  4407. ui->actionCopySource->setEnabled(true);
  4408. }
  4409. ui->actionPasteFilters->setEnabled(copyFiltersString && idx != -1);
  4410. popup.exec(QCursor::pos());
  4411. }
  4412. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4413. {
  4414. if (ui->scenes->count()) {
  4415. QModelIndex idx = ui->sources->indexAt(pos);
  4416. CreateSourcePopupMenu(idx.row(), false);
  4417. }
  4418. }
  4419. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4420. {
  4421. if (!witem)
  4422. return;
  4423. if (IsPreviewProgramMode()) {
  4424. bool doubleClickSwitch =
  4425. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  4426. "TransitionOnDoubleClick");
  4427. if (doubleClickSwitch)
  4428. TransitionClicked();
  4429. }
  4430. }
  4431. void OBSBasic::AddSource(const char *id)
  4432. {
  4433. if (id && *id) {
  4434. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  4435. sourceSelect.exec();
  4436. if (sourceSelect.newSource && strcmp(id, "group") != 0) {
  4437. CreatePropertiesWindow(sourceSelect.newSource);
  4438. }
  4439. }
  4440. }
  4441. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  4442. {
  4443. const char *unversioned_type;
  4444. const char *type;
  4445. bool foundValues = false;
  4446. bool foundDeprecated = false;
  4447. size_t idx = 0;
  4448. QMenu *popup = new QMenu(QTStr("Add"), this);
  4449. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  4450. auto getActionAfter = [](QMenu *menu, const QString &name) {
  4451. QList<QAction *> actions = menu->actions();
  4452. for (QAction *menuAction : actions) {
  4453. if (menuAction->text().compare(name) >= 0)
  4454. return menuAction;
  4455. }
  4456. return (QAction *)nullptr;
  4457. };
  4458. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  4459. const char *name) {
  4460. QString qname = QT_UTF8(name);
  4461. QAction *popupItem = new QAction(qname, this);
  4462. popupItem->setData(QT_UTF8(type));
  4463. connect(popupItem, SIGNAL(triggered(bool)), this,
  4464. SLOT(AddSourceFromAction()));
  4465. QIcon icon;
  4466. if (strcmp(type, "scene") == 0)
  4467. icon = GetSceneIcon();
  4468. else
  4469. icon = GetSourceIcon(type);
  4470. popupItem->setIcon(icon);
  4471. QAction *after = getActionAfter(popup, qname);
  4472. popup->insertAction(after, popupItem);
  4473. };
  4474. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  4475. const char *name = obs_source_get_display_name(type);
  4476. uint32_t caps = obs_get_source_output_flags(type);
  4477. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  4478. continue;
  4479. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  4480. addSource(popup, unversioned_type, name);
  4481. } else {
  4482. addSource(deprecated, unversioned_type, name);
  4483. foundDeprecated = true;
  4484. }
  4485. foundValues = true;
  4486. }
  4487. addSource(popup, "scene", Str("Basic.Scene"));
  4488. popup->addSeparator();
  4489. QAction *addGroup = new QAction(QTStr("Group"), this);
  4490. addGroup->setData(QT_UTF8("group"));
  4491. addGroup->setIcon(GetGroupIcon());
  4492. connect(addGroup, SIGNAL(triggered(bool)), this,
  4493. SLOT(AddSourceFromAction()));
  4494. popup->addAction(addGroup);
  4495. if (!foundDeprecated) {
  4496. delete deprecated;
  4497. deprecated = nullptr;
  4498. }
  4499. if (!foundValues) {
  4500. delete popup;
  4501. popup = nullptr;
  4502. } else if (foundDeprecated) {
  4503. popup->addSeparator();
  4504. popup->addMenu(deprecated);
  4505. }
  4506. return popup;
  4507. }
  4508. void OBSBasic::AddSourceFromAction()
  4509. {
  4510. QAction *action = qobject_cast<QAction *>(sender());
  4511. if (!action)
  4512. return;
  4513. AddSource(QT_TO_UTF8(action->data().toString()));
  4514. }
  4515. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  4516. {
  4517. if (!GetCurrentScene()) {
  4518. // Tell the user he needs a scene first (help beginners).
  4519. OBSMessageBox::information(
  4520. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  4521. QTStr("Basic.Main.AddSourceHelp.Text"));
  4522. return;
  4523. }
  4524. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  4525. if (popup)
  4526. popup->exec(pos);
  4527. }
  4528. void OBSBasic::on_actionAddSource_triggered()
  4529. {
  4530. AddSourcePopupMenu(QCursor::pos());
  4531. }
  4532. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  4533. {
  4534. vector<OBSSceneItem> &items =
  4535. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  4536. if (obs_sceneitem_selected(item)) {
  4537. items.emplace_back(item);
  4538. } else if (obs_sceneitem_is_group(item)) {
  4539. obs_sceneitem_group_enum_items(item, remove_items, &items);
  4540. }
  4541. return true;
  4542. };
  4543. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  4544. std::vector<obs_source_t *> *sources)
  4545. {
  4546. obs_data_array_t *undo_array = obs_data_array_create();
  4547. if (!sources) {
  4548. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  4549. } else {
  4550. for (obs_source_t *source : *sources) {
  4551. obs_data_t *source_data = obs_save_source(source);
  4552. obs_data_array_push_back(undo_array, source_data);
  4553. obs_data_release(source_data);
  4554. }
  4555. }
  4556. obs_data_t *scene_data = obs_save_source(obs_scene_get_source(scene));
  4557. obs_data_array_push_back(undo_array, scene_data);
  4558. obs_data_release(scene_data);
  4559. OBSData data = obs_data_create();
  4560. obs_data_release(data);
  4561. obs_data_set_array(data, "array", undo_array);
  4562. obs_data_get_json(data);
  4563. obs_data_array_release(undo_array);
  4564. return data;
  4565. }
  4566. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  4567. {
  4568. auto sources = static_cast<std::vector<obs_source_t *> *>(p);
  4569. sources->push_back(obs_sceneitem_get_source(item));
  4570. return true;
  4571. }
  4572. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  4573. OBSData undo_data, OBSData redo_data)
  4574. {
  4575. auto undo_redo = [this](const std::string &json) {
  4576. obs_data_t *base = obs_data_create_from_json(json.c_str());
  4577. obs_data_array_t *array = obs_data_get_array(base, "array");
  4578. std::vector<obs_source_t *> sources;
  4579. std::vector<obs_source_t *> old_sources;
  4580. /* create missing sources */
  4581. const size_t count = obs_data_array_count(array);
  4582. sources.reserve(count);
  4583. for (size_t i = 0; i < count; i++) {
  4584. obs_data_t *data = obs_data_array_item(array, i);
  4585. const char *name = obs_data_get_string(data, "name");
  4586. obs_source_t *source = obs_get_source_by_name(name);
  4587. if (!source)
  4588. source = obs_load_source(data);
  4589. sources.push_back(source);
  4590. /* update scene/group settings to restore their
  4591. * contents to their saved settings */
  4592. obs_scene_t *scene =
  4593. obs_group_or_scene_from_source(source);
  4594. if (scene) {
  4595. obs_scene_enum_items(scene, add_source_enum,
  4596. &old_sources);
  4597. obs_data_t *scene_settings =
  4598. obs_data_get_obj(data, "settings");
  4599. obs_source_update(source, scene_settings);
  4600. obs_data_release(scene_settings);
  4601. }
  4602. obs_data_release(data);
  4603. }
  4604. for (obs_source_t *source : old_sources)
  4605. obs_source_addref(source);
  4606. /* actually load sources now */
  4607. for (obs_source_t *source : sources)
  4608. obs_source_load2(source);
  4609. /* release sources */
  4610. for (obs_source_t *source : sources)
  4611. obs_source_release(source);
  4612. for (obs_source_t *source : old_sources)
  4613. obs_source_release(source);
  4614. obs_data_array_release(array);
  4615. obs_data_release(base);
  4616. ui->sources->RefreshItems();
  4617. };
  4618. const char *undo_json = obs_data_get_last_json(undo_data);
  4619. const char *redo_json = obs_data_get_last_json(redo_data);
  4620. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  4621. redo_json);
  4622. }
  4623. void OBSBasic::on_actionRemoveSource_triggered()
  4624. {
  4625. vector<OBSSceneItem> items;
  4626. OBSScene scene = GetCurrentScene();
  4627. obs_source_t *scene_source = obs_scene_get_source(scene);
  4628. obs_scene_enum_items(scene, remove_items, &items);
  4629. if (!items.size())
  4630. return;
  4631. /* ------------------------------------- */
  4632. /* confirm action with user */
  4633. bool confirmed = false;
  4634. if (items.size() > 1) {
  4635. QString text = QTStr("ConfirmRemove.TextMultiple")
  4636. .arg(QString::number(items.size()));
  4637. QMessageBox remove_items(this);
  4638. remove_items.setText(text);
  4639. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  4640. QMessageBox::YesRole);
  4641. remove_items.setDefaultButton(Yes);
  4642. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  4643. remove_items.setIcon(QMessageBox::Question);
  4644. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  4645. remove_items.exec();
  4646. confirmed = Yes == remove_items.clickedButton();
  4647. } else {
  4648. OBSSceneItem &item = items[0];
  4649. obs_source_t *source = obs_sceneitem_get_source(item);
  4650. if (source && QueryRemoveSource(source))
  4651. confirmed = true;
  4652. }
  4653. if (!confirmed)
  4654. return;
  4655. App()->DisableHotkeys();
  4656. /* ----------------------------------------------- */
  4657. /* save undo data */
  4658. OBSData undo_data = BackupScene(scene_source);
  4659. /* ----------------------------------------------- */
  4660. /* remove items */
  4661. for (auto &item : items)
  4662. obs_sceneitem_remove(item);
  4663. /* ----------------------------------------------- */
  4664. /* save redo data */
  4665. OBSData redo_data = BackupScene(scene_source);
  4666. /* ----------------------------------------------- */
  4667. /* add undo/redo action */
  4668. QString action_name;
  4669. if (items.size() > 1) {
  4670. action_name = QTStr("Undo.Sources.Multi")
  4671. .arg(QString::number(items.size()));
  4672. } else {
  4673. QString str = QTStr("Undo.Delete");
  4674. action_name = str.arg(obs_source_get_name(
  4675. obs_sceneitem_get_source(items[0])));
  4676. }
  4677. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  4678. App()->UpdateHotkeyFocusSetting();
  4679. }
  4680. void OBSBasic::on_actionInteract_triggered()
  4681. {
  4682. OBSSceneItem item = GetCurrentSceneItem();
  4683. OBSSource source = obs_sceneitem_get_source(item);
  4684. if (source)
  4685. CreateInteractionWindow(source);
  4686. }
  4687. void OBSBasic::on_actionSourceProperties_triggered()
  4688. {
  4689. OBSSceneItem item = GetCurrentSceneItem();
  4690. OBSSource source = obs_sceneitem_get_source(item);
  4691. if (source)
  4692. CreatePropertiesWindow(source);
  4693. }
  4694. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  4695. const QString &action_name)
  4696. {
  4697. OBSSceneItem item = GetCurrentSceneItem();
  4698. obs_source_t *source = obs_sceneitem_get_source(item);
  4699. if (!source)
  4700. return;
  4701. OBSScene scene = GetCurrentScene();
  4702. std::vector<obs_source_t *> sources;
  4703. if (scene != obs_sceneitem_get_scene(item))
  4704. sources.push_back(
  4705. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  4706. OBSData undo_data = BackupScene(scene, &sources);
  4707. obs_sceneitem_set_order(item, movement);
  4708. const char *source_name = obs_source_get_name(source);
  4709. const char *scene_name =
  4710. obs_source_get_name(obs_scene_get_source(scene));
  4711. OBSData redo_data = BackupScene(scene, &sources);
  4712. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  4713. undo_data, redo_data);
  4714. }
  4715. void OBSBasic::on_actionSourceUp_triggered()
  4716. {
  4717. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4718. }
  4719. void OBSBasic::on_actionSourceDown_triggered()
  4720. {
  4721. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4722. }
  4723. void OBSBasic::on_actionMoveUp_triggered()
  4724. {
  4725. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  4726. }
  4727. void OBSBasic::on_actionMoveDown_triggered()
  4728. {
  4729. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  4730. }
  4731. void OBSBasic::on_actionMoveToTop_triggered()
  4732. {
  4733. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  4734. }
  4735. void OBSBasic::on_actionMoveToBottom_triggered()
  4736. {
  4737. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  4738. }
  4739. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  4740. {
  4741. char logDir[512];
  4742. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  4743. return nullptr;
  4744. string path = logDir;
  4745. path += "/";
  4746. path += log;
  4747. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  4748. if (!file)
  4749. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  4750. return file;
  4751. }
  4752. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  4753. {
  4754. BPtr<char> fileString{ReadLogFile(subdir, file)};
  4755. if (!fileString)
  4756. return;
  4757. if (!*fileString)
  4758. return;
  4759. ui->menuLogFiles->setEnabled(false);
  4760. #if defined(_WIN32)
  4761. ui->menuCrashLogs->setEnabled(false);
  4762. #endif
  4763. stringstream ss;
  4764. ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
  4765. << CurrentDateTimeString() << "\n\n"
  4766. << fileString;
  4767. if (logUploadThread) {
  4768. logUploadThread->wait();
  4769. }
  4770. RemoteTextThread *thread =
  4771. new RemoteTextThread("https://obsproject.com/logs/upload",
  4772. "text/plain", ss.str().c_str());
  4773. logUploadThread.reset(thread);
  4774. if (crash) {
  4775. connect(thread, &RemoteTextThread::Result, this,
  4776. &OBSBasic::crashUploadFinished);
  4777. } else {
  4778. connect(thread, &RemoteTextThread::Result, this,
  4779. &OBSBasic::logUploadFinished);
  4780. }
  4781. logUploadThread->start();
  4782. }
  4783. void OBSBasic::on_actionShowLogs_triggered()
  4784. {
  4785. char logDir[512];
  4786. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  4787. return;
  4788. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4789. QDesktopServices::openUrl(url);
  4790. }
  4791. void OBSBasic::on_actionUploadCurrentLog_triggered()
  4792. {
  4793. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  4794. }
  4795. void OBSBasic::on_actionUploadLastLog_triggered()
  4796. {
  4797. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  4798. }
  4799. void OBSBasic::on_actionViewCurrentLog_triggered()
  4800. {
  4801. if (!logView)
  4802. logView = new OBSLogViewer();
  4803. logView->show();
  4804. logView->setWindowState(
  4805. (logView->windowState() & ~Qt::WindowMinimized) |
  4806. Qt::WindowActive);
  4807. logView->activateWindow();
  4808. logView->raise();
  4809. }
  4810. void OBSBasic::on_actionShowCrashLogs_triggered()
  4811. {
  4812. char logDir[512];
  4813. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  4814. return;
  4815. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  4816. QDesktopServices::openUrl(url);
  4817. }
  4818. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  4819. {
  4820. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  4821. }
  4822. void OBSBasic::on_actionCheckForUpdates_triggered()
  4823. {
  4824. CheckForUpdates(true);
  4825. }
  4826. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  4827. {
  4828. ui->menuLogFiles->setEnabled(true);
  4829. #if defined(_WIN32)
  4830. ui->menuCrashLogs->setEnabled(true);
  4831. #endif
  4832. if (text.isEmpty()) {
  4833. OBSMessageBox::critical(
  4834. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4835. error);
  4836. return;
  4837. }
  4838. openLogDialog(text, false);
  4839. }
  4840. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  4841. {
  4842. ui->menuLogFiles->setEnabled(true);
  4843. #if defined(_WIN32)
  4844. ui->menuCrashLogs->setEnabled(true);
  4845. #endif
  4846. if (text.isEmpty()) {
  4847. OBSMessageBox::critical(
  4848. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  4849. error);
  4850. return;
  4851. }
  4852. openLogDialog(text, true);
  4853. }
  4854. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  4855. {
  4856. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  4857. string resURL = obs_data_get_string(returnData, "url");
  4858. QString logURL = resURL.c_str();
  4859. obs_data_release(returnData);
  4860. OBSLogReply logDialog(this, logURL, crash);
  4861. logDialog.exec();
  4862. }
  4863. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  4864. obs_source_t *source, const string &name)
  4865. {
  4866. const char *prevName = obs_source_get_name(source);
  4867. if (name == prevName)
  4868. return;
  4869. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  4870. QListWidgetItem *listItem = listWidget->currentItem();
  4871. if (foundSource || name.empty()) {
  4872. listItem->setText(QT_UTF8(prevName));
  4873. if (foundSource) {
  4874. OBSMessageBox::warning(parent,
  4875. QTStr("NameExists.Title"),
  4876. QTStr("NameExists.Text"));
  4877. } else if (name.empty()) {
  4878. OBSMessageBox::warning(parent,
  4879. QTStr("NoNameEntered.Title"),
  4880. QTStr("NoNameEntered.Text"));
  4881. }
  4882. obs_source_release(foundSource);
  4883. } else {
  4884. auto undo = [prev = std::string(prevName)](
  4885. const std::string &data) {
  4886. obs_source_t *source =
  4887. obs_get_source_by_name(data.c_str());
  4888. obs_source_set_name(source, prev.c_str());
  4889. obs_source_release(source);
  4890. };
  4891. auto redo = [name](const std::string &data) {
  4892. obs_source_t *source =
  4893. obs_get_source_by_name(data.c_str());
  4894. obs_source_set_name(source, name.c_str());
  4895. obs_source_release(source);
  4896. };
  4897. std::string undo_data(name);
  4898. std::string redo_data(prevName);
  4899. parent->undo_s.add_action(
  4900. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  4901. undo_data, redo_data);
  4902. listItem->setText(QT_UTF8(name.c_str()));
  4903. obs_source_set_name(source, name.c_str());
  4904. }
  4905. }
  4906. void OBSBasic::SceneNameEdited(QWidget *editor,
  4907. QAbstractItemDelegate::EndEditHint endHint)
  4908. {
  4909. App()->UpdateHotkeyFocusSetting();
  4910. OBSScene scene = GetCurrentScene();
  4911. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  4912. string text = QT_TO_UTF8(edit->text().trimmed());
  4913. if (!scene)
  4914. return;
  4915. obs_source_t *source = obs_scene_get_source(scene);
  4916. RenameListItem(this, ui->scenes, source, text);
  4917. ui->scenesDock->addAction(renameScene);
  4918. if (api)
  4919. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  4920. UNUSED_PARAMETER(endHint);
  4921. }
  4922. void OBSBasic::OpenFilters(OBSSource source)
  4923. {
  4924. if (source == nullptr) {
  4925. OBSSceneItem item = GetCurrentSceneItem();
  4926. source = obs_sceneitem_get_source(item);
  4927. }
  4928. CreateFiltersWindow(source);
  4929. }
  4930. void OBSBasic::OpenProperties(OBSSource source)
  4931. {
  4932. if (source == nullptr) {
  4933. OBSSceneItem item = GetCurrentSceneItem();
  4934. source = obs_sceneitem_get_source(item);
  4935. }
  4936. CreatePropertiesWindow(source);
  4937. }
  4938. void OBSBasic::OpenSceneFilters()
  4939. {
  4940. OBSScene scene = GetCurrentScene();
  4941. OBSSource source = obs_scene_get_source(scene);
  4942. CreateFiltersWindow(source);
  4943. }
  4944. #define RECORDING_START \
  4945. "==== Recording Start ==============================================="
  4946. #define RECORDING_STOP \
  4947. "==== Recording Stop ================================================"
  4948. #define REPLAY_BUFFER_START \
  4949. "==== Replay Buffer Start ==========================================="
  4950. #define REPLAY_BUFFER_STOP \
  4951. "==== Replay Buffer Stop ============================================"
  4952. #define STREAMING_START \
  4953. "==== Streaming Start ==============================================="
  4954. #define STREAMING_STOP \
  4955. "==== Streaming Stop ================================================"
  4956. #define VIRTUAL_CAM_START \
  4957. "==== Virtual Camera Start =========================================="
  4958. #define VIRTUAL_CAM_STOP \
  4959. "==== Virtual Camera Stop ==========================================="
  4960. void OBSBasic::DisplayStreamStartError()
  4961. {
  4962. QString message = !outputHandler->lastError.empty()
  4963. ? QTStr(outputHandler->lastError.c_str())
  4964. : QTStr("Output.StartFailedGeneric");
  4965. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  4966. ui->streamButton->setEnabled(true);
  4967. ui->streamButton->setChecked(false);
  4968. if (sysTrayStream) {
  4969. sysTrayStream->setText(ui->streamButton->text());
  4970. sysTrayStream->setEnabled(true);
  4971. }
  4972. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  4973. }
  4974. #if YOUTUBE_ENABLED
  4975. void OBSBasic::YouTubeActionDialogOk(const QString &id, const QString &key,
  4976. bool autostart, bool autostop)
  4977. {
  4978. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  4979. obs_service_t *service_obj = GetService();
  4980. obs_data_t *settings = obs_service_get_settings(service_obj);
  4981. const std::string a_key = QT_TO_UTF8(key);
  4982. obs_data_set_string(settings, "key", a_key.c_str());
  4983. const std::string an_id = QT_TO_UTF8(id);
  4984. obs_data_set_string(settings, "stream_id", an_id.c_str());
  4985. obs_service_update(service_obj, settings);
  4986. autoStartBroadcast = autostart;
  4987. autoStopBroadcast = autostop;
  4988. obs_data_release(settings);
  4989. }
  4990. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  4991. {
  4992. YoutubeApiWrappers *apiYouTube(
  4993. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  4994. if (!apiYouTube) {
  4995. /* technically we should never get here -Jim */
  4996. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  4997. Qt::QueuedConnection);
  4998. youtubeStreamCheckThread->deleteLater();
  4999. blog(LOG_ERROR, "==========================================");
  5000. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5001. blog(LOG_ERROR, "==========================================");
  5002. return;
  5003. }
  5004. int timeout = 0;
  5005. json11::Json json;
  5006. QString id = key.c_str();
  5007. while (StreamingActive()) {
  5008. if (timeout == 14) {
  5009. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5010. Qt::QueuedConnection);
  5011. break;
  5012. }
  5013. if (!apiYouTube->FindStream(id, json)) {
  5014. QMetaObject::invokeMethod(this,
  5015. "DisplayStreamStartError",
  5016. Qt::QueuedConnection);
  5017. QMetaObject::invokeMethod(this, "StopStreaming",
  5018. Qt::QueuedConnection);
  5019. break;
  5020. }
  5021. auto item = json["items"][0];
  5022. auto status = item["status"]["streamStatus"].string_value();
  5023. if (status == "active") {
  5024. QMetaObject::invokeMethod(ui->broadcastButton,
  5025. "setEnabled",
  5026. Q_ARG(bool, true));
  5027. break;
  5028. } else {
  5029. QThread::sleep(1);
  5030. timeout++;
  5031. }
  5032. }
  5033. youtubeStreamCheckThread->deleteLater();
  5034. }
  5035. void OBSBasic::ShowYouTubeAutoStartWarning()
  5036. {
  5037. auto msgBox = []() {
  5038. QMessageBox msgbox(App()->GetMainWindow());
  5039. msgbox.setWindowTitle(QTStr(
  5040. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5041. msgbox.setText(
  5042. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5043. msgbox.setIcon(QMessageBox::Icon::Information);
  5044. msgbox.addButton(QMessageBox::Ok);
  5045. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5046. msgbox.setCheckBox(cb);
  5047. msgbox.exec();
  5048. if (cb->isChecked()) {
  5049. config_set_bool(App()->GlobalConfig(), "General",
  5050. "WarnedAboutYouTubeAutoStart", true);
  5051. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5052. }
  5053. };
  5054. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5055. "WarnedAboutYouTubeAutoStart");
  5056. if (!warned) {
  5057. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5058. Q_ARG(VoidFunc, msgBox));
  5059. }
  5060. }
  5061. #endif
  5062. void OBSBasic::StartStreaming()
  5063. {
  5064. if (outputHandler->StreamingActive())
  5065. return;
  5066. if (disableOutputsRef)
  5067. return;
  5068. Auth *auth = GetAuth();
  5069. if (auth) {
  5070. auth->OnStreamConfig();
  5071. #if YOUTUBE_ENABLED
  5072. if (!broadcastActive && autoStartBroadcast &&
  5073. IsYouTubeService(auth->service())) {
  5074. OBSYoutubeActions *dialog;
  5075. dialog = new OBSYoutubeActions(this, auth);
  5076. connect(dialog, &OBSYoutubeActions::ok, this,
  5077. &OBSBasic::YouTubeActionDialogOk);
  5078. int result = dialog->Valid() ? dialog->exec()
  5079. : QDialog::Rejected;
  5080. if (result != QDialog::Accepted) {
  5081. ui->streamButton->setText(
  5082. QTStr("Basic.Main.StartStreaming"));
  5083. ui->streamButton->setEnabled(true);
  5084. ui->streamButton->setChecked(false);
  5085. if (sysTrayStream) {
  5086. sysTrayStream->setText(
  5087. ui->streamButton->text());
  5088. sysTrayStream->setEnabled(true);
  5089. }
  5090. return;
  5091. }
  5092. }
  5093. #endif
  5094. }
  5095. if (!outputHandler->SetupStreaming(service)) {
  5096. DisplayStreamStartError();
  5097. return;
  5098. }
  5099. if (api)
  5100. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5101. SaveProject();
  5102. ui->streamButton->setEnabled(false);
  5103. ui->streamButton->setChecked(false);
  5104. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5105. if (sysTrayStream) {
  5106. sysTrayStream->setEnabled(false);
  5107. sysTrayStream->setText(ui->streamButton->text());
  5108. }
  5109. if (!outputHandler->StartStreaming(service)) {
  5110. DisplayStreamStartError();
  5111. return;
  5112. }
  5113. if (!autoStartBroadcast) {
  5114. ui->broadcastButton->setVisible(true);
  5115. ui->broadcastButton->setText(
  5116. QTStr("Basic.Main.StartBroadcast"));
  5117. ui->broadcastButton->setProperty("broadcastState", "ready");
  5118. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5119. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5120. // well, we need to disable button while stream is not active
  5121. ui->broadcastButton->setEnabled(false);
  5122. } else if (!autoStopBroadcast) {
  5123. broadcastActive = true;
  5124. ui->broadcastButton->setVisible(true);
  5125. ui->broadcastButton->setText(QTStr("Basic.Main.StopBroadcast"));
  5126. ui->broadcastButton->setProperty("broadcastState", "active");
  5127. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5128. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5129. }
  5130. bool recordWhenStreaming = config_get_bool(
  5131. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5132. if (recordWhenStreaming)
  5133. StartRecording();
  5134. bool replayBufferWhileStreaming = config_get_bool(
  5135. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5136. if (replayBufferWhileStreaming)
  5137. StartReplayBuffer();
  5138. #if YOUTUBE_ENABLED
  5139. if (!autoStartBroadcast)
  5140. OBSBasic::ShowYouTubeAutoStartWarning();
  5141. #endif
  5142. }
  5143. void OBSBasic::BroadcastButtonClicked()
  5144. {
  5145. if (!autoStartBroadcast) {
  5146. #if YOUTUBE_ENABLED
  5147. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5148. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5149. if (ytAuth.get()) {
  5150. ytAuth->StartLatestBroadcast();
  5151. }
  5152. #endif
  5153. broadcastActive = true;
  5154. autoStartBroadcast = true; // and clear the flag
  5155. if (!autoStopBroadcast) {
  5156. ui->broadcastButton->setText(
  5157. QTStr("Basic.Main.StopBroadcast"));
  5158. ui->broadcastButton->setProperty("broadcastState",
  5159. "active");
  5160. ui->broadcastButton->style()->unpolish(
  5161. ui->broadcastButton);
  5162. ui->broadcastButton->style()->polish(
  5163. ui->broadcastButton);
  5164. } else {
  5165. ui->broadcastButton->setVisible(false);
  5166. }
  5167. } else if (!autoStopBroadcast) {
  5168. #if YOUTUBE_ENABLED
  5169. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5170. "WarnBeforeStoppingStream");
  5171. if (confirm && isVisible()) {
  5172. QMessageBox::StandardButton button = OBSMessageBox::question(
  5173. this, QTStr("ConfirmStop.Title"),
  5174. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5175. QMessageBox::Yes | QMessageBox::No,
  5176. QMessageBox::No);
  5177. if (button == QMessageBox::No) {
  5178. return;
  5179. }
  5180. }
  5181. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5182. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5183. if (ytAuth.get()) {
  5184. ytAuth->StopLatestBroadcast();
  5185. }
  5186. #endif
  5187. broadcastActive = false;
  5188. autoStopBroadcast = true;
  5189. ui->broadcastButton->setVisible(false);
  5190. QMetaObject::invokeMethod(this, "StopStreaming");
  5191. }
  5192. }
  5193. #ifdef _WIN32
  5194. static inline void UpdateProcessPriority()
  5195. {
  5196. const char *priority = config_get_string(App()->GlobalConfig(),
  5197. "General", "ProcessPriority");
  5198. if (priority && strcmp(priority, "Normal") != 0)
  5199. SetProcessPriority(priority);
  5200. }
  5201. static inline void ClearProcessPriority()
  5202. {
  5203. const char *priority = config_get_string(App()->GlobalConfig(),
  5204. "General", "ProcessPriority");
  5205. if (priority && strcmp(priority, "Normal") != 0)
  5206. SetProcessPriority("Normal");
  5207. }
  5208. #else
  5209. #define UpdateProcessPriority() \
  5210. do { \
  5211. } while (false)
  5212. #define ClearProcessPriority() \
  5213. do { \
  5214. } while (false)
  5215. #endif
  5216. inline void OBSBasic::OnActivate()
  5217. {
  5218. if (ui->profileMenu->isEnabled()) {
  5219. ui->profileMenu->setEnabled(false);
  5220. ui->autoConfigure->setEnabled(false);
  5221. App()->IncrementSleepInhibition();
  5222. UpdateProcessPriority();
  5223. if (trayIcon && trayIcon->isVisible()) {
  5224. #ifdef __APPLE__
  5225. QIcon trayMask =
  5226. QIcon(":/res/images/tray_active_macos.png");
  5227. trayMask.setIsMask(true);
  5228. trayIcon->setIcon(
  5229. QIcon::fromTheme("obs-tray", trayMask));
  5230. #else
  5231. trayIcon->setIcon(QIcon::fromTheme(
  5232. "obs-tray-active",
  5233. QIcon(":/res/images/tray_active.png")));
  5234. #endif
  5235. }
  5236. }
  5237. }
  5238. extern volatile bool recording_paused;
  5239. extern volatile bool replaybuf_active;
  5240. inline void OBSBasic::OnDeactivate()
  5241. {
  5242. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5243. ui->profileMenu->setEnabled(true);
  5244. ui->autoConfigure->setEnabled(true);
  5245. App()->DecrementSleepInhibition();
  5246. ClearProcessPriority();
  5247. if (trayIcon && trayIcon->isVisible()) {
  5248. #ifdef __APPLE__
  5249. QIcon trayIconFile =
  5250. QIcon(":/res/images/obs_macos.png");
  5251. trayIconFile.setIsMask(true);
  5252. #else
  5253. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5254. #endif
  5255. trayIcon->setIcon(
  5256. QIcon::fromTheme("obs-tray", trayIconFile));
  5257. }
  5258. } else if (outputHandler->Active() && trayIcon &&
  5259. trayIcon->isVisible()) {
  5260. if (os_atomic_load_bool(&recording_paused)) {
  5261. #ifdef __APPLE__
  5262. QIcon trayIconFile =
  5263. QIcon(":/res/images/obs_paused_macos.png");
  5264. trayIconFile.setIsMask(true);
  5265. #else
  5266. QIcon trayIconFile =
  5267. QIcon(":/res/images/obs_paused.png");
  5268. #endif
  5269. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5270. trayIconFile));
  5271. } else {
  5272. #ifdef __APPLE__
  5273. QIcon trayIconFile =
  5274. QIcon(":/res/images/tray_active_macos.png");
  5275. trayIconFile.setIsMask(true);
  5276. #else
  5277. QIcon trayIconFile =
  5278. QIcon(":/res/images/tray_active.png");
  5279. #endif
  5280. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5281. trayIconFile));
  5282. }
  5283. }
  5284. }
  5285. void OBSBasic::StopStreaming()
  5286. {
  5287. SaveProject();
  5288. if (outputHandler->StreamingActive())
  5289. outputHandler->StopStreaming(streamingStopping);
  5290. // special case: force reset broadcast state if
  5291. // no autostart and no autostop selected
  5292. if (!autoStartBroadcast && !broadcastActive) {
  5293. broadcastActive = false;
  5294. autoStartBroadcast = true;
  5295. autoStopBroadcast = true;
  5296. ui->broadcastButton->setVisible(false);
  5297. }
  5298. if (autoStopBroadcast)
  5299. broadcastActive = false;
  5300. OnDeactivate();
  5301. bool recordWhenStreaming = config_get_bool(
  5302. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5303. bool keepRecordingWhenStreamStops =
  5304. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5305. "KeepRecordingWhenStreamStops");
  5306. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5307. StopRecording();
  5308. bool replayBufferWhileStreaming = config_get_bool(
  5309. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5310. bool keepReplayBufferStreamStops =
  5311. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5312. "KeepReplayBufferStreamStops");
  5313. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5314. StopReplayBuffer();
  5315. }
  5316. void OBSBasic::ForceStopStreaming()
  5317. {
  5318. SaveProject();
  5319. if (outputHandler->StreamingActive())
  5320. outputHandler->StopStreaming(true);
  5321. // special case: force reset broadcast state if
  5322. // no autostart and no autostop selected
  5323. if (!autoStartBroadcast && !broadcastActive) {
  5324. broadcastActive = false;
  5325. autoStartBroadcast = true;
  5326. autoStopBroadcast = true;
  5327. ui->broadcastButton->setVisible(false);
  5328. }
  5329. if (autoStopBroadcast)
  5330. broadcastActive = false;
  5331. OnDeactivate();
  5332. bool recordWhenStreaming = config_get_bool(
  5333. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5334. bool keepRecordingWhenStreamStops =
  5335. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5336. "KeepRecordingWhenStreamStops");
  5337. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5338. StopRecording();
  5339. bool replayBufferWhileStreaming = config_get_bool(
  5340. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5341. bool keepReplayBufferStreamStops =
  5342. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5343. "KeepReplayBufferStreamStops");
  5344. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5345. StopReplayBuffer();
  5346. }
  5347. void OBSBasic::StreamDelayStarting(int sec)
  5348. {
  5349. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5350. ui->streamButton->setEnabled(true);
  5351. ui->streamButton->setChecked(true);
  5352. if (sysTrayStream) {
  5353. sysTrayStream->setText(ui->streamButton->text());
  5354. sysTrayStream->setEnabled(true);
  5355. }
  5356. if (!startStreamMenu.isNull())
  5357. startStreamMenu->deleteLater();
  5358. startStreamMenu = new QMenu();
  5359. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  5360. SLOT(StopStreaming()));
  5361. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5362. SLOT(ForceStopStreaming()));
  5363. ui->streamButton->setMenu(startStreamMenu);
  5364. ui->statusbar->StreamDelayStarting(sec);
  5365. OnActivate();
  5366. }
  5367. void OBSBasic::StreamDelayStopping(int sec)
  5368. {
  5369. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5370. ui->streamButton->setEnabled(true);
  5371. ui->streamButton->setChecked(false);
  5372. if (sysTrayStream) {
  5373. sysTrayStream->setText(ui->streamButton->text());
  5374. sysTrayStream->setEnabled(true);
  5375. }
  5376. if (!startStreamMenu.isNull())
  5377. startStreamMenu->deleteLater();
  5378. startStreamMenu = new QMenu();
  5379. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  5380. SLOT(StartStreaming()));
  5381. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  5382. SLOT(ForceStopStreaming()));
  5383. ui->streamButton->setMenu(startStreamMenu);
  5384. ui->statusbar->StreamDelayStopping(sec);
  5385. if (api)
  5386. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5387. }
  5388. void OBSBasic::StreamingStart()
  5389. {
  5390. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  5391. ui->streamButton->setEnabled(true);
  5392. ui->streamButton->setChecked(true);
  5393. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  5394. if (sysTrayStream) {
  5395. sysTrayStream->setText(ui->streamButton->text());
  5396. sysTrayStream->setEnabled(true);
  5397. }
  5398. #if YOUTUBE_ENABLED
  5399. // get a current stream key
  5400. obs_service_t *service_obj = GetService();
  5401. obs_data_t *settings = obs_service_get_settings(service_obj);
  5402. std::string key = obs_data_get_string(settings, "stream_id");
  5403. if (!key.empty() && !youtubeStreamCheckThread) {
  5404. youtubeStreamCheckThread =
  5405. CreateQThread([this, key] { YoutubeStreamCheck(key); });
  5406. youtubeStreamCheckThread->setObjectName(
  5407. "YouTubeStreamCheckThread");
  5408. youtubeStreamCheckThread->start();
  5409. }
  5410. #endif
  5411. if (api)
  5412. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  5413. OnActivate();
  5414. blog(LOG_INFO, STREAMING_START);
  5415. }
  5416. void OBSBasic::StreamStopping()
  5417. {
  5418. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  5419. if (sysTrayStream)
  5420. sysTrayStream->setText(ui->streamButton->text());
  5421. streamingStopping = true;
  5422. if (api)
  5423. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  5424. }
  5425. void OBSBasic::StreamingStop(int code, QString last_error)
  5426. {
  5427. const char *errorDescription = "";
  5428. DStr errorMessage;
  5429. bool use_last_error = false;
  5430. bool encode_error = false;
  5431. switch (code) {
  5432. case OBS_OUTPUT_BAD_PATH:
  5433. errorDescription = Str("Output.ConnectFail.BadPath");
  5434. break;
  5435. case OBS_OUTPUT_CONNECT_FAILED:
  5436. use_last_error = true;
  5437. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  5438. break;
  5439. case OBS_OUTPUT_INVALID_STREAM:
  5440. errorDescription = Str("Output.ConnectFail.InvalidStream");
  5441. break;
  5442. case OBS_OUTPUT_ENCODE_ERROR:
  5443. encode_error = true;
  5444. break;
  5445. default:
  5446. case OBS_OUTPUT_ERROR:
  5447. use_last_error = true;
  5448. errorDescription = Str("Output.ConnectFail.Error");
  5449. break;
  5450. case OBS_OUTPUT_DISCONNECTED:
  5451. /* doesn't happen if output is set to reconnect. note that
  5452. * reconnects are handled in the output, not in the UI */
  5453. use_last_error = true;
  5454. errorDescription = Str("Output.ConnectFail.Disconnected");
  5455. }
  5456. if (use_last_error && !last_error.isEmpty())
  5457. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5458. QT_TO_UTF8(last_error));
  5459. else
  5460. dstr_copy(errorMessage, errorDescription);
  5461. ui->statusbar->StreamStopped();
  5462. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5463. ui->streamButton->setEnabled(true);
  5464. ui->streamButton->setChecked(false);
  5465. if (sysTrayStream) {
  5466. sysTrayStream->setText(ui->streamButton->text());
  5467. sysTrayStream->setEnabled(true);
  5468. }
  5469. streamingStopping = false;
  5470. if (api)
  5471. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  5472. OnDeactivate();
  5473. blog(LOG_INFO, STREAMING_STOP);
  5474. if (encode_error) {
  5475. OBSMessageBox::information(
  5476. this, QTStr("Output.StreamEncodeError.Title"),
  5477. QTStr("Output.StreamEncodeError.Msg"));
  5478. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5479. OBSMessageBox::information(this,
  5480. QTStr("Output.ConnectFail.Title"),
  5481. QT_UTF8(errorMessage));
  5482. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5483. SysTrayNotify(QT_UTF8(errorDescription),
  5484. QSystemTrayIcon::Warning);
  5485. }
  5486. if (!startStreamMenu.isNull()) {
  5487. ui->streamButton->setMenu(nullptr);
  5488. startStreamMenu->deleteLater();
  5489. startStreamMenu = nullptr;
  5490. }
  5491. }
  5492. void OBSBasic::AutoRemux(QString input)
  5493. {
  5494. bool autoRemux = config_get_bool(Config(), "Video", "AutoRemux");
  5495. if (!autoRemux)
  5496. return;
  5497. const char *recType = config_get_string(Config(), "AdvOut", "RecType");
  5498. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  5499. if (ffmpegOutput)
  5500. return;
  5501. if (input.isEmpty())
  5502. return;
  5503. QFileInfo fi(input);
  5504. QString suffix = fi.suffix();
  5505. /* do not remux if lossless */
  5506. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  5507. return;
  5508. }
  5509. QString path = fi.path();
  5510. QString output = input;
  5511. output.resize(output.size() - suffix.size());
  5512. output += "mp4";
  5513. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  5514. remux->show();
  5515. remux->AutoRemux(input, output);
  5516. }
  5517. void OBSBasic::StartRecording()
  5518. {
  5519. if (outputHandler->RecordingActive())
  5520. return;
  5521. if (disableOutputsRef)
  5522. return;
  5523. if (!OutputPathValid()) {
  5524. OutputPathInvalidMessage();
  5525. ui->recordButton->setChecked(false);
  5526. return;
  5527. }
  5528. if (LowDiskSpace()) {
  5529. DiskSpaceMessage();
  5530. ui->recordButton->setChecked(false);
  5531. return;
  5532. }
  5533. if (api)
  5534. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  5535. SaveProject();
  5536. if (!outputHandler->StartRecording())
  5537. ui->recordButton->setChecked(false);
  5538. }
  5539. void OBSBasic::RecordStopping()
  5540. {
  5541. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  5542. if (sysTrayRecord)
  5543. sysTrayRecord->setText(ui->recordButton->text());
  5544. recordingStopping = true;
  5545. if (api)
  5546. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  5547. }
  5548. void OBSBasic::StopRecording()
  5549. {
  5550. SaveProject();
  5551. if (outputHandler->RecordingActive())
  5552. outputHandler->StopRecording(recordingStopping);
  5553. OnDeactivate();
  5554. }
  5555. void OBSBasic::RecordingStart()
  5556. {
  5557. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  5558. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  5559. ui->recordButton->setChecked(true);
  5560. if (sysTrayRecord)
  5561. sysTrayRecord->setText(ui->recordButton->text());
  5562. recordingStopping = false;
  5563. if (api)
  5564. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  5565. if (!diskFullTimer->isActive())
  5566. diskFullTimer->start(1000);
  5567. OnActivate();
  5568. UpdatePause();
  5569. blog(LOG_INFO, RECORDING_START);
  5570. }
  5571. void OBSBasic::RecordingStop(int code, QString last_error)
  5572. {
  5573. ui->statusbar->RecordingStopped();
  5574. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  5575. ui->recordButton->setChecked(false);
  5576. if (sysTrayRecord)
  5577. sysTrayRecord->setText(ui->recordButton->text());
  5578. blog(LOG_INFO, RECORDING_STOP);
  5579. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5580. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5581. QTStr("Output.RecordFail.Unsupported"));
  5582. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  5583. OBSMessageBox::warning(
  5584. this, QTStr("Output.RecordError.Title"),
  5585. QTStr("Output.RecordError.EncodeErrorMsg"));
  5586. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5587. OBSMessageBox::warning(this,
  5588. QTStr("Output.RecordNoSpace.Title"),
  5589. QTStr("Output.RecordNoSpace.Msg"));
  5590. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5591. const char *errorDescription;
  5592. DStr errorMessage;
  5593. bool use_last_error = true;
  5594. errorDescription = Str("Output.RecordError.Msg");
  5595. if (use_last_error && !last_error.isEmpty())
  5596. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  5597. QT_TO_UTF8(last_error));
  5598. else
  5599. dstr_copy(errorMessage, errorDescription);
  5600. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5601. QT_UTF8(errorMessage));
  5602. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5603. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5604. QSystemTrayIcon::Warning);
  5605. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5606. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5607. QSystemTrayIcon::Warning);
  5608. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5609. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5610. QSystemTrayIcon::Warning);
  5611. } else if (code == OBS_OUTPUT_SUCCESS) {
  5612. if (outputHandler) {
  5613. std::string path = outputHandler->lastRecordingPath;
  5614. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  5615. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  5616. }
  5617. }
  5618. if (api)
  5619. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  5620. if (diskFullTimer->isActive())
  5621. diskFullTimer->stop();
  5622. AutoRemux(outputHandler->lastRecordingPath.c_str());
  5623. OnDeactivate();
  5624. UpdatePause(false);
  5625. }
  5626. void OBSBasic::ShowReplayBufferPauseWarning()
  5627. {
  5628. auto msgBox = []() {
  5629. QMessageBox msgbox(App()->GetMainWindow());
  5630. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  5631. "PauseWarning.Title"));
  5632. msgbox.setText(QTStr("Output.ReplayBuffer."
  5633. "PauseWarning.Text"));
  5634. msgbox.setIcon(QMessageBox::Icon::Information);
  5635. msgbox.addButton(QMessageBox::Ok);
  5636. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5637. msgbox.setCheckBox(cb);
  5638. msgbox.exec();
  5639. if (cb->isChecked()) {
  5640. config_set_bool(App()->GlobalConfig(), "General",
  5641. "WarnedAboutReplayBufferPausing", true);
  5642. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5643. }
  5644. };
  5645. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5646. "WarnedAboutReplayBufferPausing");
  5647. if (!warned) {
  5648. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5649. Q_ARG(VoidFunc, msgBox));
  5650. }
  5651. }
  5652. void OBSBasic::StartReplayBuffer()
  5653. {
  5654. if (!outputHandler || !outputHandler->replayBuffer)
  5655. return;
  5656. if (outputHandler->ReplayBufferActive())
  5657. return;
  5658. if (disableOutputsRef)
  5659. return;
  5660. if (!UIValidation::NoSourcesConfirmation(this)) {
  5661. replayBufferButton->setChecked(false);
  5662. return;
  5663. }
  5664. if (LowDiskSpace()) {
  5665. DiskSpaceMessage();
  5666. replayBufferButton->setChecked(false);
  5667. return;
  5668. }
  5669. if (api)
  5670. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  5671. SaveProject();
  5672. if (!outputHandler->StartReplayBuffer()) {
  5673. replayBufferButton->setChecked(false);
  5674. } else if (os_atomic_load_bool(&recording_paused)) {
  5675. ShowReplayBufferPauseWarning();
  5676. }
  5677. }
  5678. void OBSBasic::ReplayBufferStopping()
  5679. {
  5680. if (!outputHandler || !outputHandler->replayBuffer)
  5681. return;
  5682. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  5683. if (sysTrayReplayBuffer)
  5684. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5685. replayBufferStopping = true;
  5686. if (api)
  5687. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  5688. }
  5689. void OBSBasic::StopReplayBuffer()
  5690. {
  5691. if (!outputHandler || !outputHandler->replayBuffer)
  5692. return;
  5693. SaveProject();
  5694. if (outputHandler->ReplayBufferActive())
  5695. outputHandler->StopReplayBuffer(replayBufferStopping);
  5696. OnDeactivate();
  5697. }
  5698. void OBSBasic::ReplayBufferStart()
  5699. {
  5700. if (!outputHandler || !outputHandler->replayBuffer)
  5701. return;
  5702. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  5703. replayBufferButton->setChecked(true);
  5704. if (sysTrayReplayBuffer)
  5705. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5706. replayBufferStopping = false;
  5707. if (api)
  5708. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  5709. OnActivate();
  5710. UpdateReplayBuffer();
  5711. blog(LOG_INFO, REPLAY_BUFFER_START);
  5712. }
  5713. void OBSBasic::ReplayBufferSave()
  5714. {
  5715. if (!outputHandler || !outputHandler->replayBuffer)
  5716. return;
  5717. if (!outputHandler->ReplayBufferActive())
  5718. return;
  5719. calldata_t cd = {0};
  5720. proc_handler_t *ph =
  5721. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5722. proc_handler_call(ph, "save", &cd);
  5723. calldata_free(&cd);
  5724. }
  5725. void OBSBasic::ReplayBufferSaved()
  5726. {
  5727. if (!outputHandler || !outputHandler->replayBuffer)
  5728. return;
  5729. if (!outputHandler->ReplayBufferActive())
  5730. return;
  5731. calldata_t cd = {0};
  5732. proc_handler_t *ph =
  5733. obs_output_get_proc_handler(outputHandler->replayBuffer);
  5734. proc_handler_call(ph, "get_last_replay", &cd);
  5735. QString path = QT_UTF8(calldata_string(&cd, "path"));
  5736. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(path);
  5737. ShowStatusBarMessage(msg);
  5738. calldata_free(&cd);
  5739. if (api)
  5740. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  5741. AutoRemux(path);
  5742. }
  5743. void OBSBasic::ReplayBufferStop(int code)
  5744. {
  5745. if (!outputHandler || !outputHandler->replayBuffer)
  5746. return;
  5747. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  5748. replayBufferButton->setChecked(false);
  5749. if (sysTrayReplayBuffer)
  5750. sysTrayReplayBuffer->setText(replayBufferButton->text());
  5751. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  5752. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  5753. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  5754. QTStr("Output.RecordFail.Unsupported"));
  5755. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  5756. OBSMessageBox::warning(this,
  5757. QTStr("Output.RecordNoSpace.Title"),
  5758. QTStr("Output.RecordNoSpace.Msg"));
  5759. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  5760. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  5761. QTStr("Output.RecordError.Msg"));
  5762. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  5763. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  5764. QSystemTrayIcon::Warning);
  5765. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  5766. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  5767. QSystemTrayIcon::Warning);
  5768. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  5769. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  5770. QSystemTrayIcon::Warning);
  5771. }
  5772. if (api)
  5773. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  5774. OnDeactivate();
  5775. UpdateReplayBuffer(false);
  5776. }
  5777. void OBSBasic::StartVirtualCam()
  5778. {
  5779. if (!outputHandler || !outputHandler->virtualCam)
  5780. return;
  5781. if (outputHandler->VirtualCamActive())
  5782. return;
  5783. if (disableOutputsRef)
  5784. return;
  5785. SaveProject();
  5786. if (!outputHandler->StartVirtualCam()) {
  5787. vcamButton->setChecked(false);
  5788. }
  5789. }
  5790. void OBSBasic::StopVirtualCam()
  5791. {
  5792. if (!outputHandler || !outputHandler->virtualCam)
  5793. return;
  5794. SaveProject();
  5795. if (outputHandler->VirtualCamActive())
  5796. outputHandler->StopVirtualCam();
  5797. OnDeactivate();
  5798. }
  5799. void OBSBasic::OnVirtualCamStart()
  5800. {
  5801. if (!outputHandler || !outputHandler->virtualCam)
  5802. return;
  5803. vcamButton->setText(QTStr("Basic.Main.StopVirtualCam"));
  5804. if (sysTrayVirtualCam)
  5805. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  5806. vcamButton->setChecked(true);
  5807. if (api)
  5808. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  5809. OnActivate();
  5810. blog(LOG_INFO, VIRTUAL_CAM_START);
  5811. }
  5812. void OBSBasic::OnVirtualCamStop(int)
  5813. {
  5814. if (!outputHandler || !outputHandler->virtualCam)
  5815. return;
  5816. vcamButton->setText(QTStr("Basic.Main.StartVirtualCam"));
  5817. if (sysTrayVirtualCam)
  5818. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  5819. vcamButton->setChecked(false);
  5820. if (api)
  5821. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  5822. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  5823. OnDeactivate();
  5824. }
  5825. void OBSBasic::on_streamButton_clicked()
  5826. {
  5827. if (outputHandler->StreamingActive()) {
  5828. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5829. "WarnBeforeStoppingStream");
  5830. #if YOUTUBE_ENABLED
  5831. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  5832. autoStopBroadcast) {
  5833. QMessageBox::StandardButton button = OBSMessageBox::question(
  5834. this, QTStr("ConfirmStop.Title"),
  5835. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5836. QMessageBox::Yes | QMessageBox::No,
  5837. QMessageBox::No);
  5838. if (button == QMessageBox::No) {
  5839. ui->streamButton->setChecked(true);
  5840. return;
  5841. }
  5842. confirm = false;
  5843. }
  5844. #endif
  5845. if (confirm && isVisible()) {
  5846. QMessageBox::StandardButton button =
  5847. OBSMessageBox::question(
  5848. this, QTStr("ConfirmStop.Title"),
  5849. QTStr("ConfirmStop.Text"),
  5850. QMessageBox::Yes | QMessageBox::No,
  5851. QMessageBox::No);
  5852. if (button == QMessageBox::No) {
  5853. ui->streamButton->setChecked(true);
  5854. return;
  5855. }
  5856. }
  5857. StopStreaming();
  5858. } else {
  5859. if (!UIValidation::NoSourcesConfirmation(this)) {
  5860. ui->streamButton->setChecked(false);
  5861. return;
  5862. }
  5863. Auth *auth = GetAuth();
  5864. auto action =
  5865. (auth && auth->external())
  5866. ? StreamSettingsAction::ContinueStream
  5867. : UIValidation::StreamSettingsConfirmation(
  5868. this, service);
  5869. switch (action) {
  5870. case StreamSettingsAction::ContinueStream:
  5871. break;
  5872. case StreamSettingsAction::OpenSettings:
  5873. on_action_Settings_triggered();
  5874. ui->streamButton->setChecked(false);
  5875. return;
  5876. case StreamSettingsAction::Cancel:
  5877. ui->streamButton->setChecked(false);
  5878. return;
  5879. }
  5880. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5881. "WarnBeforeStartingStream");
  5882. bool bwtest = false;
  5883. if (this->auth) {
  5884. obs_data_t *settings =
  5885. obs_service_get_settings(service);
  5886. bwtest = obs_data_get_bool(settings, "bwtest");
  5887. obs_data_release(settings);
  5888. }
  5889. if (bwtest && isVisible()) {
  5890. QMessageBox::StandardButton button =
  5891. OBSMessageBox::question(
  5892. this, QTStr("ConfirmBWTest.Title"),
  5893. QTStr("ConfirmBWTest.Text"));
  5894. if (button == QMessageBox::No) {
  5895. ui->streamButton->setChecked(false);
  5896. return;
  5897. }
  5898. } else if (confirm && isVisible()) {
  5899. QMessageBox::StandardButton button =
  5900. OBSMessageBox::question(
  5901. this, QTStr("ConfirmStart.Title"),
  5902. QTStr("ConfirmStart.Text"),
  5903. QMessageBox::Yes | QMessageBox::No,
  5904. QMessageBox::No);
  5905. if (button == QMessageBox::No) {
  5906. ui->streamButton->setChecked(false);
  5907. return;
  5908. }
  5909. }
  5910. StartStreaming();
  5911. }
  5912. }
  5913. void OBSBasic::on_recordButton_clicked()
  5914. {
  5915. if (outputHandler->RecordingActive()) {
  5916. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5917. "WarnBeforeStoppingRecord");
  5918. if (confirm && isVisible()) {
  5919. QMessageBox::StandardButton button =
  5920. OBSMessageBox::question(
  5921. this, QTStr("ConfirmStopRecord.Title"),
  5922. QTStr("ConfirmStopRecord.Text"),
  5923. QMessageBox::Yes | QMessageBox::No,
  5924. QMessageBox::No);
  5925. if (button == QMessageBox::No) {
  5926. ui->recordButton->setChecked(true);
  5927. return;
  5928. }
  5929. }
  5930. StopRecording();
  5931. } else {
  5932. if (!UIValidation::NoSourcesConfirmation(this)) {
  5933. ui->recordButton->setChecked(false);
  5934. return;
  5935. }
  5936. StartRecording();
  5937. }
  5938. }
  5939. void OBSBasic::VCamButtonClicked()
  5940. {
  5941. if (outputHandler->VirtualCamActive()) {
  5942. StopVirtualCam();
  5943. } else {
  5944. if (!UIValidation::NoSourcesConfirmation(this)) {
  5945. vcamButton->setChecked(false);
  5946. return;
  5947. }
  5948. StartVirtualCam();
  5949. }
  5950. }
  5951. void OBSBasic::on_settingsButton_clicked()
  5952. {
  5953. on_action_Settings_triggered();
  5954. }
  5955. void OBSBasic::on_actionHelpPortal_triggered()
  5956. {
  5957. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  5958. QDesktopServices::openUrl(url);
  5959. }
  5960. void OBSBasic::on_actionWebsite_triggered()
  5961. {
  5962. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  5963. QDesktopServices::openUrl(url);
  5964. }
  5965. void OBSBasic::on_actionDiscord_triggered()
  5966. {
  5967. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  5968. QDesktopServices::openUrl(url);
  5969. }
  5970. void OBSBasic::on_actionShowSettingsFolder_triggered()
  5971. {
  5972. char path[512];
  5973. int ret = GetConfigPath(path, 512, "obs-studio");
  5974. if (ret <= 0)
  5975. return;
  5976. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5977. }
  5978. void OBSBasic::on_actionShowProfileFolder_triggered()
  5979. {
  5980. char path[512];
  5981. int ret = GetProfilePath(path, 512, "");
  5982. if (ret <= 0)
  5983. return;
  5984. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  5985. }
  5986. int OBSBasic::GetTopSelectedSourceItem()
  5987. {
  5988. QModelIndexList selectedItems =
  5989. ui->sources->selectionModel()->selectedIndexes();
  5990. return selectedItems.count() ? selectedItems[0].row() : -1;
  5991. }
  5992. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  5993. {
  5994. return ui->sources->selectionModel()->selectedIndexes();
  5995. }
  5996. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  5997. {
  5998. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  5999. UNUSED_PARAMETER(pos);
  6000. }
  6001. void OBSBasic::ProgramViewContextMenuRequested(const QPoint &)
  6002. {
  6003. QMenu popup(this);
  6004. QPointer<QMenu> studioProgramProjector;
  6005. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6006. AddProjectorMenuMonitors(studioProgramProjector, this,
  6007. SLOT(OpenStudioProgramProjector()));
  6008. popup.addMenu(studioProgramProjector);
  6009. QAction *studioProgramWindow =
  6010. popup.addAction(QTStr("StudioProgramWindow"), this,
  6011. SLOT(OpenStudioProgramWindow()));
  6012. popup.addAction(studioProgramWindow);
  6013. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6014. SLOT(ScreenshotProgram()));
  6015. popup.exec(QCursor::pos());
  6016. }
  6017. void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
  6018. {
  6019. QMenu popup(this);
  6020. delete previewProjectorMain;
  6021. QAction *action =
  6022. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6023. this, SLOT(TogglePreview()));
  6024. action->setCheckable(true);
  6025. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6026. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6027. AddProjectorMenuMonitors(previewProjectorMain, this,
  6028. SLOT(OpenPreviewProjector()));
  6029. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6030. SLOT(OpenPreviewWindow()));
  6031. popup.addMenu(previewProjectorMain);
  6032. popup.addAction(previewWindow);
  6033. popup.exec(QCursor::pos());
  6034. UNUSED_PARAMETER(pos);
  6035. }
  6036. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6037. {
  6038. #ifndef _WIN32
  6039. /* Make sure all dialogs are safely and successfully closed before
  6040. * switching the always on top mode due to the fact that windows all
  6041. * have to be recreated, so queue the actual toggle to happen after
  6042. * all events related to closing the dialogs have finished */
  6043. CloseDialogs();
  6044. #endif
  6045. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6046. Qt::QueuedConnection);
  6047. }
  6048. void OBSBasic::ToggleAlwaysOnTop()
  6049. {
  6050. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6051. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6052. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6053. show();
  6054. }
  6055. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6056. {
  6057. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6058. if (strcmp(val, "10") == 0) {
  6059. num = 10;
  6060. den = 1;
  6061. } else if (strcmp(val, "20") == 0) {
  6062. num = 20;
  6063. den = 1;
  6064. } else if (strcmp(val, "24 NTSC") == 0) {
  6065. num = 24000;
  6066. den = 1001;
  6067. } else if (strcmp(val, "25 PAL") == 0) {
  6068. num = 25;
  6069. den = 1;
  6070. } else if (strcmp(val, "29.97") == 0) {
  6071. num = 30000;
  6072. den = 1001;
  6073. } else if (strcmp(val, "48") == 0) {
  6074. num = 48;
  6075. den = 1;
  6076. } else if (strcmp(val, "50 PAL") == 0) {
  6077. num = 50;
  6078. den = 1;
  6079. } else if (strcmp(val, "59.94") == 0) {
  6080. num = 60000;
  6081. den = 1001;
  6082. } else if (strcmp(val, "60") == 0) {
  6083. num = 60;
  6084. den = 1;
  6085. } else {
  6086. num = 30;
  6087. den = 1;
  6088. }
  6089. }
  6090. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6091. {
  6092. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6093. den = 1;
  6094. }
  6095. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6096. {
  6097. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6098. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6099. }
  6100. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6101. {
  6102. num = 1000000000;
  6103. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6104. }
  6105. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6106. {
  6107. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6108. if (type == 1) //"Integer"
  6109. GetFPSInteger(num, den);
  6110. else if (type == 2) //"Fraction"
  6111. GetFPSFraction(num, den);
  6112. else if (false) //"Nanoseconds", currently not implemented
  6113. GetFPSNanoseconds(num, den);
  6114. else
  6115. GetFPSCommon(num, den);
  6116. }
  6117. config_t *OBSBasic::Config() const
  6118. {
  6119. return basicConfig;
  6120. }
  6121. void OBSBasic::on_actionEditTransform_triggered()
  6122. {
  6123. if (transformWindow)
  6124. transformWindow->close();
  6125. if (!GetCurrentSceneItem())
  6126. return;
  6127. transformWindow = new OBSBasicTransform(this);
  6128. transformWindow->show();
  6129. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  6130. }
  6131. static obs_transform_info copiedTransformInfo;
  6132. static obs_sceneitem_crop copiedCropInfo;
  6133. void OBSBasic::on_actionCopyTransform_triggered()
  6134. {
  6135. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  6136. if (!obs_sceneitem_selected(item))
  6137. return true;
  6138. obs_sceneitem_defer_update_begin(item);
  6139. obs_sceneitem_get_info(item, &copiedTransformInfo);
  6140. obs_sceneitem_get_crop(item, &copiedCropInfo);
  6141. obs_sceneitem_defer_update_end(item);
  6142. UNUSED_PARAMETER(scene);
  6143. UNUSED_PARAMETER(param);
  6144. return true;
  6145. };
  6146. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  6147. ui->actionPasteTransform->setEnabled(true);
  6148. }
  6149. void undo_redo(const std::string &data)
  6150. {
  6151. obs_data_t *dat = obs_data_create_from_json(data.c_str());
  6152. obs_source_t *source =
  6153. obs_get_source_by_name(obs_data_get_string(dat, "scene_name"));
  6154. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  6155. ->SetCurrentScene(source, true);
  6156. obs_source_release(source);
  6157. obs_data_release(dat);
  6158. obs_scene_load_transform_states(data.c_str());
  6159. }
  6160. void OBSBasic::on_actionPasteTransform_triggered()
  6161. {
  6162. obs_data_t *wrapper =
  6163. obs_scene_save_transform_states(GetCurrentScene(), false);
  6164. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
  6165. if (!obs_sceneitem_selected(item))
  6166. return true;
  6167. obs_sceneitem_defer_update_begin(item);
  6168. obs_sceneitem_set_info(item, &copiedTransformInfo);
  6169. obs_sceneitem_set_crop(item, &copiedCropInfo);
  6170. obs_sceneitem_defer_update_end(item);
  6171. UNUSED_PARAMETER(scene);
  6172. UNUSED_PARAMETER(param);
  6173. return true;
  6174. };
  6175. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  6176. obs_data_t *rwrapper =
  6177. obs_scene_save_transform_states(GetCurrentScene(), false);
  6178. std::string undo_data(obs_data_get_json(wrapper));
  6179. std::string redo_data(obs_data_get_json(rwrapper));
  6180. undo_s.add_action(
  6181. QTStr("Undo.Transform.Paste")
  6182. .arg(obs_source_get_name(GetCurrentSceneSource())),
  6183. undo_redo, undo_redo, undo_data, redo_data);
  6184. obs_data_release(wrapper);
  6185. obs_data_release(rwrapper);
  6186. }
  6187. static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  6188. {
  6189. if (obs_sceneitem_is_group(item))
  6190. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  6191. if (!obs_sceneitem_selected(item))
  6192. return true;
  6193. if (obs_sceneitem_locked(item))
  6194. return true;
  6195. obs_sceneitem_defer_update_begin(item);
  6196. obs_transform_info info;
  6197. vec2_set(&info.pos, 0.0f, 0.0f);
  6198. vec2_set(&info.scale, 1.0f, 1.0f);
  6199. info.rot = 0.0f;
  6200. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  6201. info.bounds_type = OBS_BOUNDS_NONE;
  6202. info.bounds_alignment = OBS_ALIGN_CENTER;
  6203. vec2_set(&info.bounds, 0.0f, 0.0f);
  6204. obs_sceneitem_set_info(item, &info);
  6205. obs_sceneitem_crop crop = {};
  6206. obs_sceneitem_set_crop(item, &crop);
  6207. obs_sceneitem_defer_update_end(item);
  6208. UNUSED_PARAMETER(scene);
  6209. UNUSED_PARAMETER(param);
  6210. return true;
  6211. }
  6212. void OBSBasic::on_actionResetTransform_triggered()
  6213. {
  6214. obs_scene_t *scene = GetCurrentScene();
  6215. obs_data_t *wrapper = obs_scene_save_transform_states(scene, false);
  6216. obs_scene_enum_items(scene, reset_tr, nullptr);
  6217. obs_data_t *rwrapper = obs_scene_save_transform_states(scene, false);
  6218. std::string undo_data(obs_data_get_json(wrapper));
  6219. std::string redo_data(obs_data_get_json(rwrapper));
  6220. undo_s.add_action(
  6221. QTStr("Undo.Transform.Reset")
  6222. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  6223. undo_redo, undo_redo, undo_data, redo_data);
  6224. obs_data_release(wrapper);
  6225. obs_data_release(rwrapper);
  6226. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  6227. }
  6228. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  6229. {
  6230. matrix4 boxTransform;
  6231. obs_sceneitem_get_box_transform(item, &boxTransform);
  6232. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  6233. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  6234. auto GetMinPos = [&](float x, float y) {
  6235. vec3 pos;
  6236. vec3_set(&pos, x, y, 0.0f);
  6237. vec3_transform(&pos, &pos, &boxTransform);
  6238. vec3_min(&tl, &tl, &pos);
  6239. vec3_max(&br, &br, &pos);
  6240. };
  6241. GetMinPos(0.0f, 0.0f);
  6242. GetMinPos(1.0f, 0.0f);
  6243. GetMinPos(0.0f, 1.0f);
  6244. GetMinPos(1.0f, 1.0f);
  6245. }
  6246. static vec3 GetItemTL(obs_sceneitem_t *item)
  6247. {
  6248. vec3 tl, br;
  6249. GetItemBox(item, tl, br);
  6250. return tl;
  6251. }
  6252. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  6253. {
  6254. vec3 newTL;
  6255. vec2 pos;
  6256. obs_sceneitem_get_pos(item, &pos);
  6257. newTL = GetItemTL(item);
  6258. pos.x += tl.x - newTL.x;
  6259. pos.y += tl.y - newTL.y;
  6260. obs_sceneitem_set_pos(item, &pos);
  6261. }
  6262. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  6263. void *param)
  6264. {
  6265. if (obs_sceneitem_is_group(item))
  6266. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  6267. param);
  6268. if (!obs_sceneitem_selected(item))
  6269. return true;
  6270. if (obs_sceneitem_locked(item))
  6271. return true;
  6272. float rot = *reinterpret_cast<float *>(param);
  6273. vec3 tl = GetItemTL(item);
  6274. rot += obs_sceneitem_get_rot(item);
  6275. if (rot >= 360.0f)
  6276. rot -= 360.0f;
  6277. else if (rot <= -360.0f)
  6278. rot += 360.0f;
  6279. obs_sceneitem_set_rot(item, rot);
  6280. obs_sceneitem_force_update_transform(item);
  6281. SetItemTL(item, tl);
  6282. UNUSED_PARAMETER(scene);
  6283. return true;
  6284. };
  6285. void OBSBasic::on_actionRotate90CW_triggered()
  6286. {
  6287. float f90CW = 90.0f;
  6288. obs_data_t *wrapper =
  6289. obs_scene_save_transform_states(GetCurrentScene(), false);
  6290. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  6291. obs_data_t *rwrapper =
  6292. obs_scene_save_transform_states(GetCurrentScene(), false);
  6293. std::string undo_data(obs_data_get_json(wrapper));
  6294. std::string redo_data(obs_data_get_json(rwrapper));
  6295. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6296. .arg(obs_source_get_name(obs_scene_get_source(
  6297. GetCurrentScene()))),
  6298. undo_redo, undo_redo, undo_data, redo_data);
  6299. obs_data_release(wrapper);
  6300. obs_data_release(rwrapper);
  6301. }
  6302. void OBSBasic::on_actionRotate90CCW_triggered()
  6303. {
  6304. float f90CCW = -90.0f;
  6305. obs_data_t *wrapper =
  6306. obs_scene_save_transform_states(GetCurrentScene(), false);
  6307. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  6308. obs_data_t *rwrapper =
  6309. obs_scene_save_transform_states(GetCurrentScene(), false);
  6310. std::string undo_data(obs_data_get_json(wrapper));
  6311. std::string redo_data(obs_data_get_json(rwrapper));
  6312. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6313. .arg(obs_source_get_name(obs_scene_get_source(
  6314. GetCurrentScene()))),
  6315. undo_redo, undo_redo, undo_data, redo_data);
  6316. obs_data_release(wrapper);
  6317. obs_data_release(rwrapper);
  6318. }
  6319. void OBSBasic::on_actionRotate180_triggered()
  6320. {
  6321. float f180 = 180.0f;
  6322. obs_data_t *wrapper =
  6323. obs_scene_save_transform_states(GetCurrentScene(), false);
  6324. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  6325. obs_data_t *rwrapper =
  6326. obs_scene_save_transform_states(GetCurrentScene(), false);
  6327. std::string undo_data(obs_data_get_json(wrapper));
  6328. std::string redo_data(obs_data_get_json(rwrapper));
  6329. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  6330. .arg(obs_source_get_name(obs_scene_get_source(
  6331. GetCurrentScene()))),
  6332. undo_redo, undo_redo, undo_data, redo_data);
  6333. obs_data_release(wrapper);
  6334. obs_data_release(rwrapper);
  6335. }
  6336. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  6337. void *param)
  6338. {
  6339. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  6340. if (obs_sceneitem_is_group(item))
  6341. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  6342. param);
  6343. if (!obs_sceneitem_selected(item))
  6344. return true;
  6345. if (obs_sceneitem_locked(item))
  6346. return true;
  6347. vec3 tl = GetItemTL(item);
  6348. vec2 scale;
  6349. obs_sceneitem_get_scale(item, &scale);
  6350. vec2_mul(&scale, &scale, &mul);
  6351. obs_sceneitem_set_scale(item, &scale);
  6352. obs_sceneitem_force_update_transform(item);
  6353. SetItemTL(item, tl);
  6354. UNUSED_PARAMETER(scene);
  6355. return true;
  6356. }
  6357. void OBSBasic::on_actionFlipHorizontal_triggered()
  6358. {
  6359. vec2 scale;
  6360. vec2_set(&scale, -1.0f, 1.0f);
  6361. obs_data_t *wrapper =
  6362. obs_scene_save_transform_states(GetCurrentScene(), false);
  6363. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6364. &scale);
  6365. obs_data_t *rwrapper =
  6366. obs_scene_save_transform_states(GetCurrentScene(), false);
  6367. std::string undo_data(obs_data_get_json(wrapper));
  6368. std::string redo_data(obs_data_get_json(rwrapper));
  6369. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  6370. .arg(obs_source_get_name(obs_scene_get_source(
  6371. GetCurrentScene()))),
  6372. undo_redo, undo_redo, undo_data, redo_data);
  6373. obs_data_release(wrapper);
  6374. obs_data_release(rwrapper);
  6375. }
  6376. void OBSBasic::on_actionFlipVertical_triggered()
  6377. {
  6378. vec2 scale;
  6379. vec2_set(&scale, 1.0f, -1.0f);
  6380. obs_data_t *wrapper =
  6381. obs_scene_save_transform_states(GetCurrentScene(), false);
  6382. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  6383. &scale);
  6384. obs_data_t *rwrapper =
  6385. obs_scene_save_transform_states(GetCurrentScene(), false);
  6386. std::string undo_data(obs_data_get_json(wrapper));
  6387. std::string redo_data(obs_data_get_json(rwrapper));
  6388. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  6389. .arg(obs_source_get_name(obs_scene_get_source(
  6390. GetCurrentScene()))),
  6391. undo_redo, undo_redo, undo_data, redo_data);
  6392. obs_data_release(wrapper);
  6393. obs_data_release(rwrapper);
  6394. }
  6395. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  6396. void *param)
  6397. {
  6398. obs_bounds_type boundsType =
  6399. *reinterpret_cast<obs_bounds_type *>(param);
  6400. if (obs_sceneitem_is_group(item))
  6401. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  6402. param);
  6403. if (!obs_sceneitem_selected(item))
  6404. return true;
  6405. if (obs_sceneitem_locked(item))
  6406. return true;
  6407. obs_video_info ovi;
  6408. obs_get_video_info(&ovi);
  6409. obs_transform_info itemInfo;
  6410. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  6411. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  6412. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  6413. itemInfo.rot = 0.0f;
  6414. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  6415. float(ovi.base_height));
  6416. itemInfo.bounds_type = boundsType;
  6417. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  6418. obs_sceneitem_set_info(item, &itemInfo);
  6419. UNUSED_PARAMETER(scene);
  6420. return true;
  6421. }
  6422. void OBSBasic::on_actionFitToScreen_triggered()
  6423. {
  6424. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  6425. obs_data_t *wrapper =
  6426. obs_scene_save_transform_states(GetCurrentScene(), false);
  6427. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6428. &boundsType);
  6429. obs_data_t *rwrapper =
  6430. obs_scene_save_transform_states(GetCurrentScene(), false);
  6431. std::string undo_data(obs_data_get_json(wrapper));
  6432. std::string redo_data(obs_data_get_json(rwrapper));
  6433. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  6434. .arg(obs_source_get_name(obs_scene_get_source(
  6435. GetCurrentScene()))),
  6436. undo_redo, undo_redo, undo_data, redo_data);
  6437. obs_data_release(wrapper);
  6438. obs_data_release(rwrapper);
  6439. }
  6440. void OBSBasic::on_actionStretchToScreen_triggered()
  6441. {
  6442. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  6443. obs_data_t *wrapper =
  6444. obs_scene_save_transform_states(GetCurrentScene(), false);
  6445. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  6446. &boundsType);
  6447. obs_data_t *rwrapper =
  6448. obs_scene_save_transform_states(GetCurrentScene(), false);
  6449. std::string undo_data(obs_data_get_json(wrapper));
  6450. std::string redo_data(obs_data_get_json(rwrapper));
  6451. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  6452. .arg(obs_source_get_name(obs_scene_get_source(
  6453. GetCurrentScene()))),
  6454. undo_redo, undo_redo, undo_data, redo_data);
  6455. obs_data_release(wrapper);
  6456. obs_data_release(rwrapper);
  6457. }
  6458. enum class CenterType {
  6459. Scene,
  6460. Vertical,
  6461. Horizontal,
  6462. };
  6463. static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6464. {
  6465. CenterType centerType = *reinterpret_cast<CenterType *>(param);
  6466. vec3 tl, br, itemCenter, screenCenter, offset;
  6467. obs_video_info ovi;
  6468. obs_transform_info oti;
  6469. if (obs_sceneitem_is_group(item))
  6470. obs_sceneitem_group_enum_items(item, center_to_scene,
  6471. &centerType);
  6472. if (!obs_sceneitem_selected(item))
  6473. return true;
  6474. if (obs_sceneitem_locked(item))
  6475. return true;
  6476. obs_get_video_info(&ovi);
  6477. obs_sceneitem_get_info(item, &oti);
  6478. if (centerType == CenterType::Scene)
  6479. vec3_set(&screenCenter, float(ovi.base_width),
  6480. float(ovi.base_height), 0.0f);
  6481. else if (centerType == CenterType::Vertical)
  6482. vec3_set(&screenCenter, float(oti.bounds.x),
  6483. float(ovi.base_height), 0.0f);
  6484. else if (centerType == CenterType::Horizontal)
  6485. vec3_set(&screenCenter, float(ovi.base_width),
  6486. float(oti.bounds.y), 0.0f);
  6487. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  6488. GetItemBox(item, tl, br);
  6489. vec3_sub(&itemCenter, &br, &tl);
  6490. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  6491. vec3_add(&itemCenter, &itemCenter, &tl);
  6492. vec3_sub(&offset, &screenCenter, &itemCenter);
  6493. vec3_add(&tl, &tl, &offset);
  6494. if (centerType == CenterType::Vertical)
  6495. tl.x = oti.pos.x;
  6496. else if (centerType == CenterType::Horizontal)
  6497. tl.y = oti.pos.y;
  6498. SetItemTL(item, tl);
  6499. return true;
  6500. };
  6501. void OBSBasic::on_actionCenterToScreen_triggered()
  6502. {
  6503. CenterType centerType = CenterType::Scene;
  6504. obs_data_t *wrapper =
  6505. obs_scene_save_transform_states(GetCurrentScene(), false);
  6506. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6507. obs_data_t *rwrapper =
  6508. obs_scene_save_transform_states(GetCurrentScene(), false);
  6509. std::string undo_data(obs_data_get_json(wrapper));
  6510. std::string redo_data(obs_data_get_json(rwrapper));
  6511. undo_s.add_action(QTStr("Undo.Transform.Center")
  6512. .arg(obs_source_get_name(obs_scene_get_source(
  6513. GetCurrentScene()))),
  6514. undo_redo, undo_redo, undo_data, redo_data);
  6515. obs_data_release(wrapper);
  6516. obs_data_release(rwrapper);
  6517. }
  6518. void OBSBasic::on_actionVerticalCenter_triggered()
  6519. {
  6520. CenterType centerType = CenterType::Vertical;
  6521. obs_data_t *wrapper =
  6522. obs_scene_save_transform_states(GetCurrentScene(), false);
  6523. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6524. obs_data_t *rwrapper =
  6525. obs_scene_save_transform_states(GetCurrentScene(), false);
  6526. std::string undo_data(obs_data_get_json(wrapper));
  6527. std::string redo_data(obs_data_get_json(rwrapper));
  6528. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  6529. .arg(obs_source_get_name(obs_scene_get_source(
  6530. GetCurrentScene()))),
  6531. undo_redo, undo_redo, undo_data, redo_data);
  6532. obs_data_release(wrapper);
  6533. obs_data_release(rwrapper);
  6534. }
  6535. void OBSBasic::on_actionHorizontalCenter_triggered()
  6536. {
  6537. CenterType centerType = CenterType::Horizontal;
  6538. obs_data_t *wrapper =
  6539. obs_scene_save_transform_states(GetCurrentScene(), false);
  6540. obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
  6541. obs_data_t *rwrapper =
  6542. obs_scene_save_transform_states(GetCurrentScene(), false);
  6543. std::string undo_data(obs_data_get_json(wrapper));
  6544. std::string redo_data(obs_data_get_json(rwrapper));
  6545. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  6546. .arg(obs_source_get_name(obs_scene_get_source(
  6547. GetCurrentScene()))),
  6548. undo_redo, undo_redo, undo_data, redo_data);
  6549. obs_data_release(wrapper);
  6550. obs_data_release(rwrapper);
  6551. }
  6552. void OBSBasic::EnablePreviewDisplay(bool enable)
  6553. {
  6554. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  6555. ui->preview->setVisible(enable);
  6556. ui->previewDisabledWidget->setVisible(!enable);
  6557. }
  6558. void OBSBasic::TogglePreview()
  6559. {
  6560. previewEnabled = !previewEnabled;
  6561. EnablePreviewDisplay(previewEnabled);
  6562. }
  6563. void OBSBasic::EnablePreview()
  6564. {
  6565. if (previewProgramMode)
  6566. return;
  6567. previewEnabled = true;
  6568. EnablePreviewDisplay(true);
  6569. }
  6570. void OBSBasic::DisablePreview()
  6571. {
  6572. if (previewProgramMode)
  6573. return;
  6574. previewEnabled = false;
  6575. EnablePreviewDisplay(false);
  6576. }
  6577. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  6578. {
  6579. if (obs_sceneitem_locked(item))
  6580. return true;
  6581. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  6582. struct vec2 pos;
  6583. if (!obs_sceneitem_selected(item)) {
  6584. if (obs_sceneitem_is_group(item)) {
  6585. struct vec3 offset3;
  6586. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  6587. struct matrix4 matrix;
  6588. obs_sceneitem_get_draw_transform(item, &matrix);
  6589. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  6590. matrix4_inv(&matrix, &matrix);
  6591. vec3_transform(&offset3, &offset3, &matrix);
  6592. struct vec2 new_offset;
  6593. vec2_set(&new_offset, offset3.x, offset3.y);
  6594. obs_sceneitem_group_enum_items(item, nudge_callback,
  6595. &new_offset);
  6596. }
  6597. return true;
  6598. }
  6599. obs_sceneitem_get_pos(item, &pos);
  6600. vec2_add(&pos, &pos, &offset);
  6601. obs_sceneitem_set_pos(item, &pos);
  6602. return true;
  6603. }
  6604. void OBSBasic::Nudge(int dist, MoveDir dir)
  6605. {
  6606. if (ui->preview->Locked())
  6607. return;
  6608. struct vec2 offset;
  6609. vec2_set(&offset, 0.0f, 0.0f);
  6610. switch (dir) {
  6611. case MoveDir::Up:
  6612. offset.y = (float)-dist;
  6613. break;
  6614. case MoveDir::Down:
  6615. offset.y = (float)dist;
  6616. break;
  6617. case MoveDir::Left:
  6618. offset.x = (float)-dist;
  6619. break;
  6620. case MoveDir::Right:
  6621. offset.x = (float)dist;
  6622. break;
  6623. }
  6624. if (!recent_nudge) {
  6625. recent_nudge = true;
  6626. obs_data_t *wrapper = obs_scene_save_transform_states(
  6627. GetCurrentScene(), true);
  6628. std::string undo_data(obs_data_get_json(wrapper));
  6629. nudge_timer = new QTimer;
  6630. QObject::connect(
  6631. nudge_timer, &QTimer::timeout,
  6632. [this, &recent_nudge = recent_nudge, undo_data]() {
  6633. obs_data_t *rwrapper =
  6634. obs_scene_save_transform_states(
  6635. GetCurrentScene(), true);
  6636. std::string redo_data(
  6637. obs_data_get_json(rwrapper));
  6638. undo_s.add_action(
  6639. QTStr("Undo.Transform")
  6640. .arg(obs_source_get_name(
  6641. GetCurrentSceneSource())),
  6642. undo_redo, undo_redo, undo_data,
  6643. redo_data);
  6644. recent_nudge = false;
  6645. obs_data_release(rwrapper);
  6646. });
  6647. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  6648. &QTimer::deleteLater);
  6649. nudge_timer->setSingleShot(true);
  6650. obs_data_release(wrapper);
  6651. }
  6652. if (nudge_timer) {
  6653. nudge_timer->stop();
  6654. nudge_timer->start(1000);
  6655. } else {
  6656. blog(LOG_ERROR, "No nudge timer!");
  6657. }
  6658. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  6659. }
  6660. void OBSBasic::NudgeUp()
  6661. {
  6662. Nudge(1, MoveDir::Up);
  6663. }
  6664. void OBSBasic::NudgeDown()
  6665. {
  6666. Nudge(1, MoveDir::Down);
  6667. }
  6668. void OBSBasic::NudgeLeft()
  6669. {
  6670. Nudge(1, MoveDir::Left);
  6671. }
  6672. void OBSBasic::NudgeRight()
  6673. {
  6674. Nudge(1, MoveDir::Right);
  6675. }
  6676. void OBSBasic::DeleteProjector(OBSProjector *projector)
  6677. {
  6678. for (size_t i = 0; i < projectors.size(); i++) {
  6679. if (projectors[i] == projector) {
  6680. projectors[i]->deleteLater();
  6681. projectors.erase(projectors.begin() + i);
  6682. break;
  6683. }
  6684. }
  6685. }
  6686. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  6687. ProjectorType type)
  6688. {
  6689. /* seriously? 10 monitors? */
  6690. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  6691. return nullptr;
  6692. OBSProjector *projector =
  6693. new OBSProjector(nullptr, source, monitor, type);
  6694. projectors.emplace_back(projector);
  6695. return projector;
  6696. }
  6697. void OBSBasic::OpenStudioProgramProjector()
  6698. {
  6699. int monitor = sender()->property("monitor").toInt();
  6700. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  6701. }
  6702. void OBSBasic::OpenPreviewProjector()
  6703. {
  6704. int monitor = sender()->property("monitor").toInt();
  6705. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  6706. }
  6707. void OBSBasic::OpenSourceProjector()
  6708. {
  6709. int monitor = sender()->property("monitor").toInt();
  6710. OBSSceneItem item = GetCurrentSceneItem();
  6711. if (!item)
  6712. return;
  6713. OpenProjector(obs_sceneitem_get_source(item), monitor,
  6714. ProjectorType::Source);
  6715. }
  6716. void OBSBasic::OpenMultiviewProjector()
  6717. {
  6718. int monitor = sender()->property("monitor").toInt();
  6719. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  6720. }
  6721. void OBSBasic::OpenSceneProjector()
  6722. {
  6723. int monitor = sender()->property("monitor").toInt();
  6724. OBSScene scene = GetCurrentScene();
  6725. if (!scene)
  6726. return;
  6727. OpenProjector(obs_scene_get_source(scene), monitor,
  6728. ProjectorType::Scene);
  6729. }
  6730. void OBSBasic::OpenStudioProgramWindow()
  6731. {
  6732. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  6733. }
  6734. void OBSBasic::OpenPreviewWindow()
  6735. {
  6736. OpenProjector(nullptr, -1, ProjectorType::Preview);
  6737. }
  6738. void OBSBasic::OpenSourceWindow()
  6739. {
  6740. OBSSceneItem item = GetCurrentSceneItem();
  6741. if (!item)
  6742. return;
  6743. OBSSource source = obs_sceneitem_get_source(item);
  6744. OpenProjector(obs_sceneitem_get_source(item), -1,
  6745. ProjectorType::Source);
  6746. }
  6747. void OBSBasic::OpenMultiviewWindow()
  6748. {
  6749. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  6750. }
  6751. void OBSBasic::OpenSceneWindow()
  6752. {
  6753. OBSScene scene = GetCurrentScene();
  6754. if (!scene)
  6755. return;
  6756. OBSSource source = obs_scene_get_source(scene);
  6757. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  6758. }
  6759. void OBSBasic::OpenSavedProjectors()
  6760. {
  6761. for (SavedProjectorInfo *info : savedProjectorsArray) {
  6762. OpenSavedProjector(info);
  6763. }
  6764. }
  6765. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  6766. {
  6767. if (info) {
  6768. OBSProjector *projector = nullptr;
  6769. switch (info->type) {
  6770. case ProjectorType::Source:
  6771. case ProjectorType::Scene: {
  6772. OBSSource source =
  6773. obs_get_source_by_name(info->name.c_str());
  6774. if (!source)
  6775. return;
  6776. projector = OpenProjector(source, info->monitor,
  6777. info->type);
  6778. obs_source_release(source);
  6779. break;
  6780. }
  6781. default: {
  6782. projector = OpenProjector(nullptr, info->monitor,
  6783. info->type);
  6784. break;
  6785. }
  6786. }
  6787. if (projector && !info->geometry.empty() && info->monitor < 0) {
  6788. QByteArray byteArray = QByteArray::fromBase64(
  6789. QByteArray(info->geometry.c_str()));
  6790. projector->restoreGeometry(byteArray);
  6791. if (!WindowPositionValid(projector->normalGeometry())) {
  6792. QRect rect = QGuiApplication::primaryScreen()
  6793. ->geometry();
  6794. projector->setGeometry(QStyle::alignedRect(
  6795. Qt::LeftToRight, Qt::AlignCenter,
  6796. size(), rect));
  6797. }
  6798. if (info->alwaysOnTopOverridden)
  6799. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  6800. true);
  6801. }
  6802. }
  6803. }
  6804. void OBSBasic::on_actionFullscreenInterface_triggered()
  6805. {
  6806. if (!isFullScreen())
  6807. showFullScreen();
  6808. else
  6809. showNormal();
  6810. }
  6811. void OBSBasic::UpdateTitleBar()
  6812. {
  6813. stringstream name;
  6814. const char *profile =
  6815. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  6816. const char *sceneCollection = config_get_string(
  6817. App()->GlobalConfig(), "Basic", "SceneCollection");
  6818. name << "OBS ";
  6819. if (previewProgramMode)
  6820. name << "Studio ";
  6821. name << App()->GetVersionString();
  6822. if (App()->IsPortableMode())
  6823. name << " - Portable Mode";
  6824. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  6825. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  6826. setWindowTitle(QT_UTF8(name.str().c_str()));
  6827. }
  6828. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  6829. {
  6830. char profiles_path[512];
  6831. const char *profile =
  6832. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  6833. int ret;
  6834. if (!profile)
  6835. return -1;
  6836. if (!path)
  6837. return -1;
  6838. if (!file)
  6839. file = "";
  6840. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  6841. if (ret <= 0)
  6842. return ret;
  6843. if (!*file)
  6844. return snprintf(path, size, "%s/%s", profiles_path, profile);
  6845. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  6846. }
  6847. void OBSBasic::on_resetUI_triggered()
  6848. {
  6849. /* prune deleted extra docks */
  6850. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6851. if (!extraDocks[i]) {
  6852. extraDocks.removeAt(i);
  6853. }
  6854. }
  6855. if (extraDocks.size()) {
  6856. QMessageBox::StandardButton button = QMessageBox::question(
  6857. this, QTStr("ResetUIWarning.Title"),
  6858. QTStr("ResetUIWarning.Text"));
  6859. if (button == QMessageBox::No)
  6860. return;
  6861. }
  6862. /* undock/hide/center extra docks */
  6863. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6864. if (extraDocks[i]) {
  6865. extraDocks[i]->setVisible(true);
  6866. extraDocks[i]->setFloating(true);
  6867. extraDocks[i]->move(frameGeometry().topLeft() +
  6868. rect().center() -
  6869. extraDocks[i]->rect().center());
  6870. extraDocks[i]->setVisible(false);
  6871. }
  6872. }
  6873. restoreState(startingDockLayout);
  6874. int cx = width();
  6875. int cy = height();
  6876. int cx22_5 = cx * 225 / 1000;
  6877. int cx5 = cx * 5 / 100;
  6878. cy = cy * 225 / 1000;
  6879. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  6880. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  6881. ui->mixerDock, ui->transitionsDock,
  6882. ui->controlsDock};
  6883. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
  6884. ui->scenesDock->setVisible(true);
  6885. ui->sourcesDock->setVisible(true);
  6886. ui->mixerDock->setVisible(true);
  6887. ui->transitionsDock->setVisible(true);
  6888. ui->controlsDock->setVisible(true);
  6889. statsDock->setVisible(false);
  6890. statsDock->setFloating(true);
  6891. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  6892. resizeDocks(docks, sizes, Qt::Horizontal);
  6893. activateWindow();
  6894. }
  6895. void OBSBasic::on_lockUI_toggled(bool lock)
  6896. {
  6897. QDockWidget::DockWidgetFeatures features =
  6898. lock ? QDockWidget::NoDockWidgetFeatures
  6899. : (QDockWidget::DockWidgetClosable |
  6900. QDockWidget::DockWidgetMovable |
  6901. QDockWidget::DockWidgetFloatable);
  6902. QDockWidget::DockWidgetFeatures mainFeatures = features;
  6903. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  6904. ui->scenesDock->setFeatures(mainFeatures);
  6905. ui->sourcesDock->setFeatures(mainFeatures);
  6906. ui->mixerDock->setFeatures(mainFeatures);
  6907. ui->transitionsDock->setFeatures(mainFeatures);
  6908. ui->controlsDock->setFeatures(mainFeatures);
  6909. statsDock->setFeatures(features);
  6910. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  6911. if (!extraDocks[i]) {
  6912. extraDocks.removeAt(i);
  6913. } else {
  6914. extraDocks[i]->setFeatures(features);
  6915. }
  6916. }
  6917. }
  6918. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  6919. {
  6920. ui->sourcesToolbar->setVisible(visible);
  6921. ui->scenesToolbar->setVisible(visible);
  6922. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6923. "ShowListboxToolbars", visible);
  6924. }
  6925. void OBSBasic::ShowContextBar()
  6926. {
  6927. on_toggleContextBar_toggled(true);
  6928. }
  6929. void OBSBasic::HideContextBar()
  6930. {
  6931. on_toggleContextBar_toggled(false);
  6932. }
  6933. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  6934. {
  6935. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  6936. "ShowContextToolbars", visible);
  6937. this->ui->contextContainer->setVisible(visible);
  6938. UpdateContextBar(true);
  6939. }
  6940. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  6941. {
  6942. ui->statusbar->setVisible(visible);
  6943. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  6944. visible);
  6945. }
  6946. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  6947. {
  6948. ui->sources->SetIconsVisible(visible);
  6949. if (advAudioWindow != nullptr)
  6950. advAudioWindow->SetIconsVisible(visible);
  6951. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  6952. visible);
  6953. }
  6954. void OBSBasic::on_actionLockPreview_triggered()
  6955. {
  6956. ui->preview->ToggleLocked();
  6957. ui->actionLockPreview->setChecked(ui->preview->Locked());
  6958. }
  6959. void OBSBasic::on_scalingMenu_aboutToShow()
  6960. {
  6961. obs_video_info ovi;
  6962. obs_get_video_info(&ovi);
  6963. QAction *action = ui->actionScaleCanvas;
  6964. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  6965. text = text.arg(QString::number(ovi.base_width),
  6966. QString::number(ovi.base_height));
  6967. action->setText(text);
  6968. action = ui->actionScaleOutput;
  6969. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  6970. text = text.arg(QString::number(ovi.output_width),
  6971. QString::number(ovi.output_height));
  6972. action->setText(text);
  6973. action->setVisible(!(ovi.output_width == ovi.base_width &&
  6974. ovi.output_height == ovi.base_height));
  6975. UpdatePreviewScalingMenu();
  6976. }
  6977. void OBSBasic::on_actionScaleWindow_triggered()
  6978. {
  6979. ui->preview->SetFixedScaling(false);
  6980. ui->preview->ResetScrollingOffset();
  6981. emit ui->preview->DisplayResized();
  6982. }
  6983. void OBSBasic::on_actionScaleCanvas_triggered()
  6984. {
  6985. ui->preview->SetFixedScaling(true);
  6986. ui->preview->SetScalingLevel(0);
  6987. emit ui->preview->DisplayResized();
  6988. }
  6989. void OBSBasic::on_actionScaleOutput_triggered()
  6990. {
  6991. obs_video_info ovi;
  6992. obs_get_video_info(&ovi);
  6993. ui->preview->SetFixedScaling(true);
  6994. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  6995. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  6996. int32_t approxScalingLevel =
  6997. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  6998. ui->preview->SetScalingLevel(approxScalingLevel);
  6999. ui->preview->SetScalingAmount(scalingAmount);
  7000. emit ui->preview->DisplayResized();
  7001. }
  7002. void OBSBasic::SetShowing(bool showing)
  7003. {
  7004. if (!showing && isVisible()) {
  7005. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7006. "geometry",
  7007. saveGeometry().toBase64().constData());
  7008. /* hide all visible child dialogs */
  7009. visDlgPositions.clear();
  7010. if (!visDialogs.isEmpty()) {
  7011. for (QDialog *dlg : visDialogs) {
  7012. visDlgPositions.append(dlg->pos());
  7013. dlg->hide();
  7014. }
  7015. }
  7016. if (showHide)
  7017. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7018. QTimer::singleShot(250, this, SLOT(hide()));
  7019. setVisible(false);
  7020. #ifdef __APPLE__
  7021. EnableOSXDockIcon(false);
  7022. #endif
  7023. } else if (showing && !isVisible()) {
  7024. if (showHide)
  7025. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7026. QTimer::singleShot(250, this, SLOT(show()));
  7027. setVisible(true);
  7028. #ifdef __APPLE__
  7029. EnableOSXDockIcon(true);
  7030. #endif
  7031. /* raise and activate window to ensure it is on top */
  7032. raise();
  7033. activateWindow();
  7034. /* show all child dialogs that was visible earlier */
  7035. if (!visDialogs.isEmpty()) {
  7036. for (int i = 0; i < visDialogs.size(); ++i) {
  7037. QDialog *dlg = visDialogs[i];
  7038. dlg->move(visDlgPositions[i]);
  7039. dlg->show();
  7040. }
  7041. }
  7042. /* Unminimize window if it was hidden to tray instead of task
  7043. * bar. */
  7044. if (sysTrayMinimizeToTray()) {
  7045. Qt::WindowStates state;
  7046. state = windowState() & ~Qt::WindowMinimized;
  7047. state |= Qt::WindowActive;
  7048. setWindowState(state);
  7049. }
  7050. }
  7051. }
  7052. void OBSBasic::ToggleShowHide()
  7053. {
  7054. bool showing = isVisible();
  7055. if (showing) {
  7056. /* check for modal dialogs */
  7057. EnumDialogs();
  7058. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7059. return;
  7060. }
  7061. SetShowing(!showing);
  7062. }
  7063. void OBSBasic::SystemTrayInit()
  7064. {
  7065. #ifdef __APPLE__
  7066. QIcon trayIconFile = QIcon(":/res/images/obs_macos.png");
  7067. trayIconFile.setIsMask(true);
  7068. #else
  7069. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  7070. #endif
  7071. trayIcon.reset(new QSystemTrayIcon(
  7072. QIcon::fromTheme("obs-tray", trayIconFile), this));
  7073. trayIcon->setToolTip("OBS Studio");
  7074. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  7075. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  7076. trayIcon.data());
  7077. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  7078. trayIcon.data());
  7079. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  7080. trayIcon.data());
  7081. sysTrayVirtualCam = new QAction(QTStr("Basic.Main.StartVirtualCam"),
  7082. trayIcon.data());
  7083. exit = new QAction(QTStr("Exit"), trayIcon.data());
  7084. trayMenu = new QMenu;
  7085. previewProjector = new QMenu(QTStr("PreviewProjector"));
  7086. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  7087. AddProjectorMenuMonitors(previewProjector, this,
  7088. SLOT(OpenPreviewProjector()));
  7089. AddProjectorMenuMonitors(studioProgramProjector, this,
  7090. SLOT(OpenStudioProgramProjector()));
  7091. trayMenu->addAction(showHide);
  7092. trayMenu->addMenu(previewProjector);
  7093. trayMenu->addMenu(studioProgramProjector);
  7094. trayMenu->addAction(sysTrayStream);
  7095. trayMenu->addAction(sysTrayRecord);
  7096. trayMenu->addAction(sysTrayReplayBuffer);
  7097. trayMenu->addAction(sysTrayVirtualCam);
  7098. trayMenu->addAction(exit);
  7099. trayIcon->setContextMenu(trayMenu);
  7100. trayIcon->show();
  7101. if (outputHandler && !outputHandler->replayBuffer)
  7102. sysTrayReplayBuffer->setEnabled(false);
  7103. sysTrayVirtualCam->setEnabled(vcamEnabled);
  7104. connect(trayIcon.data(),
  7105. SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
  7106. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  7107. connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
  7108. connect(sysTrayStream, SIGNAL(triggered()), this,
  7109. SLOT(on_streamButton_clicked()));
  7110. connect(sysTrayRecord, SIGNAL(triggered()), this,
  7111. SLOT(on_recordButton_clicked()));
  7112. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  7113. &OBSBasic::ReplayBufferClicked);
  7114. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  7115. &OBSBasic::VCamButtonClicked);
  7116. connect(exit, SIGNAL(triggered()), this, SLOT(close()));
  7117. }
  7118. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  7119. {
  7120. // Refresh projector list
  7121. previewProjector->clear();
  7122. studioProgramProjector->clear();
  7123. AddProjectorMenuMonitors(previewProjector, this,
  7124. SLOT(OpenPreviewProjector()));
  7125. AddProjectorMenuMonitors(studioProgramProjector, this,
  7126. SLOT(OpenStudioProgramProjector()));
  7127. #ifdef __APPLE__
  7128. UNUSED_PARAMETER(reason);
  7129. #else
  7130. if (reason == QSystemTrayIcon::Trigger) {
  7131. EnablePreviewDisplay(previewEnabled && !isVisible());
  7132. ToggleShowHide();
  7133. }
  7134. #endif
  7135. }
  7136. void OBSBasic::SysTrayNotify(const QString &text,
  7137. QSystemTrayIcon::MessageIcon n)
  7138. {
  7139. if (trayIcon && trayIcon->isVisible() &&
  7140. QSystemTrayIcon::supportsMessages()) {
  7141. QSystemTrayIcon::MessageIcon icon =
  7142. QSystemTrayIcon::MessageIcon(n);
  7143. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  7144. }
  7145. }
  7146. void OBSBasic::SystemTray(bool firstStarted)
  7147. {
  7148. if (!QSystemTrayIcon::isSystemTrayAvailable())
  7149. return;
  7150. if (!trayIcon && !firstStarted)
  7151. return;
  7152. bool sysTrayWhenStarted = config_get_bool(
  7153. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  7154. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7155. "SysTrayEnabled");
  7156. if (firstStarted)
  7157. SystemTrayInit();
  7158. if (!sysTrayEnabled) {
  7159. trayIcon->hide();
  7160. } else {
  7161. trayIcon->show();
  7162. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  7163. QTimer::singleShot(50, this, SLOT(hide()));
  7164. EnablePreviewDisplay(false);
  7165. setVisible(false);
  7166. #ifdef __APPLE__
  7167. EnableOSXDockIcon(false);
  7168. #endif
  7169. opt_minimize_tray = false;
  7170. }
  7171. }
  7172. if (isVisible())
  7173. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7174. else
  7175. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7176. }
  7177. bool OBSBasic::sysTrayMinimizeToTray()
  7178. {
  7179. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  7180. "SysTrayMinimizeToTray");
  7181. }
  7182. void OBSBasic::on_actionMainUndo_triggered()
  7183. {
  7184. undo_s.undo();
  7185. }
  7186. void OBSBasic::on_actionMainRedo_triggered()
  7187. {
  7188. undo_s.redo();
  7189. }
  7190. void OBSBasic::on_actionCopySource_triggered()
  7191. {
  7192. copyStrings.clear();
  7193. bool allowPastingDuplicate = true;
  7194. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  7195. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  7196. if (!item)
  7197. continue;
  7198. on_actionCopyTransform_triggered();
  7199. OBSSource source = obs_sceneitem_get_source(item);
  7200. copyStrings.push_front(obs_source_get_name(source));
  7201. copyVisible = obs_sceneitem_visible(item);
  7202. uint32_t output_flags = obs_source_get_output_flags(source);
  7203. if (output_flags & OBS_SOURCE_DO_NOT_DUPLICATE)
  7204. allowPastingDuplicate = false;
  7205. }
  7206. ui->actionPasteRef->setEnabled(true);
  7207. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  7208. }
  7209. void OBSBasic::on_actionPasteRef_triggered()
  7210. {
  7211. OBSSource scene_source = GetCurrentSceneSource();
  7212. OBSData undo_data = BackupScene(scene_source);
  7213. undo_s.push_disabled();
  7214. for (auto &copyString : copyStrings) {
  7215. /* do not allow duplicate refs of the same group in the same scene */
  7216. OBSScene scene = GetCurrentScene();
  7217. if (!!obs_scene_get_group(scene, copyString))
  7218. continue;
  7219. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  7220. false);
  7221. on_actionPasteTransform_triggered();
  7222. }
  7223. undo_s.pop_disabled();
  7224. QString action_name = QTStr("Undo.PasteSourceRef");
  7225. const char *scene_name = obs_source_get_name(scene_source);
  7226. OBSData redo_data = BackupScene(scene_source);
  7227. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7228. redo_data);
  7229. }
  7230. void OBSBasic::on_actionPasteDup_triggered()
  7231. {
  7232. OBSSource scene_source = GetCurrentSceneSource();
  7233. OBSData undo_data = BackupScene(scene_source);
  7234. undo_s.push_disabled();
  7235. for (auto &copyString : copyStrings) {
  7236. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
  7237. true);
  7238. on_actionPasteTransform_triggered();
  7239. }
  7240. undo_s.pop_disabled();
  7241. QString action_name = QTStr("Undo.PasteSource");
  7242. const char *scene_name = obs_source_get_name(scene_source);
  7243. OBSData redo_data = BackupScene(scene_source);
  7244. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  7245. redo_data);
  7246. }
  7247. void OBSBasic::AudioMixerCopyFilters()
  7248. {
  7249. QAction *action = reinterpret_cast<QAction *>(sender());
  7250. VolControl *vol = action->property("volControl").value<VolControl *>();
  7251. obs_source_t *source = vol->GetSource();
  7252. copyFiltersString = obs_source_get_name(source);
  7253. }
  7254. void OBSBasic::AudioMixerPasteFilters()
  7255. {
  7256. QAction *action = reinterpret_cast<QAction *>(sender());
  7257. VolControl *vol = action->property("volControl").value<VolControl *>();
  7258. obs_source_t *dstSource = vol->GetSource();
  7259. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7260. obs_source_release(source);
  7261. if (source == dstSource)
  7262. return;
  7263. obs_source_copy_filters(dstSource, source);
  7264. }
  7265. void OBSBasic::SceneCopyFilters()
  7266. {
  7267. copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
  7268. }
  7269. void OBSBasic::ScenePasteFilters()
  7270. {
  7271. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7272. obs_source_release(source);
  7273. OBSSource dstSource = GetCurrentSceneSource();
  7274. if (source == dstSource)
  7275. return;
  7276. obs_source_copy_filters(dstSource, source);
  7277. }
  7278. void OBSBasic::on_actionCopyFilters_triggered()
  7279. {
  7280. OBSSceneItem item = GetCurrentSceneItem();
  7281. if (!item)
  7282. return;
  7283. OBSSource source = obs_sceneitem_get_source(item);
  7284. copyFiltersString = obs_source_get_name(source);
  7285. ui->actionPasteFilters->setEnabled(true);
  7286. }
  7287. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  7288. obs_source_t *source,
  7289. obs_data_array_t *undo_array,
  7290. obs_data_array_t *redo_array)
  7291. {
  7292. auto undo_redo = [this](const std::string &json) {
  7293. obs_data_t *data = obs_data_create_from_json(json.c_str());
  7294. obs_data_array_t *array = obs_data_get_array(data, "array");
  7295. const char *name = obs_data_get_string(data, "name");
  7296. obs_source_t *source = obs_get_source_by_name(name);
  7297. obs_source_restore_filters(source, array);
  7298. obs_source_release(source);
  7299. obs_data_array_release(array);
  7300. obs_data_release(data);
  7301. if (filters)
  7302. filters->UpdateSource(source);
  7303. };
  7304. const char *name = obs_source_get_name(source);
  7305. obs_data_t *undo_data = obs_data_create();
  7306. obs_data_t *redo_data = obs_data_create();
  7307. obs_data_set_array(undo_data, "array", undo_array);
  7308. obs_data_set_array(redo_data, "array", redo_array);
  7309. obs_data_set_string(undo_data, "name", name);
  7310. obs_data_set_string(redo_data, "name", name);
  7311. undo_s.add_action(text, undo_redo, undo_redo,
  7312. obs_data_get_json(undo_data),
  7313. obs_data_get_json(redo_data));
  7314. obs_data_release(undo_data);
  7315. obs_data_release(redo_data);
  7316. }
  7317. void OBSBasic::on_actionPasteFilters_triggered()
  7318. {
  7319. OBSSource source = obs_get_source_by_name(copyFiltersString);
  7320. obs_source_release(source);
  7321. OBSSceneItem sceneItem = GetCurrentSceneItem();
  7322. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  7323. if (source == dstSource)
  7324. return;
  7325. obs_data_array_t *undo_array = obs_source_backup_filters(dstSource);
  7326. obs_source_copy_filters(dstSource, source);
  7327. obs_data_array_t *redo_array = obs_source_backup_filters(dstSource);
  7328. const char *srcName = obs_source_get_name(source);
  7329. const char *dstName = obs_source_get_name(dstSource);
  7330. QString text =
  7331. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  7332. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  7333. redo_array);
  7334. obs_data_array_release(undo_array);
  7335. obs_data_array_release(redo_array);
  7336. }
  7337. static void ConfirmColor(SourceTree *sources, const QColor &color,
  7338. QModelIndexList selectedItems)
  7339. {
  7340. for (int x = 0; x < selectedItems.count(); x++) {
  7341. SourceTreeItem *treeItem =
  7342. sources->GetItemWidget(selectedItems[x].row());
  7343. treeItem->setStyleSheet("background: " +
  7344. color.name(QColor::HexArgb));
  7345. treeItem->style()->unpolish(treeItem);
  7346. treeItem->style()->polish(treeItem);
  7347. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  7348. obs_data_t *privData =
  7349. obs_sceneitem_get_private_settings(sceneItem);
  7350. obs_data_set_int(privData, "color-preset", 1);
  7351. obs_data_set_string(privData, "color",
  7352. QT_TO_UTF8(color.name(QColor::HexArgb)));
  7353. obs_data_release(privData);
  7354. }
  7355. }
  7356. void OBSBasic::ColorChange()
  7357. {
  7358. QModelIndexList selectedItems =
  7359. ui->sources->selectionModel()->selectedIndexes();
  7360. QAction *action = qobject_cast<QAction *>(sender());
  7361. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  7362. if (selectedItems.count() == 0)
  7363. return;
  7364. if (colorButton) {
  7365. int preset = colorButton->property("bgColor").value<int>();
  7366. for (int x = 0; x < selectedItems.count(); x++) {
  7367. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  7368. selectedItems[x].row());
  7369. treeItem->setStyleSheet("");
  7370. treeItem->setProperty("bgColor", preset);
  7371. treeItem->style()->unpolish(treeItem);
  7372. treeItem->style()->polish(treeItem);
  7373. OBSSceneItem sceneItem =
  7374. ui->sources->Get(selectedItems[x].row());
  7375. obs_data_t *privData =
  7376. obs_sceneitem_get_private_settings(sceneItem);
  7377. obs_data_set_int(privData, "color-preset", preset + 1);
  7378. obs_data_set_string(privData, "color", "");
  7379. obs_data_release(privData);
  7380. }
  7381. for (int i = 1; i < 9; i++) {
  7382. stringstream button;
  7383. button << "preset" << i;
  7384. QPushButton *cButton =
  7385. colorButton->parentWidget()
  7386. ->findChild<QPushButton *>(
  7387. button.str().c_str());
  7388. cButton->setStyleSheet("border: 1px solid black");
  7389. }
  7390. colorButton->setStyleSheet("border: 2px solid black");
  7391. } else if (action) {
  7392. int preset = action->property("bgColor").value<int>();
  7393. if (preset == 1) {
  7394. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  7395. SourceTreeItem *curTreeItem =
  7396. GetItemWidgetFromSceneItem(curSceneItem);
  7397. obs_data_t *curPrivData =
  7398. obs_sceneitem_get_private_settings(
  7399. curSceneItem);
  7400. int oldPreset =
  7401. obs_data_get_int(curPrivData, "color-preset");
  7402. const QString oldSheet = curTreeItem->styleSheet();
  7403. auto liveChangeColor = [=](const QColor &color) {
  7404. if (color.isValid()) {
  7405. curTreeItem->setStyleSheet(
  7406. "background: " +
  7407. color.name(QColor::HexArgb));
  7408. }
  7409. };
  7410. auto changedColor = [=](const QColor &color) {
  7411. if (color.isValid()) {
  7412. ConfirmColor(ui->sources, color,
  7413. selectedItems);
  7414. }
  7415. };
  7416. auto rejected = [=]() {
  7417. if (oldPreset == 1) {
  7418. curTreeItem->setStyleSheet(oldSheet);
  7419. curTreeItem->setProperty("bgColor", 0);
  7420. } else if (oldPreset == 0) {
  7421. curTreeItem->setStyleSheet(
  7422. "background: none");
  7423. curTreeItem->setProperty("bgColor", 0);
  7424. } else {
  7425. curTreeItem->setStyleSheet("");
  7426. curTreeItem->setProperty("bgColor",
  7427. oldPreset - 1);
  7428. }
  7429. curTreeItem->style()->unpolish(curTreeItem);
  7430. curTreeItem->style()->polish(curTreeItem);
  7431. };
  7432. QColorDialog::ColorDialogOptions options =
  7433. QColorDialog::ShowAlphaChannel;
  7434. const char *oldColor =
  7435. obs_data_get_string(curPrivData, "color");
  7436. const char *customColor = *oldColor != 0 ? oldColor
  7437. : "#55FF0000";
  7438. #ifndef _WIN32
  7439. options |= QColorDialog::DontUseNativeDialog;
  7440. #endif
  7441. QColorDialog *colorDialog = new QColorDialog(this);
  7442. colorDialog->setOptions(options);
  7443. colorDialog->setCurrentColor(QColor(customColor));
  7444. connect(colorDialog, &QColorDialog::currentColorChanged,
  7445. liveChangeColor);
  7446. connect(colorDialog, &QColorDialog::colorSelected,
  7447. changedColor);
  7448. connect(colorDialog, &QColorDialog::rejected, rejected);
  7449. colorDialog->open();
  7450. obs_data_release(curPrivData);
  7451. } else {
  7452. for (int x = 0; x < selectedItems.count(); x++) {
  7453. SourceTreeItem *treeItem =
  7454. ui->sources->GetItemWidget(
  7455. selectedItems[x].row());
  7456. treeItem->setStyleSheet("background: none");
  7457. treeItem->setProperty("bgColor", preset);
  7458. treeItem->style()->unpolish(treeItem);
  7459. treeItem->style()->polish(treeItem);
  7460. OBSSceneItem sceneItem = ui->sources->Get(
  7461. selectedItems[x].row());
  7462. obs_data_t *privData =
  7463. obs_sceneitem_get_private_settings(
  7464. sceneItem);
  7465. obs_data_set_int(privData, "color-preset",
  7466. preset);
  7467. obs_data_set_string(privData, "color", "");
  7468. obs_data_release(privData);
  7469. }
  7470. }
  7471. }
  7472. }
  7473. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  7474. {
  7475. int i = 0;
  7476. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  7477. OBSSceneItem item = ui->sources->Get(i);
  7478. int64_t id = obs_sceneitem_get_id(sceneItem);
  7479. while (treeItem && obs_sceneitem_get_id(item) != id) {
  7480. i++;
  7481. treeItem = ui->sources->GetItemWidget(i);
  7482. item = ui->sources->Get(i);
  7483. }
  7484. if (treeItem)
  7485. return treeItem;
  7486. return nullptr;
  7487. }
  7488. void OBSBasic::on_autoConfigure_triggered()
  7489. {
  7490. AutoConfig test(this);
  7491. test.setModal(true);
  7492. test.show();
  7493. test.exec();
  7494. }
  7495. void OBSBasic::on_stats_triggered()
  7496. {
  7497. if (!stats.isNull()) {
  7498. stats->show();
  7499. stats->raise();
  7500. return;
  7501. }
  7502. OBSBasicStats *statsDlg;
  7503. statsDlg = new OBSBasicStats(nullptr);
  7504. statsDlg->show();
  7505. stats = statsDlg;
  7506. }
  7507. void OBSBasic::on_actionShowAbout_triggered()
  7508. {
  7509. if (about)
  7510. about->close();
  7511. about = new OBSAbout(this);
  7512. about->show();
  7513. about->setAttribute(Qt::WA_DeleteOnClose, true);
  7514. }
  7515. void OBSBasic::ResizeOutputSizeOfSource()
  7516. {
  7517. if (obs_video_active())
  7518. return;
  7519. QMessageBox resize_output(this);
  7520. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  7521. QTStr("ResizeOutputSizeOfSource.Continue"));
  7522. QAbstractButton *Yes =
  7523. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  7524. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  7525. resize_output.setIcon(QMessageBox::Warning);
  7526. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  7527. resize_output.exec();
  7528. if (resize_output.clickedButton() != Yes)
  7529. return;
  7530. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  7531. int width = obs_source_get_width(source);
  7532. int height = obs_source_get_height(source);
  7533. config_set_uint(basicConfig, "Video", "BaseCX", width);
  7534. config_set_uint(basicConfig, "Video", "BaseCY", height);
  7535. config_set_uint(basicConfig, "Video", "OutputCX", width);
  7536. config_set_uint(basicConfig, "Video", "OutputCY", height);
  7537. ResetVideo();
  7538. ResetOutputs();
  7539. config_save_safe(basicConfig, "tmp", nullptr);
  7540. on_actionFitToScreen_triggered();
  7541. }
  7542. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  7543. {
  7544. QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
  7545. action->setCheckable(true);
  7546. assignDockToggle(dock, action);
  7547. extraDocks.push_back(dock);
  7548. bool lock = ui->lockUI->isChecked();
  7549. QDockWidget::DockWidgetFeatures features =
  7550. lock ? QDockWidget::NoDockWidgetFeatures
  7551. : (QDockWidget::DockWidgetClosable |
  7552. QDockWidget::DockWidgetMovable |
  7553. QDockWidget::DockWidgetFloatable);
  7554. dock->setFeatures(features);
  7555. /* prune deleted docks */
  7556. for (int i = extraDocks.size() - 1; i >= 0; i--) {
  7557. if (!extraDocks[i]) {
  7558. extraDocks.removeAt(i);
  7559. }
  7560. }
  7561. return action;
  7562. }
  7563. OBSBasic *OBSBasic::Get()
  7564. {
  7565. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  7566. }
  7567. bool OBSBasic::StreamingActive()
  7568. {
  7569. if (!outputHandler)
  7570. return false;
  7571. return outputHandler->StreamingActive();
  7572. }
  7573. bool OBSBasic::RecordingActive()
  7574. {
  7575. if (!outputHandler)
  7576. return false;
  7577. return outputHandler->RecordingActive();
  7578. }
  7579. bool OBSBasic::ReplayBufferActive()
  7580. {
  7581. if (!outputHandler)
  7582. return false;
  7583. return outputHandler->ReplayBufferActive();
  7584. }
  7585. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  7586. : QStyledItemDelegate(parent)
  7587. {
  7588. }
  7589. void SceneRenameDelegate::setEditorData(QWidget *editor,
  7590. const QModelIndex &index) const
  7591. {
  7592. QStyledItemDelegate::setEditorData(editor, index);
  7593. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7594. if (lineEdit)
  7595. lineEdit->selectAll();
  7596. }
  7597. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  7598. {
  7599. if (event->type() == QEvent::KeyPress) {
  7600. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  7601. if (keyEvent->key() == Qt::Key_Escape) {
  7602. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  7603. if (lineEdit)
  7604. lineEdit->undo();
  7605. }
  7606. }
  7607. return QStyledItemDelegate::eventFilter(editor, event);
  7608. }
  7609. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  7610. {
  7611. if (!error.isEmpty())
  7612. return;
  7613. patronJson = QT_TO_UTF8(text);
  7614. }
  7615. void OBSBasic::PauseRecording()
  7616. {
  7617. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7618. os_atomic_load_bool(&recording_paused))
  7619. return;
  7620. obs_output_t *output = outputHandler->fileOutput;
  7621. if (obs_output_pause(output, true)) {
  7622. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  7623. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  7624. pause->blockSignals(true);
  7625. pause->setChecked(true);
  7626. pause->blockSignals(false);
  7627. ui->statusbar->RecordingPaused();
  7628. if (trayIcon && trayIcon->isVisible()) {
  7629. #ifdef __APPLE__
  7630. QIcon trayIconFile =
  7631. QIcon(":/res/images/obs_paused_macos.png");
  7632. trayIconFile.setIsMask(true);
  7633. #else
  7634. QIcon trayIconFile =
  7635. QIcon(":/res/images/obs_paused.png");
  7636. #endif
  7637. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  7638. trayIconFile));
  7639. }
  7640. os_atomic_set_bool(&recording_paused, true);
  7641. if (api)
  7642. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  7643. if (os_atomic_load_bool(&replaybuf_active))
  7644. ShowReplayBufferPauseWarning();
  7645. }
  7646. }
  7647. void OBSBasic::UnpauseRecording()
  7648. {
  7649. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  7650. !os_atomic_load_bool(&recording_paused))
  7651. return;
  7652. obs_output_t *output = outputHandler->fileOutput;
  7653. if (obs_output_pause(output, false)) {
  7654. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7655. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7656. pause->blockSignals(true);
  7657. pause->setChecked(false);
  7658. pause->blockSignals(false);
  7659. ui->statusbar->RecordingUnpaused();
  7660. if (trayIcon && trayIcon->isVisible()) {
  7661. #ifdef __APPLE__
  7662. QIcon trayIconFile =
  7663. QIcon(":/res/images/tray_active_macos.png");
  7664. trayIconFile.setIsMask(true);
  7665. #else
  7666. QIcon trayIconFile =
  7667. QIcon(":/res/images/tray_active.png");
  7668. #endif
  7669. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  7670. trayIconFile));
  7671. }
  7672. os_atomic_set_bool(&recording_paused, false);
  7673. if (api)
  7674. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  7675. }
  7676. }
  7677. void OBSBasic::PauseToggled()
  7678. {
  7679. if (!pause || !outputHandler || !outputHandler->fileOutput)
  7680. return;
  7681. obs_output_t *output = outputHandler->fileOutput;
  7682. bool enable = !obs_output_paused(output);
  7683. if (enable)
  7684. PauseRecording();
  7685. else
  7686. UnpauseRecording();
  7687. }
  7688. void OBSBasic::UpdatePause(bool activate)
  7689. {
  7690. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  7691. pause.reset();
  7692. return;
  7693. }
  7694. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  7695. bool adv = astrcmpi(mode, "Advanced") == 0;
  7696. bool shared;
  7697. if (adv) {
  7698. const char *recType =
  7699. config_get_string(basicConfig, "AdvOut", "RecType");
  7700. if (astrcmpi(recType, "FFmpeg") == 0) {
  7701. shared = config_get_bool(basicConfig, "AdvOut",
  7702. "FFOutputToFile");
  7703. } else {
  7704. const char *recordEncoder = config_get_string(
  7705. basicConfig, "AdvOut", "RecEncoder");
  7706. shared = astrcmpi(recordEncoder, "none") == 0;
  7707. }
  7708. } else {
  7709. const char *quality = config_get_string(
  7710. basicConfig, "SimpleOutput", "RecQuality");
  7711. shared = strcmp(quality, "Stream") == 0;
  7712. }
  7713. if (!shared) {
  7714. pause.reset(new QPushButton());
  7715. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  7716. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  7717. pause->setCheckable(true);
  7718. pause->setChecked(false);
  7719. pause->setProperty("themeID",
  7720. QVariant(QStringLiteral("pauseIconSmall")));
  7721. QSizePolicy sp;
  7722. sp.setHeightForWidth(true);
  7723. pause->setSizePolicy(sp);
  7724. connect(pause.data(), &QAbstractButton::clicked, this,
  7725. &OBSBasic::PauseToggled);
  7726. ui->recordingLayout->addWidget(pause.data());
  7727. } else {
  7728. pause.reset();
  7729. }
  7730. }
  7731. void OBSBasic::UpdateReplayBuffer(bool activate)
  7732. {
  7733. if (!activate || !outputHandler ||
  7734. !outputHandler->ReplayBufferActive()) {
  7735. replay.reset();
  7736. return;
  7737. }
  7738. replay.reset(new QPushButton());
  7739. replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
  7740. replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
  7741. replay->setChecked(false);
  7742. replay->setProperty("themeID",
  7743. QVariant(QStringLiteral("replayIconSmall")));
  7744. QSizePolicy sp;
  7745. sp.setHeightForWidth(true);
  7746. replay->setSizePolicy(sp);
  7747. connect(replay.data(), &QAbstractButton::clicked, this,
  7748. &OBSBasic::ReplayBufferSave);
  7749. replayLayout->addWidget(replay.data());
  7750. setTabOrder(replayLayout->itemAt(0)->widget(),
  7751. replayLayout->itemAt(1)->widget());
  7752. setTabOrder(replayLayout->itemAt(1)->widget(),
  7753. ui->buttonsVLayout->itemAt(3)->widget());
  7754. }
  7755. #define MBYTE (1024ULL * 1024ULL)
  7756. #define MBYTES_LEFT_STOP_REC 50ULL
  7757. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  7758. const char *OBSBasic::GetCurrentOutputPath()
  7759. {
  7760. const char *path = nullptr;
  7761. const char *mode = config_get_string(Config(), "Output", "Mode");
  7762. if (strcmp(mode, "Advanced") == 0) {
  7763. const char *advanced_mode =
  7764. config_get_string(Config(), "AdvOut", "RecType");
  7765. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  7766. path = config_get_string(Config(), "AdvOut",
  7767. "FFFilePath");
  7768. } else {
  7769. path = config_get_string(Config(), "AdvOut",
  7770. "RecFilePath");
  7771. }
  7772. } else {
  7773. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  7774. }
  7775. return path;
  7776. }
  7777. void OBSBasic::OutputPathInvalidMessage()
  7778. {
  7779. blog(LOG_ERROR, "Recording stopped because of bad output path");
  7780. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  7781. QTStr("Output.BadPath.Text"));
  7782. }
  7783. bool OBSBasic::OutputPathValid()
  7784. {
  7785. const char *mode = config_get_string(Config(), "Output", "Mode");
  7786. if (strcmp(mode, "Advanced") == 0) {
  7787. const char *advanced_mode =
  7788. config_get_string(Config(), "AdvOut", "RecType");
  7789. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  7790. bool is_local = config_get_bool(Config(), "AdvOut",
  7791. "FFOutputToFile");
  7792. if (!is_local)
  7793. return true;
  7794. }
  7795. }
  7796. const char *path = GetCurrentOutputPath();
  7797. return path && *path && QDir(path).exists();
  7798. }
  7799. void OBSBasic::DiskSpaceMessage()
  7800. {
  7801. blog(LOG_ERROR, "Recording stopped because of low disk space");
  7802. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  7803. QTStr("Output.RecordNoSpace.Msg"));
  7804. }
  7805. bool OBSBasic::LowDiskSpace()
  7806. {
  7807. const char *path;
  7808. path = GetCurrentOutputPath();
  7809. if (!path)
  7810. return false;
  7811. uint64_t num_bytes = os_get_free_disk_space(path);
  7812. if (num_bytes < (MAX_BYTES_LEFT))
  7813. return true;
  7814. else
  7815. return false;
  7816. }
  7817. void OBSBasic::CheckDiskSpaceRemaining()
  7818. {
  7819. if (LowDiskSpace()) {
  7820. StopRecording();
  7821. StopReplayBuffer();
  7822. DiskSpaceMessage();
  7823. }
  7824. }
  7825. void OBSBasic::ScenesReordered()
  7826. {
  7827. OBSProjector::UpdateMultiviewProjectors();
  7828. }
  7829. void OBSBasic::ResetStatsHotkey()
  7830. {
  7831. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  7832. foreach(OBSBasicStats * s, list) s->Reset();
  7833. }
  7834. void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
  7835. {
  7836. QWidget *widget = childAt(pos);
  7837. const char *className = nullptr;
  7838. if (widget != nullptr)
  7839. className = widget->metaObject()->className();
  7840. if (!className || strstr(className, "Dock") != nullptr)
  7841. ui->viewMenuDocks->exec(mapToGlobal(pos));
  7842. }
  7843. void OBSBasic::UpdateProjectorHideCursor()
  7844. {
  7845. for (size_t i = 0; i < projectors.size(); i++)
  7846. projectors[i]->SetHideCursor();
  7847. }
  7848. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  7849. {
  7850. for (size_t i = 0; i < projectors.size(); i++)
  7851. SetAlwaysOnTop(projectors[i], top);
  7852. }
  7853. void OBSBasic::ResetProjectors()
  7854. {
  7855. obs_data_array_t *savedProjectorList = SaveProjectors();
  7856. ClearProjectors();
  7857. LoadSavedProjectors(savedProjectorList);
  7858. OpenSavedProjectors();
  7859. obs_data_array_release(savedProjectorList);
  7860. }
  7861. void OBSBasic::on_sourcePropertiesButton_clicked()
  7862. {
  7863. on_actionSourceProperties_triggered();
  7864. }
  7865. void OBSBasic::on_sourceFiltersButton_clicked()
  7866. {
  7867. OpenFilters();
  7868. }
  7869. void OBSBasic::on_sourceInteractButton_clicked()
  7870. {
  7871. on_actionInteract_triggered();
  7872. }
  7873. void OBSBasic::ShowStatusBarMessage(const QString &message)
  7874. {
  7875. ui->statusbar->clearMessage();
  7876. ui->statusbar->showMessage(message, 10000);
  7877. }
  7878. void OBSBasic::UpdatePreviewSafeAreas()
  7879. {
  7880. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  7881. "ShowSafeAreas");
  7882. }