window-basic-main.cpp 277 KB

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