window-basic-main.cpp 277 KB

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