window-basic-main.cpp 255 KB

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