window-basic-main.cpp 256 KB

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