window-basic-main.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819
  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 <time.h>
  17. #include <obs.hpp>
  18. #include <QGuiApplication>
  19. #include <QMessageBox>
  20. #include <QShowEvent>
  21. #include <QDesktopServices>
  22. #include <QFileDialog>
  23. #include <QDesktopWidget>
  24. #include <QRect>
  25. #include <QScreen>
  26. #include <util/dstr.h>
  27. #include <util/util.hpp>
  28. #include <util/platform.h>
  29. #include <util/profiler.hpp>
  30. #include <util/dstr.hpp>
  31. #include <graphics/math-defs.h>
  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-basic-properties.hpp"
  44. #include "window-log-reply.hpp"
  45. #include "window-projector.hpp"
  46. #include "window-remux.hpp"
  47. #include "qt-wrappers.hpp"
  48. #include "display-helpers.hpp"
  49. #include "volume-control.hpp"
  50. #include "remote-text.hpp"
  51. #if defined(_WIN32) && defined(ENABLE_WIN_UPDATER)
  52. #include "win-update/win-update.hpp"
  53. #endif
  54. #include "ui_OBSBasic.h"
  55. #include <fstream>
  56. #include <sstream>
  57. #include <QScreen>
  58. #include <QWindow>
  59. using namespace std;
  60. namespace {
  61. template <typename OBSRef>
  62. struct SignalContainer {
  63. OBSRef ref;
  64. vector<shared_ptr<OBSSignal>> handlers;
  65. };
  66. }
  67. Q_DECLARE_METATYPE(OBSScene);
  68. Q_DECLARE_METATYPE(OBSSceneItem);
  69. Q_DECLARE_METATYPE(OBSSource);
  70. Q_DECLARE_METATYPE(obs_order_movement);
  71. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  72. template <typename T>
  73. static T GetOBSRef(QListWidgetItem *item)
  74. {
  75. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  76. }
  77. template <typename T>
  78. static void SetOBSRef(QListWidgetItem *item, T &&val)
  79. {
  80. item->setData(static_cast<int>(QtDataRole::OBSRef),
  81. QVariant::fromValue(val));
  82. }
  83. static void AddExtraModulePaths()
  84. {
  85. char base_module_dir[512];
  86. #if defined(_WIN32) || defined(__APPLE__)
  87. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  88. "obs-studio/plugins/%module%");
  89. #else
  90. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  91. "obs-studio/plugins/%module%");
  92. #endif
  93. if (ret <= 0)
  94. return;
  95. string path = (char*)base_module_dir;
  96. #if defined(__APPLE__)
  97. obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
  98. BPtr<char> config_bin = os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
  99. BPtr<char> config_data = os_get_config_path_ptr("obs-studio/plugins/%module%/data");
  100. obs_add_module_path(config_bin, config_data);
  101. #elif ARCH_BITS == 64
  102. obs_add_module_path((path + "/bin/64bit").c_str(),
  103. (path + "/data").c_str());
  104. #else
  105. obs_add_module_path((path + "/bin/32bit").c_str(),
  106. (path + "/data").c_str());
  107. #endif
  108. }
  109. static QList<QKeySequence> DeleteKeys;
  110. OBSBasic::OBSBasic(QWidget *parent)
  111. : OBSMainWindow (parent),
  112. ui (new Ui::OBSBasic)
  113. {
  114. setAttribute(Qt::WA_NativeWindow);
  115. projectorArray.resize(10, "");
  116. previewProjectorArray.resize(10, 0);
  117. setAcceptDrops(true);
  118. ui->setupUi(this);
  119. ui->previewDisabledLabel->setVisible(false);
  120. startingDockLayout = saveState();
  121. copyActionsDynamicProperties();
  122. ui->sources->setItemDelegate(new VisibilityItemDelegate(ui->sources));
  123. char styleSheetPath[512];
  124. int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
  125. "stylesheet.qss");
  126. if (ret > 0) {
  127. if (QFile::exists(styleSheetPath)) {
  128. QString path = QString("file:///") +
  129. QT_UTF8(styleSheetPath);
  130. App()->setStyleSheet(path);
  131. }
  132. }
  133. qRegisterMetaType<OBSScene> ("OBSScene");
  134. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  135. qRegisterMetaType<OBSSource> ("OBSSource");
  136. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  137. qRegisterMetaTypeStreamOperators<
  138. std::vector<std::shared_ptr<OBSSignal>>>(
  139. "std::vector<std::shared_ptr<OBSSignal>>");
  140. qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
  141. qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
  142. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  143. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  144. auto displayResize = [this]() {
  145. struct obs_video_info ovi;
  146. if (obs_get_video_info(&ovi))
  147. ResizePreview(ovi.base_width, ovi.base_height);
  148. };
  149. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  150. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  151. installEventFilter(CreateShortcutFilter());
  152. stringstream name;
  153. name << "OBS " << App()->GetVersionString();
  154. blog(LOG_INFO, "%s", name.str().c_str());
  155. blog(LOG_INFO, "---------------------------------");
  156. UpdateTitleBar();
  157. connect(ui->scenes->itemDelegate(),
  158. SIGNAL(closeEditor(QWidget*,
  159. QAbstractItemDelegate::EndEditHint)),
  160. this,
  161. SLOT(SceneNameEdited(QWidget*,
  162. QAbstractItemDelegate::EndEditHint)));
  163. connect(ui->sources->itemDelegate(),
  164. SIGNAL(closeEditor(QWidget*,
  165. QAbstractItemDelegate::EndEditHint)),
  166. this,
  167. SLOT(SceneItemNameEdited(QWidget*,
  168. QAbstractItemDelegate::EndEditHint)));
  169. cpuUsageInfo = os_cpu_usage_info_start();
  170. cpuUsageTimer = new QTimer(this);
  171. connect(cpuUsageTimer, SIGNAL(timeout()),
  172. ui->statusbar, SLOT(UpdateCPUUsage()));
  173. cpuUsageTimer->start(3000);
  174. DeleteKeys =
  175. #ifdef __APPLE__
  176. QList<QKeySequence>{{Qt::Key_Backspace}} <<
  177. #endif
  178. QKeySequence::keyBindings(QKeySequence::Delete);
  179. #ifdef __APPLE__
  180. ui->actionRemoveSource->setShortcuts(DeleteKeys);
  181. ui->actionRemoveScene->setShortcuts(DeleteKeys);
  182. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  183. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  184. #endif
  185. auto addNudge = [this](const QKeySequence &seq, const char *s)
  186. {
  187. QAction *nudge = new QAction(ui->preview);
  188. nudge->setShortcut(seq);
  189. nudge->setShortcutContext(Qt::WidgetShortcut);
  190. ui->preview->addAction(nudge);
  191. connect(nudge, SIGNAL(triggered()), this, s);
  192. };
  193. addNudge(Qt::Key_Up, SLOT(NudgeUp()));
  194. addNudge(Qt::Key_Down, SLOT(NudgeDown()));
  195. addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
  196. addNudge(Qt::Key_Right, SLOT(NudgeRight()));
  197. auto assignDockToggle = [this](QDockWidget *dock, QAction *action)
  198. {
  199. auto handleWindowToggle = [action] (bool vis)
  200. {
  201. action->blockSignals(true);
  202. action->setChecked(vis);
  203. action->blockSignals(false);
  204. };
  205. auto handleMenuToggle = [dock] (bool check)
  206. {
  207. dock->blockSignals(true);
  208. dock->setVisible(check);
  209. dock->blockSignals(false);
  210. };
  211. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  212. handleWindowToggle);
  213. dock->connect(action, &QAction::toggled,
  214. handleMenuToggle);
  215. };
  216. assignDockToggle(ui->scenesDock, ui->toggleScenes);
  217. assignDockToggle(ui->sourcesDock, ui->toggleSources);
  218. assignDockToggle(ui->mixerDock, ui->toggleMixer);
  219. assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
  220. assignDockToggle(ui->controlsDock, ui->toggleControls);
  221. //hide all docking panes
  222. ui->toggleScenes->setChecked(false);
  223. ui->toggleSources->setChecked(false);
  224. ui->toggleMixer->setChecked(false);
  225. ui->toggleTransitions->setChecked(false);
  226. ui->toggleControls->setChecked(false);
  227. //restore parent window geometry
  228. const char *geometry = config_get_string(App()->GlobalConfig(),
  229. "BasicWindow", "geometry");
  230. if (geometry != NULL) {
  231. QByteArray byteArray = QByteArray::fromBase64(
  232. QByteArray(geometry));
  233. restoreGeometry(byteArray);
  234. QRect windowGeometry = normalGeometry();
  235. if (!WindowPositionValid(windowGeometry)) {
  236. QRect rect = App()->desktop()->geometry();
  237. setGeometry(QStyle::alignedRect(
  238. Qt::LeftToRight,
  239. Qt::AlignCenter,
  240. size(), rect));
  241. }
  242. }
  243. }
  244. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  245. vector<OBSSource> &audioSources)
  246. {
  247. obs_source_t *source = obs_get_output_source(channel);
  248. if (!source)
  249. return;
  250. audioSources.push_back(source);
  251. obs_data_t *data = obs_save_source(source);
  252. obs_data_set_obj(parent, name, data);
  253. obs_data_release(data);
  254. obs_source_release(source);
  255. }
  256. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  257. obs_data_array_t *quickTransitionData, int transitionDuration,
  258. obs_data_array_t *transitions,
  259. OBSScene &scene, OBSSource &curProgramScene,
  260. obs_data_array_t *savedProjectorList,
  261. obs_data_array_t *savedPreviewProjectorList)
  262. {
  263. obs_data_t *saveData = obs_data_create();
  264. vector<OBSSource> audioSources;
  265. audioSources.reserve(5);
  266. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  267. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  268. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  269. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  270. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  271. auto FilterAudioSources = [&](obs_source_t *source)
  272. {
  273. return find(begin(audioSources), end(audioSources), source) ==
  274. end(audioSources);
  275. };
  276. using FilterAudioSources_t = decltype(FilterAudioSources);
  277. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  278. [](void *data, obs_source_t *source)
  279. {
  280. return (*static_cast<FilterAudioSources_t*>(data))(source);
  281. }, static_cast<void*>(&FilterAudioSources));
  282. obs_source_t *transition = obs_get_output_source(0);
  283. obs_source_t *currentScene = obs_scene_get_source(scene);
  284. const char *sceneName = obs_source_get_name(currentScene);
  285. const char *programName = obs_source_get_name(curProgramScene);
  286. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  287. "Basic", "SceneCollection");
  288. obs_data_set_string(saveData, "current_scene", sceneName);
  289. obs_data_set_string(saveData, "current_program_scene", programName);
  290. obs_data_set_array(saveData, "scene_order", sceneOrder);
  291. obs_data_set_string(saveData, "name", sceneCollection);
  292. obs_data_set_array(saveData, "sources", sourcesArray);
  293. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  294. obs_data_set_array(saveData, "transitions", transitions);
  295. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  296. obs_data_set_array(saveData, "saved_preview_projectors",
  297. savedPreviewProjectorList);
  298. obs_data_array_release(sourcesArray);
  299. obs_data_set_string(saveData, "current_transition",
  300. obs_source_get_name(transition));
  301. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  302. obs_source_release(transition);
  303. return saveData;
  304. }
  305. void OBSBasic::copyActionsDynamicProperties()
  306. {
  307. // Themes need the QAction dynamic properties
  308. for (QAction *x : ui->scenesToolbar->actions()) {
  309. QWidget* temp = ui->scenesToolbar->widgetForAction(x);
  310. for (QByteArray &y : x->dynamicPropertyNames()) {
  311. temp->setProperty(y, x->property(y));
  312. }
  313. }
  314. for (QAction *x : ui->sourcesToolbar->actions()) {
  315. QWidget* temp = ui->sourcesToolbar->widgetForAction(x);
  316. for (QByteArray &y : x->dynamicPropertyNames()) {
  317. temp->setProperty(y, x->property(y));
  318. }
  319. }
  320. }
  321. void OBSBasic::ClearVolumeControls()
  322. {
  323. VolControl *control;
  324. for (size_t i = 0; i < volumes.size(); i++) {
  325. control = volumes[i];
  326. delete control;
  327. }
  328. volumes.clear();
  329. }
  330. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  331. {
  332. obs_data_array_t *sceneOrder = obs_data_array_create();
  333. for (int i = 0; i < ui->scenes->count(); i++) {
  334. obs_data_t *data = obs_data_create();
  335. obs_data_set_string(data, "name",
  336. QT_TO_UTF8(ui->scenes->item(i)->text()));
  337. obs_data_array_push_back(sceneOrder, data);
  338. obs_data_release(data);
  339. }
  340. return sceneOrder;
  341. }
  342. obs_data_array_t *OBSBasic::SaveProjectors()
  343. {
  344. obs_data_array_t *saveProjector = obs_data_array_create();
  345. for (size_t i = 0; i < projectorArray.size(); i++) {
  346. obs_data_t *data = obs_data_create();
  347. obs_data_set_string(data, "saved_projectors",
  348. projectorArray.at(i).c_str());
  349. obs_data_array_push_back(saveProjector, data);
  350. obs_data_release(data);
  351. }
  352. return saveProjector;
  353. }
  354. obs_data_array_t *OBSBasic::SavePreviewProjectors()
  355. {
  356. obs_data_array_t *saveProjector = obs_data_array_create();
  357. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  358. obs_data_t *data = obs_data_create();
  359. obs_data_set_int(data, "saved_preview_projectors",
  360. previewProjectorArray.at(i));
  361. obs_data_array_push_back(saveProjector, data);
  362. obs_data_release(data);
  363. }
  364. return saveProjector;
  365. }
  366. void OBSBasic::Save(const char *file)
  367. {
  368. OBSScene scene = GetCurrentScene();
  369. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  370. if (!curProgramScene)
  371. curProgramScene = obs_scene_get_source(scene);
  372. obs_data_array_t *sceneOrder = SaveSceneListOrder();
  373. obs_data_array_t *transitions = SaveTransitions();
  374. obs_data_array_t *quickTrData = SaveQuickTransitions();
  375. obs_data_array_t *savedProjectorList = SaveProjectors();
  376. obs_data_array_t *savedPreviewProjectorList = SavePreviewProjectors();
  377. obs_data_t *saveData = GenerateSaveData(sceneOrder, quickTrData,
  378. ui->transitionDuration->value(), transitions,
  379. scene, curProgramScene, savedProjectorList,
  380. savedPreviewProjectorList);
  381. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  382. obs_data_set_bool(saveData, "scaling_enabled",
  383. ui->preview->IsFixedScaling());
  384. obs_data_set_int(saveData, "scaling_level",
  385. ui->preview->GetScalingLevel());
  386. obs_data_set_double(saveData, "scaling_off_x",
  387. ui->preview->GetScrollX());
  388. obs_data_set_double(saveData, "scaling_off_y",
  389. ui->preview->GetScrollY());
  390. if (api) {
  391. obs_data_t *moduleObj = obs_data_create();
  392. api->on_save(moduleObj);
  393. obs_data_set_obj(saveData, "modules", moduleObj);
  394. obs_data_release(moduleObj);
  395. }
  396. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  397. blog(LOG_ERROR, "Could not save scene data to %s", file);
  398. obs_data_release(saveData);
  399. obs_data_array_release(sceneOrder);
  400. obs_data_array_release(quickTrData);
  401. obs_data_array_release(transitions);
  402. obs_data_array_release(savedProjectorList);
  403. obs_data_array_release(savedPreviewProjectorList);
  404. }
  405. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  406. {
  407. obs_data_t *data = obs_data_get_obj(parent, name);
  408. if (!data)
  409. return;
  410. obs_source_t *source = obs_load_source(data);
  411. if (source) {
  412. obs_set_output_source(channel, source);
  413. obs_source_release(source);
  414. }
  415. obs_data_release(data);
  416. }
  417. static inline bool HasAudioDevices(const char *source_id)
  418. {
  419. const char *output_id = source_id;
  420. obs_properties_t *props = obs_get_source_properties(output_id);
  421. size_t count = 0;
  422. if (!props)
  423. return false;
  424. obs_property_t *devices = obs_properties_get(props, "device_id");
  425. if (devices)
  426. count = obs_property_list_item_count(devices);
  427. obs_properties_destroy(props);
  428. return count != 0;
  429. }
  430. void OBSBasic::CreateFirstRunSources()
  431. {
  432. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  433. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  434. if (hasDesktopAudio)
  435. ResetAudioDevice(App()->OutputAudioSource(), "default",
  436. Str("Basic.DesktopDevice1"), 1);
  437. if (hasInputAudio)
  438. ResetAudioDevice(App()->InputAudioSource(), "default",
  439. Str("Basic.AuxDevice1"), 3);
  440. }
  441. void OBSBasic::CreateDefaultScene(bool firstStart)
  442. {
  443. disableSaving++;
  444. ClearSceneData();
  445. InitDefaultTransitions();
  446. CreateDefaultQuickTransitions();
  447. ui->transitionDuration->setValue(300);
  448. SetTransition(fadeTransition);
  449. obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
  450. if (firstStart)
  451. CreateFirstRunSources();
  452. AddScene(obs_scene_get_source(scene));
  453. SetCurrentScene(scene, true);
  454. obs_scene_release(scene);
  455. disableSaving--;
  456. }
  457. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  458. {
  459. for (int i = 0; i < lw->count(); i++) {
  460. QListWidgetItem *item = lw->item(i);
  461. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  462. if (newIndex != i) {
  463. item = lw->takeItem(i);
  464. lw->insertItem(newIndex, item);
  465. }
  466. break;
  467. }
  468. }
  469. }
  470. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  471. {
  472. size_t num = obs_data_array_count(array);
  473. for (size_t i = 0; i < num; i++) {
  474. obs_data_t *data = obs_data_array_item(array, i);
  475. const char *name = obs_data_get_string(data, "name");
  476. ReorderItemByName(ui->scenes, name, (int)i);
  477. obs_data_release(data);
  478. }
  479. }
  480. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  481. {
  482. size_t num = obs_data_array_count(array);
  483. for (size_t i = 0; i < num; i++) {
  484. obs_data_t *data = obs_data_array_item(array, i);
  485. projectorArray.at(i) = obs_data_get_string(data,
  486. "saved_projectors");
  487. obs_data_release(data);
  488. }
  489. }
  490. void OBSBasic::LoadSavedPreviewProjectors(obs_data_array_t *array)
  491. {
  492. size_t num = obs_data_array_count(array);
  493. for (size_t i = 0; i < num; i++) {
  494. obs_data_t *data = obs_data_array_item(array, i);
  495. previewProjectorArray.at(i) = obs_data_get_int(data,
  496. "saved_preview_projectors");
  497. obs_data_release(data);
  498. }
  499. }
  500. static void LogFilter(obs_source_t*, obs_source_t *filter, void *v_val)
  501. {
  502. const char *name = obs_source_get_name(filter);
  503. const char *id = obs_source_get_id(filter);
  504. int val = (int)(intptr_t)v_val;
  505. string indent;
  506. for (int i = 0; i < val; i++)
  507. indent += " ";
  508. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  509. }
  510. static bool LogSceneItem(obs_scene_t*, obs_sceneitem_t *item, void*)
  511. {
  512. obs_source_t *source = obs_sceneitem_get_source(item);
  513. const char *name = obs_source_get_name(source);
  514. const char *id = obs_source_get_id(source);
  515. blog(LOG_INFO, " - source: '%s' (%s)", name, id);
  516. obs_monitoring_type monitoring_type =
  517. obs_source_get_monitoring_type(source);
  518. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  519. const char *type =
  520. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  521. ? "monitor only"
  522. : "monitor and output";
  523. blog(LOG_INFO, " - monitoring: %s", type);
  524. }
  525. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)2);
  526. return true;
  527. }
  528. void OBSBasic::LogScenes()
  529. {
  530. blog(LOG_INFO, "------------------------------------------------");
  531. blog(LOG_INFO, "Loaded scenes:");
  532. for (int i = 0; i < ui->scenes->count(); i++) {
  533. QListWidgetItem *item = ui->scenes->item(i);
  534. OBSScene scene = GetOBSRef<OBSScene>(item);
  535. obs_source_t *source = obs_scene_get_source(scene);
  536. const char *name = obs_source_get_name(source);
  537. blog(LOG_INFO, "- scene '%s':", name);
  538. obs_scene_enum_items(scene, LogSceneItem, nullptr);
  539. obs_source_enum_filters(source, LogFilter, (void*)(intptr_t)1);
  540. }
  541. blog(LOG_INFO, "------------------------------------------------");
  542. }
  543. void OBSBasic::Load(const char *file)
  544. {
  545. disableSaving++;
  546. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  547. if (!data) {
  548. disableSaving--;
  549. blog(LOG_INFO, "No scene file found, creating default scene");
  550. CreateDefaultScene(true);
  551. SaveProject();
  552. return;
  553. }
  554. ClearSceneData();
  555. InitDefaultTransitions();
  556. obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
  557. obs_data_array_t *sources = obs_data_get_array(data, "sources");
  558. obs_data_array_t *transitions= obs_data_get_array(data, "transitions");
  559. const char *sceneName = obs_data_get_string(data,
  560. "current_scene");
  561. const char *programSceneName = obs_data_get_string(data,
  562. "current_program_scene");
  563. const char *transitionName = obs_data_get_string(data,
  564. "current_transition");
  565. if (!opt_starting_scene.empty()) {
  566. programSceneName = opt_starting_scene.c_str();
  567. if (!IsPreviewProgramMode())
  568. sceneName = opt_starting_scene.c_str();
  569. }
  570. int newDuration = obs_data_get_int(data, "transition_duration");
  571. if (!newDuration)
  572. newDuration = 300;
  573. if (!transitionName)
  574. transitionName = obs_source_get_name(fadeTransition);
  575. const char *curSceneCollection = config_get_string(
  576. App()->GlobalConfig(), "Basic", "SceneCollection");
  577. obs_data_set_default_string(data, "name", curSceneCollection);
  578. const char *name = obs_data_get_string(data, "name");
  579. obs_source_t *curScene;
  580. obs_source_t *curProgramScene;
  581. obs_source_t *curTransition;
  582. if (!name || !*name)
  583. name = curSceneCollection;
  584. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  585. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  586. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  587. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  588. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  589. obs_load_sources(sources, OBSBasic::SourceLoaded, this);
  590. if (transitions)
  591. LoadTransitions(transitions);
  592. if (sceneOrder)
  593. LoadSceneListOrder(sceneOrder);
  594. obs_data_array_release(transitions);
  595. curTransition = FindTransition(transitionName);
  596. if (!curTransition)
  597. curTransition = fadeTransition;
  598. ui->transitionDuration->setValue(newDuration);
  599. SetTransition(curTransition);
  600. obs_data_array_t *savedProjectors = obs_data_get_array(data,
  601. "saved_projectors");
  602. if (savedProjectors)
  603. LoadSavedProjectors(savedProjectors);
  604. obs_data_array_release(savedProjectors);
  605. obs_data_array_t *savedPreviewProjectors = obs_data_get_array(data,
  606. "saved_preview_projectors");
  607. if (savedPreviewProjectors)
  608. LoadSavedPreviewProjectors(savedPreviewProjectors);
  609. obs_data_array_release(savedPreviewProjectors);
  610. retryScene:
  611. curScene = obs_get_source_by_name(sceneName);
  612. curProgramScene = obs_get_source_by_name(programSceneName);
  613. /* if the starting scene command line parameter is bad at all,
  614. * fall back to original settings */
  615. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  616. sceneName = obs_data_get_string(data, "current_scene");
  617. programSceneName = obs_data_get_string(data,
  618. "current_program_scene");
  619. obs_source_release(curScene);
  620. obs_source_release(curProgramScene);
  621. opt_starting_scene.clear();
  622. goto retryScene;
  623. }
  624. if (!curProgramScene) {
  625. curProgramScene = curScene;
  626. obs_source_addref(curScene);
  627. }
  628. SetCurrentScene(curScene, true);
  629. if (IsPreviewProgramMode())
  630. TransitionToScene(curProgramScene, true);
  631. obs_source_release(curScene);
  632. obs_source_release(curProgramScene);
  633. obs_data_array_release(sources);
  634. obs_data_array_release(sceneOrder);
  635. std::string file_base = strrchr(file, '/') + 1;
  636. file_base.erase(file_base.size() - 5, 5);
  637. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  638. name);
  639. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  640. file_base.c_str());
  641. obs_data_array_t *quickTransitionData = obs_data_get_array(data,
  642. "quick_transitions");
  643. LoadQuickTransitions(quickTransitionData);
  644. obs_data_array_release(quickTransitionData);
  645. RefreshQuickTransitions();
  646. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  647. ui->preview->SetLocked(previewLocked);
  648. ui->actionLockPreview->setChecked(previewLocked);
  649. /* ---------------------- */
  650. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  651. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  652. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  653. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  654. if (fixedScaling) {
  655. ui->preview->SetScalingLevel(scalingLevel);
  656. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  657. }
  658. ui->preview->SetFixedScaling(fixedScaling);
  659. /* ---------------------- */
  660. if (api) {
  661. obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
  662. api->on_load(modulesObj);
  663. obs_data_release(modulesObj);
  664. }
  665. obs_data_release(data);
  666. if (!opt_starting_scene.empty())
  667. opt_starting_scene.clear();
  668. if (opt_start_streaming) {
  669. QMetaObject::invokeMethod(this, "StartStreaming",
  670. Qt::QueuedConnection);
  671. opt_start_streaming = false;
  672. }
  673. if (opt_start_recording) {
  674. QMetaObject::invokeMethod(this, "StartRecording",
  675. Qt::QueuedConnection);
  676. opt_start_recording = false;
  677. }
  678. if (opt_start_replaybuffer) {
  679. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  680. Qt::QueuedConnection);
  681. opt_start_replaybuffer = false;
  682. }
  683. LogScenes();
  684. disableSaving--;
  685. }
  686. #define SERVICE_PATH "service.json"
  687. void OBSBasic::SaveService()
  688. {
  689. if (!service)
  690. return;
  691. char serviceJsonPath[512];
  692. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  693. SERVICE_PATH);
  694. if (ret <= 0)
  695. return;
  696. obs_data_t *data = obs_data_create();
  697. obs_data_t *settings = obs_service_get_settings(service);
  698. obs_data_set_string(data, "type", obs_service_get_type(service));
  699. obs_data_set_obj(data, "settings", settings);
  700. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  701. blog(LOG_WARNING, "Failed to save service");
  702. obs_data_release(settings);
  703. obs_data_release(data);
  704. }
  705. bool OBSBasic::LoadService()
  706. {
  707. const char *type;
  708. char serviceJsonPath[512];
  709. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  710. SERVICE_PATH);
  711. if (ret <= 0)
  712. return false;
  713. obs_data_t *data = obs_data_create_from_json_file_safe(serviceJsonPath,
  714. "bak");
  715. obs_data_set_default_string(data, "type", "rtmp_common");
  716. type = obs_data_get_string(data, "type");
  717. obs_data_t *settings = obs_data_get_obj(data, "settings");
  718. obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
  719. service = obs_service_create(type, "default_service", settings,
  720. hotkey_data);
  721. obs_service_release(service);
  722. obs_data_release(hotkey_data);
  723. obs_data_release(settings);
  724. obs_data_release(data);
  725. return !!service;
  726. }
  727. bool OBSBasic::InitService()
  728. {
  729. ProfileScope("OBSBasic::InitService");
  730. if (LoadService())
  731. return true;
  732. service = obs_service_create("rtmp_common", "default_service", nullptr,
  733. nullptr);
  734. if (!service)
  735. return false;
  736. obs_service_release(service);
  737. return true;
  738. }
  739. static const double scaled_vals[] =
  740. {
  741. 1.0,
  742. 1.25,
  743. (1.0/0.75),
  744. 1.5,
  745. (1.0/0.6),
  746. 1.75,
  747. 2.0,
  748. 2.25,
  749. 2.5,
  750. 2.75,
  751. 3.0,
  752. 0.0
  753. };
  754. bool OBSBasic::InitBasicConfigDefaults()
  755. {
  756. QList<QScreen*> screens = QGuiApplication::screens();
  757. if (!screens.size()) {
  758. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  759. "technically shouldn't be possible.");
  760. return false;
  761. }
  762. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  763. uint32_t cx = primaryScreen->size().width();
  764. uint32_t cy = primaryScreen->size().height();
  765. bool oldResolutionDefaults = config_get_bool(App()->GlobalConfig(),
  766. "General", "Pre19Defaults");
  767. /* use 1920x1080 for new default base res if main monitor is above
  768. * 1920x1080, but don't apply for people from older builds -- only to
  769. * new users */
  770. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  771. cx = 1920;
  772. cy = 1080;
  773. }
  774. /* ----------------------------------------------------- */
  775. /* move over mixer values in advanced if older config */
  776. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  777. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  778. uint64_t track = config_get_uint(basicConfig, "AdvOut",
  779. "RecTrackIndex");
  780. track = 1ULL << (track - 1);
  781. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  782. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  783. config_save_safe(basicConfig, "tmp", nullptr);
  784. }
  785. /* ----------------------------------------------------- */
  786. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  787. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  788. GetDefaultVideoSavePath().c_str());
  789. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
  790. "flv");
  791. config_set_default_uint (basicConfig, "SimpleOutput", "VBitrate",
  792. 2500);
  793. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  794. SIMPLE_ENCODER_X264);
  795. config_set_default_uint (basicConfig, "SimpleOutput", "ABitrate", 160);
  796. config_set_default_bool (basicConfig, "SimpleOutput", "UseAdvanced",
  797. false);
  798. config_set_default_bool (basicConfig, "SimpleOutput", "EnforceBitrate",
  799. true);
  800. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  801. "veryfast");
  802. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  803. "Stream");
  804. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  805. SIMPLE_ENCODER_X264);
  806. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  807. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  808. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  809. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  810. "Replay");
  811. config_set_default_bool (basicConfig, "AdvOut", "ApplyServiceSettings",
  812. true);
  813. config_set_default_bool (basicConfig, "AdvOut", "UseRescale", false);
  814. config_set_default_uint (basicConfig, "AdvOut", "TrackIndex", 1);
  815. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  816. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  817. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  818. GetDefaultVideoSavePath().c_str());
  819. config_set_default_string(basicConfig, "AdvOut", "RecFormat", "flv");
  820. config_set_default_bool (basicConfig, "AdvOut", "RecUseRescale",
  821. false);
  822. config_set_default_uint (basicConfig, "AdvOut", "RecTracks", (1<<0));
  823. config_set_default_string(basicConfig, "AdvOut", "RecEncoder",
  824. "none");
  825. config_set_default_bool (basicConfig, "AdvOut", "FFOutputToFile",
  826. true);
  827. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  828. GetDefaultVideoSavePath().c_str());
  829. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  830. config_set_default_uint (basicConfig, "AdvOut", "FFVBitrate", 2500);
  831. config_set_default_uint (basicConfig, "AdvOut", "FFVGOPSize", 250);
  832. config_set_default_bool (basicConfig, "AdvOut", "FFUseRescale",
  833. false);
  834. config_set_default_bool (basicConfig, "AdvOut", "FFIgnoreCompat",
  835. false);
  836. config_set_default_uint (basicConfig, "AdvOut", "FFABitrate", 160);
  837. config_set_default_uint (basicConfig, "AdvOut", "FFAudioTrack", 1);
  838. config_set_default_uint (basicConfig, "AdvOut", "Track1Bitrate", 160);
  839. config_set_default_uint (basicConfig, "AdvOut", "Track2Bitrate", 160);
  840. config_set_default_uint (basicConfig, "AdvOut", "Track3Bitrate", 160);
  841. config_set_default_uint (basicConfig, "AdvOut", "Track4Bitrate", 160);
  842. config_set_default_uint (basicConfig, "AdvOut", "Track5Bitrate", 160);
  843. config_set_default_uint (basicConfig, "AdvOut", "Track6Bitrate", 160);
  844. config_set_default_bool (basicConfig, "AdvOut", "RecRB", false);
  845. config_set_default_uint (basicConfig, "AdvOut", "RecRBTime", 20);
  846. config_set_default_int (basicConfig, "AdvOut", "RecRBSize", 512);
  847. config_set_default_uint (basicConfig, "Video", "BaseCX", cx);
  848. config_set_default_uint (basicConfig, "Video", "BaseCY", cy);
  849. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  850. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  851. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  852. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  853. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  854. config_save_safe(basicConfig, "tmp", nullptr);
  855. }
  856. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  857. "%CCYY-%MM-%DD %hh-%mm-%ss");
  858. config_set_default_bool (basicConfig, "Output", "DelayEnable", false);
  859. config_set_default_uint (basicConfig, "Output", "DelaySec", 20);
  860. config_set_default_bool (basicConfig, "Output", "DelayPreserve", true);
  861. config_set_default_bool (basicConfig, "Output", "Reconnect", true);
  862. config_set_default_uint (basicConfig, "Output", "RetryDelay", 10);
  863. config_set_default_uint (basicConfig, "Output", "MaxRetries", 20);
  864. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  865. config_set_default_bool (basicConfig, "Output", "NewSocketLoopEnable",
  866. false);
  867. config_set_default_bool (basicConfig, "Output", "LowLatencyEnable",
  868. false);
  869. int i = 0;
  870. uint32_t scale_cx = cx;
  871. uint32_t scale_cy = cy;
  872. /* use a default scaled resolution that has a pixel count no higher
  873. * than 1280x720 */
  874. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  875. double scale = scaled_vals[i++];
  876. scale_cx = uint32_t(double(cx) / scale);
  877. scale_cy = uint32_t(double(cy) / scale);
  878. }
  879. config_set_default_uint (basicConfig, "Video", "OutputCX", scale_cx);
  880. config_set_default_uint (basicConfig, "Video", "OutputCY", scale_cy);
  881. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  882. * changing */
  883. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  884. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  885. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  886. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  887. config_save_safe(basicConfig, "tmp", nullptr);
  888. }
  889. config_set_default_uint (basicConfig, "Video", "FPSType", 0);
  890. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  891. config_set_default_uint (basicConfig, "Video", "FPSInt", 30);
  892. config_set_default_uint (basicConfig, "Video", "FPSNum", 30);
  893. config_set_default_uint (basicConfig, "Video", "FPSDen", 1);
  894. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  895. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  896. config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
  897. config_set_default_string(basicConfig, "Video", "ColorRange",
  898. "Partial");
  899. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  900. "default");
  901. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceName",
  902. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  903. ".Default"));
  904. config_set_default_uint (basicConfig, "Audio", "SampleRate", 44100);
  905. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  906. "Stereo");
  907. return true;
  908. }
  909. bool OBSBasic::InitBasicConfig()
  910. {
  911. ProfileScope("OBSBasic::InitBasicConfig");
  912. char configPath[512];
  913. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  914. if (ret <= 0) {
  915. OBSErrorBox(nullptr, "Failed to get profile path");
  916. return false;
  917. }
  918. if (os_mkdir(configPath) == MKDIR_ERROR) {
  919. OBSErrorBox(nullptr, "Failed to create profile path");
  920. return false;
  921. }
  922. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  923. if (ret <= 0) {
  924. OBSErrorBox(nullptr, "Failed to get base.ini path");
  925. return false;
  926. }
  927. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  928. if (code != CONFIG_SUCCESS) {
  929. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  930. return false;
  931. }
  932. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  933. const char *curName = config_get_string(App()->GlobalConfig(),
  934. "Basic", "Profile");
  935. config_set_string(basicConfig, "General", "Name", curName);
  936. basicConfig.SaveSafe("tmp");
  937. }
  938. return InitBasicConfigDefaults();
  939. }
  940. void OBSBasic::InitOBSCallbacks()
  941. {
  942. ProfileScope("OBSBasic::InitOBSCallbacks");
  943. signalHandlers.reserve(signalHandlers.size() + 6);
  944. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  945. OBSBasic::SourceRemoved, this);
  946. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  947. OBSBasic::SourceActivated, this);
  948. signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate",
  949. OBSBasic::SourceDeactivated, this);
  950. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  951. OBSBasic::SourceRenamed, this);
  952. }
  953. void OBSBasic::InitPrimitives()
  954. {
  955. ProfileScope("OBSBasic::InitPrimitives");
  956. obs_enter_graphics();
  957. gs_render_start(true);
  958. gs_vertex2f(0.0f, 0.0f);
  959. gs_vertex2f(0.0f, 1.0f);
  960. gs_vertex2f(1.0f, 1.0f);
  961. gs_vertex2f(1.0f, 0.0f);
  962. gs_vertex2f(0.0f, 0.0f);
  963. box = gs_render_save();
  964. gs_render_start(true);
  965. gs_vertex2f(0.0f, 0.0f);
  966. gs_vertex2f(0.0f, 1.0f);
  967. boxLeft = gs_render_save();
  968. gs_render_start(true);
  969. gs_vertex2f(0.0f, 0.0f);
  970. gs_vertex2f(1.0f, 0.0f);
  971. boxTop = gs_render_save();
  972. gs_render_start(true);
  973. gs_vertex2f(1.0f, 0.0f);
  974. gs_vertex2f(1.0f, 1.0f);
  975. boxRight = gs_render_save();
  976. gs_render_start(true);
  977. gs_vertex2f(0.0f, 1.0f);
  978. gs_vertex2f(1.0f, 1.0f);
  979. boxBottom = gs_render_save();
  980. gs_render_start(true);
  981. for (int i = 0; i <= 360; i += (360/20)) {
  982. float pos = RAD(float(i));
  983. gs_vertex2f(cosf(pos), sinf(pos));
  984. }
  985. circle = gs_render_save();
  986. obs_leave_graphics();
  987. }
  988. void OBSBasic::ReplayBufferClicked()
  989. {
  990. if (outputHandler->ReplayBufferActive())
  991. StopReplayBuffer();
  992. else
  993. StartReplayBuffer();
  994. };
  995. void OBSBasic::ResetOutputs()
  996. {
  997. ProfileScope("OBSBasic::ResetOutputs");
  998. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  999. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1000. if (!outputHandler || !outputHandler->Active()) {
  1001. outputHandler.reset();
  1002. outputHandler.reset(advOut ?
  1003. CreateAdvancedOutputHandler(this) :
  1004. CreateSimpleOutputHandler(this));
  1005. delete replayBufferButton;
  1006. if (outputHandler->replayBuffer) {
  1007. replayBufferButton = new QPushButton(
  1008. QTStr("Basic.Main.StartReplayBuffer"),
  1009. this);
  1010. connect(replayBufferButton.data(),
  1011. &QPushButton::clicked,
  1012. this,
  1013. &OBSBasic::ReplayBufferClicked);
  1014. replayBufferButton->setProperty("themeID", "replayBufferButton");
  1015. ui->buttonsVLayout->insertWidget(2, replayBufferButton);
  1016. }
  1017. if (sysTrayReplayBuffer)
  1018. sysTrayReplayBuffer->setEnabled(
  1019. !!outputHandler->replayBuffer);
  1020. } else {
  1021. outputHandler->Update();
  1022. }
  1023. }
  1024. #define STARTUP_SEPARATOR \
  1025. "==== Startup complete ==============================================="
  1026. #define SHUTDOWN_SEPARATOR \
  1027. "==== Shutting down =================================================="
  1028. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  1029. #define UNSUPPORTED_ERROR \
  1030. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1031. "not found. Your GPU may not be supported."
  1032. #define UNKNOWN_ERROR \
  1033. "Failed to initialize video. Your GPU may not be supported, " \
  1034. "or your graphics drivers may need to be updated."
  1035. void OBSBasic::OBSInit()
  1036. {
  1037. ProfileScope("OBSBasic::OBSInit");
  1038. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1039. "Basic", "SceneCollectionFile");
  1040. char savePath[512];
  1041. char fileName[512];
  1042. int ret;
  1043. if (!sceneCollection)
  1044. throw "Failed to get scene collection name";
  1045. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1046. sceneCollection);
  1047. if (ret <= 0)
  1048. throw "Failed to create scene collection file name";
  1049. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1050. if (ret <= 0)
  1051. throw "Failed to get scene collection json file path";
  1052. if (!InitBasicConfig())
  1053. throw "Failed to load basic.ini";
  1054. if (!ResetAudio())
  1055. throw "Failed to initialize audio";
  1056. ret = ResetVideo();
  1057. switch (ret) {
  1058. case OBS_VIDEO_MODULE_NOT_FOUND:
  1059. throw "Failed to initialize video: Graphics module not found";
  1060. case OBS_VIDEO_NOT_SUPPORTED:
  1061. throw UNSUPPORTED_ERROR;
  1062. case OBS_VIDEO_INVALID_PARAM:
  1063. throw "Failed to initialize video: Invalid parameters";
  1064. default:
  1065. if (ret != OBS_VIDEO_SUCCESS)
  1066. throw UNKNOWN_ERROR;
  1067. }
  1068. /* load audio monitoring */
  1069. #if defined(_WIN32) || defined(__APPLE__)
  1070. const char *device_name = config_get_string(basicConfig, "Audio",
  1071. "MonitoringDeviceName");
  1072. const char *device_id = config_get_string(basicConfig, "Audio",
  1073. "MonitoringDeviceId");
  1074. obs_set_audio_monitoring_device(device_name, device_id);
  1075. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1076. device_name, device_id);
  1077. #endif
  1078. InitOBSCallbacks();
  1079. InitHotkeys();
  1080. api = InitializeAPIInterface(this);
  1081. AddExtraModulePaths();
  1082. blog(LOG_INFO, "---------------------------------");
  1083. obs_load_all_modules();
  1084. blog(LOG_INFO, "---------------------------------");
  1085. obs_log_loaded_modules();
  1086. blog(LOG_INFO, "---------------------------------");
  1087. obs_post_load_modules();
  1088. blog(LOG_INFO, STARTUP_SEPARATOR);
  1089. ResetOutputs();
  1090. CreateHotkeys();
  1091. if (!InitService())
  1092. throw "Failed to initialize service";
  1093. InitPrimitives();
  1094. sceneDuplicationMode = config_get_bool(App()->GlobalConfig(),
  1095. "BasicWindow", "SceneDuplicationMode");
  1096. swapScenesMode = config_get_bool(App()->GlobalConfig(),
  1097. "BasicWindow", "SwapScenesMode");
  1098. editPropertiesMode = config_get_bool(App()->GlobalConfig(),
  1099. "BasicWindow", "EditPropertiesMode");
  1100. if (!opt_studio_mode) {
  1101. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1102. "BasicWindow", "PreviewProgramMode"));
  1103. } else {
  1104. SetPreviewProgramMode(true);
  1105. opt_studio_mode = false;
  1106. }
  1107. #define SET_VISIBILITY(name, control) \
  1108. do { \
  1109. if (config_has_user_value(App()->GlobalConfig(), \
  1110. "BasicWindow", name)) { \
  1111. bool visible = config_get_bool(App()->GlobalConfig(), \
  1112. "BasicWindow", name); \
  1113. ui->control->setChecked(visible); \
  1114. } \
  1115. } while (false)
  1116. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1117. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1118. #undef SET_VISIBILITY
  1119. {
  1120. ProfileScope("OBSBasic::Load");
  1121. disableSaving--;
  1122. Load(savePath);
  1123. disableSaving++;
  1124. }
  1125. TimedCheckForUpdates();
  1126. loaded = true;
  1127. previewEnabled = config_get_bool(App()->GlobalConfig(),
  1128. "BasicWindow", "PreviewEnabled");
  1129. if (!previewEnabled && !IsPreviewProgramMode())
  1130. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1131. Qt::QueuedConnection,
  1132. Q_ARG(bool, previewEnabled));
  1133. #ifdef _WIN32
  1134. uint32_t winVer = GetWindowsVersion();
  1135. if (winVer > 0 && winVer < 0x602) {
  1136. bool disableAero = config_get_bool(basicConfig, "Video",
  1137. "DisableAero");
  1138. SetAeroEnabled(!disableAero);
  1139. }
  1140. #endif
  1141. RefreshSceneCollections();
  1142. RefreshProfiles();
  1143. disableSaving--;
  1144. auto addDisplay = [this] (OBSQTDisplay *window)
  1145. {
  1146. obs_display_add_draw_callback(window->GetDisplay(),
  1147. OBSBasic::RenderMain, this);
  1148. struct obs_video_info ovi;
  1149. if (obs_get_video_info(&ovi))
  1150. ResizePreview(ovi.base_width, ovi.base_height);
  1151. };
  1152. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1153. #ifdef _WIN32
  1154. SetWin32DropStyle(this);
  1155. show();
  1156. #endif
  1157. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1158. "AlwaysOnTop");
  1159. if (alwaysOnTop || opt_always_on_top) {
  1160. SetAlwaysOnTop(this, true);
  1161. ui->actionAlwaysOnTop->setChecked(true);
  1162. }
  1163. #ifndef _WIN32
  1164. show();
  1165. #endif
  1166. const char *dockStateStr = config_get_string(App()->GlobalConfig(),
  1167. "BasicWindow", "DockState");
  1168. if (!dockStateStr) {
  1169. on_resetUI_triggered();
  1170. } else {
  1171. QByteArray dockState =
  1172. QByteArray::fromBase64(QByteArray(dockStateStr));
  1173. if (!restoreState(dockState))
  1174. on_resetUI_triggered();
  1175. }
  1176. config_set_default_bool(App()->GlobalConfig(), "BasicWindow",
  1177. "DocksLocked", true);
  1178. bool docksLocked = config_get_bool(App()->GlobalConfig(),
  1179. "BasicWindow", "DocksLocked");
  1180. on_lockUI_toggled(docksLocked);
  1181. ui->lockUI->blockSignals(true);
  1182. ui->lockUI->setChecked(docksLocked);
  1183. ui->lockUI->blockSignals(false);
  1184. SystemTray(true);
  1185. OpenSavedProjectors();
  1186. if (windowState().testFlag(Qt::WindowFullScreen))
  1187. fullscreenInterface = true;
  1188. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1189. "General", "LastVersion");
  1190. bool first_run = config_get_bool(App()->GlobalConfig(), "General",
  1191. "FirstRun");
  1192. if (!first_run) {
  1193. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1194. true);
  1195. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1196. }
  1197. if (!first_run && !has_last_version && !Active()) {
  1198. QString msg;
  1199. msg = QTStr("Basic.FirstStartup.RunWizard");
  1200. msg += "\n\n";
  1201. msg += QTStr("Basic.FirstStartup.RunWizard.BetaWarning");
  1202. QMessageBox::StandardButton button =
  1203. OBSMessageBox::question(this, QTStr("Basic.AutoConfig"),
  1204. msg);
  1205. if (button == QMessageBox::Yes) {
  1206. on_autoConfigure_triggered();
  1207. } else {
  1208. msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
  1209. OBSMessageBox::information(this,
  1210. QTStr("Basic.AutoConfig"), msg);
  1211. }
  1212. }
  1213. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1214. on_stats_triggered();
  1215. OBSBasicStats::InitializeValues();
  1216. }
  1217. void OBSBasic::InitHotkeys()
  1218. {
  1219. ProfileScope("OBSBasic::InitHotkeys");
  1220. struct obs_hotkeys_translations t = {};
  1221. t.insert = Str("Hotkeys.Insert");
  1222. t.del = Str("Hotkeys.Delete");
  1223. t.home = Str("Hotkeys.Home");
  1224. t.end = Str("Hotkeys.End");
  1225. t.page_up = Str("Hotkeys.PageUp");
  1226. t.page_down = Str("Hotkeys.PageDown");
  1227. t.num_lock = Str("Hotkeys.NumLock");
  1228. t.scroll_lock = Str("Hotkeys.ScrollLock");
  1229. t.caps_lock = Str("Hotkeys.CapsLock");
  1230. t.backspace = Str("Hotkeys.Backspace");
  1231. t.tab = Str("Hotkeys.Tab");
  1232. t.print = Str("Hotkeys.Print");
  1233. t.pause = Str("Hotkeys.Pause");
  1234. t.left = Str("Hotkeys.Left");
  1235. t.right = Str("Hotkeys.Right");
  1236. t.up = Str("Hotkeys.Up");
  1237. t.down = Str("Hotkeys.Down");
  1238. #ifdef _WIN32
  1239. t.meta = Str("Hotkeys.Windows");
  1240. #else
  1241. t.meta = Str("Hotkeys.Super");
  1242. #endif
  1243. t.menu = Str("Hotkeys.Menu");
  1244. t.space = Str("Hotkeys.Space");
  1245. t.numpad_num = Str("Hotkeys.NumpadNum");
  1246. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  1247. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  1248. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  1249. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  1250. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  1251. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  1252. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  1253. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  1254. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  1255. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  1256. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  1257. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  1258. t.mouse_num = Str("Hotkeys.MouseButton");
  1259. obs_hotkeys_set_translations(&t);
  1260. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  1261. Str("Push-to-mute"), Str("Push-to-talk"));
  1262. obs_hotkeys_set_sceneitem_hotkeys_translations(
  1263. Str("SceneItemShow"), Str("SceneItemHide"));
  1264. obs_hotkey_enable_callback_rerouting(true);
  1265. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  1266. }
  1267. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  1268. {
  1269. obs_hotkey_trigger_routed_callback(id, pressed);
  1270. }
  1271. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  1272. {
  1273. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1274. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  1275. Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed));
  1276. }
  1277. void OBSBasic::CreateHotkeys()
  1278. {
  1279. ProfileScope("OBSBasic::CreateHotkeys");
  1280. auto LoadHotkeyData = [&](const char *name) -> OBSData
  1281. {
  1282. const char *info = config_get_string(basicConfig,
  1283. "Hotkeys", name);
  1284. if (!info)
  1285. return {};
  1286. obs_data_t *data = obs_data_create_from_json(info);
  1287. if (!data)
  1288. return {};
  1289. OBSData res = data;
  1290. obs_data_release(data);
  1291. return res;
  1292. };
  1293. auto LoadHotkey = [&](obs_hotkey_id id, const char *name)
  1294. {
  1295. obs_data_array_t *array =
  1296. obs_data_get_array(LoadHotkeyData(name), "bindings");
  1297. obs_hotkey_load(id, array);
  1298. obs_data_array_release(array);
  1299. };
  1300. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  1301. const char *name1)
  1302. {
  1303. obs_data_array_t *array0 =
  1304. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  1305. obs_data_array_t *array1 =
  1306. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  1307. obs_hotkey_pair_load(id, array0, array1);
  1308. obs_data_array_release(array0);
  1309. obs_data_array_release(array1);
  1310. };
  1311. #define MAKE_CALLBACK(pred, method) \
  1312. [](void *data, obs_hotkey_pair_id, obs_hotkey_t*, bool pressed) \
  1313. { \
  1314. OBSBasic &basic = *static_cast<OBSBasic*>(data); \
  1315. if (pred && pressed) { \
  1316. method(); \
  1317. return true; \
  1318. } \
  1319. return false; \
  1320. }
  1321. streamingHotkeys = obs_hotkey_pair_register_frontend(
  1322. "OBSBasic.StartStreaming",
  1323. Str("Basic.Main.StartStreaming"),
  1324. "OBSBasic.StopStreaming",
  1325. Str("Basic.Main.StopStreaming"),
  1326. MAKE_CALLBACK(!basic.outputHandler->StreamingActive(),
  1327. basic.StartStreaming),
  1328. MAKE_CALLBACK(basic.outputHandler->StreamingActive(),
  1329. basic.StopStreaming),
  1330. this, this);
  1331. LoadHotkeyPair(streamingHotkeys,
  1332. "OBSBasic.StartStreaming", "OBSBasic.StopStreaming");
  1333. auto cb = [] (void *data, obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1334. {
  1335. OBSBasic &basic = *static_cast<OBSBasic*>(data);
  1336. if (basic.outputHandler->StreamingActive() && pressed) {
  1337. basic.ForceStopStreaming();
  1338. }
  1339. };
  1340. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  1341. "OBSBasic.ForceStopStreaming",
  1342. Str("Basic.Main.ForceStopStreaming"),
  1343. cb, this);
  1344. LoadHotkey(forceStreamingStopHotkey,
  1345. "OBSBasic.ForceStopStreaming");
  1346. recordingHotkeys = obs_hotkey_pair_register_frontend(
  1347. "OBSBasic.StartRecording",
  1348. Str("Basic.Main.StartRecording"),
  1349. "OBSBasic.StopRecording",
  1350. Str("Basic.Main.StopRecording"),
  1351. MAKE_CALLBACK(!basic.outputHandler->RecordingActive(),
  1352. basic.StartRecording),
  1353. MAKE_CALLBACK(basic.outputHandler->RecordingActive(),
  1354. basic.StopRecording),
  1355. this, this);
  1356. LoadHotkeyPair(recordingHotkeys,
  1357. "OBSBasic.StartRecording", "OBSBasic.StopRecording");
  1358. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  1359. "OBSBasic.StartReplayBuffer",
  1360. Str("Basic.Main.StartReplayBuffer"),
  1361. "OBSBasic.StopReplayBuffer",
  1362. Str("Basic.Main.StopReplayBuffer"),
  1363. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  1364. basic.StartReplayBuffer),
  1365. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  1366. basic.StopReplayBuffer),
  1367. this, this);
  1368. LoadHotkeyPair(replayBufHotkeys,
  1369. "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer");
  1370. #undef MAKE_CALLBACK
  1371. auto togglePreviewProgram = [] (void *data, obs_hotkey_id,
  1372. obs_hotkey_t*, bool pressed)
  1373. {
  1374. if (pressed)
  1375. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1376. "on_modeSwitch_clicked",
  1377. Qt::QueuedConnection);
  1378. };
  1379. togglePreviewProgramHotkey = obs_hotkey_register_frontend(
  1380. "OBSBasic.TogglePreviewProgram",
  1381. Str("Basic.TogglePreviewProgramMode"),
  1382. togglePreviewProgram, this);
  1383. LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");
  1384. auto transition = [] (void *data, obs_hotkey_id, obs_hotkey_t*,
  1385. bool pressed)
  1386. {
  1387. if (pressed)
  1388. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  1389. "TransitionClicked",
  1390. Qt::QueuedConnection);
  1391. };
  1392. transitionHotkey = obs_hotkey_register_frontend(
  1393. "OBSBasic.Transition",
  1394. Str("Transition"), transition, this);
  1395. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  1396. }
  1397. void OBSBasic::ClearHotkeys()
  1398. {
  1399. obs_hotkey_pair_unregister(streamingHotkeys);
  1400. obs_hotkey_pair_unregister(recordingHotkeys);
  1401. obs_hotkey_pair_unregister(replayBufHotkeys);
  1402. obs_hotkey_unregister(forceStreamingStopHotkey);
  1403. obs_hotkey_unregister(togglePreviewProgramHotkey);
  1404. obs_hotkey_unregister(transitionHotkey);
  1405. }
  1406. OBSBasic::~OBSBasic()
  1407. {
  1408. if (updateCheckThread && updateCheckThread->isRunning())
  1409. updateCheckThread->wait();
  1410. delete programOptions;
  1411. delete program;
  1412. /* XXX: any obs data must be released before calling obs_shutdown.
  1413. * currently, we can't automate this with C++ RAII because of the
  1414. * delicate nature of obs_shutdown needing to be freed before the UI
  1415. * can be freed, and we have no control over the destruction order of
  1416. * the Qt UI stuff, so we have to manually clear any references to
  1417. * libobs. */
  1418. delete cpuUsageTimer;
  1419. os_cpu_usage_info_destroy(cpuUsageInfo);
  1420. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  1421. ClearHotkeys();
  1422. service = nullptr;
  1423. outputHandler.reset();
  1424. if (interaction)
  1425. delete interaction;
  1426. if (properties)
  1427. delete properties;
  1428. if (filters)
  1429. delete filters;
  1430. if (transformWindow)
  1431. delete transformWindow;
  1432. if (advAudioWindow)
  1433. delete advAudioWindow;
  1434. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  1435. OBSBasic::RenderMain, this);
  1436. obs_enter_graphics();
  1437. gs_vertexbuffer_destroy(box);
  1438. gs_vertexbuffer_destroy(boxLeft);
  1439. gs_vertexbuffer_destroy(boxTop);
  1440. gs_vertexbuffer_destroy(boxRight);
  1441. gs_vertexbuffer_destroy(boxBottom);
  1442. gs_vertexbuffer_destroy(circle);
  1443. obs_leave_graphics();
  1444. /* When shutting down, sometimes source references can get in to the
  1445. * event queue, and if we don't forcibly process those events they
  1446. * won't get processed until after obs_shutdown has been called. I
  1447. * really wish there were a more elegant way to deal with this via C++,
  1448. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  1449. * normal C++ behavior for your data to be freed in the order that you
  1450. * expect or want it to. */
  1451. QApplication::sendPostedEvents(this);
  1452. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  1453. LIBOBS_API_VER);
  1454. bool alwaysOnTop = IsAlwaysOnTop(this);
  1455. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  1456. previewEnabled);
  1457. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  1458. alwaysOnTop);
  1459. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1460. "SceneDuplicationMode", sceneDuplicationMode);
  1461. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1462. "SwapScenesMode", swapScenesMode);
  1463. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1464. "EditPropertiesMode", editPropertiesMode);
  1465. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1466. "PreviewProgramMode", IsPreviewProgramMode());
  1467. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  1468. "DocksLocked", ui->lockUI->isChecked());
  1469. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1470. #ifdef _WIN32
  1471. uint32_t winVer = GetWindowsVersion();
  1472. if (winVer > 0 && winVer < 0x602) {
  1473. bool disableAero = config_get_bool(basicConfig, "Video",
  1474. "DisableAero");
  1475. if (disableAero) {
  1476. SetAeroEnabled(true);
  1477. }
  1478. }
  1479. #endif
  1480. }
  1481. void OBSBasic::SaveProjectNow()
  1482. {
  1483. if (disableSaving)
  1484. return;
  1485. projectChanged = true;
  1486. SaveProjectDeferred();
  1487. }
  1488. void OBSBasic::SaveProject()
  1489. {
  1490. if (disableSaving)
  1491. return;
  1492. projectChanged = true;
  1493. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  1494. Qt::QueuedConnection);
  1495. }
  1496. void OBSBasic::SaveProjectDeferred()
  1497. {
  1498. if (disableSaving)
  1499. return;
  1500. if (!projectChanged)
  1501. return;
  1502. projectChanged = false;
  1503. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  1504. "Basic", "SceneCollectionFile");
  1505. char savePath[512];
  1506. char fileName[512];
  1507. int ret;
  1508. if (!sceneCollection)
  1509. return;
  1510. ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
  1511. sceneCollection);
  1512. if (ret <= 0)
  1513. return;
  1514. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1515. if (ret <= 0)
  1516. return;
  1517. Save(savePath);
  1518. }
  1519. OBSScene OBSBasic::GetCurrentScene()
  1520. {
  1521. QListWidgetItem *item = ui->scenes->currentItem();
  1522. return item ? GetOBSRef<OBSScene>(item) : nullptr;
  1523. }
  1524. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  1525. {
  1526. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  1527. }
  1528. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  1529. {
  1530. return GetSceneItem(GetTopSelectedSourceItem());
  1531. }
  1532. void OBSBasic::UpdatePreviewScalingMenu()
  1533. {
  1534. bool fixedScaling = ui->preview->IsFixedScaling();
  1535. float scalingAmount = ui->preview->GetScalingAmount();
  1536. if (!fixedScaling) {
  1537. ui->actionScaleWindow->setChecked(true);
  1538. ui->actionScaleCanvas->setChecked(false);
  1539. ui->actionScaleOutput->setChecked(false);
  1540. return;
  1541. }
  1542. obs_video_info ovi;
  1543. obs_get_video_info(&ovi);
  1544. ui->actionScaleWindow->setChecked(false);
  1545. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  1546. ui->actionScaleOutput->setChecked(
  1547. scalingAmount == float(ovi.output_width) / float(ovi.base_width));
  1548. }
  1549. void OBSBasic::UpdateSources(OBSScene scene)
  1550. {
  1551. ClearListItems(ui->sources);
  1552. obs_scene_enum_items(scene,
  1553. [] (obs_scene_t *scene, obs_sceneitem_t *item, void *p)
  1554. {
  1555. OBSBasic *window = static_cast<OBSBasic*>(p);
  1556. window->InsertSceneItem(item);
  1557. UNUSED_PARAMETER(scene);
  1558. return true;
  1559. }, this);
  1560. }
  1561. void OBSBasic::InsertSceneItem(obs_sceneitem_t *item)
  1562. {
  1563. QListWidgetItem *listItem = new QListWidgetItem();
  1564. SetOBSRef(listItem, OBSSceneItem(item));
  1565. ui->sources->insertItem(0, listItem);
  1566. ui->sources->setCurrentRow(0, QItemSelectionModel::ClearAndSelect);
  1567. SetupVisibilityItem(ui->sources, listItem, item);
  1568. }
  1569. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  1570. {
  1571. if (interaction)
  1572. interaction->close();
  1573. interaction = new OBSBasicInteraction(this, source);
  1574. interaction->Init();
  1575. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  1576. }
  1577. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  1578. {
  1579. if (properties)
  1580. properties->close();
  1581. properties = new OBSBasicProperties(this, source);
  1582. properties->Init();
  1583. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  1584. }
  1585. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  1586. {
  1587. if (filters)
  1588. filters->close();
  1589. filters = new OBSBasicFilters(this, source);
  1590. filters->Init();
  1591. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  1592. }
  1593. /* Qt callbacks for invokeMethod */
  1594. void OBSBasic::AddScene(OBSSource source)
  1595. {
  1596. const char *name = obs_source_get_name(source);
  1597. obs_scene_t *scene = obs_scene_from_source(source);
  1598. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  1599. SetOBSRef(item, OBSScene(scene));
  1600. ui->scenes->addItem(item);
  1601. obs_hotkey_register_source(source, "OBSBasic.SelectScene",
  1602. Str("Basic.Hotkeys.SelectScene"),
  1603. [](void *data,
  1604. obs_hotkey_id, obs_hotkey_t*, bool pressed)
  1605. {
  1606. OBSBasic *main =
  1607. reinterpret_cast<OBSBasic*>(App()->GetMainWindow());
  1608. auto potential_source = static_cast<obs_source_t*>(data);
  1609. auto source = obs_source_get_ref(potential_source);
  1610. if (source && pressed)
  1611. main->SetCurrentScene(source);
  1612. obs_source_release(source);
  1613. }, static_cast<obs_source_t*>(source));
  1614. signal_handler_t *handler = obs_source_get_signal_handler(source);
  1615. SignalContainer<OBSScene> container;
  1616. container.ref = scene;
  1617. container.handlers.assign({
  1618. std::make_shared<OBSSignal>(handler, "item_add",
  1619. OBSBasic::SceneItemAdded, this),
  1620. std::make_shared<OBSSignal>(handler, "item_remove",
  1621. OBSBasic::SceneItemRemoved, this),
  1622. std::make_shared<OBSSignal>(handler, "item_select",
  1623. OBSBasic::SceneItemSelected, this),
  1624. std::make_shared<OBSSignal>(handler, "item_deselect",
  1625. OBSBasic::SceneItemDeselected, this),
  1626. std::make_shared<OBSSignal>(handler, "reorder",
  1627. OBSBasic::SceneReordered, this),
  1628. });
  1629. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  1630. QVariant::fromValue(container));
  1631. /* if the scene already has items (a duplicated scene) add them */
  1632. auto addSceneItem = [this] (obs_sceneitem_t *item)
  1633. {
  1634. AddSceneItem(item);
  1635. };
  1636. using addSceneItem_t = decltype(addSceneItem);
  1637. obs_scene_enum_items(scene,
  1638. [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  1639. {
  1640. addSceneItem_t *func;
  1641. func = reinterpret_cast<addSceneItem_t*>(param);
  1642. (*func)(item);
  1643. return true;
  1644. }, &addSceneItem);
  1645. SaveProject();
  1646. if (!disableSaving) {
  1647. obs_source_t *source = obs_scene_get_source(scene);
  1648. blog(LOG_INFO, "User added scene '%s'",
  1649. obs_source_get_name(source));
  1650. }
  1651. if (api)
  1652. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1653. }
  1654. void OBSBasic::RemoveScene(OBSSource source)
  1655. {
  1656. obs_scene_t *scene = obs_scene_from_source(source);
  1657. QListWidgetItem *sel = nullptr;
  1658. int count = ui->scenes->count();
  1659. for (int i = 0; i < count; i++) {
  1660. auto item = ui->scenes->item(i);
  1661. auto cur_scene = GetOBSRef<OBSScene>(item);
  1662. if (cur_scene != scene)
  1663. continue;
  1664. sel = item;
  1665. break;
  1666. }
  1667. if (sel != nullptr) {
  1668. if (sel == ui->scenes->currentItem())
  1669. ClearListItems(ui->sources);
  1670. delete sel;
  1671. }
  1672. SaveProject();
  1673. if (!disableSaving) {
  1674. blog(LOG_INFO, "User Removed scene '%s'",
  1675. obs_source_get_name(source));
  1676. }
  1677. if (api)
  1678. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  1679. }
  1680. void OBSBasic::AddSceneItem(OBSSceneItem item)
  1681. {
  1682. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1683. if (GetCurrentScene() == scene)
  1684. InsertSceneItem(item);
  1685. SaveProject();
  1686. if (!disableSaving) {
  1687. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1688. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1689. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  1690. obs_source_get_name(itemSource),
  1691. obs_source_get_id(itemSource),
  1692. obs_source_get_name(sceneSource));
  1693. }
  1694. }
  1695. void OBSBasic::RemoveSceneItem(OBSSceneItem item)
  1696. {
  1697. for (int i = 0; i < ui->sources->count(); i++) {
  1698. QListWidgetItem *listItem = ui->sources->item(i);
  1699. if (GetOBSRef<OBSSceneItem>(listItem) == item) {
  1700. DeleteListItem(ui->sources, listItem);
  1701. break;
  1702. }
  1703. }
  1704. SaveProject();
  1705. if (!disableSaving) {
  1706. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  1707. obs_source_t *sceneSource = obs_scene_get_source(scene);
  1708. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  1709. blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'",
  1710. obs_source_get_name(itemSource),
  1711. obs_source_get_id(itemSource),
  1712. obs_source_get_name(sceneSource));
  1713. }
  1714. }
  1715. void OBSBasic::UpdateSceneSelection(OBSSource source)
  1716. {
  1717. if (source) {
  1718. obs_scene_t *scene = obs_scene_from_source(source);
  1719. const char *name = obs_source_get_name(source);
  1720. if (!scene)
  1721. return;
  1722. QList<QListWidgetItem*> items =
  1723. ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);
  1724. if (items.count()) {
  1725. sceneChanging = true;
  1726. ui->scenes->setCurrentItem(items.first());
  1727. sceneChanging = false;
  1728. UpdateSources(scene);
  1729. }
  1730. }
  1731. }
  1732. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  1733. const QString &prevName)
  1734. {
  1735. QList<QListWidgetItem*> items =
  1736. listWidget->findItems(prevName, Qt::MatchExactly);
  1737. for (int i = 0; i < items.count(); i++)
  1738. items[i]->setText(newName);
  1739. }
  1740. void OBSBasic::RenameSources(QString newName, QString prevName)
  1741. {
  1742. RenameListValues(ui->scenes, newName, prevName);
  1743. for (size_t i = 0; i < volumes.size(); i++) {
  1744. if (volumes[i]->GetName().compare(prevName) == 0)
  1745. volumes[i]->SetName(newName);
  1746. }
  1747. std::string newText = newName.toUtf8().constData();
  1748. std::string prevText = prevName.toUtf8().constData();
  1749. for (size_t j = 0; j < projectorArray.size(); j++) {
  1750. if (projectorArray.at(j) == prevText)
  1751. projectorArray.at(j) = newText;
  1752. }
  1753. SaveProject();
  1754. }
  1755. void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
  1756. {
  1757. SignalBlocker sourcesSignalBlocker(ui->sources);
  1758. if (scene != GetCurrentScene() || ignoreSelectionUpdate)
  1759. return;
  1760. for (int i = 0; i < ui->sources->count(); i++) {
  1761. QListWidgetItem *witem = ui->sources->item(i);
  1762. QVariant data =
  1763. witem->data(static_cast<int>(QtDataRole::OBSRef));
  1764. if (!data.canConvert<OBSSceneItem>())
  1765. continue;
  1766. if (item != data.value<OBSSceneItem>())
  1767. continue;
  1768. witem->setSelected(select);
  1769. break;
  1770. }
  1771. }
  1772. static inline bool SourceMixerHidden(obs_source_t *source)
  1773. {
  1774. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1775. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  1776. obs_data_release(priv_settings);
  1777. return hidden;
  1778. }
  1779. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  1780. {
  1781. obs_data_t *priv_settings = obs_source_get_private_settings(source);
  1782. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  1783. obs_data_release(priv_settings);
  1784. }
  1785. void OBSBasic::GetAudioSourceFilters()
  1786. {
  1787. QAction *action = reinterpret_cast<QAction*>(sender());
  1788. VolControl *vol = action->property("volControl").value<VolControl*>();
  1789. obs_source_t *source = vol->GetSource();
  1790. CreateFiltersWindow(source);
  1791. }
  1792. void OBSBasic::GetAudioSourceProperties()
  1793. {
  1794. QAction *action = reinterpret_cast<QAction*>(sender());
  1795. VolControl *vol = action->property("volControl").value<VolControl*>();
  1796. obs_source_t *source = vol->GetSource();
  1797. CreatePropertiesWindow(source);
  1798. }
  1799. void OBSBasic::HideAudioControl()
  1800. {
  1801. QAction *action = reinterpret_cast<QAction*>(sender());
  1802. VolControl *vol = action->property("volControl").value<VolControl*>();
  1803. obs_source_t *source = vol->GetSource();
  1804. if (!SourceMixerHidden(source)) {
  1805. SetSourceMixerHidden(source, true);
  1806. DeactivateAudioSource(source);
  1807. }
  1808. }
  1809. void OBSBasic::UnhideAllAudioControls()
  1810. {
  1811. auto UnhideAudioMixer = [this] (obs_source_t *source) /* -- */
  1812. {
  1813. if (!obs_source_active(source))
  1814. return true;
  1815. if (!SourceMixerHidden(source))
  1816. return true;
  1817. SetSourceMixerHidden(source, false);
  1818. ActivateAudioSource(source);
  1819. return true;
  1820. };
  1821. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  1822. auto PreEnum = [] (void *data, obs_source_t *source) -> bool /* -- */
  1823. {
  1824. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  1825. };
  1826. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  1827. }
  1828. void OBSBasic::ToggleHideMixer()
  1829. {
  1830. OBSSceneItem item = GetCurrentSceneItem();
  1831. OBSSource source = obs_sceneitem_get_source(item);
  1832. if (!SourceMixerHidden(source)) {
  1833. SetSourceMixerHidden(source, true);
  1834. DeactivateAudioSource(source);
  1835. } else {
  1836. SetSourceMixerHidden(source, false);
  1837. ActivateAudioSource(source);
  1838. }
  1839. }
  1840. void OBSBasic::VolControlContextMenu()
  1841. {
  1842. VolControl *vol = reinterpret_cast<VolControl*>(sender());
  1843. /* ------------------- */
  1844. QAction hideAction(QTStr("Hide"), this);
  1845. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1846. QAction filtersAction(QTStr("Filters"), this);
  1847. QAction propertiesAction(QTStr("Properties"), this);
  1848. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1849. /* ------------------- */
  1850. connect(&hideAction, &QAction::triggered,
  1851. this, &OBSBasic::HideAudioControl,
  1852. Qt::DirectConnection);
  1853. connect(&unhideAllAction, &QAction::triggered,
  1854. this, &OBSBasic::UnhideAllAudioControls,
  1855. Qt::DirectConnection);
  1856. connect(&filtersAction, &QAction::triggered,
  1857. this, &OBSBasic::GetAudioSourceFilters,
  1858. Qt::DirectConnection);
  1859. connect(&propertiesAction, &QAction::triggered,
  1860. this, &OBSBasic::GetAudioSourceProperties,
  1861. Qt::DirectConnection);
  1862. connect(&advPropAction, &QAction::triggered,
  1863. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1864. Qt::DirectConnection);
  1865. /* ------------------- */
  1866. hideAction.setProperty("volControl",
  1867. QVariant::fromValue<VolControl*>(vol));
  1868. filtersAction.setProperty("volControl",
  1869. QVariant::fromValue<VolControl*>(vol));
  1870. propertiesAction.setProperty("volControl",
  1871. QVariant::fromValue<VolControl*>(vol));
  1872. /* ------------------- */
  1873. QMenu popup(this);
  1874. popup.addAction(&unhideAllAction);
  1875. popup.addAction(&hideAction);
  1876. popup.addSeparator();
  1877. popup.addAction(&filtersAction);
  1878. popup.addAction(&propertiesAction);
  1879. popup.addAction(&advPropAction);
  1880. popup.exec(QCursor::pos());
  1881. }
  1882. void OBSBasic::on_mixerScrollArea_customContextMenuRequested()
  1883. {
  1884. QAction unhideAllAction(QTStr("UnhideAll"), this);
  1885. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  1886. /* ------------------- */
  1887. connect(&unhideAllAction, &QAction::triggered,
  1888. this, &OBSBasic::UnhideAllAudioControls,
  1889. Qt::DirectConnection);
  1890. connect(&advPropAction, &QAction::triggered,
  1891. this, &OBSBasic::on_actionAdvAudioProperties_triggered,
  1892. Qt::DirectConnection);
  1893. /* ------------------- */
  1894. QMenu popup(this);
  1895. popup.addAction(&unhideAllAction);
  1896. popup.addSeparator();
  1897. popup.addAction(&advPropAction);
  1898. popup.exec(QCursor::pos());
  1899. }
  1900. void OBSBasic::ActivateAudioSource(OBSSource source)
  1901. {
  1902. if (SourceMixerHidden(source))
  1903. return;
  1904. VolControl *vol = new VolControl(source, true);
  1905. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  1906. connect(vol, &QWidget::customContextMenuRequested,
  1907. this, &OBSBasic::VolControlContextMenu);
  1908. connect(vol, &VolControl::ConfigClicked,
  1909. this, &OBSBasic::VolControlContextMenu);
  1910. volumes.push_back(vol);
  1911. ui->volumeWidgets->layout()->addWidget(vol);
  1912. }
  1913. void OBSBasic::DeactivateAudioSource(OBSSource source)
  1914. {
  1915. for (size_t i = 0; i < volumes.size(); i++) {
  1916. if (volumes[i]->GetSource() == source) {
  1917. delete volumes[i];
  1918. volumes.erase(volumes.begin() + i);
  1919. break;
  1920. }
  1921. }
  1922. }
  1923. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  1924. {
  1925. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE) {
  1926. int count = ui->scenes->count();
  1927. if (count == 1) {
  1928. OBSMessageBox::information(this,
  1929. QTStr("FinalScene.Title"),
  1930. QTStr("FinalScene.Text"));
  1931. return false;
  1932. }
  1933. }
  1934. const char *name = obs_source_get_name(source);
  1935. QString text = QTStr("ConfirmRemove.Text");
  1936. text.replace("$1", QT_UTF8(name));
  1937. QMessageBox remove_source(this);
  1938. remove_source.setText(text);
  1939. QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"),
  1940. QMessageBox::YesRole);
  1941. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  1942. remove_source.setIcon(QMessageBox::Question);
  1943. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  1944. remove_source.exec();
  1945. return Yes == remove_source.clickedButton();
  1946. }
  1947. #define UPDATE_CHECK_INTERVAL (60*60*24*4) /* 4 days */
  1948. #ifdef UPDATE_SPARKLE
  1949. void init_sparkle_updater(bool update_to_undeployed);
  1950. void trigger_sparkle_update();
  1951. #endif
  1952. void OBSBasic::TimedCheckForUpdates()
  1953. {
  1954. if (!config_get_bool(App()->GlobalConfig(), "General",
  1955. "EnableAutoUpdates"))
  1956. return;
  1957. #ifdef UPDATE_SPARKLE
  1958. init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
  1959. "UpdateToUndeployed"));
  1960. #elif ENABLE_WIN_UPDATER
  1961. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  1962. "LastUpdateCheck");
  1963. uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
  1964. "LastVersion");
  1965. if (lastVersion < LIBOBS_API_VER) {
  1966. lastUpdate = 0;
  1967. config_set_int(App()->GlobalConfig(), "General",
  1968. "LastUpdateCheck", 0);
  1969. }
  1970. long long t = (long long)time(nullptr);
  1971. long long secs = t - lastUpdate;
  1972. if (secs > UPDATE_CHECK_INTERVAL)
  1973. CheckForUpdates(false);
  1974. #endif
  1975. }
  1976. void OBSBasic::CheckForUpdates(bool manualUpdate)
  1977. {
  1978. #ifdef UPDATE_SPARKLE
  1979. trigger_sparkle_update();
  1980. #elif ENABLE_WIN_UPDATER
  1981. ui->actionCheckForUpdates->setEnabled(false);
  1982. if (updateCheckThread && updateCheckThread->isRunning())
  1983. return;
  1984. updateCheckThread = new AutoUpdateThread(manualUpdate);
  1985. updateCheckThread->start();
  1986. #endif
  1987. UNUSED_PARAMETER(manualUpdate);
  1988. }
  1989. void OBSBasic::updateCheckFinished()
  1990. {
  1991. ui->actionCheckForUpdates->setEnabled(true);
  1992. }
  1993. void OBSBasic::DuplicateSelectedScene()
  1994. {
  1995. OBSScene curScene = GetCurrentScene();
  1996. if (!curScene)
  1997. return;
  1998. OBSSource curSceneSource = obs_scene_get_source(curScene);
  1999. QString format{obs_source_get_name(curSceneSource)};
  2000. format += " %1";
  2001. int i = 2;
  2002. QString placeHolderText = format.arg(i);
  2003. obs_source_t *source = nullptr;
  2004. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2005. obs_source_release(source);
  2006. placeHolderText = format.arg(++i);
  2007. }
  2008. for (;;) {
  2009. string name;
  2010. bool accepted = NameDialog::AskForName(this,
  2011. QTStr("Basic.Main.AddSceneDlg.Title"),
  2012. QTStr("Basic.Main.AddSceneDlg.Text"),
  2013. name,
  2014. placeHolderText);
  2015. if (!accepted)
  2016. return;
  2017. if (name.empty()) {
  2018. OBSMessageBox::information(this,
  2019. QTStr("NoNameEntered.Title"),
  2020. QTStr("NoNameEntered.Text"));
  2021. continue;
  2022. }
  2023. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2024. if (source) {
  2025. OBSMessageBox::information(this,
  2026. QTStr("NameExists.Title"),
  2027. QTStr("NameExists.Text"));
  2028. obs_source_release(source);
  2029. continue;
  2030. }
  2031. obs_scene_t *scene = obs_scene_duplicate(curScene,
  2032. name.c_str(), OBS_SCENE_DUP_REFS);
  2033. source = obs_scene_get_source(scene);
  2034. AddScene(source);
  2035. SetCurrentScene(source, true);
  2036. obs_scene_release(scene);
  2037. break;
  2038. }
  2039. }
  2040. void OBSBasic::RemoveSelectedScene()
  2041. {
  2042. OBSScene scene = GetCurrentScene();
  2043. if (scene) {
  2044. obs_source_t *source = obs_scene_get_source(scene);
  2045. if (QueryRemoveSource(source)) {
  2046. obs_source_remove(source);
  2047. if (api)
  2048. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2049. }
  2050. }
  2051. }
  2052. void OBSBasic::RemoveSelectedSceneItem()
  2053. {
  2054. OBSSceneItem item = GetCurrentSceneItem();
  2055. if (item) {
  2056. obs_source_t *source = obs_sceneitem_get_source(item);
  2057. if (QueryRemoveSource(source))
  2058. obs_sceneitem_remove(item);
  2059. }
  2060. }
  2061. struct ReorderInfo {
  2062. int idx = 0;
  2063. OBSBasic *window;
  2064. inline ReorderInfo(OBSBasic *window_) : window(window_) {}
  2065. };
  2066. void OBSBasic::ReorderSceneItem(obs_sceneitem_t *item, size_t idx)
  2067. {
  2068. int count = ui->sources->count();
  2069. int idx_inv = count - (int)idx - 1;
  2070. for (int i = 0; i < count; i++) {
  2071. QListWidgetItem *listItem = ui->sources->item(i);
  2072. OBSSceneItem sceneItem = GetOBSRef<OBSSceneItem>(listItem);
  2073. if (sceneItem == item) {
  2074. if ((int)idx_inv != i) {
  2075. bool sel = (ui->sources->currentRow() == i);
  2076. listItem = TakeListItem(ui->sources, i);
  2077. if (listItem) {
  2078. ui->sources->insertItem(idx_inv,
  2079. listItem);
  2080. SetupVisibilityItem(ui->sources,
  2081. listItem, item);
  2082. if (sel)
  2083. ui->sources->setCurrentRow(
  2084. idx_inv);
  2085. }
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. void OBSBasic::ReorderSources(OBSScene scene)
  2092. {
  2093. ReorderInfo info(this);
  2094. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  2095. return;
  2096. obs_scene_enum_items(scene,
  2097. [] (obs_scene_t*, obs_sceneitem_t *item, void *p)
  2098. {
  2099. ReorderInfo *info =
  2100. reinterpret_cast<ReorderInfo*>(p);
  2101. info->window->ReorderSceneItem(item,
  2102. info->idx++);
  2103. return true;
  2104. }, &info);
  2105. SaveProject();
  2106. }
  2107. /* OBS Callbacks */
  2108. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  2109. {
  2110. OBSBasic *window = static_cast<OBSBasic*>(data);
  2111. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2112. QMetaObject::invokeMethod(window, "ReorderSources",
  2113. Q_ARG(OBSScene, OBSScene(scene)));
  2114. }
  2115. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  2116. {
  2117. OBSBasic *window = static_cast<OBSBasic*>(data);
  2118. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2119. QMetaObject::invokeMethod(window, "AddSceneItem",
  2120. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2121. }
  2122. void OBSBasic::SceneItemRemoved(void *data, calldata_t *params)
  2123. {
  2124. OBSBasic *window = static_cast<OBSBasic*>(data);
  2125. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2126. QMetaObject::invokeMethod(window, "RemoveSceneItem",
  2127. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  2128. }
  2129. void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
  2130. {
  2131. OBSBasic *window = static_cast<OBSBasic*>(data);
  2132. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2133. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2134. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2135. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2136. Q_ARG(bool, true));
  2137. }
  2138. void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
  2139. {
  2140. OBSBasic *window = static_cast<OBSBasic*>(data);
  2141. obs_scene_t *scene = (obs_scene_t*)calldata_ptr(params, "scene");
  2142. obs_sceneitem_t *item = (obs_sceneitem_t*)calldata_ptr(params, "item");
  2143. QMetaObject::invokeMethod(window, "SelectSceneItem",
  2144. Q_ARG(OBSScene, scene), Q_ARG(OBSSceneItem, item),
  2145. Q_ARG(bool, false));
  2146. }
  2147. void OBSBasic::SourceLoaded(void *data, obs_source_t *source)
  2148. {
  2149. OBSBasic *window = static_cast<OBSBasic*>(data);
  2150. if (obs_scene_from_source(source) != NULL)
  2151. QMetaObject::invokeMethod(window,
  2152. "AddScene",
  2153. Q_ARG(OBSSource, OBSSource(source)));
  2154. }
  2155. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  2156. {
  2157. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2158. if (obs_scene_from_source(source) != NULL)
  2159. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2160. "RemoveScene",
  2161. Q_ARG(OBSSource, OBSSource(source)));
  2162. }
  2163. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  2164. {
  2165. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2166. uint32_t flags = obs_source_get_output_flags(source);
  2167. if (flags & OBS_SOURCE_AUDIO)
  2168. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2169. "ActivateAudioSource",
  2170. Q_ARG(OBSSource, OBSSource(source)));
  2171. }
  2172. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  2173. {
  2174. obs_source_t *source = (obs_source_t*)calldata_ptr(params, "source");
  2175. uint32_t flags = obs_source_get_output_flags(source);
  2176. if (flags & OBS_SOURCE_AUDIO)
  2177. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2178. "DeactivateAudioSource",
  2179. Q_ARG(OBSSource, OBSSource(source)));
  2180. }
  2181. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  2182. {
  2183. const char *newName = calldata_string(params, "new_name");
  2184. const char *prevName = calldata_string(params, "prev_name");
  2185. QMetaObject::invokeMethod(static_cast<OBSBasic*>(data),
  2186. "RenameSources",
  2187. Q_ARG(QString, QT_UTF8(newName)),
  2188. Q_ARG(QString, QT_UTF8(prevName)));
  2189. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  2190. }
  2191. void OBSBasic::DrawBackdrop(float cx, float cy)
  2192. {
  2193. if (!box)
  2194. return;
  2195. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  2196. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  2197. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  2198. vec4 colorVal;
  2199. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  2200. gs_effect_set_vec4(color, &colorVal);
  2201. gs_technique_begin(tech);
  2202. gs_technique_begin_pass(tech, 0);
  2203. gs_matrix_push();
  2204. gs_matrix_identity();
  2205. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  2206. gs_load_vertexbuffer(box);
  2207. gs_draw(GS_TRISTRIP, 0, 0);
  2208. gs_matrix_pop();
  2209. gs_technique_end_pass(tech);
  2210. gs_technique_end(tech);
  2211. gs_load_vertexbuffer(nullptr);
  2212. }
  2213. void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
  2214. {
  2215. OBSBasic *window = static_cast<OBSBasic*>(data);
  2216. obs_video_info ovi;
  2217. obs_get_video_info(&ovi);
  2218. window->previewCX = int(window->previewScale * float(ovi.base_width));
  2219. window->previewCY = int(window->previewScale * float(ovi.base_height));
  2220. gs_viewport_push();
  2221. gs_projection_push();
  2222. /* --------------------------------------- */
  2223. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  2224. -100.0f, 100.0f);
  2225. gs_set_viewport(window->previewX, window->previewY,
  2226. window->previewCX, window->previewCY);
  2227. window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height));
  2228. if (window->IsPreviewProgramMode()) {
  2229. OBSScene scene = window->GetCurrentScene();
  2230. obs_source_t *source = obs_scene_get_source(scene);
  2231. if (source)
  2232. obs_source_video_render(source);
  2233. } else {
  2234. obs_render_main_view();
  2235. }
  2236. gs_load_vertexbuffer(nullptr);
  2237. /* --------------------------------------- */
  2238. QSize previewSize = GetPixelSize(window->ui->preview);
  2239. float right = float(previewSize.width()) - window->previewX;
  2240. float bottom = float(previewSize.height()) - window->previewY;
  2241. gs_ortho(-window->previewX, right,
  2242. -window->previewY, bottom,
  2243. -100.0f, 100.0f);
  2244. gs_reset_viewport();
  2245. window->ui->preview->DrawSceneEditing();
  2246. /* --------------------------------------- */
  2247. gs_projection_pop();
  2248. gs_viewport_pop();
  2249. UNUSED_PARAMETER(cx);
  2250. UNUSED_PARAMETER(cy);
  2251. }
  2252. /* Main class functions */
  2253. obs_service_t *OBSBasic::GetService()
  2254. {
  2255. if (!service) {
  2256. service = obs_service_create("rtmp_common", NULL, NULL,
  2257. nullptr);
  2258. obs_service_release(service);
  2259. }
  2260. return service;
  2261. }
  2262. void OBSBasic::SetService(obs_service_t *newService)
  2263. {
  2264. if (newService)
  2265. service = newService;
  2266. }
  2267. bool OBSBasic::StreamingActive() const
  2268. {
  2269. if (!outputHandler)
  2270. return false;
  2271. return outputHandler->StreamingActive();
  2272. }
  2273. bool OBSBasic::Active() const
  2274. {
  2275. if (!outputHandler)
  2276. return false;
  2277. return outputHandler->Active();
  2278. }
  2279. #ifdef _WIN32
  2280. #define IS_WIN32 1
  2281. #else
  2282. #define IS_WIN32 0
  2283. #endif
  2284. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  2285. {
  2286. return obs_reset_video(ovi);
  2287. }
  2288. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  2289. {
  2290. const char *scaleTypeStr = config_get_string(basicConfig,
  2291. "Video", "ScaleType");
  2292. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  2293. return OBS_SCALE_BILINEAR;
  2294. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  2295. return OBS_SCALE_LANCZOS;
  2296. else
  2297. return OBS_SCALE_BICUBIC;
  2298. }
  2299. static inline enum video_format GetVideoFormatFromName(const char *name)
  2300. {
  2301. if (astrcmpi(name, "I420") == 0)
  2302. return VIDEO_FORMAT_I420;
  2303. else if (astrcmpi(name, "NV12") == 0)
  2304. return VIDEO_FORMAT_NV12;
  2305. else if (astrcmpi(name, "I444") == 0)
  2306. return VIDEO_FORMAT_I444;
  2307. #if 0 //currently unsupported
  2308. else if (astrcmpi(name, "YVYU") == 0)
  2309. return VIDEO_FORMAT_YVYU;
  2310. else if (astrcmpi(name, "YUY2") == 0)
  2311. return VIDEO_FORMAT_YUY2;
  2312. else if (astrcmpi(name, "UYVY") == 0)
  2313. return VIDEO_FORMAT_UYVY;
  2314. #endif
  2315. else
  2316. return VIDEO_FORMAT_RGBA;
  2317. }
  2318. int OBSBasic::ResetVideo()
  2319. {
  2320. if (outputHandler && outputHandler->Active())
  2321. return OBS_VIDEO_CURRENTLY_ACTIVE;
  2322. ProfileScope("OBSBasic::ResetVideo");
  2323. struct obs_video_info ovi;
  2324. int ret;
  2325. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  2326. const char *colorFormat = config_get_string(basicConfig, "Video",
  2327. "ColorFormat");
  2328. const char *colorSpace = config_get_string(basicConfig, "Video",
  2329. "ColorSpace");
  2330. const char *colorRange = config_get_string(basicConfig, "Video",
  2331. "ColorRange");
  2332. ovi.graphics_module = App()->GetRenderModule();
  2333. ovi.base_width = (uint32_t)config_get_uint(basicConfig,
  2334. "Video", "BaseCX");
  2335. ovi.base_height = (uint32_t)config_get_uint(basicConfig,
  2336. "Video", "BaseCY");
  2337. ovi.output_width = (uint32_t)config_get_uint(basicConfig,
  2338. "Video", "OutputCX");
  2339. ovi.output_height = (uint32_t)config_get_uint(basicConfig,
  2340. "Video", "OutputCY");
  2341. ovi.output_format = GetVideoFormatFromName(colorFormat);
  2342. ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ?
  2343. VIDEO_CS_601 : VIDEO_CS_709;
  2344. ovi.range = astrcmpi(colorRange, "Full") == 0 ?
  2345. VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL;
  2346. ovi.adapter = config_get_uint(App()->GlobalConfig(),
  2347. "Video", "AdapterIdx");
  2348. ovi.gpu_conversion = true;
  2349. ovi.scale_type = GetScaleType(basicConfig);
  2350. if (ovi.base_width == 0 || ovi.base_height == 0) {
  2351. ovi.base_width = 1920;
  2352. ovi.base_height = 1080;
  2353. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  2354. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  2355. }
  2356. if (ovi.output_width == 0 || ovi.output_height == 0) {
  2357. ovi.output_width = ovi.base_width;
  2358. ovi.output_height = ovi.base_height;
  2359. config_set_uint(basicConfig, "Video", "OutputCX",
  2360. ovi.base_width);
  2361. config_set_uint(basicConfig, "Video", "OutputCY",
  2362. ovi.base_height);
  2363. }
  2364. ret = AttemptToResetVideo(&ovi);
  2365. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  2366. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  2367. blog(LOG_WARNING, "Tried to reset when "
  2368. "already active");
  2369. return ret;
  2370. }
  2371. /* Try OpenGL if DirectX fails on windows */
  2372. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  2373. blog(LOG_WARNING, "Failed to initialize obs video (%d) "
  2374. "with graphics_module='%s', retrying "
  2375. "with graphics_module='%s'",
  2376. ret, ovi.graphics_module,
  2377. DL_OPENGL);
  2378. ovi.graphics_module = DL_OPENGL;
  2379. ret = AttemptToResetVideo(&ovi);
  2380. }
  2381. } else if (ret == OBS_VIDEO_SUCCESS) {
  2382. ResizePreview(ovi.base_width, ovi.base_height);
  2383. if (program)
  2384. ResizeProgram(ovi.base_width, ovi.base_height);
  2385. }
  2386. if (ret == OBS_VIDEO_SUCCESS)
  2387. OBSBasicStats::InitializeValues();
  2388. return ret;
  2389. }
  2390. bool OBSBasic::ResetAudio()
  2391. {
  2392. ProfileScope("OBSBasic::ResetAudio");
  2393. struct obs_audio_info ai;
  2394. ai.samples_per_sec = config_get_uint(basicConfig, "Audio",
  2395. "SampleRate");
  2396. const char *channelSetupStr = config_get_string(basicConfig,
  2397. "Audio", "ChannelSetup");
  2398. if (strcmp(channelSetupStr, "Mono") == 0)
  2399. ai.speakers = SPEAKERS_MONO;
  2400. else
  2401. ai.speakers = SPEAKERS_STEREO;
  2402. return obs_reset_audio(&ai);
  2403. }
  2404. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  2405. const char *deviceDesc, int channel)
  2406. {
  2407. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  2408. obs_source_t *source;
  2409. obs_data_t *settings;
  2410. source = obs_get_output_source(channel);
  2411. if (source) {
  2412. if (disable) {
  2413. obs_set_output_source(channel, nullptr);
  2414. } else {
  2415. settings = obs_source_get_settings(source);
  2416. const char *oldId = obs_data_get_string(settings,
  2417. "device_id");
  2418. if (strcmp(oldId, deviceId) != 0) {
  2419. obs_data_set_string(settings, "device_id",
  2420. deviceId);
  2421. obs_source_update(source, settings);
  2422. }
  2423. obs_data_release(settings);
  2424. }
  2425. obs_source_release(source);
  2426. } else if (!disable) {
  2427. settings = obs_data_create();
  2428. obs_data_set_string(settings, "device_id", deviceId);
  2429. source = obs_source_create(sourceId, deviceDesc, settings,
  2430. nullptr);
  2431. obs_data_release(settings);
  2432. obs_set_output_source(channel, source);
  2433. obs_source_release(source);
  2434. }
  2435. }
  2436. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  2437. {
  2438. QSize targetSize;
  2439. bool isFixedScaling;
  2440. obs_video_info ovi;
  2441. /* resize preview panel to fix to the top section of the window */
  2442. targetSize = GetPixelSize(ui->preview);
  2443. isFixedScaling = ui->preview->IsFixedScaling();
  2444. obs_get_video_info(&ovi);
  2445. if (isFixedScaling) {
  2446. previewScale = ui->preview->GetScalingAmount();
  2447. GetCenterPosFromFixedScale(int(cx), int(cy),
  2448. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2449. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2450. previewX, previewY, previewScale);
  2451. previewX += ui->preview->GetScrollX();
  2452. previewY += ui->preview->GetScrollY();
  2453. } else {
  2454. GetScaleAndCenterPos(int(cx), int(cy),
  2455. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  2456. targetSize.height() - PREVIEW_EDGE_SIZE * 2,
  2457. previewX, previewY, previewScale);
  2458. }
  2459. previewX += float(PREVIEW_EDGE_SIZE);
  2460. previewY += float(PREVIEW_EDGE_SIZE);
  2461. }
  2462. void OBSBasic::CloseDialogs()
  2463. {
  2464. QList<QDialog*> childDialogs = this->findChildren<QDialog *>();
  2465. if (!childDialogs.isEmpty()) {
  2466. for (int i = 0; i < childDialogs.size(); ++i) {
  2467. childDialogs.at(i)->close();
  2468. }
  2469. }
  2470. for (QPointer<QWidget> &projector : windowProjectors) {
  2471. delete projector;
  2472. projector.clear();
  2473. }
  2474. for (QPointer<QWidget> &projector : projectors) {
  2475. delete projector;
  2476. projector.clear();
  2477. }
  2478. if (!stats.isNull()) stats->close(); //call close to save Stats geometry
  2479. }
  2480. void OBSBasic::EnumDialogs()
  2481. {
  2482. visDialogs.clear();
  2483. modalDialogs.clear();
  2484. visMsgBoxes.clear();
  2485. /* fill list of Visible dialogs and Modal dialogs */
  2486. QList<QDialog*> dialogs = findChildren<QDialog*>();
  2487. for (QDialog *dialog : dialogs) {
  2488. if (dialog->isVisible())
  2489. visDialogs.append(dialog);
  2490. if (dialog->isModal())
  2491. modalDialogs.append(dialog);
  2492. }
  2493. /* fill list of Visible message boxes */
  2494. QList<QMessageBox*> msgBoxes = findChildren<QMessageBox*>();
  2495. for (QMessageBox *msgbox : msgBoxes) {
  2496. if (msgbox->isVisible())
  2497. visMsgBoxes.append(msgbox);
  2498. }
  2499. }
  2500. void OBSBasic::ClearSceneData()
  2501. {
  2502. disableSaving++;
  2503. CloseDialogs();
  2504. ClearVolumeControls();
  2505. ClearListItems(ui->scenes);
  2506. ClearListItems(ui->sources);
  2507. ClearQuickTransitions();
  2508. ui->transitions->clear();
  2509. obs_set_output_source(0, nullptr);
  2510. obs_set_output_source(1, nullptr);
  2511. obs_set_output_source(2, nullptr);
  2512. obs_set_output_source(3, nullptr);
  2513. obs_set_output_source(4, nullptr);
  2514. obs_set_output_source(5, nullptr);
  2515. lastScene = nullptr;
  2516. swapScene = nullptr;
  2517. programScene = nullptr;
  2518. auto cb = [](void *unused, obs_source_t *source)
  2519. {
  2520. obs_source_remove(source);
  2521. UNUSED_PARAMETER(unused);
  2522. return true;
  2523. };
  2524. obs_enum_sources(cb, nullptr);
  2525. disableSaving--;
  2526. blog(LOG_INFO, "All scene data cleared");
  2527. blog(LOG_INFO, "------------------------------------------------");
  2528. }
  2529. void OBSBasic::closeEvent(QCloseEvent *event)
  2530. {
  2531. if (isVisible())
  2532. config_set_string(App()->GlobalConfig(),
  2533. "BasicWindow", "geometry",
  2534. saveGeometry().toBase64().constData());
  2535. config_set_string(App()->GlobalConfig(),
  2536. "BasicWindow", "DockState",
  2537. saveState().toBase64().constData());
  2538. if (outputHandler && outputHandler->Active()) {
  2539. SetShowing(true);
  2540. QMessageBox::StandardButton button = OBSMessageBox::question(
  2541. this, QTStr("ConfirmExit.Title"),
  2542. QTStr("ConfirmExit.Text"));
  2543. if (button == QMessageBox::No) {
  2544. event->ignore();
  2545. return;
  2546. }
  2547. }
  2548. QWidget::closeEvent(event);
  2549. if (!event->isAccepted())
  2550. return;
  2551. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  2552. if (updateCheckThread)
  2553. updateCheckThread->wait();
  2554. if (logUploadThread)
  2555. logUploadThread->wait();
  2556. signalHandlers.clear();
  2557. SaveProjectNow();
  2558. if (api)
  2559. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  2560. disableSaving++;
  2561. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  2562. * sources, etc) so that all references are released before shutdown */
  2563. ClearSceneData();
  2564. App()->quit();
  2565. }
  2566. void OBSBasic::changeEvent(QEvent *event)
  2567. {
  2568. if (event->type() == QEvent::WindowStateChange &&
  2569. isMinimized() &&
  2570. trayIcon &&
  2571. trayIcon->isVisible() &&
  2572. sysTrayMinimizeToTray()) {
  2573. ToggleShowHide();
  2574. }
  2575. }
  2576. void OBSBasic::on_actionShow_Recordings_triggered()
  2577. {
  2578. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2579. const char *path = strcmp(mode, "Advanced") ?
  2580. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2581. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2582. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  2583. }
  2584. void OBSBasic::on_actionRemux_triggered()
  2585. {
  2586. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  2587. const char *path = strcmp(mode, "Advanced") ?
  2588. config_get_string(basicConfig, "SimpleOutput", "FilePath") :
  2589. config_get_string(basicConfig, "AdvOut", "RecFilePath");
  2590. OBSRemux remux(path, this);
  2591. remux.exec();
  2592. }
  2593. void OBSBasic::on_action_Settings_triggered()
  2594. {
  2595. OBSBasicSettings settings(this);
  2596. settings.exec();
  2597. SystemTray(false);
  2598. }
  2599. void OBSBasic::on_actionAdvAudioProperties_triggered()
  2600. {
  2601. if (advAudioWindow != nullptr) {
  2602. advAudioWindow->raise();
  2603. return;
  2604. }
  2605. advAudioWindow = new OBSBasicAdvAudio(this);
  2606. advAudioWindow->show();
  2607. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  2608. connect(advAudioWindow, SIGNAL(destroyed()),
  2609. this, SLOT(on_advAudioProps_destroyed()));
  2610. }
  2611. void OBSBasic::on_advAudioProps_clicked()
  2612. {
  2613. on_actionAdvAudioProperties_triggered();
  2614. }
  2615. void OBSBasic::on_advAudioProps_destroyed()
  2616. {
  2617. advAudioWindow = nullptr;
  2618. }
  2619. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  2620. QListWidgetItem *prev)
  2621. {
  2622. obs_source_t *source = NULL;
  2623. if (sceneChanging)
  2624. return;
  2625. if (current) {
  2626. obs_scene_t *scene;
  2627. scene = GetOBSRef<OBSScene>(current);
  2628. source = obs_scene_get_source(scene);
  2629. }
  2630. SetCurrentScene(source);
  2631. UNUSED_PARAMETER(prev);
  2632. }
  2633. void OBSBasic::EditSceneName()
  2634. {
  2635. QListWidgetItem *item = ui->scenes->currentItem();
  2636. Qt::ItemFlags flags = item->flags();
  2637. item->setFlags(flags | Qt::ItemIsEditable);
  2638. ui->scenes->editItem(item);
  2639. item->setFlags(flags);
  2640. }
  2641. static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
  2642. const char *slot)
  2643. {
  2644. QAction *action;
  2645. QList<QScreen*> screens = QGuiApplication::screens();
  2646. for (int i = 0; i < screens.size(); i++) {
  2647. QRect screenGeometry = screens[i]->geometry();
  2648. QString str = QString("%1 %2: %3x%4 @ %5,%6").
  2649. arg(QTStr("Display"),
  2650. QString::number(i),
  2651. QString::number((int)screenGeometry.width()),
  2652. QString::number((int)screenGeometry.height()),
  2653. QString::number((int)screenGeometry.x()),
  2654. QString::number((int)screenGeometry.y()));
  2655. action = parent->addAction(str, target, slot);
  2656. action->setProperty("monitor", i);
  2657. }
  2658. }
  2659. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  2660. {
  2661. QListWidgetItem *item = ui->scenes->itemAt(pos);
  2662. QPointer<QMenu> sceneProjectorMenu;
  2663. QMenu popup(this);
  2664. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  2665. popup.addAction(QTStr("Add"),
  2666. this, SLOT(on_actionAddScene_triggered()));
  2667. if (item) {
  2668. popup.addSeparator();
  2669. popup.addAction(QTStr("Duplicate"),
  2670. this, SLOT(DuplicateSelectedScene()));
  2671. popup.addAction(QTStr("Rename"),
  2672. this, SLOT(EditSceneName()));
  2673. popup.addAction(QTStr("Remove"),
  2674. this, SLOT(RemoveSelectedScene()),
  2675. DeleteKeys.front());
  2676. popup.addSeparator();
  2677. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"),
  2678. this, SLOT(on_actionSceneUp_triggered()));
  2679. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  2680. this, SLOT(on_actionSceneDown_triggered()));
  2681. order.addSeparator();
  2682. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  2683. this, SLOT(MoveSceneToTop()));
  2684. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  2685. this, SLOT(MoveSceneToBottom()));
  2686. popup.addMenu(&order);
  2687. popup.addSeparator();
  2688. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  2689. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  2690. SLOT(OpenSceneProjector()));
  2691. popup.addMenu(sceneProjectorMenu);
  2692. QAction *sceneWindow = popup.addAction(
  2693. QTStr("SceneWindow"),
  2694. this, SLOT(OpenSceneWindow()));
  2695. popup.addAction(sceneWindow);
  2696. popup.addSeparator();
  2697. popup.addAction(QTStr("Filters"), this,
  2698. SLOT(OpenSceneFilters()));
  2699. }
  2700. popup.exec(QCursor::pos());
  2701. }
  2702. void OBSBasic::on_actionAddScene_triggered()
  2703. {
  2704. string name;
  2705. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  2706. int i = 2;
  2707. QString placeHolderText = format.arg(i);
  2708. obs_source_t *source = nullptr;
  2709. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  2710. obs_source_release(source);
  2711. placeHolderText = format.arg(++i);
  2712. }
  2713. bool accepted = NameDialog::AskForName(this,
  2714. QTStr("Basic.Main.AddSceneDlg.Title"),
  2715. QTStr("Basic.Main.AddSceneDlg.Text"),
  2716. name,
  2717. placeHolderText);
  2718. if (accepted) {
  2719. if (name.empty()) {
  2720. OBSMessageBox::information(this,
  2721. QTStr("NoNameEntered.Title"),
  2722. QTStr("NoNameEntered.Text"));
  2723. on_actionAddScene_triggered();
  2724. return;
  2725. }
  2726. obs_source_t *source = obs_get_source_by_name(name.c_str());
  2727. if (source) {
  2728. OBSMessageBox::information(this,
  2729. QTStr("NameExists.Title"),
  2730. QTStr("NameExists.Text"));
  2731. obs_source_release(source);
  2732. on_actionAddScene_triggered();
  2733. return;
  2734. }
  2735. obs_scene_t *scene = obs_scene_create(name.c_str());
  2736. source = obs_scene_get_source(scene);
  2737. AddScene(source);
  2738. SetCurrentScene(source);
  2739. obs_scene_release(scene);
  2740. }
  2741. }
  2742. void OBSBasic::on_actionRemoveScene_triggered()
  2743. {
  2744. OBSScene scene = GetCurrentScene();
  2745. obs_source_t *source = obs_scene_get_source(scene);
  2746. if (source && QueryRemoveSource(source))
  2747. obs_source_remove(source);
  2748. }
  2749. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  2750. {
  2751. int idx = ui->scenes->currentRow();
  2752. if (idx == -1 || idx == invalidIdx)
  2753. return;
  2754. sceneChanging = true;
  2755. QListWidgetItem *item = ui->scenes->takeItem(idx);
  2756. if (!relative)
  2757. idx = 0;
  2758. ui->scenes->insertItem(idx + offset, item);
  2759. ui->scenes->setCurrentRow(idx + offset);
  2760. item->setSelected(true);
  2761. sceneChanging = false;
  2762. }
  2763. void OBSBasic::on_actionSceneUp_triggered()
  2764. {
  2765. ChangeSceneIndex(true, -1, 0);
  2766. }
  2767. void OBSBasic::on_actionSceneDown_triggered()
  2768. {
  2769. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  2770. }
  2771. void OBSBasic::MoveSceneToTop()
  2772. {
  2773. ChangeSceneIndex(false, 0, 0);
  2774. }
  2775. void OBSBasic::MoveSceneToBottom()
  2776. {
  2777. ChangeSceneIndex(false, ui->scenes->count() - 1,
  2778. ui->scenes->count() - 1);
  2779. }
  2780. void OBSBasic::on_sources_itemSelectionChanged()
  2781. {
  2782. SignalBlocker sourcesSignalBlocker(ui->sources);
  2783. auto updateItemSelection = [&]()
  2784. {
  2785. ignoreSelectionUpdate = true;
  2786. for (int i = 0; i < ui->sources->count(); i++)
  2787. {
  2788. QListWidgetItem *wItem = ui->sources->item(i);
  2789. OBSSceneItem item = GetOBSRef<OBSSceneItem>(wItem);
  2790. obs_sceneitem_select(item, wItem->isSelected());
  2791. }
  2792. ignoreSelectionUpdate = false;
  2793. };
  2794. using updateItemSelection_t = decltype(updateItemSelection);
  2795. obs_scene_atomic_update(GetCurrentScene(),
  2796. [](void *data, obs_scene_t *)
  2797. {
  2798. (*static_cast<updateItemSelection_t*>(data))();
  2799. }, static_cast<void*>(&updateItemSelection));
  2800. }
  2801. void OBSBasic::EditSceneItemName()
  2802. {
  2803. QListWidgetItem *item = GetTopSelectedSourceItem();
  2804. Qt::ItemFlags flags = item->flags();
  2805. OBSSceneItem sceneItem= GetOBSRef<OBSSceneItem>(item);
  2806. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2807. const char *name = obs_source_get_name(source);
  2808. item->setText(QT_UTF8(name));
  2809. item->setFlags(flags | Qt::ItemIsEditable);
  2810. ui->sources->removeItemWidget(item);
  2811. ui->sources->editItem(item);
  2812. item->setFlags(flags);
  2813. }
  2814. void OBSBasic::SetDeinterlacingMode()
  2815. {
  2816. QAction *action = reinterpret_cast<QAction*>(sender());
  2817. obs_deinterlace_mode mode =
  2818. (obs_deinterlace_mode)action->property("mode").toInt();
  2819. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2820. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2821. obs_source_set_deinterlace_mode(source, mode);
  2822. }
  2823. void OBSBasic::SetDeinterlacingOrder()
  2824. {
  2825. QAction *action = reinterpret_cast<QAction*>(sender());
  2826. obs_deinterlace_field_order order =
  2827. (obs_deinterlace_field_order)action->property("order").toInt();
  2828. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2829. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2830. obs_source_set_deinterlace_field_order(source, order);
  2831. }
  2832. QMenu *OBSBasic::AddDeinterlacingMenu(obs_source_t *source)
  2833. {
  2834. QMenu *menu = new QMenu(QTStr("Deinterlacing"));
  2835. obs_deinterlace_mode deinterlaceMode =
  2836. obs_source_get_deinterlace_mode(source);
  2837. obs_deinterlace_field_order deinterlaceOrder =
  2838. obs_source_get_deinterlace_field_order(source);
  2839. QAction *action;
  2840. #define ADD_MODE(name, mode) \
  2841. action = menu->addAction(QTStr("" name), this, \
  2842. SLOT(SetDeinterlacingMode())); \
  2843. action->setProperty("mode", (int)mode); \
  2844. action->setCheckable(true); \
  2845. action->setChecked(deinterlaceMode == mode);
  2846. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  2847. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  2848. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  2849. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  2850. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  2851. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  2852. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  2853. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  2854. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  2855. #undef ADD_MODE
  2856. menu->addSeparator();
  2857. #define ADD_ORDER(name, order) \
  2858. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  2859. SLOT(SetDeinterlacingOrder())); \
  2860. action->setProperty("order", (int)order); \
  2861. action->setCheckable(true); \
  2862. action->setChecked(deinterlaceOrder == order);
  2863. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  2864. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  2865. #undef ADD_ORDER
  2866. return menu;
  2867. }
  2868. void OBSBasic::SetScaleFilter()
  2869. {
  2870. QAction *action = reinterpret_cast<QAction*>(sender());
  2871. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  2872. OBSSceneItem sceneItem = GetCurrentSceneItem();
  2873. obs_sceneitem_set_scale_filter(sceneItem, mode);
  2874. }
  2875. QMenu *OBSBasic::AddScaleFilteringMenu(obs_sceneitem_t *item)
  2876. {
  2877. QMenu *menu = new QMenu(QTStr("ScaleFiltering"));
  2878. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  2879. QAction *action;
  2880. #define ADD_MODE(name, mode) \
  2881. action = menu->addAction(QTStr("" name), this, \
  2882. SLOT(SetScaleFilter())); \
  2883. action->setProperty("mode", (int)mode); \
  2884. action->setCheckable(true); \
  2885. action->setChecked(scaleFilter == mode);
  2886. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  2887. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  2888. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  2889. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  2890. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  2891. #undef ADD_MODE
  2892. return menu;
  2893. }
  2894. void OBSBasic::CreateSourcePopupMenu(QListWidgetItem *item, bool preview)
  2895. {
  2896. QMenu popup(this);
  2897. QPointer<QMenu> previewProjector;
  2898. QPointer<QMenu> sourceProjector;
  2899. if (preview) {
  2900. QAction *action = popup.addAction(
  2901. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  2902. this, SLOT(TogglePreview()));
  2903. action->setCheckable(true);
  2904. action->setChecked(
  2905. obs_display_enabled(ui->preview->GetDisplay()));
  2906. if (IsPreviewProgramMode())
  2907. action->setEnabled(false);
  2908. popup.addAction(ui->actionLockPreview);
  2909. popup.addMenu(ui->scalingMenu);
  2910. previewProjector = new QMenu(QTStr("PreviewProjector"));
  2911. AddProjectorMenuMonitors(previewProjector, this,
  2912. SLOT(OpenPreviewProjector()));
  2913. popup.addMenu(previewProjector);
  2914. QAction *previewWindow = popup.addAction(
  2915. QTStr("PreviewWindow"),
  2916. this, SLOT(OpenPreviewWindow()));
  2917. popup.addAction(previewWindow);
  2918. popup.addSeparator();
  2919. }
  2920. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  2921. if (addSourceMenu)
  2922. popup.addMenu(addSourceMenu);
  2923. ui->actionCopyFilters->setEnabled(false);
  2924. popup.addSeparator();
  2925. popup.addAction(ui->actionCopySource);
  2926. popup.addAction(ui->actionPasteRef);
  2927. popup.addAction(ui->actionPasteDup);
  2928. popup.addSeparator();
  2929. popup.addSeparator();
  2930. popup.addAction(ui->actionCopyFilters);
  2931. popup.addAction(ui->actionPasteFilters);
  2932. popup.addSeparator();
  2933. if (item) {
  2934. if (addSourceMenu)
  2935. popup.addSeparator();
  2936. OBSSceneItem sceneItem = GetSceneItem(item);
  2937. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  2938. uint32_t flags = obs_source_get_output_flags(source);
  2939. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  2940. OBS_SOURCE_ASYNC_VIDEO;
  2941. bool hasAudio = (flags & OBS_SOURCE_AUDIO) ==
  2942. OBS_SOURCE_AUDIO;
  2943. QAction *action;
  2944. popup.addAction(QTStr("Rename"), this,
  2945. SLOT(EditSceneItemName()));
  2946. popup.addAction(QTStr("Remove"), this,
  2947. SLOT(on_actionRemoveSource_triggered()),
  2948. DeleteKeys.front());
  2949. popup.addSeparator();
  2950. popup.addMenu(ui->orderMenu);
  2951. popup.addMenu(ui->transformMenu);
  2952. sourceProjector = new QMenu(QTStr("SourceProjector"));
  2953. AddProjectorMenuMonitors(sourceProjector, this,
  2954. SLOT(OpenSourceProjector()));
  2955. QAction *sourceWindow = popup.addAction(
  2956. QTStr("SourceWindow"),
  2957. this, SLOT(OpenSourceWindow()));
  2958. popup.addAction(sourceWindow);
  2959. popup.addSeparator();
  2960. if (hasAudio) {
  2961. QAction *actionHideMixer = popup.addAction(
  2962. QTStr("HideMixer"),
  2963. this, SLOT(ToggleHideMixer()));
  2964. actionHideMixer->setCheckable(true);
  2965. actionHideMixer->setChecked(SourceMixerHidden(source));
  2966. }
  2967. if (isAsyncVideo) {
  2968. popup.addMenu(AddDeinterlacingMenu(source));
  2969. popup.addSeparator();
  2970. }
  2971. popup.addMenu(AddScaleFilteringMenu(sceneItem));
  2972. popup.addSeparator();
  2973. popup.addMenu(sourceProjector);
  2974. popup.addAction(sourceWindow);
  2975. popup.addSeparator();
  2976. action = popup.addAction(QTStr("Interact"), this,
  2977. SLOT(on_actionInteract_triggered()));
  2978. action->setEnabled(obs_source_get_output_flags(source) &
  2979. OBS_SOURCE_INTERACTION);
  2980. popup.addAction(QTStr("Filters"), this,
  2981. SLOT(OpenFilters()));
  2982. popup.addAction(QTStr("Properties"), this,
  2983. SLOT(on_actionSourceProperties_triggered()));
  2984. ui->actionCopyFilters->setEnabled(true);
  2985. }
  2986. popup.exec(QCursor::pos());
  2987. }
  2988. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  2989. {
  2990. if (ui->scenes->count())
  2991. CreateSourcePopupMenu(ui->sources->itemAt(pos), false);
  2992. }
  2993. void OBSBasic::on_sources_itemDoubleClicked(QListWidgetItem *witem)
  2994. {
  2995. if (!witem)
  2996. return;
  2997. OBSSceneItem item = GetSceneItem(witem);
  2998. OBSSource source = obs_sceneitem_get_source(item);
  2999. if (source)
  3000. CreatePropertiesWindow(source);
  3001. }
  3002. void OBSBasic::AddSource(const char *id)
  3003. {
  3004. if (id && *id) {
  3005. OBSBasicSourceSelect sourceSelect(this, id);
  3006. sourceSelect.exec();
  3007. if (sourceSelect.newSource)
  3008. CreatePropertiesWindow(sourceSelect.newSource);
  3009. }
  3010. }
  3011. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  3012. {
  3013. const char *type;
  3014. bool foundValues = false;
  3015. bool foundDeprecated = false;
  3016. size_t idx = 0;
  3017. QMenu *popup = new QMenu(QTStr("Add"), this);
  3018. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  3019. auto getActionAfter = [] (QMenu *menu, const QString &name)
  3020. {
  3021. QList<QAction*> actions = menu->actions();
  3022. for (QAction *menuAction : actions) {
  3023. if (menuAction->text().compare(name) >= 0)
  3024. return menuAction;
  3025. }
  3026. return (QAction*)nullptr;
  3027. };
  3028. auto addSource = [this, getActionAfter] (QMenu *popup,
  3029. const char *type, const char *name)
  3030. {
  3031. QString qname = QT_UTF8(name);
  3032. QAction *popupItem = new QAction(qname, this);
  3033. popupItem->setData(QT_UTF8(type));
  3034. connect(popupItem, SIGNAL(triggered(bool)),
  3035. this, SLOT(AddSourceFromAction()));
  3036. QAction *after = getActionAfter(popup, qname);
  3037. popup->insertAction(after, popupItem);
  3038. };
  3039. while (obs_enum_input_types(idx++, &type)) {
  3040. const char *name = obs_source_get_display_name(type);
  3041. uint32_t caps = obs_get_source_output_flags(type);
  3042. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  3043. addSource(popup, type, name);
  3044. } else {
  3045. addSource(deprecated, type, name);
  3046. foundDeprecated = true;
  3047. }
  3048. foundValues = true;
  3049. }
  3050. addSource(popup, "scene", Str("Basic.Scene"));
  3051. if (!foundDeprecated) {
  3052. delete deprecated;
  3053. deprecated = nullptr;
  3054. }
  3055. if (!foundValues) {
  3056. delete popup;
  3057. popup = nullptr;
  3058. } else if (foundDeprecated) {
  3059. popup->addMenu(deprecated);
  3060. }
  3061. return popup;
  3062. }
  3063. void OBSBasic::AddSourceFromAction()
  3064. {
  3065. QAction *action = qobject_cast<QAction*>(sender());
  3066. if (!action)
  3067. return;
  3068. AddSource(QT_TO_UTF8(action->data().toString()));
  3069. }
  3070. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  3071. {
  3072. if (!GetCurrentScene()) {
  3073. // Tell the user he needs a scene first (help beginners).
  3074. OBSMessageBox::information(this,
  3075. QTStr("Basic.Main.AddSourceHelp.Title"),
  3076. QTStr("Basic.Main.AddSourceHelp.Text"));
  3077. return;
  3078. }
  3079. QPointer<QMenu> popup = CreateAddSourcePopupMenu();
  3080. if (popup)
  3081. popup->exec(pos);
  3082. }
  3083. void OBSBasic::on_actionAddSource_triggered()
  3084. {
  3085. AddSourcePopupMenu(QCursor::pos());
  3086. }
  3087. void OBSBasic::on_actionRemoveSource_triggered()
  3088. {
  3089. vector<OBSSceneItem> items;
  3090. auto func = [] (obs_scene_t *, obs_sceneitem_t *item, void *param)
  3091. {
  3092. vector<OBSSceneItem> &items =
  3093. *reinterpret_cast<vector<OBSSceneItem>*>(param);
  3094. if (obs_sceneitem_selected(item))
  3095. items.emplace_back(item);
  3096. return true;
  3097. };
  3098. obs_scene_enum_items(GetCurrentScene(), func, &items);
  3099. if (!items.size())
  3100. return;
  3101. auto removeMultiple = [this] (size_t count)
  3102. {
  3103. QString text = QTStr("ConfirmRemove.TextMultiple")
  3104. .arg(QString::number(count));
  3105. QMessageBox remove_items(this);
  3106. remove_items.setText(text);
  3107. QAbstractButton *Yes = remove_items.addButton(QTStr("Yes"),
  3108. QMessageBox::YesRole);
  3109. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  3110. remove_items.setIcon(QMessageBox::Question);
  3111. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3112. remove_items.exec();
  3113. return Yes == remove_items.clickedButton();
  3114. };
  3115. if (items.size() == 1) {
  3116. OBSSceneItem &item = items[0];
  3117. obs_source_t *source = obs_sceneitem_get_source(item);
  3118. if (source && QueryRemoveSource(source))
  3119. obs_sceneitem_remove(item);
  3120. } else {
  3121. if (removeMultiple(items.size())) {
  3122. for (auto &item : items)
  3123. obs_sceneitem_remove(item);
  3124. }
  3125. }
  3126. }
  3127. void OBSBasic::on_actionInteract_triggered()
  3128. {
  3129. OBSSceneItem item = GetCurrentSceneItem();
  3130. OBSSource source = obs_sceneitem_get_source(item);
  3131. if (source)
  3132. CreateInteractionWindow(source);
  3133. }
  3134. void OBSBasic::on_actionSourceProperties_triggered()
  3135. {
  3136. OBSSceneItem item = GetCurrentSceneItem();
  3137. OBSSource source = obs_sceneitem_get_source(item);
  3138. if (source)
  3139. CreatePropertiesWindow(source);
  3140. }
  3141. void OBSBasic::on_actionSourceUp_triggered()
  3142. {
  3143. OBSSceneItem item = GetCurrentSceneItem();
  3144. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3145. }
  3146. void OBSBasic::on_actionSourceDown_triggered()
  3147. {
  3148. OBSSceneItem item = GetCurrentSceneItem();
  3149. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3150. }
  3151. void OBSBasic::on_actionMoveUp_triggered()
  3152. {
  3153. OBSSceneItem item = GetCurrentSceneItem();
  3154. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
  3155. }
  3156. void OBSBasic::on_actionMoveDown_triggered()
  3157. {
  3158. OBSSceneItem item = GetCurrentSceneItem();
  3159. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
  3160. }
  3161. void OBSBasic::on_actionMoveToTop_triggered()
  3162. {
  3163. OBSSceneItem item = GetCurrentSceneItem();
  3164. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
  3165. }
  3166. void OBSBasic::on_actionMoveToBottom_triggered()
  3167. {
  3168. OBSSceneItem item = GetCurrentSceneItem();
  3169. obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
  3170. }
  3171. static BPtr<char> ReadLogFile(const char *log)
  3172. {
  3173. char logDir[512];
  3174. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3175. return nullptr;
  3176. string path = (char*)logDir;
  3177. path += "/";
  3178. path += log;
  3179. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  3180. if (!file)
  3181. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  3182. return file;
  3183. }
  3184. void OBSBasic::UploadLog(const char *file)
  3185. {
  3186. BPtr<char> fileString{ReadLogFile(file)};
  3187. if (!fileString)
  3188. return;
  3189. if (!*fileString)
  3190. return;
  3191. ui->menuLogFiles->setEnabled(false);
  3192. auto data_deleter = [](obs_data_t *d) { obs_data_release(d); };
  3193. using data_t = unique_ptr<struct obs_data, decltype(data_deleter)>;
  3194. data_t content{obs_data_create(), data_deleter};
  3195. data_t files{obs_data_create(), data_deleter};
  3196. data_t request{obs_data_create(), data_deleter};
  3197. obs_data_set_string(content.get(), "content", fileString);
  3198. obs_data_set_obj(files.get(), file, content.get());
  3199. stringstream ss;
  3200. ss << "OBS " << App()->GetVersionString()
  3201. << " log file uploaded at " << CurrentDateTimeString();
  3202. obs_data_set_string(request.get(), "description", ss.str().c_str());
  3203. obs_data_set_bool(request.get(), "public", false);
  3204. obs_data_set_obj(request.get(), "files", files.get());
  3205. const char *json = obs_data_get_json(request.get());
  3206. if (!json) {
  3207. blog(LOG_ERROR, "Failed to get JSON data for log upload");
  3208. return;
  3209. }
  3210. QBuffer *postData = new QBuffer();
  3211. postData->setData(json, (int) strlen(json));
  3212. if (logUploadThread) {
  3213. logUploadThread->wait();
  3214. delete logUploadThread;
  3215. }
  3216. RemoteTextThread *thread = new RemoteTextThread(
  3217. "https://api.github.com/gists",
  3218. "application/json", json);
  3219. logUploadThread = thread;
  3220. connect(thread, &RemoteTextThread::Result,
  3221. this, &OBSBasic::logUploadFinished);
  3222. logUploadThread->start();
  3223. }
  3224. void OBSBasic::on_actionShowLogs_triggered()
  3225. {
  3226. char logDir[512];
  3227. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3228. return;
  3229. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  3230. QDesktopServices::openUrl(url);
  3231. }
  3232. void OBSBasic::on_actionUploadCurrentLog_triggered()
  3233. {
  3234. UploadLog(App()->GetCurrentLog());
  3235. }
  3236. void OBSBasic::on_actionUploadLastLog_triggered()
  3237. {
  3238. UploadLog(App()->GetLastLog());
  3239. }
  3240. void OBSBasic::on_actionViewCurrentLog_triggered()
  3241. {
  3242. char logDir[512];
  3243. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  3244. return;
  3245. const char* log = App()->GetCurrentLog();
  3246. string path = (char*)logDir;
  3247. path += "/";
  3248. path += log;
  3249. QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
  3250. QDesktopServices::openUrl(url);
  3251. }
  3252. void OBSBasic::on_actionCheckForUpdates_triggered()
  3253. {
  3254. CheckForUpdates(true);
  3255. }
  3256. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  3257. {
  3258. ui->menuLogFiles->setEnabled(true);
  3259. if (text.isEmpty()) {
  3260. OBSMessageBox::information(this,
  3261. QTStr("LogReturnDialog.ErrorUploadingLog"),
  3262. error);
  3263. return;
  3264. }
  3265. obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
  3266. QString logURL = obs_data_get_string(returnData, "html_url");
  3267. obs_data_release(returnData);
  3268. OBSLogReply logDialog(this, logURL);
  3269. logDialog.exec();
  3270. }
  3271. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  3272. obs_source_t *source, const string &name)
  3273. {
  3274. const char *prevName = obs_source_get_name(source);
  3275. if (name == prevName)
  3276. return;
  3277. obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
  3278. QListWidgetItem *listItem = listWidget->currentItem();
  3279. if (foundSource || name.empty()) {
  3280. listItem->setText(QT_UTF8(prevName));
  3281. if (foundSource) {
  3282. OBSMessageBox::information(parent,
  3283. QTStr("NameExists.Title"),
  3284. QTStr("NameExists.Text"));
  3285. } else if (name.empty()) {
  3286. OBSMessageBox::information(parent,
  3287. QTStr("NoNameEntered.Title"),
  3288. QTStr("NoNameEntered.Text"));
  3289. }
  3290. obs_source_release(foundSource);
  3291. } else {
  3292. listItem->setText(QT_UTF8(name.c_str()));
  3293. obs_source_set_name(source, name.c_str());
  3294. }
  3295. }
  3296. void OBSBasic::SceneNameEdited(QWidget *editor,
  3297. QAbstractItemDelegate::EndEditHint endHint)
  3298. {
  3299. OBSScene scene = GetCurrentScene();
  3300. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3301. string text = QT_TO_UTF8(edit->text().trimmed());
  3302. if (!scene)
  3303. return;
  3304. obs_source_t *source = obs_scene_get_source(scene);
  3305. RenameListItem(this, ui->scenes, source, text);
  3306. if (api)
  3307. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3308. UNUSED_PARAMETER(endHint);
  3309. }
  3310. void OBSBasic::SceneItemNameEdited(QWidget *editor,
  3311. QAbstractItemDelegate::EndEditHint endHint)
  3312. {
  3313. OBSSceneItem item = GetCurrentSceneItem();
  3314. QLineEdit *edit = qobject_cast<QLineEdit*>(editor);
  3315. string text = QT_TO_UTF8(edit->text().trimmed());
  3316. if (!item)
  3317. return;
  3318. obs_source_t *source = obs_sceneitem_get_source(item);
  3319. RenameListItem(this, ui->sources, source, text);
  3320. QListWidgetItem *listItem = ui->sources->currentItem();
  3321. listItem->setText(QString());
  3322. SetupVisibilityItem(ui->sources, listItem, item);
  3323. UNUSED_PARAMETER(endHint);
  3324. }
  3325. void OBSBasic::OpenFilters()
  3326. {
  3327. OBSSceneItem item = GetCurrentSceneItem();
  3328. OBSSource source = obs_sceneitem_get_source(item);
  3329. CreateFiltersWindow(source);
  3330. }
  3331. void OBSBasic::OpenSceneFilters()
  3332. {
  3333. OBSScene scene = GetCurrentScene();
  3334. OBSSource source = obs_scene_get_source(scene);
  3335. CreateFiltersWindow(source);
  3336. }
  3337. #define RECORDING_START \
  3338. "==== Recording Start ==============================================="
  3339. #define RECORDING_STOP \
  3340. "==== Recording Stop ================================================"
  3341. #define REPLAY_BUFFER_START \
  3342. "==== Replay Buffer Start ==========================================="
  3343. #define REPLAY_BUFFER_STOP \
  3344. "==== Replay Buffer Stop ============================================"
  3345. #define STREAMING_START \
  3346. "==== Streaming Start ==============================================="
  3347. #define STREAMING_STOP \
  3348. "==== Streaming Stop ================================================"
  3349. void OBSBasic::StartStreaming()
  3350. {
  3351. if (outputHandler->StreamingActive())
  3352. return;
  3353. if (disableOutputsRef)
  3354. return;
  3355. if (api)
  3356. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  3357. SaveProject();
  3358. ui->streamButton->setEnabled(false);
  3359. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  3360. if (sysTrayStream) {
  3361. sysTrayStream->setEnabled(false);
  3362. sysTrayStream->setText(ui->streamButton->text());
  3363. }
  3364. if (!outputHandler->StartStreaming(service)) {
  3365. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3366. ui->streamButton->setEnabled(true);
  3367. if (sysTrayStream) {
  3368. sysTrayStream->setText(ui->streamButton->text());
  3369. sysTrayStream->setEnabled(true);
  3370. }
  3371. QMessageBox::critical(this,
  3372. QTStr("Output.StartStreamFailed"),
  3373. QTStr("Output.StartFailedGeneric"));
  3374. return;
  3375. }
  3376. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3377. "BasicWindow", "RecordWhenStreaming");
  3378. if (recordWhenStreaming)
  3379. StartRecording();
  3380. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3381. "BasicWindow", "ReplayBufferWhileStreaming");
  3382. if (replayBufferWhileStreaming)
  3383. StartReplayBuffer();
  3384. }
  3385. #ifdef _WIN32
  3386. static inline void UpdateProcessPriority()
  3387. {
  3388. const char *priority = config_get_string(App()->GlobalConfig(),
  3389. "General", "ProcessPriority");
  3390. if (priority && strcmp(priority, "Normal") != 0)
  3391. SetProcessPriority(priority);
  3392. }
  3393. static inline void ClearProcessPriority()
  3394. {
  3395. const char *priority = config_get_string(App()->GlobalConfig(),
  3396. "General", "ProcessPriority");
  3397. if (priority && strcmp(priority, "Normal") != 0)
  3398. SetProcessPriority("Normal");
  3399. }
  3400. #else
  3401. #define UpdateProcessPriority() do {} while(false)
  3402. #define ClearProcessPriority() do {} while(false)
  3403. #endif
  3404. inline void OBSBasic::OnActivate()
  3405. {
  3406. if (ui->profileMenu->isEnabled()) {
  3407. ui->profileMenu->setEnabled(false);
  3408. ui->autoConfigure->setEnabled(false);
  3409. App()->IncrementSleepInhibition();
  3410. UpdateProcessPriority();
  3411. if (trayIcon)
  3412. trayIcon->setIcon(QIcon(":/res/images/tray_active.png"));
  3413. }
  3414. }
  3415. inline void OBSBasic::OnDeactivate()
  3416. {
  3417. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  3418. ui->profileMenu->setEnabled(true);
  3419. ui->autoConfigure->setEnabled(true);
  3420. App()->DecrementSleepInhibition();
  3421. ClearProcessPriority();
  3422. if (trayIcon)
  3423. trayIcon->setIcon(QIcon(":/res/images/obs.png"));
  3424. }
  3425. }
  3426. void OBSBasic::StopStreaming()
  3427. {
  3428. SaveProject();
  3429. if (outputHandler->StreamingActive())
  3430. outputHandler->StopStreaming(streamingStopping);
  3431. OnDeactivate();
  3432. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3433. "BasicWindow", "RecordWhenStreaming");
  3434. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3435. "BasicWindow", "KeepRecordingWhenStreamStops");
  3436. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3437. StopRecording();
  3438. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3439. "BasicWindow", "ReplayBufferWhileStreaming");
  3440. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3441. "BasicWindow", "KeepReplayBufferStreamStops");
  3442. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3443. StopReplayBuffer();
  3444. }
  3445. void OBSBasic::ForceStopStreaming()
  3446. {
  3447. SaveProject();
  3448. if (outputHandler->StreamingActive())
  3449. outputHandler->StopStreaming(true);
  3450. OnDeactivate();
  3451. bool recordWhenStreaming = config_get_bool(GetGlobalConfig(),
  3452. "BasicWindow", "RecordWhenStreaming");
  3453. bool keepRecordingWhenStreamStops = config_get_bool(GetGlobalConfig(),
  3454. "BasicWindow", "KeepRecordingWhenStreamStops");
  3455. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  3456. StopRecording();
  3457. bool replayBufferWhileStreaming = config_get_bool(GetGlobalConfig(),
  3458. "BasicWindow", "ReplayBufferWhileStreaming");
  3459. bool keepReplayBufferStreamStops = config_get_bool(GetGlobalConfig(),
  3460. "BasicWindow", "KeepReplayBufferStreamStops");
  3461. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  3462. StopReplayBuffer();
  3463. }
  3464. void OBSBasic::StreamDelayStarting(int sec)
  3465. {
  3466. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3467. ui->streamButton->setEnabled(true);
  3468. if (sysTrayStream) {
  3469. sysTrayStream->setText(ui->streamButton->text());
  3470. sysTrayStream->setEnabled(true);
  3471. }
  3472. if (!startStreamMenu.isNull())
  3473. startStreamMenu->deleteLater();
  3474. startStreamMenu = new QMenu();
  3475. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"),
  3476. this, SLOT(StopStreaming()));
  3477. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3478. this, SLOT(ForceStopStreaming()));
  3479. ui->streamButton->setMenu(startStreamMenu);
  3480. ui->statusbar->StreamDelayStarting(sec);
  3481. OnActivate();
  3482. }
  3483. void OBSBasic::StreamDelayStopping(int sec)
  3484. {
  3485. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3486. ui->streamButton->setEnabled(true);
  3487. if (sysTrayStream) {
  3488. sysTrayStream->setText(ui->streamButton->text());
  3489. sysTrayStream->setEnabled(true);
  3490. }
  3491. if (!startStreamMenu.isNull())
  3492. startStreamMenu->deleteLater();
  3493. startStreamMenu = new QMenu();
  3494. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"),
  3495. this, SLOT(StartStreaming()));
  3496. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"),
  3497. this, SLOT(ForceStopStreaming()));
  3498. ui->streamButton->setMenu(startStreamMenu);
  3499. ui->statusbar->StreamDelayStopping(sec);
  3500. }
  3501. void OBSBasic::StreamingStart()
  3502. {
  3503. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  3504. ui->streamButton->setEnabled(true);
  3505. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  3506. if (sysTrayStream) {
  3507. sysTrayStream->setText(ui->streamButton->text());
  3508. sysTrayStream->setEnabled(true);
  3509. }
  3510. if (api)
  3511. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  3512. OnActivate();
  3513. blog(LOG_INFO, STREAMING_START);
  3514. }
  3515. void OBSBasic::StreamStopping()
  3516. {
  3517. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  3518. if (sysTrayStream)
  3519. sysTrayStream->setText(ui->streamButton->text());
  3520. streamingStopping = true;
  3521. if (api)
  3522. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  3523. }
  3524. void OBSBasic::StreamingStop(int code, QString last_error)
  3525. {
  3526. const char *errorDescription;
  3527. DStr errorMessage;
  3528. bool use_last_error = false;
  3529. switch (code) {
  3530. case OBS_OUTPUT_BAD_PATH:
  3531. errorDescription = Str("Output.ConnectFail.BadPath");
  3532. break;
  3533. case OBS_OUTPUT_CONNECT_FAILED:
  3534. use_last_error = true;
  3535. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  3536. break;
  3537. case OBS_OUTPUT_INVALID_STREAM:
  3538. errorDescription = Str("Output.ConnectFail.InvalidStream");
  3539. break;
  3540. default:
  3541. case OBS_OUTPUT_ERROR:
  3542. use_last_error = true;
  3543. errorDescription = Str("Output.ConnectFail.Error");
  3544. break;
  3545. case OBS_OUTPUT_DISCONNECTED:
  3546. /* doesn't happen if output is set to reconnect. note that
  3547. * reconnects are handled in the output, not in the UI */
  3548. use_last_error = true;
  3549. errorDescription = Str("Output.ConnectFail.Disconnected");
  3550. }
  3551. if (use_last_error && !last_error.isEmpty())
  3552. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  3553. QT_TO_UTF8(last_error));
  3554. else
  3555. dstr_copy(errorMessage, errorDescription);
  3556. ui->statusbar->StreamStopped();
  3557. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  3558. ui->streamButton->setEnabled(true);
  3559. if (sysTrayStream) {
  3560. sysTrayStream->setText(ui->streamButton->text());
  3561. sysTrayStream->setEnabled(true);
  3562. }
  3563. streamingStopping = false;
  3564. if (api)
  3565. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  3566. OnDeactivate();
  3567. blog(LOG_INFO, STREAMING_STOP);
  3568. if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3569. OBSMessageBox::information(this,
  3570. QTStr("Output.ConnectFail.Title"),
  3571. QT_UTF8(errorMessage));
  3572. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3573. SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning);
  3574. }
  3575. if (!startStreamMenu.isNull()) {
  3576. ui->streamButton->setMenu(nullptr);
  3577. startStreamMenu->deleteLater();
  3578. startStreamMenu = nullptr;
  3579. }
  3580. }
  3581. void OBSBasic::StartRecording()
  3582. {
  3583. if (outputHandler->RecordingActive())
  3584. return;
  3585. if (disableOutputsRef)
  3586. return;
  3587. if (api)
  3588. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  3589. SaveProject();
  3590. outputHandler->StartRecording();
  3591. }
  3592. void OBSBasic::RecordStopping()
  3593. {
  3594. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  3595. if (sysTrayRecord)
  3596. sysTrayRecord->setText(ui->recordButton->text());
  3597. recordingStopping = true;
  3598. if (api)
  3599. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  3600. }
  3601. void OBSBasic::StopRecording()
  3602. {
  3603. SaveProject();
  3604. if (outputHandler->RecordingActive())
  3605. outputHandler->StopRecording(recordingStopping);
  3606. OnDeactivate();
  3607. }
  3608. void OBSBasic::RecordingStart()
  3609. {
  3610. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  3611. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  3612. if (sysTrayRecord)
  3613. sysTrayRecord->setText(ui->recordButton->text());
  3614. recordingStopping = false;
  3615. if (api)
  3616. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  3617. OnActivate();
  3618. blog(LOG_INFO, RECORDING_START);
  3619. }
  3620. void OBSBasic::RecordingStop(int code)
  3621. {
  3622. ui->statusbar->RecordingStopped();
  3623. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  3624. if (sysTrayRecord)
  3625. sysTrayRecord->setText(ui->recordButton->text());
  3626. blog(LOG_INFO, RECORDING_STOP);
  3627. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3628. OBSMessageBox::information(this,
  3629. QTStr("Output.RecordFail.Title"),
  3630. QTStr("Output.RecordFail.Unsupported"));
  3631. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3632. OBSMessageBox::information(this,
  3633. QTStr("Output.RecordNoSpace.Title"),
  3634. QTStr("Output.RecordNoSpace.Msg"));
  3635. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3636. OBSMessageBox::information(this,
  3637. QTStr("Output.RecordError.Title"),
  3638. QTStr("Output.RecordError.Msg"));
  3639. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3640. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3641. QSystemTrayIcon::Warning);
  3642. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3643. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3644. QSystemTrayIcon::Warning);
  3645. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3646. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3647. QSystemTrayIcon::Warning);
  3648. }
  3649. if (api)
  3650. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  3651. OnDeactivate();
  3652. }
  3653. #define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
  3654. #define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
  3655. void OBSBasic::StartReplayBuffer()
  3656. {
  3657. if (!outputHandler || !outputHandler->replayBuffer)
  3658. return;
  3659. if (outputHandler->ReplayBufferActive())
  3660. return;
  3661. if (disableOutputsRef)
  3662. return;
  3663. obs_output_t *output = outputHandler->replayBuffer;
  3664. obs_data_t *hotkeys = obs_hotkeys_save_output(output);
  3665. obs_data_array_t *bindings = obs_data_get_array(hotkeys,
  3666. "ReplayBuffer.Save");
  3667. size_t count = obs_data_array_count(bindings);
  3668. obs_data_array_release(bindings);
  3669. obs_data_release(hotkeys);
  3670. if (!count) {
  3671. OBSMessageBox::information(this,
  3672. RP_NO_HOTKEY_TITLE,
  3673. RP_NO_HOTKEY_TEXT);
  3674. return;
  3675. }
  3676. if (api)
  3677. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  3678. SaveProject();
  3679. outputHandler->StartReplayBuffer();
  3680. }
  3681. void OBSBasic::ReplayBufferStopping()
  3682. {
  3683. if (!outputHandler || !outputHandler->replayBuffer)
  3684. return;
  3685. replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));
  3686. if (sysTrayReplayBuffer)
  3687. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3688. replayBufferStopping = true;
  3689. if (api)
  3690. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  3691. }
  3692. void OBSBasic::StopReplayBuffer()
  3693. {
  3694. if (!outputHandler || !outputHandler->replayBuffer)
  3695. return;
  3696. SaveProject();
  3697. if (outputHandler->ReplayBufferActive())
  3698. outputHandler->StopReplayBuffer(replayBufferStopping);
  3699. OnDeactivate();
  3700. }
  3701. void OBSBasic::ReplayBufferStart()
  3702. {
  3703. if (!outputHandler || !outputHandler->replayBuffer)
  3704. return;
  3705. replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
  3706. if (sysTrayReplayBuffer)
  3707. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3708. replayBufferStopping = false;
  3709. if (api)
  3710. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  3711. OnActivate();
  3712. blog(LOG_INFO, REPLAY_BUFFER_START);
  3713. }
  3714. void OBSBasic::ReplayBufferStop(int code)
  3715. {
  3716. if (!outputHandler || !outputHandler->replayBuffer)
  3717. return;
  3718. replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
  3719. if (sysTrayReplayBuffer)
  3720. sysTrayReplayBuffer->setText(replayBufferButton->text());
  3721. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  3722. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  3723. OBSMessageBox::information(this,
  3724. QTStr("Output.RecordFail.Title"),
  3725. QTStr("Output.RecordFail.Unsupported"));
  3726. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  3727. OBSMessageBox::information(this,
  3728. QTStr("Output.RecordNoSpace.Title"),
  3729. QTStr("Output.RecordNoSpace.Msg"));
  3730. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  3731. OBSMessageBox::information(this,
  3732. QTStr("Output.RecordError.Title"),
  3733. QTStr("Output.RecordError.Msg"));
  3734. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  3735. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  3736. QSystemTrayIcon::Warning);
  3737. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  3738. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  3739. QSystemTrayIcon::Warning);
  3740. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  3741. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  3742. QSystemTrayIcon::Warning);
  3743. }
  3744. if (api)
  3745. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  3746. OnDeactivate();
  3747. }
  3748. void OBSBasic::on_streamButton_clicked()
  3749. {
  3750. if (outputHandler->StreamingActive()) {
  3751. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3752. "WarnBeforeStoppingStream");
  3753. if (confirm && isVisible()) {
  3754. QMessageBox::StandardButton button =
  3755. OBSMessageBox::question(this,
  3756. QTStr("ConfirmStop.Title"),
  3757. QTStr("ConfirmStop.Text"));
  3758. if (button == QMessageBox::No)
  3759. return;
  3760. }
  3761. StopStreaming();
  3762. } else {
  3763. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3764. "WarnBeforeStartingStream");
  3765. if (confirm && isVisible()) {
  3766. QMessageBox::StandardButton button =
  3767. OBSMessageBox::question(this,
  3768. QTStr("ConfirmStart.Title"),
  3769. QTStr("ConfirmStart.Text"));
  3770. if (button == QMessageBox::No)
  3771. return;
  3772. }
  3773. StartStreaming();
  3774. }
  3775. }
  3776. void OBSBasic::on_recordButton_clicked()
  3777. {
  3778. if (outputHandler->RecordingActive())
  3779. StopRecording();
  3780. else
  3781. StartRecording();
  3782. }
  3783. void OBSBasic::on_settingsButton_clicked()
  3784. {
  3785. on_action_Settings_triggered();
  3786. }
  3787. void OBSBasic::on_actionWebsite_triggered()
  3788. {
  3789. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  3790. QDesktopServices::openUrl(url);
  3791. }
  3792. void OBSBasic::on_actionShowSettingsFolder_triggered()
  3793. {
  3794. char path[512];
  3795. int ret = GetConfigPath(path, 512, "obs-studio");
  3796. if (ret <= 0)
  3797. return;
  3798. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3799. }
  3800. void OBSBasic::on_actionShowProfileFolder_triggered()
  3801. {
  3802. char path[512];
  3803. int ret = GetProfilePath(path, 512, "");
  3804. if (ret <= 0)
  3805. return;
  3806. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  3807. }
  3808. QListWidgetItem *OBSBasic::GetTopSelectedSourceItem()
  3809. {
  3810. QList<QListWidgetItem*> selectedItems = ui->sources->selectedItems();
  3811. QListWidgetItem *topItem = nullptr;
  3812. if (selectedItems.size() != 0)
  3813. topItem = selectedItems[0];
  3814. return topItem;
  3815. }
  3816. void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
  3817. {
  3818. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  3819. UNUSED_PARAMETER(pos);
  3820. }
  3821. void OBSBasic::on_previewDisabledLabel_customContextMenuRequested(
  3822. const QPoint &pos)
  3823. {
  3824. QMenu popup(this);
  3825. QPointer<QMenu> previewProjector;
  3826. QAction *action = popup.addAction(
  3827. QTStr("Basic.Main.PreviewConextMenu.Enable"),
  3828. this, SLOT(TogglePreview()));
  3829. action->setCheckable(true);
  3830. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  3831. previewProjector = new QMenu(QTStr("PreviewProjector"));
  3832. AddProjectorMenuMonitors(previewProjector, this,
  3833. SLOT(OpenPreviewProjector()));
  3834. QAction *previewWindow = popup.addAction(
  3835. QTStr("PreviewWindow"),
  3836. this, SLOT(OpenPreviewWindow()));
  3837. popup.addMenu(previewProjector);
  3838. popup.addAction(previewWindow);
  3839. popup.exec(QCursor::pos());
  3840. UNUSED_PARAMETER(pos);
  3841. }
  3842. void OBSBasic::on_actionAlwaysOnTop_triggered()
  3843. {
  3844. CloseDialogs();
  3845. /* Make sure all dialogs are safely and successfully closed before
  3846. * switching the always on top mode due to the fact that windows all
  3847. * have to be recreated, so queue the actual toggle to happen after
  3848. * all events related to closing the dialogs have finished */
  3849. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  3850. Qt::QueuedConnection);
  3851. }
  3852. void OBSBasic::ToggleAlwaysOnTop()
  3853. {
  3854. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  3855. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  3856. SetAlwaysOnTop(this, !isAlwaysOnTop);
  3857. show();
  3858. }
  3859. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  3860. {
  3861. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  3862. if (strcmp(val, "10") == 0) {
  3863. num = 10;
  3864. den = 1;
  3865. } else if (strcmp(val, "20") == 0) {
  3866. num = 20;
  3867. den = 1;
  3868. } else if (strcmp(val, "24 NTSC") == 0) {
  3869. num = 24000;
  3870. den = 1001;
  3871. } else if (strcmp(val, "25") == 0) {
  3872. num = 25;
  3873. den = 1;
  3874. } else if (strcmp(val, "29.97") == 0) {
  3875. num = 30000;
  3876. den = 1001;
  3877. } else if (strcmp(val, "48") == 0) {
  3878. num = 48;
  3879. den = 1;
  3880. } else if (strcmp(val, "59.94") == 0) {
  3881. num = 60000;
  3882. den = 1001;
  3883. } else if (strcmp(val, "60") == 0) {
  3884. num = 60;
  3885. den = 1;
  3886. } else {
  3887. num = 30;
  3888. den = 1;
  3889. }
  3890. }
  3891. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  3892. {
  3893. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  3894. den = 1;
  3895. }
  3896. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  3897. {
  3898. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  3899. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  3900. }
  3901. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  3902. {
  3903. num = 1000000000;
  3904. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  3905. }
  3906. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  3907. {
  3908. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  3909. if (type == 1) //"Integer"
  3910. GetFPSInteger(num, den);
  3911. else if (type == 2) //"Fraction"
  3912. GetFPSFraction(num, den);
  3913. else if (false) //"Nanoseconds", currently not implemented
  3914. GetFPSNanoseconds(num, den);
  3915. else
  3916. GetFPSCommon(num, den);
  3917. }
  3918. config_t *OBSBasic::Config() const
  3919. {
  3920. return basicConfig;
  3921. }
  3922. void OBSBasic::on_actionEditTransform_triggered()
  3923. {
  3924. if (transformWindow)
  3925. transformWindow->close();
  3926. transformWindow = new OBSBasicTransform(this);
  3927. transformWindow->show();
  3928. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  3929. }
  3930. static obs_transform_info copiedTransformInfo;
  3931. static obs_sceneitem_crop copiedCropInfo;
  3932. void OBSBasic::on_actionCopyTransform_triggered()
  3933. {
  3934. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3935. {
  3936. if (!obs_sceneitem_selected(item))
  3937. return true;
  3938. obs_sceneitem_defer_update_begin(item);
  3939. obs_sceneitem_get_info(item, &copiedTransformInfo);
  3940. obs_sceneitem_get_crop(item, &copiedCropInfo);
  3941. obs_sceneitem_defer_update_end(item);
  3942. UNUSED_PARAMETER(scene);
  3943. UNUSED_PARAMETER(param);
  3944. return true;
  3945. };
  3946. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3947. ui->actionPasteTransform->setEnabled(true);
  3948. }
  3949. void OBSBasic::on_actionPasteTransform_triggered()
  3950. {
  3951. auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3952. {
  3953. if (!obs_sceneitem_selected(item))
  3954. return true;
  3955. obs_sceneitem_defer_update_begin(item);
  3956. obs_sceneitem_set_info(item, &copiedTransformInfo);
  3957. obs_sceneitem_set_crop(item, &copiedCropInfo);
  3958. obs_sceneitem_defer_update_end(item);
  3959. UNUSED_PARAMETER(scene);
  3960. UNUSED_PARAMETER(param);
  3961. return true;
  3962. };
  3963. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3964. }
  3965. void OBSBasic::on_actionResetTransform_triggered()
  3966. {
  3967. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  3968. {
  3969. if (!obs_sceneitem_selected(item))
  3970. return true;
  3971. obs_sceneitem_defer_update_begin(item);
  3972. obs_transform_info info;
  3973. vec2_set(&info.pos, 0.0f, 0.0f);
  3974. vec2_set(&info.scale, 1.0f, 1.0f);
  3975. info.rot = 0.0f;
  3976. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  3977. info.bounds_type = OBS_BOUNDS_NONE;
  3978. info.bounds_alignment = OBS_ALIGN_CENTER;
  3979. vec2_set(&info.bounds, 0.0f, 0.0f);
  3980. obs_sceneitem_set_info(item, &info);
  3981. obs_sceneitem_crop crop = {};
  3982. obs_sceneitem_set_crop(item, &crop);
  3983. obs_sceneitem_defer_update_end(item);
  3984. UNUSED_PARAMETER(scene);
  3985. UNUSED_PARAMETER(param);
  3986. return true;
  3987. };
  3988. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  3989. }
  3990. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  3991. {
  3992. matrix4 boxTransform;
  3993. obs_sceneitem_get_box_transform(item, &boxTransform);
  3994. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  3995. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  3996. auto GetMinPos = [&] (float x, float y)
  3997. {
  3998. vec3 pos;
  3999. vec3_set(&pos, x, y, 0.0f);
  4000. vec3_transform(&pos, &pos, &boxTransform);
  4001. vec3_min(&tl, &tl, &pos);
  4002. vec3_max(&br, &br, &pos);
  4003. };
  4004. GetMinPos(0.0f, 0.0f);
  4005. GetMinPos(1.0f, 0.0f);
  4006. GetMinPos(0.0f, 1.0f);
  4007. GetMinPos(1.0f, 1.0f);
  4008. }
  4009. static vec3 GetItemTL(obs_sceneitem_t *item)
  4010. {
  4011. vec3 tl, br;
  4012. GetItemBox(item, tl, br);
  4013. return tl;
  4014. }
  4015. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  4016. {
  4017. vec3 newTL;
  4018. vec2 pos;
  4019. obs_sceneitem_get_pos(item, &pos);
  4020. newTL = GetItemTL(item);
  4021. pos.x += tl.x - newTL.x;
  4022. pos.y += tl.y - newTL.y;
  4023. obs_sceneitem_set_pos(item, &pos);
  4024. }
  4025. static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
  4026. void *param)
  4027. {
  4028. if (!obs_sceneitem_selected(item))
  4029. return true;
  4030. float rot = *reinterpret_cast<float*>(param);
  4031. vec3 tl = GetItemTL(item);
  4032. rot += obs_sceneitem_get_rot(item);
  4033. if (rot >= 360.0f) rot -= 360.0f;
  4034. else if (rot <= -360.0f) rot += 360.0f;
  4035. obs_sceneitem_set_rot(item, rot);
  4036. SetItemTL(item, tl);
  4037. UNUSED_PARAMETER(scene);
  4038. UNUSED_PARAMETER(param);
  4039. return true;
  4040. };
  4041. void OBSBasic::on_actionRotate90CW_triggered()
  4042. {
  4043. float f90CW = 90.0f;
  4044. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  4045. }
  4046. void OBSBasic::on_actionRotate90CCW_triggered()
  4047. {
  4048. float f90CCW = -90.0f;
  4049. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  4050. }
  4051. void OBSBasic::on_actionRotate180_triggered()
  4052. {
  4053. float f180 = 180.0f;
  4054. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  4055. }
  4056. static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
  4057. void *param)
  4058. {
  4059. vec2 &mul = *reinterpret_cast<vec2*>(param);
  4060. if (!obs_sceneitem_selected(item))
  4061. return true;
  4062. vec3 tl = GetItemTL(item);
  4063. vec2 scale;
  4064. obs_sceneitem_get_scale(item, &scale);
  4065. vec2_mul(&scale, &scale, &mul);
  4066. obs_sceneitem_set_scale(item, &scale);
  4067. SetItemTL(item, tl);
  4068. UNUSED_PARAMETER(scene);
  4069. return true;
  4070. }
  4071. void OBSBasic::on_actionFlipHorizontal_triggered()
  4072. {
  4073. vec2 scale;
  4074. vec2_set(&scale, -1.0f, 1.0f);
  4075. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4076. &scale);
  4077. }
  4078. void OBSBasic::on_actionFlipVertical_triggered()
  4079. {
  4080. vec2 scale;
  4081. vec2_set(&scale, 1.0f, -1.0f);
  4082. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  4083. &scale);
  4084. }
  4085. static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
  4086. void *param)
  4087. {
  4088. obs_bounds_type boundsType = *reinterpret_cast<obs_bounds_type*>(param);
  4089. if (!obs_sceneitem_selected(item))
  4090. return true;
  4091. obs_video_info ovi;
  4092. obs_get_video_info(&ovi);
  4093. obs_transform_info itemInfo;
  4094. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  4095. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  4096. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  4097. itemInfo.rot = 0.0f;
  4098. vec2_set(&itemInfo.bounds,
  4099. float(ovi.base_width), float(ovi.base_height));
  4100. itemInfo.bounds_type = boundsType;
  4101. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  4102. obs_sceneitem_set_info(item, &itemInfo);
  4103. UNUSED_PARAMETER(scene);
  4104. return true;
  4105. }
  4106. void OBSBasic::on_actionFitToScreen_triggered()
  4107. {
  4108. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  4109. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4110. &boundsType);
  4111. }
  4112. void OBSBasic::on_actionStretchToScreen_triggered()
  4113. {
  4114. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  4115. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  4116. &boundsType);
  4117. }
  4118. void OBSBasic::on_actionCenterToScreen_triggered()
  4119. {
  4120. auto func = [] (obs_scene_t *scene, obs_sceneitem_t *item, void *param)
  4121. {
  4122. vec3 tl, br, itemCenter, screenCenter, offset;
  4123. obs_video_info ovi;
  4124. if (!obs_sceneitem_selected(item))
  4125. return true;
  4126. obs_get_video_info(&ovi);
  4127. vec3_set(&screenCenter, float(ovi.base_width),
  4128. float(ovi.base_height), 0.0f);
  4129. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  4130. GetItemBox(item, tl, br);
  4131. vec3_sub(&itemCenter, &br, &tl);
  4132. vec3_mulf(&itemCenter, &itemCenter, 0.5f);
  4133. vec3_add(&itemCenter, &itemCenter, &tl);
  4134. vec3_sub(&offset, &screenCenter, &itemCenter);
  4135. vec3_add(&tl, &tl, &offset);
  4136. SetItemTL(item, tl);
  4137. UNUSED_PARAMETER(scene);
  4138. UNUSED_PARAMETER(param);
  4139. return true;
  4140. };
  4141. obs_scene_enum_items(GetCurrentScene(), func, nullptr);
  4142. }
  4143. void OBSBasic::EnablePreviewDisplay(bool enable)
  4144. {
  4145. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  4146. ui->preview->setVisible(enable);
  4147. ui->previewDisabledLabel->setVisible(!enable);
  4148. }
  4149. void OBSBasic::TogglePreview()
  4150. {
  4151. previewEnabled = !previewEnabled;
  4152. EnablePreviewDisplay(previewEnabled);
  4153. }
  4154. void OBSBasic::Nudge(int dist, MoveDir dir)
  4155. {
  4156. if (ui->preview->Locked())
  4157. return;
  4158. struct MoveInfo {
  4159. float dist;
  4160. MoveDir dir;
  4161. } info = {(float)dist, dir};
  4162. auto func = [] (obs_scene_t*, obs_sceneitem_t *item, void *param)
  4163. {
  4164. if (obs_sceneitem_locked(item))
  4165. return true;
  4166. MoveInfo *info = reinterpret_cast<MoveInfo*>(param);
  4167. struct vec2 dir;
  4168. struct vec2 pos;
  4169. vec2_set(&dir, 0.0f, 0.0f);
  4170. if (!obs_sceneitem_selected(item))
  4171. return true;
  4172. switch (info->dir) {
  4173. case MoveDir::Up: dir.y = -info->dist; break;
  4174. case MoveDir::Down: dir.y = info->dist; break;
  4175. case MoveDir::Left: dir.x = -info->dist; break;
  4176. case MoveDir::Right: dir.x = info->dist; break;
  4177. }
  4178. obs_sceneitem_get_pos(item, &pos);
  4179. vec2_add(&pos, &pos, &dir);
  4180. obs_sceneitem_set_pos(item, &pos);
  4181. return true;
  4182. };
  4183. obs_scene_enum_items(GetCurrentScene(), func, &info);
  4184. }
  4185. void OBSBasic::NudgeUp() {Nudge(1, MoveDir::Up);}
  4186. void OBSBasic::NudgeDown() {Nudge(1, MoveDir::Down);}
  4187. void OBSBasic::NudgeLeft() {Nudge(1, MoveDir::Left);}
  4188. void OBSBasic::NudgeRight() {Nudge(1, MoveDir::Right);}
  4189. void OBSBasic::OpenProjector(obs_source_t *source, int monitor, bool window,
  4190. QString title)
  4191. {
  4192. /* seriously? 10 monitors? */
  4193. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  4194. return;
  4195. bool isPreview = false;
  4196. if (source == nullptr)
  4197. isPreview = true;
  4198. if (!window) {
  4199. delete projectors[monitor];
  4200. projectors[monitor].clear();
  4201. RemoveSavedProjectors(monitor);
  4202. }
  4203. OBSProjector *projector = new OBSProjector(nullptr, source, !!window);
  4204. const char *name = obs_source_get_name(source);
  4205. if (!window) {
  4206. if (isPreview) {
  4207. previewProjectorArray.at((size_t)monitor) = 1;
  4208. } else {
  4209. projectorArray.at((size_t)monitor) = name;
  4210. }
  4211. }
  4212. if (!window) {
  4213. projector->Init(monitor, false, nullptr);
  4214. projectors[monitor] = projector;
  4215. } else {
  4216. projector->Init(monitor, true, title);
  4217. for (auto &projPtr : windowProjectors) {
  4218. if (!projPtr) {
  4219. projPtr = projector;
  4220. projector = nullptr;
  4221. }
  4222. }
  4223. if (projector)
  4224. windowProjectors.push_back(projector);
  4225. }
  4226. }
  4227. void OBSBasic::OpenPreviewProjector()
  4228. {
  4229. int monitor = sender()->property("monitor").toInt();
  4230. OpenProjector(nullptr, monitor, false);
  4231. }
  4232. void OBSBasic::OpenSourceProjector()
  4233. {
  4234. int monitor = sender()->property("monitor").toInt();
  4235. OBSSceneItem item = GetCurrentSceneItem();
  4236. if (!item)
  4237. return;
  4238. OpenProjector(obs_sceneitem_get_source(item), monitor, false);
  4239. }
  4240. void OBSBasic::OpenSceneProjector()
  4241. {
  4242. int monitor = sender()->property("monitor").toInt();
  4243. OBSScene scene = GetCurrentScene();
  4244. if (!scene)
  4245. return;
  4246. OpenProjector(obs_scene_get_source(scene), monitor, false);
  4247. }
  4248. void OBSBasic::OpenPreviewWindow()
  4249. {
  4250. int monitor = sender()->property("monitor").toInt();
  4251. QString title = QTStr("PreviewWindow");
  4252. OpenProjector(nullptr, monitor, true, title);
  4253. }
  4254. void OBSBasic::OpenSourceWindow()
  4255. {
  4256. int monitor = sender()->property("monitor").toInt();
  4257. OBSSceneItem item = GetCurrentSceneItem();
  4258. OBSSource source = obs_sceneitem_get_source(item);
  4259. QString text = QString::fromUtf8(obs_source_get_name(source));
  4260. QString title = QTStr("SourceWindow") + " - " + text;
  4261. if (!item)
  4262. return;
  4263. OpenProjector(obs_sceneitem_get_source(item), monitor, true, title);
  4264. }
  4265. void OBSBasic::OpenSceneWindow()
  4266. {
  4267. int monitor = sender()->property("monitor").toInt();
  4268. OBSScene scene = GetCurrentScene();
  4269. OBSSource source = obs_scene_get_source(scene);
  4270. QString text = QString::fromUtf8(obs_source_get_name(source));
  4271. QString title = QTStr("SceneWindow") + " - " + text;
  4272. if (!scene)
  4273. return;
  4274. OpenProjector(obs_scene_get_source(scene), monitor, true, title);
  4275. }
  4276. void OBSBasic::OpenSavedProjectors()
  4277. {
  4278. bool projectorSave = config_get_bool(GetGlobalConfig(),
  4279. "BasicWindow", "SaveProjectors");
  4280. if (projectorSave) {
  4281. for (size_t i = 0; i < projectorArray.size(); i++) {
  4282. if (projectorArray.at(i).empty() == false) {
  4283. OBSSource source = obs_get_source_by_name(
  4284. projectorArray.at(i).c_str());
  4285. if (!source) {
  4286. RemoveSavedProjectors((int)i);
  4287. obs_source_release(source);
  4288. continue;
  4289. }
  4290. OpenProjector(source, (int)i, false);
  4291. obs_source_release(source);
  4292. }
  4293. }
  4294. for (size_t i = 0; i < previewProjectorArray.size(); i++) {
  4295. if (previewProjectorArray.at(i) == 1) {
  4296. OpenProjector(nullptr, (int)i, false);
  4297. }
  4298. }
  4299. }
  4300. }
  4301. void OBSBasic::RemoveSavedProjectors(int monitor)
  4302. {
  4303. previewProjectorArray.at((size_t)monitor) = 0;
  4304. projectorArray.at((size_t)monitor) = "";
  4305. }
  4306. void OBSBasic::on_actionFullscreenInterface_triggered()
  4307. {
  4308. if (!fullscreenInterface)
  4309. showFullScreen();
  4310. else
  4311. showNormal();
  4312. fullscreenInterface = !fullscreenInterface;
  4313. }
  4314. void OBSBasic::UpdateTitleBar()
  4315. {
  4316. stringstream name;
  4317. const char *profile = config_get_string(App()->GlobalConfig(),
  4318. "Basic", "Profile");
  4319. const char *sceneCollection = config_get_string(App()->GlobalConfig(),
  4320. "Basic", "SceneCollection");
  4321. name << "OBS ";
  4322. if (previewProgramMode)
  4323. name << "Studio ";
  4324. name << App()->GetVersionString();
  4325. if (App()->IsPortableMode())
  4326. name << " - Portable Mode";
  4327. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  4328. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  4329. setWindowTitle(QT_UTF8(name.str().c_str()));
  4330. }
  4331. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  4332. {
  4333. char profiles_path[512];
  4334. const char *profile = config_get_string(App()->GlobalConfig(),
  4335. "Basic", "ProfileDir");
  4336. int ret;
  4337. if (!profile)
  4338. return -1;
  4339. if (!path)
  4340. return -1;
  4341. if (!file)
  4342. file = "";
  4343. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  4344. if (ret <= 0)
  4345. return ret;
  4346. if (!*file)
  4347. return snprintf(path, size, "%s/%s", profiles_path, profile);
  4348. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  4349. }
  4350. void OBSBasic::on_resetUI_triggered()
  4351. {
  4352. restoreState(startingDockLayout);
  4353. #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
  4354. int cx = width();
  4355. int cy = height();
  4356. int cx22_5 = cx * 225 / 1000;
  4357. int cx5 = cx * 5 / 100;
  4358. cy = cy * 225 / 1000;
  4359. int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);
  4360. QList<QDockWidget*> docks {
  4361. ui->scenesDock,
  4362. ui->sourcesDock,
  4363. ui->mixerDock,
  4364. ui->transitionsDock,
  4365. ui->controlsDock
  4366. };
  4367. QList<int> sizes {
  4368. cx22_5,
  4369. cx22_5,
  4370. mixerSize,
  4371. cx5,
  4372. cx5
  4373. };
  4374. ui->scenesDock->setVisible(true);
  4375. ui->sourcesDock->setVisible(true);
  4376. ui->mixerDock->setVisible(true);
  4377. ui->transitionsDock->setVisible(true);
  4378. ui->controlsDock->setVisible(true);
  4379. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  4380. resizeDocks(docks, sizes, Qt::Horizontal);
  4381. #endif
  4382. }
  4383. void OBSBasic::on_lockUI_toggled(bool lock)
  4384. {
  4385. QDockWidget::DockWidgetFeatures features = lock
  4386. ? QDockWidget::NoDockWidgetFeatures
  4387. : QDockWidget::AllDockWidgetFeatures;
  4388. ui->scenesDock->setFeatures(features);
  4389. ui->sourcesDock->setFeatures(features);
  4390. ui->mixerDock->setFeatures(features);
  4391. ui->transitionsDock->setFeatures(features);
  4392. ui->controlsDock->setFeatures(features);
  4393. }
  4394. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  4395. {
  4396. ui->sourcesToolbar->setVisible(visible);
  4397. ui->scenesToolbar->setVisible(visible);
  4398. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4399. "ShowListboxToolbars", visible);
  4400. }
  4401. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  4402. {
  4403. ui->statusbar->setVisible(visible);
  4404. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  4405. "ShowStatusBar", visible);
  4406. }
  4407. void OBSBasic::on_actionLockPreview_triggered()
  4408. {
  4409. ui->preview->ToggleLocked();
  4410. ui->actionLockPreview->setChecked(ui->preview->Locked());
  4411. }
  4412. void OBSBasic::on_scalingMenu_aboutToShow()
  4413. {
  4414. obs_video_info ovi;
  4415. obs_get_video_info(&ovi);
  4416. QAction *action = ui->actionScaleCanvas;
  4417. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  4418. text = text.arg(QString::number(ovi.base_width),
  4419. QString::number(ovi.base_height));
  4420. action->setText(text);
  4421. action = ui->actionScaleOutput;
  4422. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  4423. text = text.arg(QString::number(ovi.output_width),
  4424. QString::number(ovi.output_height));
  4425. action->setText(text);
  4426. action->setVisible(!(ovi.output_width == ovi.base_width &&
  4427. ovi.output_height == ovi.base_height));
  4428. UpdatePreviewScalingMenu();
  4429. }
  4430. void OBSBasic::on_actionScaleWindow_triggered()
  4431. {
  4432. ui->preview->SetFixedScaling(false);
  4433. ui->preview->ResetScrollingOffset();
  4434. emit ui->preview->DisplayResized();
  4435. }
  4436. void OBSBasic::on_actionScaleCanvas_triggered()
  4437. {
  4438. ui->preview->SetFixedScaling(true);
  4439. ui->preview->SetScalingLevel(0);
  4440. emit ui->preview->DisplayResized();
  4441. }
  4442. void OBSBasic::on_actionScaleOutput_triggered()
  4443. {
  4444. obs_video_info ovi;
  4445. obs_get_video_info(&ovi);
  4446. ui->preview->SetFixedScaling(true);
  4447. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  4448. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  4449. int32_t approxScalingLevel = int32_t(
  4450. round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  4451. ui->preview->SetScalingLevel(approxScalingLevel);
  4452. ui->preview->SetScalingAmount(scalingAmount);
  4453. emit ui->preview->DisplayResized();
  4454. }
  4455. void OBSBasic::SetShowing(bool showing)
  4456. {
  4457. if (!showing && isVisible()) {
  4458. config_set_string(App()->GlobalConfig(),
  4459. "BasicWindow", "geometry",
  4460. saveGeometry().toBase64().constData());
  4461. /* hide all visible child dialogs */
  4462. visDlgPositions.clear();
  4463. if (!visDialogs.isEmpty()) {
  4464. for (QDialog *dlg : visDialogs) {
  4465. visDlgPositions.append(dlg->pos());
  4466. dlg->hide();
  4467. }
  4468. }
  4469. if (showHide)
  4470. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4471. QTimer::singleShot(250, this, SLOT(hide()));
  4472. if (previewEnabled)
  4473. EnablePreviewDisplay(false);
  4474. setVisible(false);
  4475. } else if (showing && !isVisible()) {
  4476. if (showHide)
  4477. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4478. QTimer::singleShot(250, this, SLOT(show()));
  4479. if (previewEnabled)
  4480. EnablePreviewDisplay(true);
  4481. setVisible(true);
  4482. /* show all child dialogs that was visible earlier */
  4483. if (!visDialogs.isEmpty()) {
  4484. for (int i = 0; i < visDialogs.size(); ++i) {
  4485. QDialog *dlg = visDialogs[i];
  4486. dlg->move(visDlgPositions[i]);
  4487. dlg->show();
  4488. }
  4489. }
  4490. /* Unminimize window if it was hidden to tray instead of task
  4491. * bar. */
  4492. if (sysTrayMinimizeToTray()) {
  4493. Qt::WindowStates state;
  4494. state = windowState() & ~Qt::WindowMinimized;
  4495. state |= Qt::WindowActive;
  4496. setWindowState(state);
  4497. }
  4498. }
  4499. }
  4500. void OBSBasic::ToggleShowHide()
  4501. {
  4502. bool showing = isVisible();
  4503. if (showing) {
  4504. /* check for modal dialogs */
  4505. EnumDialogs();
  4506. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  4507. return;
  4508. }
  4509. SetShowing(!showing);
  4510. }
  4511. void OBSBasic::SystemTrayInit()
  4512. {
  4513. trayIcon = new QSystemTrayIcon(QIcon(":/res/images/obs.png"),
  4514. this);
  4515. trayIcon->setToolTip("OBS Studio");
  4516. showHide = new QAction(QTStr("Basic.SystemTray.Show"),
  4517. trayIcon);
  4518. sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
  4519. trayIcon);
  4520. sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
  4521. trayIcon);
  4522. sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
  4523. trayIcon);
  4524. exit = new QAction(QTStr("Exit"),
  4525. trayIcon);
  4526. if (outputHandler && !outputHandler->replayBuffer)
  4527. sysTrayReplayBuffer->setEnabled(false);
  4528. connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
  4529. this,
  4530. SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
  4531. connect(showHide, SIGNAL(triggered()),
  4532. this, SLOT(ToggleShowHide()));
  4533. connect(sysTrayStream, SIGNAL(triggered()),
  4534. this, SLOT(on_streamButton_clicked()));
  4535. connect(sysTrayRecord, SIGNAL(triggered()),
  4536. this, SLOT(on_recordButton_clicked()));
  4537. connect(sysTrayReplayBuffer.data(), &QAction::triggered,
  4538. this, &OBSBasic::ReplayBufferClicked);
  4539. connect(exit, SIGNAL(triggered()),
  4540. this, SLOT(close()));
  4541. QMenu *previewProjector = new QMenu(QTStr("PreviewProjector"));
  4542. AddProjectorMenuMonitors(previewProjector, this,
  4543. SLOT(OpenPreviewProjector()));
  4544. trayMenu = new QMenu;
  4545. trayMenu->addAction(showHide);
  4546. trayMenu->addMenu(previewProjector);
  4547. trayMenu->addAction(sysTrayStream);
  4548. trayMenu->addAction(sysTrayRecord);
  4549. trayMenu->addAction(sysTrayReplayBuffer);
  4550. trayMenu->addAction(exit);
  4551. trayIcon->setContextMenu(trayMenu);
  4552. }
  4553. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  4554. {
  4555. if (reason == QSystemTrayIcon::Trigger)
  4556. ToggleShowHide();
  4557. }
  4558. void OBSBasic::SysTrayNotify(const QString &text,
  4559. QSystemTrayIcon::MessageIcon n)
  4560. {
  4561. if (QSystemTrayIcon::supportsMessages()) {
  4562. QSystemTrayIcon::MessageIcon icon =
  4563. QSystemTrayIcon::MessageIcon(n);
  4564. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  4565. }
  4566. }
  4567. void OBSBasic::SystemTray(bool firstStarted)
  4568. {
  4569. if (!QSystemTrayIcon::isSystemTrayAvailable())
  4570. return;
  4571. bool sysTrayWhenStarted = config_get_bool(GetGlobalConfig(),
  4572. "BasicWindow", "SysTrayWhenStarted");
  4573. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(),
  4574. "BasicWindow", "SysTrayEnabled");
  4575. if (firstStarted)
  4576. SystemTrayInit();
  4577. if (!sysTrayWhenStarted && !sysTrayEnabled) {
  4578. trayIcon->hide();
  4579. } else if ((sysTrayWhenStarted && sysTrayEnabled)
  4580. || opt_minimize_tray) {
  4581. trayIcon->show();
  4582. if (firstStarted) {
  4583. QTimer::singleShot(50, this, SLOT(hide()));
  4584. EnablePreviewDisplay(false);
  4585. setVisible(false);
  4586. opt_minimize_tray = false;
  4587. }
  4588. } else if (sysTrayEnabled) {
  4589. trayIcon->show();
  4590. } else if (!sysTrayEnabled) {
  4591. trayIcon->hide();
  4592. } else if (!sysTrayWhenStarted && sysTrayEnabled) {
  4593. trayIcon->hide();
  4594. }
  4595. if (isVisible())
  4596. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  4597. else
  4598. showHide->setText(QTStr("Basic.SystemTray.Show"));
  4599. }
  4600. bool OBSBasic::sysTrayMinimizeToTray()
  4601. {
  4602. return config_get_bool(GetGlobalConfig(),
  4603. "BasicWindow", "SysTrayMinimizeToTray");
  4604. }
  4605. void OBSBasic::on_actionCopySource_triggered()
  4606. {
  4607. on_actionCopyTransform_triggered();
  4608. OBSSceneItem item = GetCurrentSceneItem();
  4609. if (!item)
  4610. return;
  4611. OBSSource source = obs_sceneitem_get_source(item);
  4612. copyString = obs_source_get_name(source);
  4613. copyVisible = obs_sceneitem_visible(item);
  4614. ui->actionPasteRef->setEnabled(true);
  4615. ui->actionPasteDup->setEnabled(true);
  4616. }
  4617. void OBSBasic::on_actionPasteRef_triggered()
  4618. {
  4619. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, false);
  4620. on_actionPasteTransform_triggered();
  4621. }
  4622. void OBSBasic::on_actionPasteDup_triggered()
  4623. {
  4624. OBSBasicSourceSelect::SourcePaste(copyString, copyVisible, true);
  4625. on_actionPasteTransform_triggered();
  4626. }
  4627. void OBSBasic::on_actionCopyFilters_triggered()
  4628. {
  4629. OBSSceneItem item = GetCurrentSceneItem();
  4630. if (!item)
  4631. return;
  4632. OBSSource source = obs_sceneitem_get_source(item);
  4633. copyFiltersString = obs_source_get_name(source);
  4634. ui->actionPasteFilters->setEnabled(true);
  4635. }
  4636. void OBSBasic::on_actionPasteFilters_triggered()
  4637. {
  4638. OBSSource source = obs_get_source_by_name(copyFiltersString);
  4639. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4640. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  4641. if (source == dstSource)
  4642. return;
  4643. obs_source_copy_filters(dstSource, source);
  4644. }
  4645. void OBSBasic::on_autoConfigure_triggered()
  4646. {
  4647. AutoConfig test(this);
  4648. test.setModal(true);
  4649. test.show();
  4650. test.exec();
  4651. }
  4652. void OBSBasic::on_stats_triggered()
  4653. {
  4654. if (!stats.isNull()) {
  4655. stats->show();
  4656. stats->raise();
  4657. return;
  4658. }
  4659. OBSBasicStats *statsDlg;
  4660. statsDlg = new OBSBasicStats(nullptr);
  4661. statsDlg->show();
  4662. stats = statsDlg;
  4663. }