window-basic-main.cpp 268 KB

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