window-basic-main.cpp 241 KB

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