window-basic-main.cpp 198 KB

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