window-basic-main.cpp 268 KB

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