window-basic-main.cpp 271 KB

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