window-basic-main.cpp 245 KB

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