window-basic-main.cpp 275 KB

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