window-basic-main.cpp 275 KB

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