View_smp.cpp 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110
  1. /*
  2. * View_smp.cpp
  3. * ------------
  4. * Purpose: Sample tab, lower panel.
  5. * Notes : (currently none)
  6. * Authors: Olivier Lapicque
  7. * OpenMPT Devs
  8. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  9. */
  10. #include "stdafx.h"
  11. #include "Mptrack.h"
  12. #include "Mainfrm.h"
  13. #include "InputHandler.h"
  14. #include "ImageLists.h"
  15. #include "Childfrm.h"
  16. #include "Clipboard.h"
  17. #include "Moddoc.h"
  18. #include "Globals.h"
  19. #include "Ctrl_smp.h"
  20. #include "Dlsbank.h"
  21. #include "ChannelManagerDlg.h"
  22. #include "View_smp.h"
  23. #include "OPLInstrDlg.h"
  24. #include "../soundlib/MIDIEvents.h"
  25. #include "SampleEditorDialogs.h"
  26. #include "../soundlib/WAVTools.h"
  27. #include "../common/FileReader.h"
  28. #include "../tracklib/SampleEdit.h"
  29. #include "openmpt/soundbase/SampleConvert.hpp"
  30. #include "openmpt/soundbase/SampleDecode.hpp"
  31. #include "../soundlib/SampleCopy.h"
  32. #include "../soundlib/mod_specifications.h"
  33. #include "../soundlib/S3MTools.h"
  34. #include "mpt/io/base.hpp"
  35. #include "mpt/io/io.hpp"
  36. #include "mpt/io/io_span.hpp"
  37. #include "mpt/io/io_stdstream.hpp"
  38. #include "mpt/io/io_virtual_wrapper.hpp"
  39. OPENMPT_NAMESPACE_BEGIN
  40. // Non-client toolbar
  41. #define SMP_LEFTBAR_CY Util::ScalePixels(29, m_hWnd)
  42. #define SMP_LEFTBAR_CXSEP Util::ScalePixels(14, m_hWnd)
  43. #define SMP_LEFTBAR_CXSPC Util::ScalePixels(3, m_hWnd)
  44. #define SMP_LEFTBAR_CXBTN Util::ScalePixels(24, m_hWnd)
  45. #define SMP_LEFTBAR_CYBTN Util::ScalePixels(22, m_hWnd)
  46. static constexpr int TIMELINE_HEIGHT = 26;
  47. static int TimelineHeight(HWND hwnd)
  48. {
  49. auto height = Util::ScalePixels(TIMELINE_HEIGHT, hwnd);
  50. if(height % 2)
  51. height++; // Avoid weird-looking triangles if timeline is scaled to odd height
  52. return height;
  53. }
  54. static constexpr int MIN_ZOOM = -6;
  55. static constexpr int MAX_ZOOM = 10;
  56. // Defines the minimum length for selection for which
  57. // trimming will be done. This is the minimum value for
  58. // selection difference, so the minimum length of result
  59. // of trimming is nTrimLengthMin + 1.
  60. static constexpr SmpLength MIN_TRIM_LENGTH = 4;
  61. static constexpr UINT cLeftBarButtons[SMP_LEFTBAR_BUTTONS] =
  62. {
  63. ID_SAMPLE_ZOOMUP,
  64. ID_SAMPLE_ZOOMDOWN,
  65. ID_SEPARATOR,
  66. ID_SAMPLE_DRAW,
  67. ID_SAMPLE_ADDSILENCE,
  68. ID_SEPARATOR,
  69. ID_SAMPLE_GRID,
  70. ID_SEPARATOR,
  71. };
  72. IMPLEMENT_SERIAL(CViewSample, CModScrollView, 0)
  73. BEGIN_MESSAGE_MAP(CViewSample, CModScrollView)
  74. //{{AFX_MSG_MAP(CViewSample)
  75. ON_WM_ERASEBKGND()
  76. ON_WM_SETFOCUS()
  77. ON_WM_SIZE()
  78. ON_WM_NCCALCSIZE()
  79. ON_WM_NCHITTEST()
  80. ON_WM_NCPAINT()
  81. ON_WM_MOUSEMOVE()
  82. ON_WM_NCMOUSEMOVE()
  83. ON_WM_LBUTTONDOWN()
  84. ON_WM_LBUTTONUP()
  85. ON_WM_LBUTTONDBLCLK()
  86. ON_WM_NCLBUTTONDOWN()
  87. ON_WM_NCLBUTTONUP()
  88. ON_WM_NCLBUTTONDBLCLK()
  89. ON_WM_RBUTTONDOWN()
  90. ON_WM_CHAR()
  91. ON_WM_DROPFILES()
  92. ON_WM_MOUSEWHEEL()
  93. ON_WM_XBUTTONUP()
  94. ON_WM_SETCURSOR()
  95. ON_COMMAND(ID_EDIT_UNDO, &CViewSample::OnEditUndo)
  96. ON_COMMAND(ID_EDIT_REDO, &CViewSample::OnEditRedo)
  97. ON_COMMAND(ID_EDIT_SELECT_ALL, &CViewSample::OnEditSelectAll)
  98. ON_COMMAND(ID_EDIT_CUT, &CViewSample::OnEditCut)
  99. ON_COMMAND(ID_EDIT_COPY, &CViewSample::OnEditCopy)
  100. ON_COMMAND(ID_EDIT_PASTE, &CViewSample::OnEditPaste)
  101. ON_COMMAND(ID_EDIT_MIXPASTE, &CViewSample::OnEditMixPaste)
  102. ON_COMMAND(ID_EDIT_PUSHFORWARDPASTE, &CViewSample::OnEditInsertPaste)
  103. ON_COMMAND(ID_SAMPLE_SETLOOP, &CViewSample::OnSetLoop)
  104. ON_COMMAND(ID_SAMPLE_SETSUSTAINLOOP, &CViewSample::OnSetSustainLoop)
  105. ON_COMMAND(ID_SAMPLE_8BITCONVERT, &CViewSample::On8BitConvert)
  106. ON_COMMAND(ID_SAMPLE_16BITCONVERT, &CViewSample::On16BitConvert)
  107. ON_COMMAND(ID_SAMPLE_MONOCONVERT, &CViewSample::OnMonoConvertMix)
  108. ON_COMMAND(ID_SAMPLE_MONOCONVERT_LEFT, &CViewSample::OnMonoConvertLeft)
  109. ON_COMMAND(ID_SAMPLE_MONOCONVERT_RIGHT, &CViewSample::OnMonoConvertRight)
  110. ON_COMMAND(ID_SAMPLE_MONOCONVERT_SPLIT, &CViewSample::OnMonoConvertSplit)
  111. ON_COMMAND(ID_SAMPLE_TRIM, &CViewSample::OnSampleTrim)
  112. ON_COMMAND(ID_PREVINSTRUMENT, &CViewSample::OnPrevInstrument)
  113. ON_COMMAND(ID_NEXTINSTRUMENT, &CViewSample::OnNextInstrument)
  114. ON_COMMAND(ID_SAMPLE_ZOOMONSEL, &CViewSample::OnZoomOnSel)
  115. ON_COMMAND(ID_SAMPLE_SETLOOPSTART, &CViewSample::OnSetLoopStart)
  116. ON_COMMAND(ID_SAMPLE_SETLOOPEND, &CViewSample::OnSetLoopEnd)
  117. ON_COMMAND(ID_CONVERT_PINGPONG_LOOP, &CViewSample::OnConvertPingPongLoop)
  118. ON_COMMAND(ID_SAMPLE_SETSUSTAINSTART, &CViewSample::OnSetSustainStart)
  119. ON_COMMAND(ID_SAMPLE_SETSUSTAINEND, &CViewSample::OnSetSustainEnd)
  120. ON_COMMAND(ID_CONVERT_PINGPONG_SUSTAIN, &CViewSample::OnConvertPingPongSustain)
  121. ON_COMMAND(ID_SAMPLE_ZOOMUP, &CViewSample::OnZoomUp)
  122. ON_COMMAND(ID_SAMPLE_ZOOMDOWN, &CViewSample::OnZoomDown)
  123. ON_COMMAND(ID_SAMPLE_DRAW, &CViewSample::OnDrawingToggle)
  124. ON_COMMAND(ID_SAMPLE_ADDSILENCE, &CViewSample::OnAddSilence)
  125. ON_COMMAND(ID_SAMPLE_GRID, &CViewSample::OnChangeGridSize)
  126. ON_COMMAND(ID_SAMPLE_QUICKFADE, &CViewSample::OnQuickFade)
  127. ON_COMMAND(ID_SAMPLE_SLICE, &CViewSample::OnSampleSlice)
  128. ON_COMMAND(ID_SAMPLE_INSERT_CUEPOINT, &CViewSample::OnSampleInsertCuePoint)
  129. ON_COMMAND(ID_SAMPLE_DELETE_CUEPOINT, &CViewSample::OnSampleDeleteCuePoint)
  130. ON_COMMAND(ID_SAMPLE_TIMELINE_SECONDS, &CViewSample::OnTimelineFormatSeconds)
  131. ON_COMMAND(ID_SAMPLE_TIMELINE_SAMPLES, &CViewSample::OnTimelineFormatSamples)
  132. ON_COMMAND(ID_SAMPLE_TIMELINE_SAMPLES_POW2, &CViewSample::OnTimelineFormatSamplesPow2)
  133. ON_COMMAND_RANGE(ID_SAMPLE_CUE_1, ID_SAMPLE_CUE_9, &CViewSample::OnSetCuePoint)
  134. ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, &CViewSample::OnUpdateUndo)
  135. ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, &CViewSample::OnUpdateRedo)
  136. ON_MESSAGE(WM_MOD_MIDIMSG, &CViewSample::OnMidiMsg)
  137. ON_MESSAGE(WM_MOD_KEYCOMMAND, &CViewSample::OnCustomKeyMsg) //rewbs.customKeys
  138. //}}AFX_MSG_MAP
  139. END_MESSAGE_MAP()
  140. ///////////////////////////////////////////////////////////////
  141. // CViewSample operations
  142. CViewSample::CViewSample()
  143. : m_lastDrawPoint(-1, -1)
  144. , m_timelineHeight(TIMELINE_HEIGHT)
  145. {
  146. MemsetZero(m_NcButtonState);
  147. m_dwNotifyPos.fill(Notification::PosInvalid);
  148. m_bmpEnvBar.Create(&CMainFrame::GetMainFrame()->m_SampleIcons);
  149. }
  150. void CViewSample::OnInitialUpdate()
  151. {
  152. CModScrollView::OnInitialUpdate();
  153. m_dwBeginSel = m_dwEndSel = 0;
  154. m_dwStatus.reset(SMPSTATUS_DRAWING);
  155. ModifyStyleEx(0, WS_EX_ACCEPTFILES);
  156. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  157. if (pMainFrm)
  158. {
  159. pMainFrm->SetInfoText(_T(""));
  160. pMainFrm->SetXInfoText(_T(""));
  161. }
  162. UpdateOPLEditor();
  163. UpdateScrollSize();
  164. UpdateNcButtonState();
  165. EnableToolTips();
  166. }
  167. // updateAll: Update all views including this one. Otherwise, only update update other views.
  168. void CViewSample::SetModified(SampleHint hint, bool updateAll, bool waveformModified)
  169. {
  170. CModDoc *pModDoc = GetDocument();
  171. pModDoc->SetModified();
  172. if(waveformModified)
  173. {
  174. // Update on-disk sample status in tree
  175. ModSample &sample = pModDoc->GetSoundFile().GetSample(m_nSample);
  176. if(sample.uFlags[SMP_KEEPONDISK] && !sample.uFlags[SMP_MODIFIED])
  177. hint.Names();
  178. sample.uFlags.set(SMP_MODIFIED);
  179. }
  180. pModDoc->UpdateAllViews(nullptr, hint.SetData(m_nSample), updateAll ? nullptr : this);
  181. }
  182. void CViewSample::UpdateScrollSize(int newZoom, bool forceRefresh, SmpLength centeredSample)
  183. {
  184. CModDoc *pModDoc = GetDocument();
  185. if(pModDoc == nullptr || (newZoom == m_nZoom && !forceRefresh))
  186. {
  187. return;
  188. }
  189. const int oldZoom = m_nZoom;
  190. m_nZoom = newZoom;
  191. GetClientRect(&m_rcClient);
  192. if(m_oplEditor && IsOPLInstrument())
  193. {
  194. const auto size = m_oplEditor->GetMinimumSize();
  195. m_oplEditor->SetWindowPos(nullptr, -m_nScrollPosX, -m_nScrollPosY, std::max(size.cx, m_rcClient.right), std::max(size.cy, m_rcClient.bottom), SWP_NOZORDER | SWP_NOACTIVATE);
  196. SetScrollSizes(MM_TEXT, size);
  197. return;
  198. }
  199. const CSoundFile &sndFile = pModDoc->GetSoundFile();
  200. SIZE sizePage, sizeLine;
  201. SmpLength dwLen = 0;
  202. uint32 sampleRate = 8363;
  203. if((m_nSample > 0) && (m_nSample <= sndFile.GetNumSamples()))
  204. {
  205. const ModSample &sample = sndFile.GetSample(m_nSample);
  206. if(sample.HasSampleData())
  207. dwLen = sample.nLength;
  208. sampleRate = sample.GetSampleRate(sndFile.GetType());
  209. }
  210. // Compute scroll size in pixels
  211. if (newZoom == 0) // Fit to display
  212. m_sizeTotal.cx = m_rcClient.Width();
  213. else if(newZoom == 1) // 1:1
  214. m_sizeTotal.cx = dwLen;
  215. else if(newZoom > 1) // Zoom out
  216. m_sizeTotal.cx = (dwLen + (1 << (newZoom - 1)) - 1) >> (newZoom - 1);
  217. else // Zoom in - here, we don't compute the real number of visible pixels so that the scroll bar doesn't grow unnecessarily long. The scrolling code in OnScrollBy() compensates for this.
  218. m_sizeTotal.cx = dwLen + m_rcClient.Width() - (m_rcClient.Width() >> (-newZoom - 1));
  219. m_sizeTotal.cy = 1;
  220. sizeLine.cx = (m_rcClient.right / 16) + 1;
  221. if(newZoom < 0)
  222. sizeLine.cx >>= (-newZoom - 1);
  223. sizeLine.cy = 1;
  224. sizePage.cx = sizeLine.cx * 4;
  225. sizePage.cy = 1;
  226. SetScrollSizes(MM_TEXT, m_sizeTotal, sizePage, sizeLine);
  227. if(oldZoom != newZoom) // After zoom change, keep the view position.
  228. {
  229. if(centeredSample != SmpLength(-1))
  230. {
  231. ScrollToSample(centeredSample, false);
  232. } else
  233. {
  234. const SmpLength nOldPos = ScrollPosToSamplePos(oldZoom);
  235. const float fPosFraction = (dwLen > 0) ? static_cast<float>(nOldPos) / dwLen : 0;
  236. SetScrollPos(SB_HORZ, static_cast<int>(fPosFraction * GetScrollLimit(SB_HORZ)));
  237. }
  238. }
  239. // Choose optimal timeline interval for this zoom level
  240. if(m_sizeTotal.cx == 0 || dwLen == 0)
  241. return;
  242. const TimelineFormat format = TrackerSettings::Instance().sampleEditorTimelineFormat;
  243. double timelineInterval = MulDiv(150, m_nDPIx, 96); // Timeline interval should be around 150 pixels
  244. if(m_nZoom > 0)
  245. timelineInterval *= 1 << (m_nZoom - 1);
  246. else if(m_nZoom < 0)
  247. timelineInterval /= 1 << (-m_nZoom - 1);
  248. else if(m_sizeTotal.cx != 0)
  249. timelineInterval = timelineInterval * dwLen / m_sizeTotal.cx;
  250. if(format == TimelineFormat::Seconds)
  251. timelineInterval *= 1000.0 / sampleRate;
  252. if(timelineInterval < 1)
  253. timelineInterval = 1;
  254. const double power = (format == TimelineFormat::SamplesPow2) ? 2.0 : 10.0;
  255. m_timelineUnit = mpt::saturate_round<int>(std::log(static_cast<double>(timelineInterval)) / std::log(power));
  256. if(m_timelineUnit < 1)
  257. m_timelineUnit = 0;
  258. m_timelineUnit = mpt::saturate_cast<int>(std::pow(power, m_timelineUnit));
  259. timelineInterval = std::max(1.0, std::round(timelineInterval / m_timelineUnit)) * m_timelineUnit;
  260. if(format == TimelineFormat::Seconds)
  261. timelineInterval *= sampleRate / 1000.0;
  262. if(m_nZoom > 0)
  263. timelineInterval /= 1 << (m_nZoom - 1);
  264. else if(m_nZoom < 0)
  265. timelineInterval *= 1 << (-m_nZoom - 1);
  266. else
  267. timelineInterval = timelineInterval * m_sizeTotal.cx / dwLen;
  268. m_timelineInterval = mpt::saturate_round<int>(timelineInterval);
  269. m_cachedSampleRate = sampleRate;
  270. }
  271. // Center given sample in the view
  272. void CViewSample::ScrollToSample(SmpLength centeredSample, bool refresh)
  273. {
  274. int scrollToSample = centeredSample >> (std::max(1, m_nZoom) - 1);
  275. scrollToSample -= (m_rcClient.Width() / 2) >> (-std::min(-1, m_nZoom) - 1);
  276. Limit(scrollToSample, 0, GetScrollLimit(SB_HORZ));
  277. SetScrollPos(SB_HORZ, scrollToSample);
  278. if(refresh) InvalidateSample();
  279. }
  280. int CViewSample::CalcScroll(int &currentPos, int amount, int style, int bar)
  281. {
  282. // Don't scroll if there is no valid scroll range (ie. no scroll bar)
  283. const CScrollBar *pBar = GetScrollBarCtrl(bar);
  284. DWORD dwStyle = GetStyle();
  285. if((pBar != nullptr && !pBar->IsWindowEnabled())
  286. || (pBar == nullptr && !(dwStyle & style)))
  287. {
  288. // Scroll bar not enabled
  289. amount = 0;
  290. }
  291. // Adjust current position
  292. int orig = GetScrollPos(bar);
  293. currentPos = Clamp(orig + amount, 0, GetScrollLimit(bar));
  294. return -(currentPos - orig);
  295. }
  296. BOOL CViewSample::OnScrollBy(CSize sizeScroll, BOOL bDoScroll)
  297. {
  298. int x = 0, y = 0;
  299. int scrollByX = CalcScroll(x, sizeScroll.cx, WS_HSCROLL, SB_HORZ);
  300. int scrollByY = CalcScroll(y, sizeScroll.cy, WS_VSCROLL, SB_VERT);
  301. if(!scrollByX && !scrollByY)
  302. {
  303. // Nothing changed!
  304. return FALSE;
  305. }
  306. if (bDoScroll)
  307. {
  308. // Don't allow to scroll into the middle of a sampling point
  309. if(m_nZoom < 0 && !IsOPLInstrument())
  310. {
  311. scrollByX *= (1 << (-m_nZoom - 1));
  312. }
  313. ScrollWindow(scrollByX, scrollByY);
  314. if(scrollByX) SetScrollPos(SB_HORZ, x);
  315. if(scrollByY) SetScrollPos(SB_VERT, y);
  316. m_forceRedrawWaveform = true;
  317. }
  318. return TRUE;
  319. }
  320. void CViewSample::SetCurrentSample(SAMPLEINDEX nSmp)
  321. {
  322. CModDoc *pModDoc = GetDocument();
  323. if(!pModDoc)
  324. return;
  325. if(nSmp < 1 || nSmp > pModDoc->GetNumSamples())
  326. return;
  327. pModDoc->SetNotifications(Notification::Sample, nSmp);
  328. pModDoc->SetFollowWnd(m_hWnd);
  329. if(nSmp == m_nSample)
  330. return;
  331. m_dwBeginSel = m_dwEndSel = 0;
  332. m_dwStatus.reset(SMPSTATUS_DRAWING);
  333. if(CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); pMainFrm)
  334. pMainFrm->SetInfoText(_T(""));
  335. const bool wasOPL = IsOPLInstrument();
  336. m_nSample = nSmp;
  337. m_dwNotifyPos.fill(Notification::PosInvalid);
  338. if(!wasOPL && IsOPLInstrument())
  339. SetScrollPos(SB_HORZ, 0);
  340. UpdateOPLEditor();
  341. UpdateScrollSize();
  342. UpdateNcButtonState();
  343. InvalidateSample();
  344. }
  345. bool CViewSample::IsOPLInstrument() const
  346. {
  347. return m_nSample >= 1 && m_nSample <= GetDocument()->GetNumSamples() && GetDocument()->GetSoundFile().GetSample(m_nSample).uFlags[CHN_ADLIB];
  348. }
  349. void CViewSample::UpdateOPLEditor()
  350. {
  351. if(!IsOPLInstrument())
  352. {
  353. if(m_oplEditor)
  354. m_oplEditor->ShowWindow(SW_HIDE);
  355. return;
  356. }
  357. CSoundFile &sndFile = GetDocument()->GetSoundFile();
  358. ModSample &sample = sndFile.GetSample(m_nSample);
  359. if(sample.uFlags[CHN_ADLIB])
  360. {
  361. if(!m_oplEditor)
  362. {
  363. try
  364. {
  365. m_oplEditor = std::make_unique<OPLInstrDlg>(*this, sndFile);
  366. } catch(mpt::out_of_memory e)
  367. {
  368. mpt::delete_out_of_memory(e);
  369. }
  370. }
  371. if(m_oplEditor)
  372. {
  373. m_oplEditor->SetPatch(sample.adlib);
  374. auto size = m_oplEditor->GetMinimumSize();
  375. m_oplEditor->SetWindowPos(nullptr, -m_nScrollPosX, -m_nScrollPosY, std::max(size.cx, m_rcClient.right), std::max(size.cy, m_rcClient.bottom), SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW);
  376. }
  377. }
  378. }
  379. void CViewSample::OnSetFocus(CWnd *pOldWnd)
  380. {
  381. CScrollView::OnSetFocus(pOldWnd);
  382. SetCurrentSample(m_nSample);
  383. }
  384. void CViewSample::SetZoom(int nZoom, SmpLength centeredSample)
  385. {
  386. if(nZoom == m_nZoom && centeredSample == SmpLength(-1))
  387. return;
  388. if(nZoom > MAX_ZOOM)
  389. return;
  390. UpdateScrollSize(nZoom, true, centeredSample);
  391. InvalidateSample();
  392. }
  393. SmpLength CViewSample::SnapToGrid(const SmpLength pos) const
  394. {
  395. if(m_nGridSegments <= 0 || GetDocument() == nullptr)
  396. return pos;
  397. const auto &sample = GetDocument()->GetSoundFile().GetSample(m_nSample);
  398. if(m_nGridSegments >= sample.nLength)
  399. return pos;
  400. const auto samplesPerSegment = static_cast<double>(sample.nLength) / m_nGridSegments;
  401. return static_cast<SmpLength>(mpt::round(pos / samplesPerSegment) * samplesPerSegment);
  402. }
  403. void CViewSample::SetCurSel(SmpLength nBegin, SmpLength nEnd)
  404. {
  405. if(GetDocument() == nullptr)
  406. return;
  407. CSoundFile &sndFile = GetDocument()->GetSoundFile();
  408. const ModSample &sample = sndFile.GetSample(m_nSample);
  409. nBegin = SnapToGrid(nBegin);
  410. nEnd = SnapToGrid(nEnd);
  411. if(nBegin > nEnd)
  412. {
  413. std::swap(nBegin, nEnd);
  414. }
  415. if ((nBegin != m_dwBeginSel) || (nEnd != m_dwEndSel))
  416. {
  417. RECT rect;
  418. SmpLength dMin = m_dwBeginSel, dMax = m_dwEndSel;
  419. if (m_dwBeginSel >= m_dwEndSel)
  420. {
  421. dMin = nBegin;
  422. dMax = nEnd;
  423. }
  424. if ((nBegin == dMin) && (dMax != nEnd))
  425. {
  426. dMin = dMax;
  427. if (nEnd < dMin) dMin = nEnd;
  428. if (nEnd > dMax) dMax = nEnd;
  429. } else if ((nEnd == dMax) && (dMin != nBegin))
  430. {
  431. dMax = dMin;
  432. if (nBegin < dMin) dMin = nBegin;
  433. if (nBegin > dMax) dMax = nBegin;
  434. } else
  435. {
  436. if (nBegin < dMin) dMin = nBegin;
  437. if (nEnd > dMax) dMax = nEnd;
  438. }
  439. m_dwBeginSel = nBegin;
  440. m_dwEndSel = nEnd;
  441. rect.top = m_rcClient.top;
  442. rect.bottom = m_rcClient.bottom;
  443. rect.left = SampleToScreen(dMin);
  444. rect.right = SampleToScreen(dMax) + 1;
  445. if (rect.left < 0) rect.left = 0;
  446. if (rect.right > m_rcClient.right) rect.right = m_rcClient.right;
  447. if (rect.right > rect.left) InvalidateRect(&rect, FALSE);
  448. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  449. if(pMainFrm)
  450. {
  451. mpt::ustring s;
  452. if(m_dwEndSel > m_dwBeginSel)
  453. {
  454. const SmpLength selLength = m_dwEndSel - m_dwBeginSel;
  455. mpt::ustring (*fmt)(unsigned int, char, const SmpLength &) = &mpt::ufmt::dec<SmpLength>;
  456. if(TrackerSettings::Instance().cursorPositionInHex)
  457. fmt = &mpt::ufmt::HEX<SmpLength>;
  458. s = MPT_UFORMAT("[{}-{}] ({} sample{}, ")(fmt(3, ',', m_dwBeginSel), fmt(3, ',', m_dwEndSel), fmt(3, ',', selLength), (selLength == 1) ? U_("") : U_("s"));
  459. // Length in seconds
  460. auto sampleRate = sample.GetSampleRate(sndFile.GetType());
  461. if(sampleRate <= 0) sampleRate = 8363;
  462. double sec = selLength / static_cast<double>(sampleRate);
  463. if(sec < 1)
  464. s += MPT_UFORMAT("{}ms")(mpt::ufmt::flt(sec * 1000.0, 3));
  465. else
  466. s += MPT_UFORMAT("{}s")(mpt::ufmt::flt(sec, 3));
  467. // Length in beats
  468. double beats = selLength;
  469. if(sndFile.m_nTempoMode == TempoMode::Modern)
  470. {
  471. beats *= sndFile.m_PlayState.m_nMusicTempo.ToDouble() * (1.0 / 60.0) / sampleRate;
  472. } else
  473. {
  474. sndFile.RecalculateSamplesPerTick();
  475. beats *= sndFile.GetSampleRate() / static_cast<double>(Util::mul32to64_unsigned(sndFile.m_PlayState.m_nCurrentRowsPerBeat, sndFile.m_PlayState.m_nMusicSpeed) * Util::mul32to64_unsigned(sndFile.m_PlayState.m_nSamplesPerTick, sampleRate));
  476. }
  477. s += MPT_UFORMAT(", {} beats)")(mpt::ufmt::flt(beats, 5));
  478. }
  479. pMainFrm->SetInfoText(mpt::ToCString(s));
  480. }
  481. }
  482. }
  483. int32 CViewSample::SampleToScreen(SmpLength pos, bool ignoreScrollPos) const
  484. {
  485. CModDoc *pModDoc = GetDocument();
  486. if((pModDoc) && (m_nSample <= pModDoc->GetNumSamples()))
  487. {
  488. SmpLength nLen = pModDoc->GetSoundFile().GetSample(m_nSample).nLength;
  489. if(!nLen)
  490. return 0;
  491. const SmpLength scrollPos = ignoreScrollPos ? 0 : m_nScrollPosX;
  492. if(m_nZoom > 0)
  493. return (pos >> (m_nZoom - 1)) - scrollPos;
  494. else if(m_nZoom < 0)
  495. return (pos - scrollPos) << (-m_nZoom - 1);
  496. else
  497. return Util::muldiv(pos, m_sizeTotal.cx, nLen);
  498. }
  499. return 0;
  500. }
  501. SmpLength CViewSample::ScreenToSample(int32 x, bool ignoreSampleLength) const
  502. {
  503. const CModDoc *pModDoc = GetDocument();
  504. SmpLength n = 0;
  505. if((pModDoc) && (m_nSample <= pModDoc->GetNumSamples()))
  506. {
  507. SmpLength smpLen = pModDoc->GetSoundFile().GetSample(m_nSample).nLength;
  508. if(!smpLen)
  509. return 0;
  510. if(m_nZoom > 0)
  511. n = std::max(0, m_nScrollPosX + x) << (m_nZoom - 1);
  512. else if(m_nZoom < 0)
  513. n = std::max(0, m_nScrollPosX + mpt::rshift_signed(x, (-m_nZoom - 1)));
  514. else
  515. {
  516. if(x < 0)
  517. x = 0;
  518. if(m_sizeTotal.cx)
  519. n = Util::muldiv(x, smpLen, m_sizeTotal.cx);
  520. }
  521. if(!ignoreSampleLength)
  522. LimitMax(n, smpLen);
  523. }
  524. return n;
  525. }
  526. int32 CViewSample::SecondsToScreen(double x) const
  527. {
  528. const ModSample &sample = GetDocument()->GetSoundFile().GetSample(m_nSample);
  529. const auto sampleRate = sample.GetSampleRate(GetDocument()->GetModType());
  530. if(sampleRate == 0 || sample.nLength == 0)
  531. return 0;
  532. x *= sampleRate;
  533. // This is essentially duplicated from SampleToScreen but carried out in double precision to avoid rounding errors at very high zoom levels
  534. if(m_nZoom > 0)
  535. x = x / (1 << (m_nZoom - 1)) - m_nScrollPosX;
  536. else if(m_nZoom < 0)
  537. x = (x - m_nScrollPosX) * (1 << (-m_nZoom - 1));
  538. else
  539. x = x * m_sizeTotal.cx / sample.nLength;
  540. return mpt::saturate_round<int32>(x);
  541. }
  542. double CViewSample::ScreenToSeconds(int32 x, bool ignoreSampleLength) const
  543. {
  544. const ModSample &sample = GetDocument()->GetSoundFile().GetSample(m_nSample);
  545. const auto sampleRate = sample.GetSampleRate(GetDocument()->GetModType());
  546. if(sampleRate == 0)
  547. return 0;
  548. return ScreenToSample(x, ignoreSampleLength) / static_cast<double>(sampleRate);
  549. }
  550. static bool HitTest(int pointX, int objX, int marginL, int marginR, int top, int bottom, CRect *rect)
  551. {
  552. if(!mpt::is_in_range(pointX, objX - marginL, objX + marginR))
  553. return false;
  554. if(rect)
  555. *rect = CRect{objX - marginL, top, objX + marginR + 1, bottom};
  556. return true;
  557. }
  558. std::pair<CViewSample::HitTestItem, SmpLength> CViewSample::PointToItem(CPoint point, CRect *rect) const
  559. {
  560. if(IsOPLInstrument())
  561. return {HitTestItem::Nothing, MAX_SAMPLE_LENGTH};
  562. const bool inTimeline = point.y < m_timelineHeight;
  563. if(m_dwEndSel > m_dwBeginSel && !inTimeline && !m_dwStatus[SMPSTATUS_DRAWING])
  564. {
  565. const int margin = Util::ScalePixels(5, m_hWnd);
  566. if(HitTest(point.x, SampleToScreen(m_dwBeginSel), margin, margin, m_timelineHeight, m_rcClient.bottom, rect))
  567. return {HitTestItem::SelectionStart, m_dwBeginSel};
  568. if(HitTest(point.x, SampleToScreen(m_dwEndSel), margin, margin, m_timelineHeight, m_rcClient.bottom, rect))
  569. return {HitTestItem::SelectionEnd, m_dwEndSel};
  570. }
  571. const auto &sndFile = GetDocument()->GetSoundFile();
  572. if(m_nSample <= sndFile.GetNumSamples() && inTimeline)
  573. {
  574. const auto &sample = sndFile.GetSample(m_nSample);
  575. if(sample.nSustainStart < sample.nSustainEnd && sample.nSustainStart < sample.nLength)
  576. {
  577. if(HitTest(point.x, SampleToScreen(sample.nSustainEnd), m_timelineHeight / 2, 0, 0, m_timelineHeight, rect))
  578. return {HitTestItem::SustainEnd, sample.nSustainEnd};
  579. if(HitTest(point.x, SampleToScreen(sample.nSustainStart), 0, m_timelineHeight / 2, 0, m_timelineHeight, rect))
  580. return {HitTestItem::SustainStart, sample.nSustainStart};
  581. }
  582. if (sample.nLoopStart < sample.nLoopEnd && sample.nLoopStart < sample.nLength)
  583. {
  584. if(HitTest(point.x, SampleToScreen(sample.nLoopEnd), m_timelineHeight / 2, 0, 0, m_timelineHeight, rect))
  585. return {HitTestItem::LoopEnd, sample.nLoopEnd};
  586. if(HitTest(point.x, SampleToScreen(sample.nLoopStart), 0, m_timelineHeight / 2, 0, m_timelineHeight, rect))
  587. return {HitTestItem::LoopStart, sample.nLoopStart };
  588. }
  589. for(size_t i = 0; i < std::size(sample.cues); i++)
  590. {
  591. size_t cue = std::size(sample.cues) - 1 - i; // If two cues overlap visually, the cue with the higher ID is drawn on top, so pick it first
  592. if(sample.cues[cue] < sample.nLength && HitTest(point.x, SampleToScreen(sample.cues[cue]), m_timelineHeight / 2, m_timelineHeight / 2, 0, m_timelineHeight, rect))
  593. return {static_cast<HitTestItem>(static_cast<size_t>(HitTestItem::CuePointFirst) + cue), sample.cues[cue]};
  594. }
  595. }
  596. if(inTimeline)
  597. return {HitTestItem::Nothing, MAX_SAMPLE_LENGTH};
  598. else
  599. return {HitTestItem::SampleData, ScreenToSample(point.x)};
  600. }
  601. void CViewSample::InvalidateSample(bool invalidateWaveform)
  602. {
  603. if(invalidateWaveform)
  604. m_forceRedrawWaveform = true;
  605. InvalidateRect(nullptr, FALSE);
  606. }
  607. void CViewSample::InvalidateTimeline()
  608. {
  609. auto rect = m_rcClient;
  610. rect.bottom = m_timelineHeight;
  611. InvalidateRect(rect, FALSE);
  612. }
  613. LRESULT CViewSample::OnModViewMsg(WPARAM wParam, LPARAM lParam)
  614. {
  615. switch(wParam)
  616. {
  617. case VIEWMSG_SETCURRENTSAMPLE:
  618. SetZoom(static_cast<int>(lParam) >> 16);
  619. SetCurrentSample(lParam & 0xFFFF);
  620. break;
  621. case VIEWMSG_LOADSTATE:
  622. if (lParam)
  623. {
  624. SAMPLEVIEWSTATE *pState = (SAMPLEVIEWSTATE *)lParam;
  625. if (pState->nSample == m_nSample)
  626. {
  627. SetCurSel(pState->dwBeginSel, pState->dwEndSel);
  628. SetScrollPos(SB_HORZ, pState->dwScrollPos);
  629. UpdateScrollSize();
  630. InvalidateSample();
  631. }
  632. }
  633. break;
  634. case VIEWMSG_SAVESTATE:
  635. if (lParam)
  636. {
  637. SAMPLEVIEWSTATE *pState = (SAMPLEVIEWSTATE *)lParam;
  638. pState->dwScrollPos = m_nScrollPosX;
  639. pState->dwBeginSel = m_dwBeginSel;
  640. pState->dwEndSel = m_dwEndSel;
  641. pState->nSample = m_nSample;
  642. }
  643. break;
  644. case VIEWMSG_SETMODIFIED:
  645. // Update from OPL editor
  646. SetModified(UpdateHint::FromLPARAM(lParam).ToType<SampleHint>(), false, true);
  647. GetDocument()->UpdateOPLInstrument(m_nSample);
  648. break;
  649. case VIEWMSG_PREPAREUNDO:
  650. GetDocument()->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Edit OPL Patch");
  651. break;
  652. case VIEWMSG_SETFOCUS:
  653. case VIEWMSG_SETACTIVE:
  654. GetParentFrame()->SetActiveView(this);
  655. if(IsOPLInstrument() && m_oplEditor)
  656. m_oplEditor->SetFocus();
  657. else
  658. SetFocus();
  659. break;
  660. default:
  661. return CModScrollView::OnModViewMsg(wParam, lParam);
  662. }
  663. return 0;
  664. }
  665. ///////////////////////////////////////////////////////////////
  666. // CViewSample drawing
  667. void CViewSample::UpdateView(UpdateHint hint, CObject *pObj)
  668. {
  669. if(pObj == this)
  670. {
  671. return;
  672. }
  673. auto modDoc = GetDocument();
  674. auto &sndFile = modDoc->GetSoundFile();
  675. const SampleHint sampleHint = hint.ToType<SampleHint>();
  676. FlagSet<HintType> hintType = sampleHint.GetType();
  677. const SAMPLEINDEX updateSmp = sampleHint.GetSample();
  678. if(hintType[HINT_MPTOPTIONS | HINT_MODTYPE]
  679. || (hintType[HINT_SAMPLEDATA] && (m_nSample == updateSmp || updateSmp == 0)))
  680. {
  681. if(hintType[HINT_SAMPLEDATA] && m_oplEditor && m_nSample <= sndFile.GetNumSamples())
  682. {
  683. ModSample &sample = sndFile.GetSample(m_nSample);
  684. if(sample.uFlags[CHN_ADLIB])
  685. m_oplEditor->SetPatch(sample.adlib);
  686. }
  687. UpdateOPLEditor();
  688. UpdateScrollSize();
  689. UpdateNcButtonState();
  690. InvalidateSample();
  691. }
  692. if(hintType[HINT_SAMPLEINFO])
  693. {
  694. // Sample rate change may imply redrawing of timeline
  695. if(m_nSample <= sndFile.GetNumSamples() && m_cachedSampleRate != sndFile.GetSample(m_nSample).GetSampleRate(sndFile.GetType()))
  696. {
  697. UpdateScrollSize();
  698. InvalidateTimeline();
  699. }
  700. if(m_nSample > sndFile.GetNumSamples() || !sndFile.GetSample(m_nSample).HasSampleData())
  701. {
  702. // Disable sample drawing if we cannot actually draw anymore.
  703. m_dwStatus.reset(SMPSTATUS_DRAWING);
  704. UpdateNcButtonState();
  705. }
  706. if(m_nSample == updateSmp || updateSmp == 0)
  707. InvalidateSample(false);
  708. }
  709. }
  710. #define YCVT(n, bits) (ymed - (((n) * yrange) >> (bits)))
  711. // Draw one channel of sample data, 1:1 ratio or higher (zoomed in)
  712. void CViewSample::DrawSampleData1(HDC hdc, int ymed, int cx, int cy, SmpLength len, SampleFlags uFlags, const void *pSampleData)
  713. {
  714. int smplsize;
  715. int yrange = cy/2;
  716. const int8 *psample = static_cast<const int8 *>(pSampleData);
  717. int y0 = 0;
  718. smplsize = (uFlags & CHN_16BIT) ? 2 : 1;
  719. if (uFlags & CHN_STEREO) smplsize *= 2;
  720. if (uFlags & CHN_16BIT)
  721. {
  722. y0 = YCVT(*((signed short *)(psample-smplsize)),15);
  723. } else
  724. {
  725. y0 = YCVT(*(psample-smplsize),7);
  726. }
  727. ::MoveToEx(hdc, -1, y0, NULL);
  728. SmpLength numDrawSamples, loopDiv = 0;
  729. int loopShift = 0;
  730. if (m_nZoom == 1)
  731. {
  732. // Linear 1:1 scale
  733. numDrawSamples = cx;
  734. } else if(m_nZoom < 0)
  735. {
  736. // 2:1, 4:1, etc... zoom
  737. loopShift = (-m_nZoom - 1);
  738. // Round up
  739. numDrawSamples = (cx + (1 << loopShift) - 1) >> loopShift;
  740. } else
  741. {
  742. // Stretch to screen
  743. ASSERT(!m_nZoom);
  744. numDrawSamples = len;
  745. loopDiv = numDrawSamples;
  746. }
  747. LimitMax(numDrawSamples, len);
  748. if (uFlags & CHN_16BIT)
  749. {
  750. // 16-Bit
  751. for (SmpLength n = 0; n <= numDrawSamples; n++)
  752. {
  753. int x = loopDiv ? ((n * cx) / loopDiv) : (n << loopShift);
  754. int y = *(const int16 *)psample;
  755. ::LineTo(hdc, x, YCVT(y,15));
  756. psample += smplsize;
  757. }
  758. } else
  759. {
  760. // 8-bit
  761. for (SmpLength n = 0; n <= numDrawSamples; n++)
  762. {
  763. int x = loopDiv ? ((n * cx) / loopDiv) : (n << loopShift);
  764. int y = *psample;
  765. ::LineTo(hdc, x, YCVT(y,7));
  766. psample += smplsize;
  767. }
  768. }
  769. }
  770. #if defined(MPT_ENABLE_ARCH_INTRINSICS_SSE2)
  771. OPENMPT_NAMESPACE_END
  772. #include <emmintrin.h>
  773. OPENMPT_NAMESPACE_BEGIN
  774. // SSE2 implementation for min/max finder, packs 8*int16 in a 128-bit XMM register.
  775. // scanlen = How many samples to process on this channel
  776. static void sse2_findminmax16(const void *p, SmpLength scanlen, int channels, int &smin, int &smax)
  777. {
  778. scanlen *= channels;
  779. // Put minimum / maximum in 8 packed int16 values
  780. __m128i minVal = _mm_set1_epi16(static_cast<int16>(smin));
  781. __m128i maxVal = _mm_set1_epi16(static_cast<int16>(smax));
  782. SmpLength scanlen8 = scanlen / 8;
  783. if(scanlen8)
  784. {
  785. const __m128i *v = static_cast<const __m128i *>(p);
  786. p = static_cast<const __m128i *>(p) + scanlen8;
  787. while(scanlen8--)
  788. {
  789. __m128i curVals = _mm_loadu_si128(v++);
  790. minVal = _mm_min_epi16(minVal, curVals);
  791. maxVal = _mm_max_epi16(maxVal, curVals);
  792. }
  793. // Now we have 8 minima and maxima each, in case of stereo they are interleaved L/R values.
  794. // Move the upper 4 values to the lower half and compute the minima/maxima of that.
  795. __m128i minVal2 = _mm_unpackhi_epi64(minVal, minVal);
  796. __m128i maxVal2 = _mm_unpackhi_epi64(maxVal, maxVal);
  797. minVal = _mm_min_epi16(minVal, minVal2);
  798. maxVal = _mm_max_epi16(maxVal, maxVal2);
  799. // Now we have 4 minima and maxima each, in case of stereo they are interleaved L/R values.
  800. // Move the upper 2 values to the lower half and compute the minima/maxima of that.
  801. minVal2 = _mm_shuffle_epi32(minVal, _MM_SHUFFLE(1, 1, 1, 1));
  802. maxVal2 = _mm_shuffle_epi32(maxVal, _MM_SHUFFLE(1, 1, 1, 1));
  803. minVal = _mm_min_epi16(minVal, minVal2);
  804. maxVal = _mm_max_epi16(maxVal, maxVal2);
  805. if(channels < 2)
  806. {
  807. // Mono: Compute the minima/maxima of the both remaining values
  808. minVal2 = _mm_shufflelo_epi16(minVal, _MM_SHUFFLE(1, 1, 1, 1));
  809. maxVal2 = _mm_shufflelo_epi16(maxVal, _MM_SHUFFLE(1, 1, 1, 1));
  810. minVal = _mm_min_epi16(minVal, minVal2);
  811. maxVal = _mm_max_epi16(maxVal, maxVal2);
  812. }
  813. }
  814. const int16 *p16 = static_cast<const int16 *>(p);
  815. while(scanlen & 7)
  816. {
  817. scanlen -= channels;
  818. __m128i curVals = _mm_set1_epi16(*p16);
  819. p16 += channels;
  820. minVal = _mm_min_epi16(minVal, curVals);
  821. maxVal = _mm_max_epi16(maxVal, curVals);
  822. }
  823. smin = static_cast<int16>(_mm_cvtsi128_si32(minVal));
  824. smax = static_cast<int16>(_mm_cvtsi128_si32(maxVal));
  825. }
  826. // SSE2 implementation for min/max finder, packs 16*int8 in a 128-bit XMM register.
  827. // scanlen = How many samples to process on this channel
  828. static void sse2_findminmax8(const void *p, SmpLength scanlen, int channels, int &smin, int &smax)
  829. {
  830. scanlen *= channels;
  831. // Put minimum / maximum in 16 packed int8 values
  832. __m128i minVal = _mm_set1_epi8(static_cast<int8>(smin ^ 0x80u));
  833. __m128i maxVal = _mm_set1_epi8(static_cast<int8>(smax ^ 0x80u));
  834. // For signed <-> unsigned conversion (_mm_min_epi8/_mm_max_epi8 is SSE4)
  835. __m128i xorVal = _mm_set1_epi8(0x80u);
  836. SmpLength scanlen16 = scanlen / 16;
  837. if(scanlen16)
  838. {
  839. const __m128i *v = static_cast<const __m128i *>(p);
  840. p = static_cast<const __m128i *>(p) + scanlen16;
  841. while(scanlen16--)
  842. {
  843. __m128i curVals = _mm_loadu_si128(v++);
  844. curVals = _mm_xor_si128(curVals, xorVal);
  845. minVal = _mm_min_epu8(minVal, curVals);
  846. maxVal = _mm_max_epu8(maxVal, curVals);
  847. }
  848. // Now we have 16 minima and maxima each, in case of stereo they are interleaved L/R values.
  849. // Move the upper 8 values to the lower half and compute the minima/maxima of that.
  850. __m128i minVal2 = _mm_unpackhi_epi64(minVal, minVal);
  851. __m128i maxVal2 = _mm_unpackhi_epi64(maxVal, maxVal);
  852. minVal = _mm_min_epu8(minVal, minVal2);
  853. maxVal = _mm_max_epu8(maxVal, maxVal2);
  854. // Now we have 8 minima and maxima each, in case of stereo they are interleaved L/R values.
  855. // Move the upper 4 values to the lower half and compute the minima/maxima of that.
  856. minVal2 = _mm_shuffle_epi32(minVal, _MM_SHUFFLE(1, 1, 1, 1));
  857. maxVal2 = _mm_shuffle_epi32(maxVal, _MM_SHUFFLE(1, 1, 1, 1));
  858. minVal = _mm_min_epu8(minVal, minVal2);
  859. maxVal = _mm_max_epu8(maxVal, maxVal2);
  860. // Now we have 4 minima and maxima each, in case of stereo they are interleaved L/R values.
  861. // Move the upper 2 values to the lower half and compute the minima/maxima of that.
  862. minVal2 = _mm_srai_epi32(minVal, 16);
  863. maxVal2 = _mm_srai_epi32(maxVal, 16);
  864. minVal = _mm_min_epu8(minVal, minVal2);
  865. maxVal = _mm_max_epu8(maxVal, maxVal2);
  866. if(channels < 2)
  867. {
  868. // Mono: Compute the minima/maxima of the both remaining values
  869. minVal2 = _mm_srai_epi16(minVal, 8);
  870. maxVal2 = _mm_srai_epi16(maxVal, 8);
  871. minVal = _mm_min_epu8(minVal, minVal2);
  872. maxVal = _mm_max_epu8(maxVal, maxVal2);
  873. }
  874. }
  875. const int8 *p8 = static_cast<const int8 *>(p);
  876. while(scanlen & 15)
  877. {
  878. scanlen -= channels;
  879. __m128i curVals = _mm_set1_epi8((*p8) ^ 0x80u);
  880. p8 += channels;
  881. minVal = _mm_min_epu8(minVal, curVals);
  882. maxVal = _mm_max_epu8(maxVal, curVals);
  883. }
  884. smin = static_cast<int8>(_mm_cvtsi128_si32(minVal) ^ 0x80u);
  885. smax = static_cast<int8>(_mm_cvtsi128_si32(maxVal) ^ 0x80u);
  886. }
  887. #endif
  888. std::pair<int, int> CViewSample::FindMinMax(const int8 *p, SmpLength numSamples, int numChannels)
  889. {
  890. int minVal = 127;
  891. int maxVal = -128;
  892. #if defined(MPT_ENABLE_ARCH_INTRINSICS_SSE2)
  893. if(CPU::HasFeatureSet(CPU::feature::sse2) && numSamples >= 16)
  894. {
  895. sse2_findminmax8(p, numSamples, numChannels, minVal, maxVal);
  896. } else
  897. #endif
  898. {
  899. while(numSamples--)
  900. {
  901. int s = *p;
  902. if(s < minVal) minVal = s;
  903. if(s > maxVal) maxVal = s;
  904. p += numChannels;
  905. }
  906. }
  907. return { minVal, maxVal };
  908. }
  909. std::pair<int, int> CViewSample::FindMinMax(const int16 *p, SmpLength numSamples, int numChannels)
  910. {
  911. int minVal = 32767;
  912. int maxVal = -32768;
  913. #if defined(MPT_ENABLE_ARCH_INTRINSICS_SSE2)
  914. if(CPU::HasFeatureSet(CPU::feature::sse2) && numSamples >= 8)
  915. {
  916. sse2_findminmax16(p, numSamples, numChannels, minVal, maxVal);
  917. } else
  918. #endif
  919. {
  920. while(numSamples--)
  921. {
  922. int s = *p;
  923. if(s < minVal) minVal = s;
  924. if(s > maxVal) maxVal = s;
  925. p += numChannels;
  926. }
  927. }
  928. return { minVal, maxVal };
  929. }
  930. // Draw one channel of zoomed-out sample data
  931. void CViewSample::DrawSampleData2(HDC hdc, int ymed, int cx, int cy, SmpLength len, SampleFlags uFlags, const void *pSampleData)
  932. {
  933. int oldsmin, oldsmax;
  934. int yrange = cy/2;
  935. const int8 *psample = static_cast<const int8 *>(pSampleData);
  936. int32 y0 = 0, xmax;
  937. SmpLength poshi;
  938. uint64 posincr, posfrac; // Increments have 16-bit fractional part
  939. if (len <= 0) return;
  940. const int numChannels = (uFlags & CHN_STEREO) ? 2 : 1;
  941. const int smplsize = ((uFlags & CHN_16BIT) ? 2 : 1) * numChannels;
  942. if (uFlags & CHN_16BIT)
  943. {
  944. y0 = YCVT(*((const int16 *)(psample-smplsize)), 15);
  945. } else
  946. {
  947. y0 = YCVT(*(psample-smplsize), 7);
  948. }
  949. oldsmin = oldsmax = y0;
  950. if (m_nZoom > 0)
  951. {
  952. xmax = len>>(m_nZoom-1);
  953. if (xmax > cx) xmax = cx;
  954. posincr = (uint64(1) << (m_nZoom-1+16));
  955. } else
  956. {
  957. xmax = cx;
  958. //posincr = Util::muldiv(len, 0x10000, cx);
  959. posincr = uint64(len) * uint64(0x10000) / uint64(cx);
  960. }
  961. ::MoveToEx(hdc, 0, ymed, NULL);
  962. posfrac = 0;
  963. poshi = 0;
  964. for (int x=0; x<xmax; x++)
  965. {
  966. //int smin, smax, scanlen;
  967. int smin, smax;
  968. SmpLength scanlen;
  969. posfrac += posincr;
  970. scanlen = static_cast<int32>((posfrac+0xffff) >> 16);
  971. if (poshi >= len) poshi = len-1;
  972. if (poshi + scanlen > len) scanlen = len-poshi;
  973. if (scanlen < 1) scanlen = 1;
  974. // 16-bit
  975. if (uFlags & CHN_16BIT)
  976. {
  977. signed short *p = (signed short *)(psample + poshi*smplsize);
  978. auto minMax = FindMinMax(p, scanlen, numChannels);
  979. smin = YCVT(minMax.first, 15);
  980. smax = YCVT(minMax.second, 15);
  981. } else
  982. // 8-bit
  983. {
  984. const int8 *p = psample + poshi * smplsize;
  985. auto minMax = FindMinMax(p, scanlen, numChannels);
  986. smin = YCVT(minMax.first, 7);
  987. smax = YCVT(minMax.second, 7);
  988. }
  989. if (smin > oldsmax)
  990. {
  991. ::MoveToEx(hdc, x-1, oldsmax - 1, NULL);
  992. ::LineTo(hdc, x, smin);
  993. }
  994. if (smax < oldsmin)
  995. {
  996. ::MoveToEx(hdc, x-1, oldsmin, NULL);
  997. ::LineTo(hdc, x, smax);
  998. }
  999. ::MoveToEx(hdc, x, smax-1, NULL);
  1000. ::LineTo(hdc, x, smin);
  1001. oldsmin = smin;
  1002. oldsmax = smax;
  1003. poshi += static_cast<int32>(posfrac>>16);
  1004. posfrac &= 0xffff;
  1005. }
  1006. }
  1007. static void DrawTriangleHorz(CDC &dc, int x, int width, int height, COLORREF color)
  1008. {
  1009. const POINT points[] =
  1010. {
  1011. {x, 0},
  1012. {x, height},
  1013. {x + width, height / 2},
  1014. };
  1015. dc.SetDCPenColor(RGB(GetRValue(color) / 2, GetGValue(color) / 2, GetBValue(color) / 2));
  1016. dc.SetDCBrushColor(color);
  1017. dc.Polygon(points, static_cast<int>(std::size(points)));
  1018. }
  1019. static void DrawTriangleVert(CDC &dc, int x, int width, int height, COLORREF color)
  1020. {
  1021. const POINT points[] =
  1022. {
  1023. {x - width, height / 2},
  1024. {x + width, height / 2},
  1025. {x, height},
  1026. };
  1027. dc.SetDCPenColor(RGB(GetRValue(color) / 2, GetGValue(color) / 2, GetBValue(color) / 2));
  1028. dc.SetDCBrushColor(color);
  1029. dc.Polygon(points, static_cast<int>(std::size(points)));
  1030. }
  1031. void CViewSample::OnDraw(CDC *pDC)
  1032. {
  1033. const CModDoc *pModDoc = GetDocument();
  1034. if ((!pModDoc) || (!pDC)) return;
  1035. const CRect rcClient = m_rcClient;
  1036. CRect rect, rc;
  1037. const SmpLength smpScrollPos = ScrollPosToSamplePos();
  1038. const auto &colors = TrackerSettings::Instance().rgbCustomColors;
  1039. const CSoundFile &sndFile = pModDoc->GetSoundFile();
  1040. const ModSample &sample = sndFile.GetSample((m_nSample <= sndFile.GetNumSamples()) ? m_nSample : 0);
  1041. if(sample.uFlags[CHN_ADLIB])
  1042. {
  1043. CModScrollView::OnDraw(pDC);
  1044. return;
  1045. }
  1046. // Create off-screen image and timeline font
  1047. if(!m_offScreenDC.m_hDC)
  1048. {
  1049. m_offScreenDC.CreateCompatibleDC(pDC);
  1050. m_offScreenBitmap.CreateCompatibleBitmap(pDC, m_rcClient.Width(), m_rcClient.Height());
  1051. m_offScreenDC.SelectObject(m_offScreenBitmap);
  1052. NONCLIENTMETRICS metrics;
  1053. metrics.cbSize = sizeof(metrics);
  1054. SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0);
  1055. metrics.lfMessageFont.lfHeight = mpt::saturate_round<int>(metrics.lfMessageFont.lfHeight * 0.8);
  1056. metrics.lfMessageFont.lfWidth = mpt::saturate_round<int>(metrics.lfMessageFont.lfWidth * 0.8);
  1057. m_timelineFont.DeleteObject();
  1058. m_timelineFont.CreateFontIndirect(&metrics.lfMessageFont);
  1059. }
  1060. if(!m_waveformDC.m_hDC)
  1061. {
  1062. m_waveformDC.CreateCompatibleDC(pDC);
  1063. m_waveformBitmap.CreateCompatibleBitmap(pDC, m_rcClient.Width(), m_rcClient.Height());
  1064. m_waveformDC.SelectObject(m_waveformBitmap);
  1065. m_forceRedrawWaveform = true;
  1066. }
  1067. const auto oldPen = m_offScreenDC.SelectObject(CMainFrame::penDarkGray);
  1068. const auto oldBrush = m_offScreenDC.SelectStockObject(DC_BRUSH);
  1069. const auto oldFont = m_offScreenDC.SelectObject(m_timelineFont);
  1070. // Draw timeline
  1071. const int timelineHeight = TimelineHeight(m_hWnd);
  1072. if(timelineHeight != m_timelineHeight)
  1073. {
  1074. m_timelineHeight = timelineHeight;
  1075. m_forceRedrawWaveform = true;
  1076. }
  1077. {
  1078. const TimelineFormat format = TrackerSettings::Instance().sampleEditorTimelineFormat;
  1079. CRect timeline = rcClient;
  1080. timeline.bottom = timeline.top + timelineHeight + 1;
  1081. m_offScreenDC.DrawEdge(timeline, EDGE_ETCHED, BF_MIDDLE | BF_BOTTOM);
  1082. m_offScreenDC.SetTextColor(GetSysColor(COLOR_BTNTEXT));
  1083. m_offScreenDC.SetBkMode(TRANSPARENT);
  1084. if(!m_timelineUnit)
  1085. m_timelineUnit = 1;
  1086. if(m_timelineInterval && sample.nLength)
  1087. {
  1088. rc = timeline;
  1089. const auto sampleRate = sample.GetSampleRate(sndFile.GetType());
  1090. const int textOffset = Util::ScalePixels(4, m_hWnd);
  1091. mpt::tstring text;
  1092. for(int x = -(SampleToScreen(ScrollPosToSamplePos(), true) % m_timelineInterval); x < m_rcClient.right + m_timelineInterval; x += m_timelineInterval)
  1093. {
  1094. text.clear();
  1095. if(format == TimelineFormat::Seconds && sampleRate)
  1096. {
  1097. const int64 time = mpt::saturate_round<int64>(std::round(ScreenToSeconds(x, true) * 1000.0 / m_timelineUnit) * m_timelineUnit);
  1098. rc.left = SecondsToScreen(time / 1000.0);
  1099. if(rc.left >= m_rcClient.right)
  1100. break;
  1101. const bool showSeconds = time >= 1000 || (time == 0 && m_timelineUnit >= 1000);
  1102. const auto secMs = std::div(time, int64(1000));
  1103. if(showSeconds)
  1104. {
  1105. const auto minSec = std::div(secMs.quot, int64(60));
  1106. const bool showMinutes = minSec.quot != 0 || (time == 0 && m_timelineUnit >= 60000);
  1107. if(showMinutes)
  1108. text += mpt::tfmt::dec(3, _T(','), minSec.quot) + _T("mn");
  1109. if(minSec.rem || !showMinutes)
  1110. text += mpt::tfmt::dec(3, _T(','), minSec.rem) + _T("s");
  1111. }
  1112. if(secMs.rem || !showSeconds)
  1113. {
  1114. text += mpt::tfmt::val(secMs.rem) + _T("ms");
  1115. }
  1116. } else
  1117. {
  1118. const SmpLength smp = mpt::saturate_round<SmpLength>(std::round(ScreenToSample(x, true) / static_cast<double>(m_timelineUnit)) * m_timelineUnit);
  1119. rc.left = SampleToScreen(smp);
  1120. if(rc.left >= m_rcClient.right)
  1121. break;
  1122. text += mpt::tfmt::dec(3, _T(','), smp) + _T(" smp");
  1123. }
  1124. rc.bottom = timelineHeight;
  1125. for(int i = 0; i < 10; i++)
  1126. {
  1127. rect = rc;
  1128. rect.left += i * m_timelineInterval / 10;
  1129. if(i == 0)
  1130. rect.top = 0;
  1131. else if(i == 5)
  1132. rect.top = timelineHeight / 2;
  1133. else
  1134. rect.top = timelineHeight - timelineHeight / 4;
  1135. m_offScreenDC.DrawEdge(rect, EDGE_ETCHED, BF_LEFT);
  1136. }
  1137. rc.bottom = timelineHeight / 2;
  1138. rc.left += textOffset;
  1139. m_offScreenDC.DrawText(text.c_str(), rc, DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
  1140. }
  1141. // Cues
  1142. m_offScreenDC.SelectStockObject(DC_PEN);
  1143. m_offScreenDC.SetTextColor(RGB(0, 0, 0));
  1144. const int arrowWidth = timelineHeight / 2;
  1145. for(size_t i = 0; i < std::size(sample.cues); i++)
  1146. {
  1147. if(sample.cues[i] >= sample.nLength)
  1148. continue;
  1149. int xl = SampleToScreen(sample.cues[i]);
  1150. if((xl >= -arrowWidth) && (xl < rcClient.right))
  1151. {
  1152. DrawTriangleVert(m_offScreenDC, xl, arrowWidth, timelineHeight, colors[MODCOLOR_SAMPLE_CUEPOINT]);
  1153. rc.SetRect(xl - arrowWidth, timelineHeight / 2 - 1, xl + arrowWidth, timelineHeight);
  1154. m_offScreenDC.DrawText(mpt::tfmt::val(i + 1).c_str(), rc, DT_CENTER | DT_SINGLELINE | DT_NOPREFIX);
  1155. }
  1156. }
  1157. // Loop Start/End
  1158. if(sample.nLoopEnd > sample.nLoopStart)
  1159. {
  1160. int xl = SampleToScreen(sample.nLoopStart);
  1161. if((xl >= -arrowWidth) && (xl <= rcClient.right + arrowWidth))
  1162. DrawTriangleHorz(m_offScreenDC, xl, arrowWidth, timelineHeight, colors[MODCOLOR_SAMPLE_LOOPMARKER]);
  1163. xl = SampleToScreen(sample.nLoopEnd);
  1164. if((xl >= -arrowWidth) && (xl <= rcClient.right + arrowWidth))
  1165. DrawTriangleHorz(m_offScreenDC, xl, -timelineHeight / 2, timelineHeight, colors[MODCOLOR_SAMPLE_LOOPMARKER]);
  1166. }
  1167. // Sustain Loop Start/End
  1168. if(sample.nSustainEnd > sample.nSustainStart)
  1169. {
  1170. int xl = SampleToScreen(sample.nSustainStart);
  1171. if((xl >= -arrowWidth) && (xl <= rcClient.right + arrowWidth))
  1172. DrawTriangleHorz(m_offScreenDC, xl, timelineHeight / 2, timelineHeight, colors[MODCOLOR_SAMPLE_SUSTAINMARKER]);
  1173. xl = SampleToScreen(sample.nSustainEnd);
  1174. if((xl >= -arrowWidth) && (xl <= rcClient.right + arrowWidth))
  1175. DrawTriangleHorz(m_offScreenDC, xl, -timelineHeight / 2, timelineHeight, colors[MODCOLOR_SAMPLE_SUSTAINMARKER]);
  1176. }
  1177. }
  1178. }
  1179. rect = rcClient;
  1180. rect.top = timelineHeight;
  1181. if((rcClient.bottom > rcClient.top) && (rcClient.right > rcClient.left))
  1182. {
  1183. const int ymed = (rect.top + rect.bottom) / 2;
  1184. const int yrange = (rect.bottom - rect.top) / 2;
  1185. // Erase background
  1186. if ((m_dwBeginSel < m_dwEndSel) && (m_dwEndSel > smpScrollPos))
  1187. {
  1188. rc = rect;
  1189. if (m_dwBeginSel > smpScrollPos)
  1190. {
  1191. rc.right = SampleToScreen(m_dwBeginSel);
  1192. if (rc.right > rcClient.right) rc.right = rcClient.right;
  1193. if (rc.right > rc.left) m_offScreenDC.FillSolidRect(&rc, colors[MODCOLOR_BACKSAMPLE]);
  1194. rc.left = rc.right;
  1195. }
  1196. if (rc.left < 0) rc.left = 0;
  1197. rc.right = SampleToScreen(m_dwEndSel) + 1;
  1198. if (rc.right > rcClient.right) rc.right = rcClient.right;
  1199. if(rc.right > rc.left)
  1200. m_offScreenDC.FillSolidRect(&rc, colors[MODCOLOR_SAMPLESELECTED]);
  1201. rc.left = rc.right;
  1202. if (rc.left < 0) rc.left = 0;
  1203. rc.right = rcClient.right;
  1204. if(rc.right > rc.left)
  1205. m_offScreenDC.FillSolidRect(&rc, colors[MODCOLOR_BACKSAMPLE]);
  1206. } else
  1207. {
  1208. m_offScreenDC.FillSolidRect(&rect, colors[MODCOLOR_BACKSAMPLE]);
  1209. }
  1210. m_offScreenDC.SelectObject(CMainFrame::penDarkGray);
  1211. if (sample.uFlags[CHN_STEREO])
  1212. {
  1213. m_offScreenDC.MoveTo(0, ymed - yrange / 2);
  1214. m_offScreenDC.LineTo(rcClient.right, ymed - yrange / 2);
  1215. m_offScreenDC.MoveTo(0, ymed + yrange / 2);
  1216. m_offScreenDC.LineTo(rcClient.right, ymed + yrange / 2);
  1217. } else
  1218. {
  1219. m_offScreenDC.MoveTo(0, ymed);
  1220. m_offScreenDC.LineTo(rcClient.right, ymed);
  1221. }
  1222. // Drawing sample
  1223. if(sample.HasSampleData() && yrange && (sample.nLength > 1) && (rect.right > 1))
  1224. {
  1225. // Loop Start/End
  1226. if ((sample.nLoopEnd > smpScrollPos) && (sample.nLoopEnd > sample.nLoopStart))
  1227. {
  1228. int xl = SampleToScreen(sample.nLoopStart);
  1229. if ((xl >= 0) && (xl < rcClient.right))
  1230. {
  1231. m_offScreenDC.MoveTo(xl, rect.top);
  1232. m_offScreenDC.LineTo(xl, rect.bottom);
  1233. }
  1234. xl = SampleToScreen(sample.nLoopEnd);
  1235. if((xl >= 0) && (xl < rcClient.right))
  1236. {
  1237. m_offScreenDC.MoveTo(xl, rect.top);
  1238. m_offScreenDC.LineTo(xl, rect.bottom);
  1239. }
  1240. }
  1241. // Sustain Loop Start/End
  1242. if ((sample.nSustainEnd > smpScrollPos) && (sample.nSustainEnd > sample.nSustainStart))
  1243. {
  1244. m_offScreenDC.SetBkMode(OPAQUE);
  1245. m_offScreenDC.SetBkColor(RGB(0xFF, 0xFF, 0xFF));
  1246. m_offScreenDC.SelectObject(CMainFrame::penHalfDarkGray);
  1247. int xl = SampleToScreen(sample.nSustainStart);
  1248. if ((xl >= 0) && (xl < rcClient.right))
  1249. {
  1250. m_offScreenDC.MoveTo(xl, rect.top);
  1251. m_offScreenDC.LineTo(xl, rect.bottom);
  1252. }
  1253. xl = SampleToScreen(sample.nSustainEnd);
  1254. if ((xl >= 0) && (xl < rcClient.right))
  1255. {
  1256. m_offScreenDC.MoveTo(xl, rect.top);
  1257. m_offScreenDC.LineTo(xl, rect.bottom);
  1258. }
  1259. }
  1260. // Active cue point
  1261. if(IsCuePoint(m_dragItem))
  1262. {
  1263. m_offScreenDC.SetBkMode(TRANSPARENT);
  1264. m_offScreenDC.SelectObject(CMainFrame::penHalfDarkGray);
  1265. int xl = SampleToScreen(sample.cues[CuePointFromItem(m_dragItem)]);
  1266. if((xl >= 0) && (xl < rcClient.right))
  1267. {
  1268. m_offScreenDC.MoveTo(xl, rect.top);
  1269. m_offScreenDC.LineTo(xl, rect.bottom);
  1270. }
  1271. }
  1272. // Drawing Sample Data
  1273. const auto backgroundCol = ~colors[MODCOLOR_SAMPLE];
  1274. if(m_forceRedrawWaveform)
  1275. {
  1276. m_forceRedrawWaveform = false;
  1277. m_waveformDC.SelectStockObject(DC_PEN);
  1278. m_waveformDC.FillSolidRect(rect, backgroundCol);
  1279. m_waveformDC.SetDCPenColor(colors[MODCOLOR_SAMPLE]);
  1280. const int smplsize = sample.GetBytesPerSample();
  1281. if(m_nZoom == 1 || m_nZoom < 0 || ((!m_nZoom) && (sample.nLength <= (SmpLength)rect.Width())))
  1282. {
  1283. // Draw sample data in 1:1 ratio or higher (zoom in)
  1284. SmpLength len = sample.nLength - smpScrollPos;
  1285. const std::byte *psample = sample.sampleb() + smpScrollPos * smplsize;
  1286. if(sample.uFlags[CHN_STEREO])
  1287. {
  1288. DrawSampleData1(m_waveformDC, ymed - yrange / 2, rect.right, yrange, len, sample.uFlags, psample);
  1289. DrawSampleData1(m_waveformDC, ymed + yrange / 2, rect.right, yrange, len, sample.uFlags, psample + smplsize / 2);
  1290. } else
  1291. {
  1292. DrawSampleData1(m_waveformDC, ymed, rect.right, yrange * 2, len, sample.uFlags, psample);
  1293. }
  1294. } else
  1295. {
  1296. // Draw zoomed-out saple data
  1297. SmpLength len = sample.nLength;
  1298. int xscroll = 0;
  1299. if(m_nZoom > 0)
  1300. {
  1301. xscroll = smpScrollPos;
  1302. len -= smpScrollPos;
  1303. }
  1304. const std::byte *psample = sample.sampleb() + xscroll * smplsize;
  1305. if(sample.uFlags[CHN_STEREO])
  1306. {
  1307. DrawSampleData2(m_waveformDC, ymed - yrange / 2, rect.right, yrange, len, sample.uFlags, psample);
  1308. DrawSampleData2(m_waveformDC, ymed + yrange / 2, rect.right, yrange, len, sample.uFlags, psample + smplsize / 2);
  1309. } else
  1310. {
  1311. DrawSampleData2(m_waveformDC, ymed, rect.right, yrange * 2, len, sample.uFlags, psample);
  1312. }
  1313. }
  1314. }
  1315. m_offScreenDC.TransparentBlt(rect.left, rect.top, rect.Width(), rect.Height(), &m_waveformDC, rect.left, rect.top, rect.Width(), rect.Height(), backgroundCol);
  1316. }
  1317. }
  1318. if(m_nGridSegments > 0 && m_nGridSegments < sample.nLength && sample.nLength != 0)
  1319. {
  1320. // Draw sample grid
  1321. m_offScreenDC.SetBkColor(TrackerSettings::Instance().rgbCustomColors[MODCOLOR_BACKSAMPLE]);
  1322. m_offScreenDC.SelectObject(CMainFrame::penHalfDarkGray);
  1323. const auto segmentsByLength = static_cast<double>(m_nGridSegments) / sample.nLength;
  1324. const auto samplesPerSegment = static_cast<double>(sample.nLength) / m_nGridSegments;
  1325. const auto leftSegment = std::max(uint32(1), mpt::saturate_round<uint32>(ScreenToSample(rect.left) * segmentsByLength));
  1326. const auto rightSegment = std::min(m_nGridSegments, mpt::saturate_round<uint32>(ScreenToSample(rect.right) * segmentsByLength));
  1327. for(uint32 i = leftSegment; i <= rightSegment; i++)
  1328. {
  1329. int screenPos = SampleToScreen(mpt::saturate_round<SmpLength>(samplesPerSegment * i));
  1330. m_offScreenDC.MoveTo(screenPos, rect.top);
  1331. m_offScreenDC.LineTo(screenPos, rect.bottom);
  1332. }
  1333. }
  1334. DrawPositionMarks();
  1335. BitBlt(pDC->m_hDC, m_rcClient.left, m_rcClient.top, m_rcClient.Width(), m_rcClient.Height(), m_offScreenDC, 0, 0, SRCCOPY);
  1336. if(oldFont)
  1337. m_offScreenDC.SelectObject(oldFont);
  1338. if(oldBrush)
  1339. m_offScreenDC.SelectObject(oldBrush);
  1340. if(oldPen)
  1341. m_offScreenDC.SelectObject(oldPen);
  1342. }
  1343. void CViewSample::DrawPositionMarks()
  1344. {
  1345. const ModSample &sample = GetDocument()->GetSoundFile().GetSample(m_nSample);
  1346. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB])
  1347. {
  1348. return;
  1349. }
  1350. CRect rect;
  1351. for(auto pos : m_dwNotifyPos) if (pos != Notification::PosInvalid)
  1352. {
  1353. rect.top = m_timelineHeight;
  1354. rect.left = SampleToScreen(pos);
  1355. rect.right = rect.left + 1;
  1356. rect.bottom = m_rcClient.bottom + 1;
  1357. if ((rect.right >= 0) && (rect.right < m_rcClient.right)) m_offScreenDC.InvertRect(&rect);
  1358. }
  1359. }
  1360. LRESULT CViewSample::OnPlayerNotify(Notification *pnotify)
  1361. {
  1362. CModDoc *pModDoc = GetDocument();
  1363. if ((!pnotify) || (!pModDoc)) return 0;
  1364. if (pnotify->type[Notification::Stop])
  1365. {
  1366. bool invalidate = false;
  1367. for(auto &pos : m_dwNotifyPos)
  1368. {
  1369. if(pos != Notification::PosInvalid)
  1370. {
  1371. pos = Notification::PosInvalid;
  1372. invalidate = true;
  1373. }
  1374. }
  1375. if(invalidate)
  1376. InvalidateSample(false);
  1377. } else if (pnotify->type[Notification::Sample] && pnotify->item == m_nSample && !IsOPLInstrument())
  1378. {
  1379. if(m_dwNotifyPos != pnotify->pos)
  1380. {
  1381. HDC hdc = ::GetDC(m_hWnd);
  1382. DrawPositionMarks(); // Erase old marks...
  1383. m_dwNotifyPos = pnotify->pos;
  1384. DrawPositionMarks(); // ...and draw new ones
  1385. BitBlt(hdc, m_rcClient.left, m_rcClient.top, m_rcClient.Width(), m_rcClient.Height(), m_offScreenDC, 0, 0, SRCCOPY);
  1386. ::ReleaseDC(m_hWnd, hdc);
  1387. }
  1388. }
  1389. return 0;
  1390. }
  1391. bool CViewSample::GetNcButtonRect(UINT button, CRect &rect) const
  1392. {
  1393. rect.left = 4;
  1394. rect.top = 3;
  1395. rect.bottom = rect.top + SMP_LEFTBAR_CYBTN;
  1396. if(button >= SMP_LEFTBAR_BUTTONS) return false;
  1397. for(UINT i = 0; i < button; i++)
  1398. {
  1399. if(cLeftBarButtons[i] == ID_SEPARATOR)
  1400. rect.left += SMP_LEFTBAR_CXSEP;
  1401. else
  1402. rect.left += SMP_LEFTBAR_CXBTN + SMP_LEFTBAR_CXSPC;
  1403. }
  1404. if(cLeftBarButtons[button] == ID_SEPARATOR)
  1405. {
  1406. rect.left += SMP_LEFTBAR_CXSEP/2 - 2;
  1407. rect.right = rect.left + 2;
  1408. return false;
  1409. } else
  1410. {
  1411. rect.right = rect.left + SMP_LEFTBAR_CXBTN;
  1412. }
  1413. return true;
  1414. }
  1415. UINT CViewSample::GetNcButtonAtPoint(CPoint point, CRect *outRect) const
  1416. {
  1417. CRect rect, rcWnd;
  1418. UINT button = uint32_max;
  1419. GetWindowRect(&rcWnd);
  1420. for(UINT i = 0; i < SMP_LEFTBAR_BUTTONS; i++)
  1421. {
  1422. if(!(m_NcButtonState[i] & NCBTNS_DISABLED) && GetNcButtonRect(i, rect))
  1423. {
  1424. rect.OffsetRect(rcWnd.left, rcWnd.top);
  1425. if(rect.PtInRect(point))
  1426. {
  1427. button = i;
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. if(outRect)
  1433. *outRect = rect;
  1434. return button;
  1435. }
  1436. void CViewSample::DrawNcButton(CDC *pDC, UINT nBtn)
  1437. {
  1438. CRect rect;
  1439. COLORREF crHi = GetSysColor(COLOR_3DHILIGHT);
  1440. COLORREF crDk = GetSysColor(COLOR_3DSHADOW);
  1441. COLORREF crFc = GetSysColor(COLOR_3DFACE);
  1442. COLORREF c1, c2;
  1443. if(GetNcButtonRect(nBtn, rect))
  1444. {
  1445. DWORD dwStyle = m_NcButtonState[nBtn];
  1446. COLORREF c3, c4;
  1447. int xofs = 0, yofs = 0, nImage = 0;
  1448. c1 = c2 = c3 = c4 = crFc;
  1449. if (!(TrackerSettings::Instance().m_dwPatternSetup & PATTERN_FLATBUTTONS))
  1450. {
  1451. c1 = c3 = crHi;
  1452. c2 = crDk;
  1453. c4 = RGB(0,0,0);
  1454. }
  1455. if (dwStyle & (NCBTNS_PUSHED|NCBTNS_CHECKED))
  1456. {
  1457. c1 = crDk;
  1458. c2 = crHi;
  1459. if (!(TrackerSettings::Instance().m_dwPatternSetup & PATTERN_FLATBUTTONS))
  1460. {
  1461. c4 = crHi;
  1462. c3 = (dwStyle & NCBTNS_PUSHED) ? RGB(0,0,0) : crDk;
  1463. }
  1464. xofs = yofs = 1;
  1465. } else
  1466. if ((dwStyle & NCBTNS_MOUSEOVER) && (TrackerSettings::Instance().m_dwPatternSetup & PATTERN_FLATBUTTONS))
  1467. {
  1468. c1 = crHi;
  1469. c2 = crDk;
  1470. }
  1471. switch(cLeftBarButtons[nBtn])
  1472. {
  1473. case ID_SAMPLE_ZOOMUP: nImage = SIMAGE_ZOOMUP; break;
  1474. case ID_SAMPLE_ZOOMDOWN: nImage = SIMAGE_ZOOMDOWN; break;
  1475. case ID_SAMPLE_DRAW: nImage = SIMAGE_DRAW; break;
  1476. case ID_SAMPLE_ADDSILENCE: nImage = SIMAGE_RESIZE; break;
  1477. case ID_SAMPLE_GRID: nImage = SIMAGE_GRID; break;
  1478. }
  1479. pDC->Draw3dRect(rect.left-1, rect.top-1, SMP_LEFTBAR_CXBTN+2, SMP_LEFTBAR_CYBTN+2, c3, c4);
  1480. pDC->Draw3dRect(rect.left, rect.top, SMP_LEFTBAR_CXBTN, SMP_LEFTBAR_CYBTN, c1, c2);
  1481. rect.DeflateRect(1, 1);
  1482. pDC->FillSolidRect(&rect, crFc);
  1483. rect.left += xofs;
  1484. rect.top += yofs;
  1485. if (dwStyle & NCBTNS_CHECKED) m_bmpEnvBar.Draw(pDC, SIMAGE_CHECKED, rect.TopLeft(), ILD_NORMAL);
  1486. m_bmpEnvBar.Draw(pDC, nImage, rect.TopLeft(), ILD_NORMAL);
  1487. } else
  1488. {
  1489. c1 = c2 = crFc;
  1490. if (TrackerSettings::Instance().m_dwPatternSetup & PATTERN_FLATBUTTONS)
  1491. {
  1492. c1 = crDk;
  1493. c2 = crHi;
  1494. }
  1495. pDC->Draw3dRect(rect.left, rect.top, 2, SMP_LEFTBAR_CYBTN, c1, c2);
  1496. }
  1497. }
  1498. void CViewSample::OnNcPaint()
  1499. {
  1500. RECT rect;
  1501. CModScrollView::OnNcPaint();
  1502. GetWindowRect(&rect);
  1503. // Assumes there is no other non-client items
  1504. rect.bottom = SMP_LEFTBAR_CY;
  1505. rect.right -= rect.left;
  1506. rect.left = 0;
  1507. rect.top = 0;
  1508. if ((rect.left < rect.right) && (rect.top < rect.bottom))
  1509. {
  1510. CDC *pDC = GetWindowDC();
  1511. {
  1512. // Shadow
  1513. auto shadowRect = rect;
  1514. shadowRect.top = shadowRect.bottom - 1;
  1515. pDC->FillSolidRect(&shadowRect, GetSysColor(COLOR_BTNSHADOW));
  1516. }
  1517. rect.bottom--;
  1518. if(rect.top < rect.bottom)
  1519. pDC->FillSolidRect(&rect, GetSysColor(COLOR_BTNFACE));
  1520. if(rect.top + 2 < rect.bottom)
  1521. {
  1522. for (UINT i=0; i<SMP_LEFTBAR_BUTTONS; i++)
  1523. {
  1524. DrawNcButton(pDC, i);
  1525. }
  1526. }
  1527. ReleaseDC(pDC);
  1528. }
  1529. }
  1530. void CViewSample::UpdateNcButtonState()
  1531. {
  1532. CModDoc *pModDoc = GetDocument();
  1533. CDC *pDC = NULL;
  1534. if (!pModDoc) return;
  1535. for (UINT i=0; i<SMP_LEFTBAR_BUTTONS; i++) if (cLeftBarButtons[i] != ID_SEPARATOR)
  1536. {
  1537. DWORD dwStyle = 0;
  1538. if (m_nBtnMouseOver == i)
  1539. {
  1540. dwStyle |= NCBTNS_MOUSEOVER;
  1541. if(m_dwStatus[SMPSTATUS_NCLBTNDOWN]) dwStyle |= NCBTNS_PUSHED;
  1542. }
  1543. switch(cLeftBarButtons[i])
  1544. {
  1545. case ID_SAMPLE_DRAW:
  1546. if(m_dwStatus[SMPSTATUS_DRAWING]) dwStyle |= NCBTNS_CHECKED;
  1547. if(m_nSample > pModDoc->GetNumSamples() || IsOPLInstrument())
  1548. {
  1549. dwStyle |= NCBTNS_DISABLED;
  1550. }
  1551. break;
  1552. case ID_SAMPLE_ZOOMUP:
  1553. case ID_SAMPLE_ZOOMDOWN:
  1554. case ID_SAMPLE_GRID:
  1555. if(IsOPLInstrument()) dwStyle |= NCBTNS_DISABLED;
  1556. break;
  1557. }
  1558. if (dwStyle != m_NcButtonState[i])
  1559. {
  1560. m_NcButtonState[i] = dwStyle;
  1561. if (!pDC) pDC = GetWindowDC();
  1562. DrawNcButton(pDC, i);
  1563. }
  1564. }
  1565. if (pDC) ReleaseDC(pDC);
  1566. }
  1567. ///////////////////////////////////////////////////////////////
  1568. // CViewSample messages
  1569. void CViewSample::OnSize(UINT nType, int cx, int cy)
  1570. {
  1571. CModScrollView::OnSize(nType, cx, cy);
  1572. m_offScreenBitmap.DeleteObject();
  1573. m_offScreenDC.DeleteDC();
  1574. m_waveformBitmap.DeleteObject();
  1575. m_waveformDC.DeleteDC();
  1576. if (((nType == SIZE_RESTORED) || (nType == SIZE_MAXIMIZED)) && (cx > 0) && (cy > 0))
  1577. {
  1578. UpdateScrollSize();
  1579. }
  1580. }
  1581. void CViewSample::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp)
  1582. {
  1583. CModScrollView::OnNcCalcSize(bCalcValidRects, lpncsp);
  1584. if (lpncsp)
  1585. {
  1586. lpncsp->rgrc[0].top += SMP_LEFTBAR_CY;
  1587. if (lpncsp->rgrc[0].bottom < lpncsp->rgrc[0].top) lpncsp->rgrc[0].top = lpncsp->rgrc[0].bottom;
  1588. }
  1589. }
  1590. void CViewSample::ScrollToPosition(int x) // logical coordinates
  1591. {
  1592. CPoint pt;
  1593. // now in device coordinates - limit if out of range
  1594. int xMax = GetScrollLimit(SB_HORZ);
  1595. pt.x = x;
  1596. pt.y = 0;
  1597. if (pt.x < 0)
  1598. pt.x = 0;
  1599. else if (pt.x > xMax)
  1600. pt.x = xMax;
  1601. ScrollToDevicePosition(pt);
  1602. }
  1603. template<class T, class uT>
  1604. T CViewSample::GetSampleValueFromPoint(const ModSample &smp, const CPoint &point) const
  1605. {
  1606. static_assert(sizeof(T) == sizeof(uT) && sizeof(T) <= 2);
  1607. const int channelHeight = (m_rcClient.Height() - m_timelineHeight) / smp.GetNumChannels();
  1608. int yPos = point.y - m_drawChannel * channelHeight - m_timelineHeight;
  1609. int value = std::numeric_limits<T>::max() - std::numeric_limits<uT>::max() * yPos / channelHeight;
  1610. Limit(value, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
  1611. return static_cast<T>(value);
  1612. }
  1613. template<class T, class uT>
  1614. void CViewSample::SetInitialDrawPoint(ModSample &smp, const CPoint &point)
  1615. {
  1616. if(m_rcClient.Height() >= m_timelineHeight)
  1617. m_drawChannel = (point.y - m_timelineHeight) * smp.GetNumChannels() / (m_rcClient.Height() - m_timelineHeight);
  1618. else
  1619. m_drawChannel = 0;
  1620. Limit(m_drawChannel, 0, (int)smp.GetNumChannels() - 1);
  1621. T *data = static_cast<T *>(smp.samplev()) + m_drawChannel;
  1622. data[m_dwEndDrag * smp.GetNumChannels()] = GetSampleValueFromPoint<T, uT>(smp, point);
  1623. }
  1624. template<class T, class uT>
  1625. void CViewSample::SetSampleData(ModSample &smp, const CPoint &point, const SmpLength old)
  1626. {
  1627. T *data = static_cast<T *>(smp.samplev()) + m_drawChannel + old * smp.GetNumChannels();
  1628. const int oldvalue = *data;
  1629. const int value = GetSampleValueFromPoint<T, uT>(smp, point);
  1630. const int inc = (m_dwEndDrag > old ? 1 : -1);
  1631. const int ptrInc = inc * smp.GetNumChannels();
  1632. for(SmpLength i = old; i != m_dwEndDrag; i += inc, data += ptrInc)
  1633. {
  1634. *data = static_cast<T>(static_cast<double>(oldvalue) + (value - oldvalue) * (static_cast<double>(i - old) / static_cast<double>(m_dwEndDrag - old)));
  1635. }
  1636. *data = static_cast<T>(value);
  1637. }
  1638. void CViewSample::OnMouseMove(UINT flags, CPoint point)
  1639. {
  1640. CModDoc *pModDoc = GetDocument();
  1641. if(m_nBtnMouseOver < SMP_LEFTBAR_BUTTONS || m_dwStatus[SMPSTATUS_NCLBTNDOWN])
  1642. {
  1643. m_dwStatus.reset(SMPSTATUS_NCLBTNDOWN);
  1644. m_nBtnMouseOver = 0xFFFF;
  1645. UpdateNcButtonState();
  1646. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  1647. if (pMainFrm) pMainFrm->SetHelpText(_T(""));
  1648. }
  1649. if(!pModDoc)
  1650. return;
  1651. CSoundFile &sndFile = pModDoc->GetSoundFile();
  1652. if(m_nSample > sndFile.GetNumSamples())
  1653. return;
  1654. auto &sample = sndFile.GetSample(m_nSample);
  1655. if (m_rcClient.PtInRect(point))
  1656. {
  1657. const SmpLength x = ScreenToSample(point.x);
  1658. CString(*fmt)(unsigned int, char, const SmpLength &) = &mpt::cfmt::dec<SmpLength>;
  1659. if(TrackerSettings::Instance().cursorPositionInHex)
  1660. fmt = &mpt::cfmt::HEX<SmpLength>;
  1661. UpdateIndicator(MPT_CFORMAT("Cursor: {}")(fmt(3, ',', x)));
  1662. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  1663. if(pMainFrm && m_dwEndSel <= m_dwBeginSel)
  1664. {
  1665. // Show cursor position as offset effect if no selection is made.
  1666. if(m_nSample > 0 && sample.HasSampleData() && x < sample.nLength)
  1667. {
  1668. const SmpLength xLow = (x / 0x100) % 0x100;
  1669. const SmpLength xHigh = x / 0x10000;
  1670. const char offsetChar = sndFile.GetModSpecifications().GetEffectLetter(CMD_OFFSET);
  1671. const bool hasHighOffset = (sndFile.GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM));
  1672. const char highOffsetChar = sndFile.GetModSpecifications().GetEffectLetter(static_cast<ModCommand::COMMAND>(sndFile.GetModSpecifications().HasCommand(CMD_S3MCMDEX) ? CMD_S3MCMDEX : CMD_XFINEPORTAUPDOWN));
  1673. CString s;
  1674. if(xHigh == 0)
  1675. s.Format(_T("Offset: %c%02X"), offsetChar, xLow);
  1676. else if(hasHighOffset && xHigh < 0x10)
  1677. s.Format(_T("Offset: %c%02X, %cA%X"), offsetChar, xLow, highOffsetChar, xHigh);
  1678. else
  1679. s = _T("Beyond offset range");
  1680. pMainFrm->SetInfoText(s);
  1681. double linear;
  1682. SmpLength offset = x * sample.GetNumChannels() + (point.y - m_timelineHeight) * sample.GetNumChannels() / (m_rcClient.Height() - m_timelineHeight);
  1683. if(sample.uFlags[CHN_16BIT])
  1684. linear = sample.sample16()[offset] / 32768.0;
  1685. else
  1686. linear = sample.sample8()[offset] / 128.0;
  1687. pMainFrm->SetXInfoText(MPT_TFORMAT("Value At Cursor: {}% / {}")(mpt::tfmt::fix(linear * 100.0, 3), CModDoc::LinearToDecibels(std::abs(linear), 1.0)).c_str());
  1688. } else
  1689. {
  1690. pMainFrm->SetInfoText(_T(""));
  1691. pMainFrm->SetXInfoText(_T(""));
  1692. }
  1693. }
  1694. } else
  1695. {
  1696. UpdateIndicator(nullptr);
  1697. }
  1698. if(m_dwStatus[SMPSTATUS_MOUSEDRAG])
  1699. {
  1700. const SmpLength len = sndFile.GetSample(m_nSample).nLength;
  1701. if(!len)
  1702. return;
  1703. SmpLength old = m_dwEndDrag;
  1704. if(m_nZoom)
  1705. {
  1706. if(point.x < 0)
  1707. {
  1708. CPoint pt;
  1709. pt.x = point.x;
  1710. pt.y = 0;
  1711. if(OnScrollBy(pt))
  1712. {
  1713. UpdateWindow();
  1714. }
  1715. point.x = 0;
  1716. }
  1717. if (point.x > m_rcClient.right)
  1718. {
  1719. CPoint pt;
  1720. pt.x = point.x - m_rcClient.right;
  1721. pt.y = 0;
  1722. if (OnScrollBy(pt))
  1723. {
  1724. UpdateWindow();
  1725. }
  1726. point.x = m_rcClient.right;
  1727. }
  1728. }
  1729. // Note: point.x might have changed in if block above in case we're scrolling.
  1730. SmpLength x;
  1731. if(m_dwStatus[SMPSTATUS_DRAWING])
  1732. {
  1733. // Do not snap to grid and adjust for mouse-down position when drawing
  1734. x = ScreenToSample(point.x);
  1735. } else if(m_fineDrag)
  1736. {
  1737. x = m_startDragValue + (point.x - m_startDragPoint.x) / Util::ScalePixels(2, m_hWnd);
  1738. } else if (m_nZoom < 0 || (m_nZoom == 0 && sample.nLength > static_cast<SmpLength>(m_rcClient.Width())))
  1739. {
  1740. // Don't adjust selection to mouse down point when zooming into the sample
  1741. x = SnapToGrid(ScreenToSample(point.x));
  1742. } else
  1743. {
  1744. x = SnapToGrid(ScreenToSample(SampleToScreen(m_startDragValue) + point.x - m_startDragPoint.x));
  1745. }
  1746. if((flags & MK_SHIFT) && !m_fineDrag)
  1747. {
  1748. m_fineDrag = true;
  1749. m_startDragPoint = point;
  1750. m_startDragValue = x;
  1751. } else if(!(flags & MK_SHIFT) && m_fineDrag)
  1752. {
  1753. m_fineDrag = false;
  1754. m_startDragPoint = point;
  1755. m_startDragValue = ScreenToSample(point.x);
  1756. }
  1757. bool update = false;
  1758. SmpLength *updateLoopPoint = nullptr;
  1759. const char *updateLoopDesc = nullptr;
  1760. switch(m_dragItem)
  1761. {
  1762. case HitTestItem::SelectionStart:
  1763. case HitTestItem::SelectionEnd:
  1764. if(m_dwEndDrag != x)
  1765. {
  1766. m_dwEndDrag = x;
  1767. SetCurSel(m_dwBeginDrag, m_dwEndDrag);
  1768. update = true;
  1769. }
  1770. break;
  1771. case HitTestItem::LoopStart:
  1772. if(x < sample.nLoopEnd)
  1773. {
  1774. updateLoopPoint = &sample.nLoopStart;
  1775. updateLoopDesc = "Set Loop Start";
  1776. }
  1777. break;
  1778. case HitTestItem::LoopEnd:
  1779. if(x > sample.nLoopStart)
  1780. {
  1781. updateLoopPoint = &sample.nLoopEnd;
  1782. updateLoopDesc = "Set Loop End";
  1783. }
  1784. break;
  1785. case HitTestItem::SustainStart:
  1786. if(x < sample.nSustainEnd)
  1787. {
  1788. updateLoopPoint = &sample.nSustainStart;
  1789. updateLoopDesc = "Set Sustain Start";
  1790. }
  1791. break;
  1792. case HitTestItem::SustainEnd:
  1793. if(x > sample.nSustainStart)
  1794. {
  1795. updateLoopPoint = &sample.nSustainEnd;
  1796. updateLoopDesc = "Set Sustain End";
  1797. }
  1798. break;
  1799. default:
  1800. if(IsCuePoint(m_dragItem))
  1801. {
  1802. int cue = CuePointFromItem(m_dragItem);
  1803. updateLoopPoint = &sample.cues[cue];
  1804. updateLoopDesc ="Set Cue Point";
  1805. }
  1806. break;
  1807. }
  1808. if(updateLoopPoint && updateLoopDesc && *updateLoopPoint != x)
  1809. {
  1810. if(!m_dragPreparedUndo)
  1811. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, updateLoopDesc);
  1812. m_dragPreparedUndo = true;
  1813. update = true;
  1814. *updateLoopPoint = x;
  1815. sample.PrecomputeLoops(sndFile, true);
  1816. SetModified(SampleHint().Info(), true, false);
  1817. }
  1818. if(m_dwStatus[SMPSTATUS_DRAWING] && m_dragItem == HitTestItem::SampleData)
  1819. {
  1820. m_dwEndDrag = x;
  1821. if(m_dwEndDrag < len)
  1822. {
  1823. // Shift = draw horizontal lines
  1824. if(flags & MK_SHIFT)
  1825. {
  1826. if(m_lastDrawPoint.y != -1)
  1827. point.y = m_lastDrawPoint.y;
  1828. m_lastDrawPoint = point;
  1829. } else
  1830. {
  1831. m_lastDrawPoint.SetPoint(-1, -1);
  1832. }
  1833. LimitMax(old, sample.nLength);
  1834. if(sample.GetElementarySampleSize() == 2)
  1835. SetSampleData<int16, uint16>(sample, point, old);
  1836. else if(sample.GetElementarySampleSize() == 1)
  1837. SetSampleData<int8, uint8>(sample, point, old);
  1838. sample.PrecomputeLoops(sndFile, false);
  1839. InvalidateSample();
  1840. SetModified(SampleHint().Data(), false, true);
  1841. }
  1842. } else if(update)
  1843. {
  1844. UpdateWindow();
  1845. }
  1846. }
  1847. }
  1848. BOOL CViewSample::OnSetCursor(CWnd *pWnd, UINT nHitTest, UINT message)
  1849. {
  1850. // Update mouse cursor if we are close to a selection point
  1851. if(nHitTest == HTCLIENT && (message == WM_MOUSEMOVE || message == WM_LBUTTONDOWN))
  1852. {
  1853. CPoint point;
  1854. GetCursorPos(&point);
  1855. ScreenToClient(&point);
  1856. const auto item = PointToItem(point).first;
  1857. if(item != HitTestItem::Nothing && item != HitTestItem::SampleData)
  1858. {
  1859. SetCursor(CMainFrame::curVSplit);
  1860. return TRUE;
  1861. }
  1862. }
  1863. return CModScrollView::OnSetCursor(pWnd, nHitTest, message);
  1864. }
  1865. void CViewSample::OnLButtonDown(UINT flags, CPoint point)
  1866. {
  1867. CModDoc *pModDoc = GetDocument();
  1868. if(m_dwStatus[SMPSTATUS_MOUSEDRAG] || (!pModDoc)) return;
  1869. CSoundFile &sndFile = pModDoc->GetSoundFile();
  1870. ModSample &sample = sndFile.GetSample(m_nSample);
  1871. if (!sample.nLength)
  1872. return;
  1873. m_dwStatus.set(SMPSTATUS_MOUSEDRAG);
  1874. SetFocus();
  1875. SetCapture();
  1876. bool oldsel = (m_dwBeginSel != m_dwEndSel);
  1877. // shift + click = update selection
  1878. const auto [item, itemPos] = PointToItem(point);
  1879. if(!m_dwStatus[SMPSTATUS_DRAWING] && (flags & MK_SHIFT) && item == HitTestItem::SampleData)
  1880. {
  1881. oldsel = true;
  1882. m_dwEndDrag = itemPos;
  1883. SetCurSel(m_dwBeginDrag, m_dwEndDrag);
  1884. } else
  1885. {
  1886. m_dragItem = item;
  1887. m_startDragPoint = point;
  1888. m_startDragValue = itemPos;
  1889. m_fineDrag = (flags & MK_SHIFT);
  1890. m_dragPreparedUndo = false;
  1891. switch(m_dragItem)
  1892. {
  1893. case HitTestItem::SampleData:
  1894. m_dwBeginDrag = m_dwEndDrag = ScreenToSample(point.x);
  1895. if(!m_dwStatus[SMPSTATUS_DRAWING])
  1896. m_dragItem = HitTestItem::SelectionEnd;
  1897. break;
  1898. case HitTestItem::SelectionStart:
  1899. m_dwBeginDrag = m_dwEndSel;
  1900. m_dwEndDrag = itemPos;
  1901. break;
  1902. case HitTestItem::SelectionEnd:
  1903. m_dwBeginDrag = m_dwBeginSel;
  1904. m_dwEndDrag = itemPos;
  1905. break;
  1906. default:
  1907. if(IsCuePoint(m_dragItem))
  1908. InvalidateSample(false);
  1909. break;
  1910. }
  1911. }
  1912. if(oldsel)
  1913. SetCurSel(m_dwBeginDrag, m_dwEndDrag);
  1914. // set initial point for sample drawing
  1915. if (m_dwStatus[SMPSTATUS_DRAWING] && m_dragItem == HitTestItem::SampleData)
  1916. {
  1917. m_lastDrawPoint = point;
  1918. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Draw Sample");
  1919. if(sample.GetElementarySampleSize() == 2)
  1920. SetInitialDrawPoint<int16, uint16>(sample, point);
  1921. else if(sample.GetElementarySampleSize() == 1)
  1922. SetInitialDrawPoint<int8, uint8>(sample, point);
  1923. sndFile.GetSample(m_nSample).PrecomputeLoops(sndFile, false);
  1924. InvalidateSample();
  1925. SetModified(SampleHint().Data(), false, true);
  1926. } else
  1927. {
  1928. // ctrl + click = play from cursor pos
  1929. if(flags & MK_CONTROL)
  1930. PlayNote(NOTE_MIDDLEC, ScreenToSample(point.x));
  1931. }
  1932. }
  1933. void CViewSample::OnLButtonUp(UINT, CPoint)
  1934. {
  1935. if(m_dwStatus[SMPSTATUS_MOUSEDRAG])
  1936. {
  1937. m_dwStatus.reset(SMPSTATUS_MOUSEDRAG);
  1938. ReleaseCapture();
  1939. }
  1940. if(IsCuePoint(m_dragItem))
  1941. InvalidateSample(false);
  1942. m_dragItem = HitTestItem::Nothing;
  1943. m_startDragValue = MAX_SAMPLE_LENGTH;
  1944. m_lastDrawPoint.SetPoint(-1, -1);
  1945. }
  1946. void CViewSample::OnLButtonDblClk(UINT, CPoint)
  1947. {
  1948. CModDoc *pModDoc = GetDocument();
  1949. if (pModDoc)
  1950. {
  1951. SmpLength len = pModDoc->GetSoundFile().GetSample(m_nSample).nLength;
  1952. if (len && !m_dwStatus[SMPSTATUS_DRAWING]) SetCurSel(0, len);
  1953. }
  1954. }
  1955. void CViewSample::OnRButtonDown(UINT, CPoint pt)
  1956. {
  1957. CModDoc *pModDoc = GetDocument();
  1958. if(pModDoc)
  1959. {
  1960. const CSoundFile &sndFile = pModDoc->GetSoundFile();
  1961. const ModSample &sample = sndFile.GetSample(m_nSample);
  1962. HMENU hMenu = ::CreatePopupMenu();
  1963. CInputHandler* ih = CMainFrame::GetInputHandler();
  1964. if(!hMenu)
  1965. return;
  1966. TCHAR s[256];
  1967. if(pt.y < m_timelineHeight)
  1968. {
  1969. const auto item = PointToItem(pt).first;
  1970. if(IsCuePoint(item))
  1971. {
  1972. m_dwMenuParam = CuePointFromItem(item);
  1973. wsprintf(s, _T("&Delete Cue Point %d"), 1 + static_cast<int>(m_dwMenuParam));
  1974. ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_DELETE_CUEPOINT, s);
  1975. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  1976. } else
  1977. {
  1978. if(*std::max_element(sample.cues.begin(), sample.cues.end()) >= sample.nLength)
  1979. {
  1980. m_dwMenuParam = ScreenToSample(pt.x);
  1981. wsprintf(s, _T("&Insert Cue Point at %s"), mpt::cfmt::dec(3, ',', m_dwMenuParam).GetString());
  1982. ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_INSERT_CUEPOINT, s);
  1983. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  1984. }
  1985. }
  1986. auto fmt = TrackerSettings::Instance().sampleEditorTimelineFormat.Get();
  1987. ::AppendMenu(hMenu, MF_STRING | (fmt == TimelineFormat::Seconds ? MF_CHECKED : 0), ID_SAMPLE_TIMELINE_SECONDS, _T("&Seconds"));
  1988. ::AppendMenu(hMenu, MF_STRING | (fmt == TimelineFormat::Samples ? MF_CHECKED : 0), ID_SAMPLE_TIMELINE_SAMPLES, _T("S&amples"));
  1989. ::AppendMenu(hMenu, MF_STRING | (fmt == TimelineFormat::SamplesPow2 ? MF_CHECKED : 0), ID_SAMPLE_TIMELINE_SAMPLES_POW2, _T("Samples (&Power of 2)"));
  1990. ClientToScreen(&pt);
  1991. ::TrackPopupMenu(hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, 0, m_hWnd, NULL);
  1992. ::DestroyMenu(hMenu);
  1993. return;
  1994. }
  1995. if (sample.HasSampleData() && !sample.uFlags[CHN_ADLIB])
  1996. {
  1997. if (m_dwEndSel >= m_dwBeginSel + 4)
  1998. {
  1999. ::AppendMenu(hMenu, MF_STRING | (CanZoomSelection() ? 0 : MF_GRAYED), ID_SAMPLE_ZOOMONSEL, ih->GetKeyTextFromCommand(kcSampleZoomSelection, _T("Zoom")));
  2000. ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_SETLOOP, _T("Set As Loop"));
  2001. if (sndFile.GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT))
  2002. ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_SETSUSTAINLOOP, _T("Set As Sustain Loop"));
  2003. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  2004. } else
  2005. {
  2006. SmpLength dwPos = ScreenToSample(pt.x);
  2007. CString pos = mpt::cfmt::dec(3, ',', dwPos);
  2008. if (dwPos <= sample.nLength)
  2009. {
  2010. //Set loop points
  2011. SmpLength loopEnd = (sample.nLoopEnd > 0) ? sample.nLoopEnd : sample.nLength;
  2012. wsprintf(s, _T("Set &Loop Start to:\t%s"), pos.GetString());
  2013. ::AppendMenu(hMenu, MF_STRING | (dwPos + 4 <= loopEnd ? 0 : MF_GRAYED),
  2014. ID_SAMPLE_SETLOOPSTART, s);
  2015. wsprintf(s, _T("Set &Loop End to:\t%s"), pos.GetString());
  2016. ::AppendMenu(hMenu, MF_STRING | (dwPos >= sample.nLoopStart + 4 ? 0 : MF_GRAYED),
  2017. ID_SAMPLE_SETLOOPEND, s);
  2018. if(sample.HasPingPongLoop())
  2019. ::AppendMenu(hMenu, MF_STRING, ID_CONVERT_PINGPONG_LOOP, ih->GetKeyTextFromCommand(kcSampleConvertPingPongLoop, _T("Convert to Unidirectional Loop")));
  2020. if (sndFile.GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT))
  2021. {
  2022. //Set sustain loop points
  2023. SmpLength sustainEnd = (sample.nSustainEnd > 0) ? sample.nSustainEnd : sample.nLength;
  2024. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  2025. wsprintf(s, _T("Set &Sustain Start to:\t%s"), pos.GetString());
  2026. ::AppendMenu(hMenu, MF_STRING | (dwPos + 4 <= sustainEnd ? 0 : MF_GRAYED),
  2027. ID_SAMPLE_SETSUSTAINSTART, s);
  2028. wsprintf(s, _T("Set &Sustain End to:\t%s"), pos.GetString());
  2029. ::AppendMenu(hMenu, MF_STRING | (dwPos >= sample.nSustainStart + 4 ? 0 : MF_GRAYED),
  2030. ID_SAMPLE_SETSUSTAINEND, s);
  2031. if(sample.HasPingPongSustainLoop())
  2032. ::AppendMenu(hMenu, MF_STRING, ID_CONVERT_PINGPONG_SUSTAIN, ih->GetKeyTextFromCommand(kcSampleConvertPingPongSustain, _T("Convert to Unidirectional Sustain Loop")));
  2033. }
  2034. //if(sndFile.GetModSpecifications().HasVolCommand(VOLCMD_OFFSET))
  2035. {
  2036. // Sample cues
  2037. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  2038. HMENU hCueMenu = ::CreatePopupMenu();
  2039. bool hasValidCues = false;
  2040. for(std::size_t i = 0; i < std::size(sample.cues); i++)
  2041. {
  2042. const SmpLength cue = sample.cues[i];
  2043. wsprintf(s, _T("Cue &%d: %s"), 1 + static_cast<int>(i),
  2044. cue < sample.nLength ? mpt::cfmt::dec(3, ',', cue).GetString() : _T("unused"));
  2045. ::AppendMenu(hCueMenu, MF_STRING, ID_SAMPLE_CUE_1 + i, s);
  2046. if(cue > 0 && cue < sample.nLength) hasValidCues = true;
  2047. }
  2048. wsprintf(s, _T("Set Sample Cu&e to:\t%s"), pos.GetString());
  2049. ::AppendMenu(hMenu, MF_POPUP, reinterpret_cast<UINT_PTR>(hCueMenu), s);
  2050. ::AppendMenu(hMenu, MF_STRING | (hasValidCues ? 0 : MF_GRAYED), ID_SAMPLE_SLICE, ih->GetKeyTextFromCommand(kcSampleSlice, _T("Slice at cue points")));
  2051. }
  2052. ::AppendMenu(hMenu, MF_SEPARATOR, 0, _T(""));
  2053. m_dwMenuParam = dwPos;
  2054. }
  2055. }
  2056. if(sample.GetElementarySampleSize() > 1) ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_8BITCONVERT, ih->GetKeyTextFromCommand(kcSample8Bit, _T("Convert to &8-bit")));
  2057. else ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_16BITCONVERT, ih->GetKeyTextFromCommand(kcSample8Bit, _T("Convert to &16-bit")));
  2058. if(sample.GetNumChannels() > 1)
  2059. {
  2060. HMENU hMonoMenu = ::CreatePopupMenu();
  2061. ::AppendMenu(hMonoMenu, MF_STRING, ID_SAMPLE_MONOCONVERT, ih->GetKeyTextFromCommand(kcSampleMonoMix, _T("&Mix Channels")));
  2062. ::AppendMenu(hMonoMenu, MF_STRING, ID_SAMPLE_MONOCONVERT_LEFT, ih->GetKeyTextFromCommand(kcSampleMonoLeft, _T("&Left Channel")));
  2063. ::AppendMenu(hMonoMenu, MF_STRING, ID_SAMPLE_MONOCONVERT_RIGHT, ih->GetKeyTextFromCommand(kcSampleMonoRight, _T("&Right Channel")));
  2064. ::AppendMenu(hMonoMenu, MF_STRING, ID_SAMPLE_MONOCONVERT_SPLIT, ih->GetKeyTextFromCommand(kcSampleMonoSplit, _T("&Split Sample")));
  2065. ::AppendMenu(hMenu, MF_POPUP, reinterpret_cast<UINT_PTR>(hMonoMenu), _T("Convert to &Mono"));
  2066. }
  2067. // "Trim" menu item is responding differently if there's no selection,
  2068. // but a loop present: "trim around loop point"! (jojo in topic 2258)
  2069. CString trimMenuText = _T("Tr&im");
  2070. bool isGrayed = ((m_dwEndSel <= m_dwBeginSel) || (m_dwEndSel - m_dwBeginSel < MIN_TRIM_LENGTH)
  2071. || (m_dwEndSel - m_dwBeginSel == sample.nLength));
  2072. if ((m_dwBeginSel == m_dwEndSel) && (sample.nLoopStart < sample.nLoopEnd))
  2073. {
  2074. // no selection => use loop points
  2075. trimMenuText += _T(" around loop points");
  2076. // Check whether trim menu item can be enabled (loop not too short or long for trimming).
  2077. if( (sample.nLoopEnd <= sample.nLength) &&
  2078. (sample.nLoopEnd - sample.nLoopStart >= MIN_TRIM_LENGTH) &&
  2079. (sample.nLoopEnd - sample.nLoopStart < sample.nLength) )
  2080. isGrayed = false;
  2081. }
  2082. ::AppendMenu(hMenu, MF_STRING | (isGrayed ? MF_GRAYED : 0), ID_SAMPLE_TRIM, ih->GetKeyTextFromCommand(kcSampleTrim, trimMenuText));
  2083. if((m_dwBeginSel == 0 && m_dwEndSel != 0) || (m_dwBeginSel < sample.nLength && m_dwEndSel == sample.nLength))
  2084. {
  2085. ::AppendMenu(hMenu, MF_STRING, ID_SAMPLE_QUICKFADE, ih->GetKeyTextFromCommand(kcSampleQuickFade, _T("Quick &Fade")));
  2086. }
  2087. ::AppendMenu(hMenu, MF_STRING, ID_EDIT_CUT, ih->GetKeyTextFromCommand(kcEditCut, _T("Cu&t")));
  2088. ::AppendMenu(hMenu, MF_STRING, ID_EDIT_COPY, ih->GetKeyTextFromCommand(kcEditCopy, _T("&Copy")));
  2089. }
  2090. const UINT clipboardFlag = (IsClipboardFormatAvailable(CF_WAVE) ? 0 : MF_GRAYED);
  2091. ::AppendMenu(hMenu, MF_STRING | clipboardFlag, ID_EDIT_PASTE, ih->GetKeyTextFromCommand(kcEditPaste, _T("&Paste (Replace)")));
  2092. ::AppendMenu(hMenu, MF_STRING | clipboardFlag, ID_EDIT_PUSHFORWARDPASTE, ih->GetKeyTextFromCommand(kcEditPushForwardPaste, _T("Paste (&Insert)")));
  2093. ::AppendMenu(hMenu, MF_STRING | clipboardFlag, ID_EDIT_MIXPASTE, ih->GetKeyTextFromCommand(kcEditMixPaste, _T("Mi&x Paste")));
  2094. ::AppendMenu(hMenu, MF_STRING | (pModDoc->GetSampleUndo().CanUndo(m_nSample) ? 0 : MF_GRAYED), ID_EDIT_UNDO, ih->GetKeyTextFromCommand(kcEditUndo, _T("&Undo ") + mpt::ToCString(pModDoc->GetSoundFile().GetCharsetInternal(), pModDoc->GetSampleUndo().GetUndoName(m_nSample))));
  2095. ::AppendMenu(hMenu, MF_STRING | (pModDoc->GetSampleUndo().CanRedo(m_nSample) ? 0 : MF_GRAYED), ID_EDIT_REDO, ih->GetKeyTextFromCommand(kcEditRedo, _T("&Redo ") + mpt::ToCString(pModDoc->GetSoundFile().GetCharsetInternal(), pModDoc->GetSampleUndo().GetRedoName(m_nSample))));
  2096. ClientToScreen(&pt);
  2097. ::TrackPopupMenu(hMenu, TPM_LEFTALIGN|TPM_RIGHTBUTTON, pt.x, pt.y, 0, m_hWnd, NULL);
  2098. ::DestroyMenu(hMenu);
  2099. }
  2100. }
  2101. void CViewSample::OnNcMouseMove(UINT nHitTest, CPoint point)
  2102. {
  2103. const auto button = GetNcButtonAtPoint(point);
  2104. if(button != m_nBtnMouseOver)
  2105. {
  2106. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  2107. if(pMainFrm)
  2108. {
  2109. CString strText;
  2110. if(button < SMP_LEFTBAR_BUTTONS && cLeftBarButtons[button] != ID_SEPARATOR)
  2111. {
  2112. strText = LoadResourceString(cLeftBarButtons[button]);
  2113. }
  2114. pMainFrm->SetHelpText(strText);
  2115. }
  2116. m_nBtnMouseOver = button;
  2117. UpdateNcButtonState();
  2118. }
  2119. CModScrollView::OnNcMouseMove(nHitTest, point);
  2120. }
  2121. void CViewSample::OnNcLButtonDown(UINT uFlags, CPoint point)
  2122. {
  2123. if (m_nBtnMouseOver < SMP_LEFTBAR_BUTTONS)
  2124. {
  2125. m_dwStatus.set(SMPSTATUS_NCLBTNDOWN);
  2126. if (cLeftBarButtons[m_nBtnMouseOver] != ID_SEPARATOR)
  2127. {
  2128. PostMessage(WM_COMMAND, cLeftBarButtons[m_nBtnMouseOver]);
  2129. UpdateNcButtonState();
  2130. }
  2131. }
  2132. CModScrollView::OnNcLButtonDown(uFlags, point);
  2133. }
  2134. void CViewSample::OnNcLButtonUp(UINT uFlags, CPoint point)
  2135. {
  2136. if(m_dwStatus[SMPSTATUS_NCLBTNDOWN])
  2137. {
  2138. m_dwStatus.reset(SMPSTATUS_NCLBTNDOWN);
  2139. UpdateNcButtonState();
  2140. }
  2141. CModScrollView::OnNcLButtonUp(uFlags, point);
  2142. }
  2143. void CViewSample::OnNcLButtonDblClk(UINT uFlags, CPoint point)
  2144. {
  2145. OnNcLButtonDown(uFlags, point);
  2146. }
  2147. LRESULT CViewSample::OnNcHitTest(CPoint point)
  2148. {
  2149. CRect rect;
  2150. GetWindowRect(&rect);
  2151. rect.bottom = rect.top + SMP_LEFTBAR_CY;
  2152. if (rect.PtInRect(point))
  2153. {
  2154. return HTBORDER;
  2155. }
  2156. return CModScrollView::OnNcHitTest(point);
  2157. }
  2158. void CViewSample::OnPrevInstrument()
  2159. {
  2160. SendCtrlMessage(CTRLMSG_SMP_PREVINSTRUMENT);
  2161. }
  2162. void CViewSample::OnNextInstrument()
  2163. {
  2164. SendCtrlMessage(CTRLMSG_SMP_NEXTINSTRUMENT);
  2165. }
  2166. void CViewSample::OnSetLoop()
  2167. {
  2168. CModDoc *pModDoc = GetDocument();
  2169. if (pModDoc)
  2170. {
  2171. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2172. ModSample &sample = sndFile.GetSample(m_nSample);
  2173. if ((m_dwEndSel > m_dwBeginSel + 15) && (m_dwEndSel <= sample.nLength))
  2174. {
  2175. if ((sample.nLoopStart != m_dwBeginSel) || (sample.nLoopEnd != m_dwEndSel))
  2176. {
  2177. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Loop");
  2178. sample.SetLoop(m_dwBeginSel, m_dwEndSel, true, sample.uFlags[CHN_PINGPONGLOOP], sndFile);
  2179. SetModified(SampleHint().Info(), true, false);
  2180. }
  2181. }
  2182. }
  2183. }
  2184. void CViewSample::OnSetSustainLoop()
  2185. {
  2186. CModDoc *pModDoc = GetDocument();
  2187. if (pModDoc)
  2188. {
  2189. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2190. ModSample &sample = sndFile.GetSample(m_nSample);
  2191. if ((m_dwEndSel > m_dwBeginSel + 15) && (m_dwEndSel <= sample.nLength))
  2192. {
  2193. if ((sample.nSustainStart != m_dwBeginSel) || (sample.nSustainEnd != m_dwEndSel))
  2194. {
  2195. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Sustain Loop");
  2196. sample.SetSustainLoop(m_dwBeginSel, m_dwEndSel, true, sample.uFlags[CHN_PINGPONGSUSTAIN], sndFile);
  2197. SetModified(SampleHint().Info(), true, false);
  2198. }
  2199. }
  2200. }
  2201. }
  2202. void CViewSample::OnEditSelectAll()
  2203. {
  2204. CModDoc *pModDoc = GetDocument();
  2205. if (pModDoc)
  2206. {
  2207. SmpLength len = pModDoc->GetSoundFile().GetSample(m_nSample).nLength;
  2208. if (len) SetCurSel(0, len);
  2209. }
  2210. }
  2211. void CViewSample::OnEditDelete()
  2212. {
  2213. CModDoc *pModDoc = GetDocument();
  2214. SampleHint updateHint;
  2215. updateHint.Info().Data();
  2216. if (!pModDoc) return;
  2217. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2218. ModSample &sample = sndFile.GetSample(m_nSample);
  2219. if (!sample.HasSampleData()) return;
  2220. if (m_dwEndSel > sample.nLength) m_dwEndSel = sample.nLength;
  2221. if ((m_dwBeginSel >= m_dwEndSel)
  2222. || (m_dwEndSel - m_dwBeginSel + 4 >= sample.nLength))
  2223. {
  2224. if (Reporting::Confirm("Remove this sample?", "Remove Sample", true) != cnfYes) return;
  2225. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Delete Sample");
  2226. sndFile.DestroySampleThreadsafe(m_nSample);
  2227. updateHint.Names();
  2228. } else
  2229. {
  2230. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_delete, "Delete Selection", m_dwBeginSel, m_dwEndSel);
  2231. CriticalSection cs;
  2232. SampleEdit::RemoveRange(sample, m_dwBeginSel, m_dwEndSel, sndFile);
  2233. }
  2234. SetCurSel(0, 0);
  2235. SetModified(updateHint, true, true);
  2236. }
  2237. void CViewSample::OnEditCut()
  2238. {
  2239. OnEditCopy();
  2240. OnEditDelete();
  2241. }
  2242. void CViewSample::OnEditCopy()
  2243. {
  2244. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  2245. if(pMainFrm == nullptr || GetDocument() == nullptr)
  2246. {
  2247. return;
  2248. }
  2249. const CSoundFile &sndFile = GetDocument()->GetSoundFile();
  2250. const ModSample &sample = sndFile.GetSample(m_nSample);
  2251. if(sample.uFlags[CHN_ADLIB])
  2252. {
  2253. // We cannot store an OPL patch in a Wave file...
  2254. Clipboard clipboard(CF_WAVE, sizeof(S3MSampleHeader));
  2255. if(clipboard.IsValid())
  2256. {
  2257. S3MSampleHeader sampleHeader;
  2258. MemsetZero(sampleHeader);
  2259. sampleHeader.ConvertToS3M(sample);
  2260. mpt::String::WriteBuf(mpt::String::nullTerminated, sampleHeader.name) = sndFile.m_szNames[m_nSample];
  2261. mpt::String::WriteBuf(mpt::String::maybeNullTerminated, sampleHeader.reserved2) = mpt::ToCharset(mpt::Charset::UTF8, Version::Current().GetOpenMPTVersionString());
  2262. clipboard = sampleHeader;
  2263. }
  2264. return;
  2265. }
  2266. bool addLoopInfo = true;
  2267. size_t smpSize = sample.nLength;
  2268. size_t smpOffset = 0;
  2269. // First things first: Calculate sample size, taking partial selections into account.
  2270. LimitMax(m_dwEndSel, sample.nLength);
  2271. if(m_dwEndSel > m_dwBeginSel)
  2272. {
  2273. smpSize = m_dwEndSel - m_dwBeginSel;
  2274. smpOffset = m_dwBeginSel;
  2275. addLoopInfo = false;
  2276. }
  2277. smpSize *= sample.GetBytesPerSample();
  2278. smpOffset *= sample.GetBytesPerSample();
  2279. // Ok, now calculate size of the resulting WAV file.
  2280. size_t memSize = sizeof(RIFFHeader) // RIFF Header
  2281. + sizeof(RIFFChunk) + sizeof(WAVFormatChunk) // Sample format
  2282. + sizeof(RIFFChunk) + ((smpSize + 1) & ~1) // Sample data
  2283. + sizeof(RIFFChunk) + sizeof(WAVExtraChunk) // Sample metadata
  2284. + MAX_SAMPLENAME + MAX_SAMPLEFILENAME; // Sample name
  2285. static_assert((sizeof(WAVExtraChunk) % 2u) == 0);
  2286. static_assert((MAX_SAMPLENAME % 2u) == 0);
  2287. static_assert((MAX_SAMPLEFILENAME % 2u) == 0);
  2288. if(addLoopInfo)
  2289. {
  2290. // We want to store some loop metadata as well.
  2291. memSize += sizeof(RIFFChunk) + sizeof(WAVSampleInfoChunk) + 2 * sizeof(WAVSampleLoop);
  2292. // ...and cue points, too.
  2293. memSize += sizeof(RIFFChunk) + sizeof(uint32) + std::size(sample.cues) * sizeof(WAVCuePoint);
  2294. }
  2295. ASSERT((memSize % 2u) == 0);
  2296. BeginWaitCursor();
  2297. Clipboard clipboard(CF_WAVE, memSize);
  2298. if(auto data = clipboard.Get(); data.data())
  2299. {
  2300. std::pair<mpt::byte_span, mpt::IO::Offset> mf(data, 0);
  2301. mpt::IO::OFile<std::pair<mpt::byte_span, mpt::IO::Offset>> ff(mf);
  2302. WAVWriter file(ff);
  2303. // Write sample format
  2304. file.WriteFormat(sample.GetSampleRate(sndFile.GetType()), sample.GetElementarySampleSize() * 8, sample.GetNumChannels(), WAVFormatChunk::fmtPCM);
  2305. // Write sample data
  2306. file.StartChunk(RIFFChunk::iddata);
  2307. uint8 *sampleData = mpt::byte_cast<uint8 *>(data.data()) + file.GetPosition();
  2308. memcpy(sampleData, sample.sampleb() + smpOffset, smpSize);
  2309. if(sample.GetElementarySampleSize() == 1)
  2310. {
  2311. // 8-Bit samples have to be unsigned.
  2312. for(size_t i = smpSize; i != 0; i--)
  2313. {
  2314. *(sampleData++) ^= 0x80u;
  2315. }
  2316. }
  2317. file.Skip(smpSize);
  2318. if(addLoopInfo)
  2319. {
  2320. file.WriteLoopInformation(sample);
  2321. file.WriteCueInformation(sample);
  2322. }
  2323. file.WriteExtraInformation(sample, sndFile.GetType(), sndFile.GetSampleName(m_nSample));
  2324. file.Finalize();
  2325. clipboard.Close();
  2326. }
  2327. EndWaitCursor();
  2328. }
  2329. void CViewSample::OnEditPaste()
  2330. {
  2331. DoPaste(PasteMode::Replace);
  2332. }
  2333. void CViewSample::OnEditMixPaste()
  2334. {
  2335. CMixSampleDlg::sampleOffset = m_dwMenuParam;
  2336. DoPaste(PasteMode::MixPaste);
  2337. }
  2338. void CViewSample::OnEditInsertPaste()
  2339. {
  2340. if(m_dwBeginSel <= m_dwEndSel)
  2341. m_dwBeginSel = m_dwEndSel = m_dwBeginDrag = m_dwEndDrag = m_dwMenuParam;
  2342. DoPaste(PasteMode::Insert);
  2343. }
  2344. template<typename Tdst, typename Tsrc>
  2345. static void MixSampleLoop(SmpLength numSamples, const Tsrc *src, uint8 srcInc, int srcFact, Tdst *dst, uint8 dstInc)
  2346. {
  2347. SC::Convert<Tdst, Tsrc> conv;
  2348. while(numSamples--)
  2349. {
  2350. *dst = mpt::saturate_cast<Tdst>(*dst + Util::muldivr(conv(*src), srcFact, 100));
  2351. src += srcInc;
  2352. dst += dstInc;
  2353. }
  2354. }
  2355. static void MixSampleOnto(const ModSample &sample, SmpLength offset, int amplify, uint8 chn, uint8 newNumChannels, int16 *pNewSample)
  2356. {
  2357. uint8 numChannels = sample.GetNumChannels();
  2358. switch(sample.GetElementarySampleSize())
  2359. {
  2360. case 1:
  2361. MixSampleLoop(sample.nLength, sample.sample8() + (chn % numChannels), numChannels, amplify, pNewSample + offset * newNumChannels + chn, newNumChannels);
  2362. break;
  2363. case 2:
  2364. MixSampleLoop(sample.nLength, sample.sample16() + (chn % numChannels), numChannels, amplify, pNewSample + offset * newNumChannels + chn, newNumChannels);
  2365. break;
  2366. default:
  2367. MPT_ASSERT_NOTREACHED();
  2368. }
  2369. }
  2370. void CViewSample::DoPaste(PasteMode pasteMode)
  2371. {
  2372. CModDoc *pModDoc = GetDocument();
  2373. BeginWaitCursor();
  2374. Clipboard clipboard(CF_WAVE);
  2375. if(auto data = clipboard.Get(); data.data())
  2376. {
  2377. SmpLength selBegin = 0, selEnd = 0;
  2378. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Paste");
  2379. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2380. ModSample &sample = sndFile.GetSample(m_nSample);
  2381. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB])
  2382. pasteMode = PasteMode::Replace;
  2383. // Show mix paste dialog
  2384. if(pasteMode == PasteMode::MixPaste)
  2385. {
  2386. CMixSampleDlg dlg(this);
  2387. if(dlg.DoModal() != IDOK)
  2388. {
  2389. EndWaitCursor();
  2390. return;
  2391. }
  2392. }
  2393. // Save old data for mixpaste
  2394. ModSample oldSample = sample;
  2395. std::string oldSampleName = sndFile.m_szNames[m_nSample];
  2396. if(pasteMode != PasteMode::Replace)
  2397. {
  2398. sample.pData.pSample = nullptr; // prevent old sample from being deleted.
  2399. }
  2400. FileReader file(data);
  2401. CriticalSection cs;
  2402. bool ok = sndFile.ReadSampleFromFile(m_nSample, file, TrackerSettings::Instance().m_MayNormalizeSamplesOnLoad);
  2403. clipboard.Close();
  2404. if(sample.uFlags[CHN_ADLIB] != oldSample.uFlags[CHN_ADLIB] && pasteMode != PasteMode::Replace)
  2405. {
  2406. // Cannot mix PCM with FM
  2407. pasteMode = PasteMode::Replace;
  2408. oldSample.FreeSample();
  2409. }
  2410. if (!sndFile.m_szNames[m_nSample][0] || pasteMode != PasteMode::Replace)
  2411. {
  2412. sndFile.m_szNames[m_nSample] = oldSampleName;
  2413. }
  2414. if (!sample.filename[0])
  2415. {
  2416. sample.filename = oldSample.filename;
  2417. }
  2418. if(pasteMode == PasteMode::MixPaste && ok)
  2419. {
  2420. // Mix new sample (stored in the actual sample slot) and old sample (stored in oldSample)
  2421. SmpLength newLength = std::max(oldSample.nLength, CMixSampleDlg::sampleOffset + sample.nLength);
  2422. const uint8 newNumChannels = std::max(oldSample.GetNumChannels(), sample.GetNumChannels());
  2423. // Result is at least 9 bits (when mixing two 8-bit samples), so always enforce 16-bit resolution
  2424. int16 *pNewSample = static_cast<int16 *>(ModSample::AllocateSample(newLength, 2u * newNumChannels));
  2425. if(pNewSample == nullptr)
  2426. {
  2427. ErrorBox(IDS_ERR_OUTOFMEMORY, this);
  2428. ok = false;
  2429. } else
  2430. {
  2431. selBegin = CMixSampleDlg::sampleOffset;
  2432. selEnd = selBegin + sample.nLength;
  2433. for(uint8 chn = 0; chn < newNumChannels; chn++)
  2434. {
  2435. MixSampleOnto(oldSample, 0, CMixSampleDlg::amplifyOriginal, chn, newNumChannels, pNewSample);
  2436. MixSampleOnto(sample, CMixSampleDlg::sampleOffset, CMixSampleDlg::amplifyMix, chn, newNumChannels, pNewSample);
  2437. }
  2438. sndFile.DestroySample(m_nSample);
  2439. sample = oldSample;
  2440. sample.uFlags.set(CHN_16BIT);
  2441. sample.uFlags.set(CHN_STEREO, newNumChannels == 2);
  2442. ctrlSmp::ReplaceSample(sample, pNewSample, newLength, sndFile);
  2443. }
  2444. } else if(pasteMode == PasteMode::Insert && ok)
  2445. {
  2446. // Insert / replace selection
  2447. SmpLength oldLength = oldSample.nLength;
  2448. SmpLength selLength = m_dwEndSel - m_dwBeginSel;
  2449. if(m_dwEndSel > m_dwBeginSel)
  2450. {
  2451. // Replace selection with pasted data
  2452. if(selLength >= sample.nLength)
  2453. ok = true;
  2454. else
  2455. ok = SampleEdit::InsertSilence(oldSample, sample.nLength - selLength, m_dwBeginSel, sndFile) > oldLength;
  2456. } else
  2457. {
  2458. m_dwBeginSel = m_dwBeginDrag;
  2459. ok = SampleEdit::InsertSilence(oldSample, sample.nLength, m_dwBeginSel, sndFile) > oldLength;
  2460. }
  2461. if(ok && sample.GetNumChannels() > oldSample.GetNumChannels())
  2462. {
  2463. // Keep channel configuration with higher channel count
  2464. ok = ctrlSmp::ConvertToStereo(oldSample, sndFile);
  2465. }
  2466. if(ok && sample.GetElementarySampleSize() > oldSample.GetElementarySampleSize())
  2467. {
  2468. // Keep higher bit depth of the two samples
  2469. ok = SampleEdit::ConvertTo16Bit(oldSample, sndFile);
  2470. }
  2471. if(ok)
  2472. {
  2473. selBegin = m_dwBeginSel;
  2474. selEnd = selBegin + sample.nLength;
  2475. uint8 numChannels = oldSample.GetNumChannels();
  2476. SmpLength offset = m_dwBeginSel * numChannels;
  2477. for(uint8 chn = 0; chn < numChannels; chn++)
  2478. {
  2479. uint8 newChn = chn % sample.GetNumChannels();
  2480. if(oldSample.GetElementarySampleSize() == 1 && sample.GetElementarySampleSize() == 1)
  2481. {
  2482. CopySample(oldSample.sample8() + offset + chn, sample.nLength, numChannels, sample.sample8() + newChn, sample.GetSampleSizeInBytes(), sample.GetNumChannels(), SC::ConversionChain<SC::Convert<int8, int8>, SC::DecodeIdentity<int8> >());
  2483. } else if(oldSample.GetElementarySampleSize() == 2 && sample.GetElementarySampleSize() == 1)
  2484. {
  2485. CopySample(oldSample.sample16() + offset + chn, sample.nLength, numChannels, sample.sample8() + newChn, sample.GetSampleSizeInBytes(), sample.GetNumChannels(), SC::ConversionChain<SC::Convert<int16, int8>, SC::DecodeIdentity<int8> >());
  2486. } else if(oldSample.GetElementarySampleSize() == 2 && sample.GetElementarySampleSize() == 2)
  2487. {
  2488. CopySample(oldSample.sample16() + offset + chn, sample.nLength, numChannels, sample.sample16() + newChn, sample.GetSampleSizeInBytes(), sample.GetNumChannels(), SC::ConversionChain<SC::Convert<int16, int16>, SC::DecodeIdentity<int16> >());
  2489. } else
  2490. {
  2491. MPT_ASSERT_NOTREACHED();
  2492. }
  2493. }
  2494. } else
  2495. {
  2496. ErrorBox(IDS_ERR_OUTOFMEMORY, this);
  2497. }
  2498. sndFile.DestroySample(m_nSample);
  2499. sample = oldSample;
  2500. }
  2501. if(ok)
  2502. {
  2503. SetCurSel(selBegin, selEnd);
  2504. sample.PrecomputeLoops(sndFile, true);
  2505. SetModified(SampleHint().Info().Data().Names(), true, false);
  2506. if(pasteMode == PasteMode::Replace)
  2507. sndFile.ResetSamplePath(m_nSample);
  2508. } else
  2509. {
  2510. if(pasteMode == PasteMode::MixPaste)
  2511. ModSample::FreeSample(oldSample.samplev());
  2512. pModDoc->GetSampleUndo().Undo(m_nSample);
  2513. sndFile.m_szNames[m_nSample] = oldSampleName;
  2514. }
  2515. }
  2516. EndWaitCursor();
  2517. }
  2518. void CViewSample::OnEditUndo()
  2519. {
  2520. CModDoc *pModDoc = GetDocument();
  2521. if(pModDoc == nullptr) return;
  2522. if(pModDoc->GetSampleUndo().Undo(m_nSample))
  2523. {
  2524. SetModified(SampleHint().Info().Data().Names(), true, false);
  2525. }
  2526. }
  2527. void CViewSample::OnEditRedo()
  2528. {
  2529. CModDoc *pModDoc = GetDocument();
  2530. if(pModDoc == nullptr) return;
  2531. if(pModDoc->GetSampleUndo().Redo(m_nSample))
  2532. {
  2533. SetModified(SampleHint().Info().Data().Names(), true, false);
  2534. }
  2535. }
  2536. void CViewSample::On8BitConvert()
  2537. {
  2538. CModDoc *pModDoc = GetDocument();
  2539. BeginWaitCursor();
  2540. if ((pModDoc) && (m_nSample <= pModDoc->GetNumSamples()))
  2541. {
  2542. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2543. ModSample &sample = sndFile.GetSample(m_nSample);
  2544. if(sample.uFlags[CHN_16BIT] && !sample.uFlags[CHN_ADLIB] && sample.HasSampleData())
  2545. {
  2546. ASSERT(sample.GetElementarySampleSize() == 2);
  2547. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "8-Bit Conversion");
  2548. CriticalSection cs;
  2549. SampleEdit::ConvertTo8Bit(sample, sndFile);
  2550. cs.Leave();
  2551. SetModified(SampleHint().Info().Data(), true, true);
  2552. }
  2553. }
  2554. EndWaitCursor();
  2555. }
  2556. void CViewSample::On16BitConvert()
  2557. {
  2558. CModDoc *pModDoc = GetDocument();
  2559. BeginWaitCursor();
  2560. if ((pModDoc) && (m_nSample <= pModDoc->GetNumSamples()))
  2561. {
  2562. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2563. ModSample &sample = sndFile.GetSample(m_nSample);
  2564. if(!sample.uFlags[CHN_16BIT] && !sample.uFlags[CHN_ADLIB] && sample.HasSampleData())
  2565. {
  2566. ASSERT(sample.GetElementarySampleSize() == 1);
  2567. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "16-Bit Conversion");
  2568. if(!SampleEdit::ConvertTo16Bit(sample, sndFile))
  2569. {
  2570. pModDoc->GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2571. } else
  2572. {
  2573. SetModified(SampleHint().Info().Data(), true, true);
  2574. }
  2575. }
  2576. }
  2577. EndWaitCursor();
  2578. }
  2579. void CViewSample::OnMonoConvert(ctrlSmp::StereoToMonoMode convert)
  2580. {
  2581. CModDoc *pModDoc = GetDocument();
  2582. BeginWaitCursor();
  2583. if(pModDoc != nullptr && (m_nSample <= pModDoc->GetNumSamples()))
  2584. {
  2585. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2586. ModSample &sample = sndFile.GetSample(m_nSample);
  2587. if(sample.GetNumChannels() > 1 && sample.HasSampleData() && !sample.uFlags[CHN_ADLIB])
  2588. {
  2589. SAMPLEINDEX rightSmp = SAMPLEINDEX_INVALID;
  2590. if(convert == ctrlSmp::splitSample)
  2591. {
  2592. // Split sample into two slots
  2593. rightSmp = pModDoc->InsertSample();
  2594. if(rightSmp == SAMPLEINDEX_INVALID)
  2595. return;
  2596. }
  2597. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Mono Conversion");
  2598. bool success = false;
  2599. if(convert == ctrlSmp::splitSample)
  2600. {
  2601. ModSample &right = sndFile.GetSample(rightSmp);
  2602. success = ctrlSmp::SplitStereo(sample, sample, right, sndFile);
  2603. // Try to create a new instrument as well which maps to the right sample.
  2604. if(success)
  2605. {
  2606. INSTRUMENTINDEX ins = pModDoc->FindSampleParent(m_nSample);
  2607. if(ins != INSTRUMENTINDEX_INVALID)
  2608. {
  2609. INSTRUMENTINDEX rightIns = pModDoc->InsertInstrument(0, ins);
  2610. if(rightIns != INSTRUMENTINDEX_INVALID)
  2611. {
  2612. for(auto &smp : sndFile.Instruments[rightIns]->Keyboard)
  2613. {
  2614. if(smp == m_nSample)
  2615. smp = rightSmp;
  2616. }
  2617. }
  2618. pModDoc->UpdateAllViews(this, InstrumentHint(rightIns).Info().Envelope().Names(), this);
  2619. }
  2620. // Finally, adjust sample panning
  2621. if(sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_XM))
  2622. {
  2623. sample.uFlags.set(CHN_PANNING);
  2624. sample.nPan = 0;
  2625. right.uFlags.set(CHN_PANNING);
  2626. right.nPan = 256;
  2627. }
  2628. pModDoc->UpdateAllViews(this, SampleHint(rightSmp).Info().Data().Names(), this);
  2629. }
  2630. } else
  2631. {
  2632. success = ctrlSmp::ConvertToMono(sample, sndFile, convert);
  2633. }
  2634. if(success)
  2635. SetModified(SampleHint().Info().Data().Names(), true, true);
  2636. else
  2637. pModDoc->GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2638. }
  2639. }
  2640. EndWaitCursor();
  2641. }
  2642. void CViewSample::TrimSample(bool trimToLoopEnd)
  2643. {
  2644. CModDoc *pModDoc = GetDocument();
  2645. //nothing loaded or invalid sample slot.
  2646. if(!pModDoc || m_nSample > pModDoc->GetNumSamples() || IsOPLInstrument()) return;
  2647. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2648. ModSample &sample = sndFile.GetSample(m_nSample);
  2649. if(trimToLoopEnd)
  2650. {
  2651. m_dwBeginSel = 0;
  2652. m_dwEndSel = sample.nLoopEnd;
  2653. } else if(m_dwBeginSel == m_dwEndSel)
  2654. {
  2655. // Trim around loop points if there's no selection
  2656. m_dwBeginSel = sample.nLoopStart;
  2657. m_dwEndSel = sample.nLoopEnd;
  2658. }
  2659. if (m_dwBeginSel >= m_dwEndSel) return; // invalid selection
  2660. BeginWaitCursor();
  2661. SmpLength nStart = m_dwBeginSel;
  2662. SmpLength nEnd = m_dwEndSel - m_dwBeginSel;
  2663. if(sample.HasSampleData() && (nStart + nEnd <= sample.nLength) && (nEnd >= MIN_TRIM_LENGTH))
  2664. {
  2665. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Trim");
  2666. CriticalSection cs;
  2667. // Note: Sample is overwritten in-place! Unused data is not deallocated!
  2668. memmove(sample.sampleb(), sample.sampleb() + nStart * sample.GetBytesPerSample(), nEnd * sample.GetBytesPerSample());
  2669. for(SmpLength &point : SampleEdit::GetCuesAndLoops(sample))
  2670. {
  2671. if(point >= nStart)
  2672. point -= nStart;
  2673. else
  2674. point = sample.nLength;
  2675. }
  2676. sample.nLength = nEnd;
  2677. sample.PrecomputeLoops(sndFile);
  2678. cs.Leave();
  2679. SetCurSel(0, 0);
  2680. SetModified(SampleHint().Info().Data(), true, true);
  2681. }
  2682. EndWaitCursor();
  2683. }
  2684. void CViewSample::OnChar(UINT /*nChar*/, UINT, UINT /*nFlags*/)
  2685. {
  2686. }
  2687. void CViewSample::PlayNote(ModCommand::NOTE note, const SmpLength nStartPos, int volume)
  2688. {
  2689. CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
  2690. CModDoc *pModDoc = GetDocument();
  2691. if ((pModDoc) && (pMainFrm))
  2692. {
  2693. if (note >= NOTE_MIN_SPECIAL)
  2694. {
  2695. pModDoc->NoteOff(0, (note == NOTE_NOTECUT));
  2696. } else
  2697. {
  2698. if(m_dwStatus[SMPSTATUS_KEYDOWN])
  2699. pModDoc->NoteOff(note, true, m_noteChannel[note - NOTE_MIN]);
  2700. else
  2701. pModDoc->NoteOff(0, true);
  2702. const CSoundFile &sndFile = pModDoc->GetSoundFile();
  2703. const ModSample &sample = sndFile.GetSample(m_nSample);
  2704. SmpLength loopstart = m_dwBeginSel, loopend = m_dwEndSel;
  2705. // If selection is too small -> no loop
  2706. if((m_nZoom >= 0 && loopend - loopstart < (SmpLength)(4 << m_nZoom))
  2707. || (m_nZoom < 0 && loopend - loopstart < 4)
  2708. || (loopstart >= sample.nLength))
  2709. {
  2710. loopend = loopstart = 0;
  2711. }
  2712. pModDoc->PlayNote(PlayNoteParam(note).Sample(m_nSample).Volume(volume).LoopStart(loopstart).LoopEnd(loopend).Offset(nStartPos), &m_noteChannel);
  2713. m_dwStatus.set(SMPSTATUS_KEYDOWN);
  2714. uint32 freq = sndFile.GetFreqFromPeriod(sndFile.GetPeriodFromNote(note + (sndFile.GetType() == MOD_TYPE_XM ? sample.RelativeTone : 0), sample.nFineTune, sample.nC5Speed), sample.nC5Speed, 0);
  2715. pMainFrm->SetInfoText(MPT_CFORMAT("{} ({}.{} Hz)")(
  2716. mpt::ToCString(sndFile.GetNoteName((ModCommand::NOTE)note)),
  2717. freq >> FREQ_FRACBITS,
  2718. mpt::cfmt::dec0<2>(Util::muldiv(freq & ((1 << FREQ_FRACBITS) - 1), 100, 1 << FREQ_FRACBITS))));
  2719. }
  2720. }
  2721. }
  2722. void CViewSample::NoteOff(ModCommand::NOTE note)
  2723. {
  2724. CSoundFile &sndFile = GetDocument()->GetSoundFile();
  2725. ModChannel &chn = sndFile.m_PlayState.Chn[m_noteChannel[note - NOTE_MIN]];
  2726. sndFile.KeyOff(chn);
  2727. chn.dwFlags.set(CHN_NOTEFADE);
  2728. m_noteChannel[note - NOTE_MIN] = CHANNELINDEX_INVALID;
  2729. }
  2730. // Drop files from Windows
  2731. void CViewSample::OnDropFiles(HDROP hDropInfo)
  2732. {
  2733. const UINT nFiles = ::DragQueryFile(hDropInfo, (UINT)-1, NULL, 0);
  2734. CMainFrame::GetMainFrame()->SetForegroundWindow();
  2735. for(UINT f = 0; f < nFiles; f++)
  2736. {
  2737. UINT size = ::DragQueryFile(hDropInfo, f, nullptr, 0) + 1;
  2738. std::vector<TCHAR> fileName(size, _T('\0'));
  2739. if(::DragQueryFile(hDropInfo, f, fileName.data(), size))
  2740. {
  2741. const mpt::PathString file = mpt::PathString::FromNative(fileName.data());
  2742. if(SendCtrlMessage(CTRLMSG_SMP_OPENFILE, (LPARAM)&file) && f < nFiles - 1)
  2743. {
  2744. // Insert more sample slots
  2745. if(!SendCtrlMessage(CTRLMSG_SMP_NEWSAMPLE))
  2746. break;
  2747. }
  2748. }
  2749. }
  2750. ::DragFinish(hDropInfo);
  2751. }
  2752. BOOL CViewSample::OnDragonDrop(BOOL doDrop, const DRAGONDROP *dropInfo)
  2753. {
  2754. CModDoc *modDoc = GetDocument();
  2755. bool canDrop = false;
  2756. if ((!dropInfo) || (!modDoc)) return FALSE;
  2757. CSoundFile &sndFile = modDoc->GetSoundFile();
  2758. switch(dropInfo->dropType)
  2759. {
  2760. case DRAGONDROP_SAMPLE:
  2761. if (dropInfo->sndFile == &sndFile)
  2762. {
  2763. canDrop = ((dropInfo->dropItem)
  2764. && (dropInfo->dropItem <= sndFile.GetNumSamples()));
  2765. } else
  2766. {
  2767. canDrop = ((dropInfo->dropItem)
  2768. && ((dropInfo->dropParam) || (dropInfo->sndFile)));
  2769. }
  2770. break;
  2771. case DRAGONDROP_DLS:
  2772. canDrop = ((dropInfo->dropItem < CTrackApp::gpDLSBanks.size())
  2773. && (CTrackApp::gpDLSBanks[dropInfo->dropItem]));
  2774. break;
  2775. case DRAGONDROP_SOUNDFILE:
  2776. case DRAGONDROP_MIDIINSTR:
  2777. canDrop = !dropInfo->GetPath().empty();
  2778. break;
  2779. }
  2780. const bool insertNew = CMainFrame::GetInputHandler()->ShiftPressed();
  2781. if(insertNew && !sndFile.CanAddMoreSamples())
  2782. canDrop = false;
  2783. if(!canDrop || !doDrop)
  2784. return canDrop;
  2785. // Do the drop
  2786. BeginWaitCursor();
  2787. bool modified = false;
  2788. switch(dropInfo->dropType)
  2789. {
  2790. case DRAGONDROP_SAMPLE:
  2791. if(dropInfo->sndFile == &sndFile)
  2792. {
  2793. SendCtrlMessage(CTRLMSG_SETCURRENTINSTRUMENT, dropInfo->dropItem);
  2794. } else
  2795. {
  2796. if(insertNew && !SendCtrlMessage(CTRLMSG_SMP_NEWSAMPLE))
  2797. canDrop = false;
  2798. else
  2799. SendCtrlMessage(CTRLMSG_SMP_SONGDROP, (LPARAM)dropInfo);
  2800. }
  2801. break;
  2802. case DRAGONDROP_MIDIINSTR:
  2803. if (CDLSBank::IsDLSBank(dropInfo->GetPath()))
  2804. {
  2805. CDLSBank dlsbank;
  2806. if (dlsbank.Open(dropInfo->GetPath()))
  2807. {
  2808. const DLSINSTRUMENT *pDlsIns;
  2809. UINT nIns = 0, nRgn = 0xFF;
  2810. int transpose = 0;
  2811. // Drums
  2812. if (dropInfo->dropItem & 0x80)
  2813. {
  2814. UINT key = dropInfo->dropItem & 0x7F;
  2815. pDlsIns = dlsbank.FindInstrument(TRUE, 0xFFFF, 0xFF, key, &nIns);
  2816. if(pDlsIns)
  2817. {
  2818. nRgn = dlsbank.GetRegionFromKey(nIns, key);
  2819. const auto &region = pDlsIns->Regions[nRgn];
  2820. if(region.tuning != 0)
  2821. transpose = (region.uKeyMin + (region.uKeyMax - region.uKeyMin) / 2) - 60;
  2822. }
  2823. } else
  2824. // Melodic
  2825. {
  2826. pDlsIns = dlsbank.FindInstrument(FALSE, 0xFFFF, dropInfo->dropItem, 60, &nIns);
  2827. if (pDlsIns) nRgn = dlsbank.GetRegionFromKey(nIns, 60);
  2828. }
  2829. canDrop = FALSE;
  2830. if (pDlsIns)
  2831. {
  2832. if(!insertNew || SendCtrlMessage(CTRLMSG_SMP_NEWSAMPLE))
  2833. {
  2834. CriticalSection cs;
  2835. modDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Replace");
  2836. canDrop = modified = dlsbank.ExtractSample(sndFile, m_nSample, nIns, nRgn, transpose);
  2837. }
  2838. }
  2839. break;
  2840. }
  2841. }
  2842. [[fallthrough]];
  2843. case DRAGONDROP_SOUNDFILE:
  2844. if(!insertNew || SendCtrlMessage(CTRLMSG_SMP_NEWSAMPLE))
  2845. SendCtrlMessage(CTRLMSG_SMP_OPENFILE, dropInfo->dropParam);
  2846. break;
  2847. case DRAGONDROP_DLS:
  2848. {
  2849. const CDLSBank dlsBank = *CTrackApp::gpDLSBanks[dropInfo->dropItem];
  2850. UINT nIns = dropInfo->dropParam & 0xFFFF;
  2851. UINT nRgn;
  2852. int transpose = 0;
  2853. // Drums: (0x80000000) | (Region << 16) | (Instrument)
  2854. if (dropInfo->dropParam & 0x80000000)
  2855. {
  2856. nRgn = (dropInfo->dropParam & 0x7FFF0000) >> 16;
  2857. const auto &region = dlsBank.GetInstrument(nIns)->Regions[nRgn];
  2858. if(region.tuning != 0)
  2859. transpose = (region.uKeyMin + (region.uKeyMax - region.uKeyMin) / 2) - 60;
  2860. } else
  2861. // Melodic: (Instrument)
  2862. {
  2863. nRgn = dlsBank.GetRegionFromKey(nIns, 60);
  2864. }
  2865. if(!insertNew || SendCtrlMessage(CTRLMSG_SMP_NEWSAMPLE))
  2866. {
  2867. CriticalSection cs;
  2868. modDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Replace");
  2869. canDrop = modified = dlsBank.ExtractSample(sndFile, m_nSample, nIns, nRgn, transpose);
  2870. }
  2871. }
  2872. break;
  2873. }
  2874. if(modified)
  2875. {
  2876. SetModified(SampleHint().Info().Data().Names(), true, false);
  2877. }
  2878. CMDIChildWnd *pMDIFrame = (CMDIChildWnd *)GetParentFrame();
  2879. if (pMDIFrame)
  2880. {
  2881. pMDIFrame->MDIActivate();
  2882. pMDIFrame->SetActiveView(this);
  2883. SetFocus();
  2884. }
  2885. EndWaitCursor();
  2886. return canDrop;
  2887. }
  2888. void CViewSample::OnZoomOnSel()
  2889. {
  2890. int zoom = 0;
  2891. SmpLength selLength = (m_dwEndSel - m_dwBeginSel);
  2892. if (selLength > 0 && m_rcClient.right > 0)
  2893. {
  2894. zoom = GetZoomLevel(selLength);
  2895. if(zoom < 0)
  2896. {
  2897. zoom++;
  2898. if(zoom >= -1)
  2899. zoom = 1;
  2900. else if(zoom < MIN_ZOOM)
  2901. zoom = MIN_ZOOM;
  2902. } else if(zoom > MAX_ZOOM)
  2903. {
  2904. zoom = 0;
  2905. }
  2906. }
  2907. if(zoom)
  2908. {
  2909. SetZoom(zoom, m_dwBeginSel + selLength / 2);
  2910. }
  2911. SendCtrlMessage(CTRLMSG_SMP_SETZOOM, zoom);
  2912. }
  2913. SmpLength CViewSample::ScrollPosToSamplePos(int nZoom) const
  2914. {
  2915. if(nZoom < 0)
  2916. return m_nScrollPosX;
  2917. else if(nZoom > 0)
  2918. return m_nScrollPosX << (nZoom - 1);
  2919. else
  2920. return 0;
  2921. }
  2922. void CViewSample::OnSetLoopStart()
  2923. {
  2924. CModDoc *pModDoc = GetDocument();
  2925. if (pModDoc)
  2926. {
  2927. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2928. ModSample &sample = sndFile.GetSample(m_nSample);
  2929. SmpLength loopEnd = (sample.nLoopEnd > 0) ? sample.nLoopEnd : sample.nLength;
  2930. if ((m_dwMenuParam + 4 <= loopEnd) && (sample.nLoopStart != m_dwMenuParam))
  2931. {
  2932. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Loop Start");
  2933. sample.SetLoop(m_dwMenuParam, loopEnd, true, sample.uFlags[CHN_PINGPONGLOOP], sndFile);
  2934. SetModified(SampleHint().Info(), true, false);
  2935. }
  2936. }
  2937. }
  2938. void CViewSample::OnSetLoopEnd()
  2939. {
  2940. CModDoc *pModDoc = GetDocument();
  2941. if (pModDoc)
  2942. {
  2943. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2944. ModSample &sample = sndFile.GetSample(m_nSample);
  2945. if ((m_dwMenuParam >= sample.nLoopStart + 4) && (sample.nLoopEnd != m_dwMenuParam))
  2946. {
  2947. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Loop End");
  2948. sample.SetLoop(sample.nLoopStart, m_dwMenuParam, true, sample.uFlags[CHN_PINGPONGLOOP], sndFile);
  2949. SetModified(SampleHint().Info(), true, false);
  2950. }
  2951. }
  2952. }
  2953. void CViewSample::OnConvertPingPongLoop()
  2954. {
  2955. CModDoc *pModDoc = GetDocument();
  2956. if(pModDoc)
  2957. {
  2958. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2959. ModSample &sample = sndFile.GetSample(m_nSample);
  2960. if(!sample.HasPingPongLoop())
  2961. return;
  2962. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Convert Bidi Loop");
  2963. if(SampleEdit::ConvertPingPongLoop(sample, sndFile, false))
  2964. SetModified(SampleHint().Info().Data(), true, true);
  2965. else
  2966. pModDoc->GetSampleUndo().RemoveLastUndoStep(m_nSample);
  2967. }
  2968. }
  2969. void CViewSample::OnSetSustainStart()
  2970. {
  2971. CModDoc *pModDoc = GetDocument();
  2972. if (pModDoc)
  2973. {
  2974. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2975. ModSample &sample = sndFile.GetSample(m_nSample);
  2976. SmpLength sustainEnd = (sample.nSustainEnd > 0) ? sample.nSustainEnd : sample.nLength;
  2977. if ((m_dwMenuParam + 4 <= sustainEnd) && (sample.nSustainStart != m_dwMenuParam))
  2978. {
  2979. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Sustain Start");
  2980. sample.SetSustainLoop(m_dwMenuParam, sustainEnd, true, sample.uFlags[CHN_PINGPONGSUSTAIN], sndFile);
  2981. SetModified(SampleHint().Info(), true, false);
  2982. }
  2983. }
  2984. }
  2985. void CViewSample::OnSetSustainEnd()
  2986. {
  2987. CModDoc *pModDoc = GetDocument();
  2988. if (pModDoc)
  2989. {
  2990. CSoundFile &sndFile = pModDoc->GetSoundFile();
  2991. ModSample &sample = sndFile.GetSample(m_nSample);
  2992. if ((m_dwMenuParam >= sample.nSustainStart + 4) && (sample.nSustainEnd != m_dwMenuParam))
  2993. {
  2994. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Sustain End");
  2995. sample.SetSustainLoop(sample.nSustainStart, m_dwMenuParam, true, sample.uFlags[CHN_PINGPONGSUSTAIN], sndFile);
  2996. SetModified(SampleHint().Info(), true, false);
  2997. }
  2998. }
  2999. }
  3000. void CViewSample::OnConvertPingPongSustain()
  3001. {
  3002. CModDoc *pModDoc = GetDocument();
  3003. if(pModDoc)
  3004. {
  3005. CSoundFile &sndFile = pModDoc->GetSoundFile();
  3006. ModSample &sample = sndFile.GetSample(m_nSample);
  3007. if(!sample.HasPingPongSustainLoop())
  3008. return;
  3009. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Convert Bidi Sustain Loop");
  3010. if(SampleEdit::ConvertPingPongLoop(sample, sndFile, true))
  3011. SetModified(SampleHint().Info().Data(), true, true);
  3012. else
  3013. pModDoc->GetSampleUndo().RemoveLastUndoStep(m_nSample);
  3014. }
  3015. }
  3016. void CViewSample::OnSetCuePoint(UINT nID)
  3017. {
  3018. nID -= ID_SAMPLE_CUE_1;
  3019. CModDoc *pModDoc = GetDocument();
  3020. if (pModDoc)
  3021. {
  3022. CSoundFile &sndFile = pModDoc->GetSoundFile();
  3023. ModSample &sample = sndFile.GetSample(m_nSample);
  3024. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Set Cue Point");
  3025. sample.cues[nID] = m_dwMenuParam;
  3026. SetModified(SampleHint().Info(), true, false);
  3027. }
  3028. }
  3029. void CViewSample::OnZoomUp()
  3030. {
  3031. DoZoom(1);
  3032. }
  3033. void CViewSample::OnZoomDown()
  3034. {
  3035. DoZoom(-1);
  3036. }
  3037. void CViewSample::OnDrawingToggle()
  3038. {
  3039. const CModDoc *pModDoc = GetDocument();
  3040. if(!pModDoc) return;
  3041. const CSoundFile &sndFile = pModDoc->GetSoundFile();
  3042. const ModSample &sample = sndFile.GetSample(m_nSample);
  3043. if(!sample.HasSampleData())
  3044. {
  3045. OnAddSilence();
  3046. if(!sample.HasSampleData())
  3047. {
  3048. return;
  3049. }
  3050. }
  3051. m_dwStatus.flip(SMPSTATUS_DRAWING);
  3052. UpdateNcButtonState();
  3053. }
  3054. void CViewSample::OnAddSilence()
  3055. {
  3056. CModDoc *pModDoc = GetDocument();
  3057. if (!pModDoc) return;
  3058. CSoundFile &sndFile = pModDoc->GetSoundFile();
  3059. ModSample &sample = sndFile.GetSample(m_nSample);
  3060. const SmpLength oldLength = IsOPLInstrument() ? 0 : sample.nLength;
  3061. AddSilenceDlg dlg(this, oldLength, sample.GetSampleRate(sndFile.GetType()), sndFile.SupportsOPL());
  3062. if (dlg.DoModal() != IDOK) return;
  3063. if(dlg.m_editOption == AddSilenceDlg::kOPLInstrument)
  3064. {
  3065. SendCtrlMessage(CTRLMSG_SMP_INITOPL);
  3066. return;
  3067. }
  3068. if(MAX_SAMPLE_LENGTH - oldLength < dlg.m_numSamples && dlg.m_editOption != AddSilenceDlg::kResize)
  3069. {
  3070. CString str; str.Format(_T("Cannot add silence because the new sample length would exceed maximum sample length %u."), MAX_SAMPLE_LENGTH);
  3071. Reporting::Information(str);
  3072. return;
  3073. }
  3074. BeginWaitCursor();
  3075. if(sample.nLength == 0 && sample.nVolume == 0)
  3076. {
  3077. sample.nVolume = 256;
  3078. }
  3079. if(dlg.m_editOption == AddSilenceDlg::kResize)
  3080. {
  3081. // resize - dlg.m_nSamples = new size
  3082. if(dlg.m_numSamples == 0)
  3083. {
  3084. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_replace, "Delete Sample");
  3085. sndFile.DestroySampleThreadsafe(m_nSample);
  3086. } else if(dlg.m_numSamples != sample.nLength)
  3087. {
  3088. CriticalSection cs;
  3089. if(dlg.m_numSamples < sample.nLength) // make it shorter!
  3090. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_delete, "Resize", dlg.m_numSamples, sample.nLength);
  3091. else // make it longer!
  3092. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_insert, "Add Silence", sample.nLength, dlg.m_numSamples);
  3093. sample.SetAdlib(false);
  3094. SampleEdit::ResizeSample(sample, dlg.m_numSamples, sndFile);
  3095. }
  3096. } else
  3097. {
  3098. // add silence - dlg.m_nSamples = amount of bytes to be added
  3099. if(dlg.m_numSamples > 0)
  3100. {
  3101. CriticalSection cs;
  3102. SmpLength nStart = (dlg.m_editOption == AddSilenceDlg::kSilenceAtEnd) ? sample.nLength : 0;
  3103. pModDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_insert, "Add Silence", nStart, nStart + dlg.m_numSamples);
  3104. sample.SetAdlib(false);
  3105. SampleEdit::InsertSilence(sample, dlg.m_numSamples, nStart, sndFile);
  3106. }
  3107. }
  3108. EndWaitCursor();
  3109. if(oldLength != sample.nLength)
  3110. {
  3111. SetCurSel(0, 0);
  3112. SetModified(SampleHint().Info().Data().Names(), true, true);
  3113. }
  3114. }
  3115. LRESULT CViewSample::OnMidiMsg(WPARAM midiDataParam, LPARAM)
  3116. {
  3117. const uint32 midiData = static_cast<uint32>(midiDataParam);
  3118. static uint8 midiVolume = 127;
  3119. CModDoc *pModDoc = GetDocument();
  3120. const uint8 midiByte1 = MIDIEvents::GetDataByte1FromEvent(midiData);
  3121. const uint8 midiByte2 = MIDIEvents::GetDataByte2FromEvent(midiData);
  3122. const uint8 channel = MIDIEvents::GetChannelFromEvent(midiData);
  3123. CSoundFile *pSndFile = (pModDoc) ? &pModDoc->GetSoundFile() : nullptr;
  3124. if (!pSndFile) return 0;
  3125. uint8 nNote = midiByte1 + NOTE_MIN;
  3126. int nVol = midiByte2;
  3127. MIDIEvents::EventType event = MIDIEvents::GetTypeFromEvent(midiData);
  3128. if(event == MIDIEvents::evNoteOn && !nVol)
  3129. event = MIDIEvents::evNoteOff; //Convert event to note-off if req'd
  3130. // Handle MIDI messages assigned to shortcuts
  3131. CInputHandler *ih = CMainFrame::GetInputHandler();
  3132. if(ih->HandleMIDIMessage(kCtxViewSamples, midiData) != kcNull
  3133. || ih->HandleMIDIMessage(kCtxAllContexts, midiData) != kcNull)
  3134. {
  3135. // Mapped to a command, no need to pass message on.
  3136. return 1;
  3137. }
  3138. switch(event)
  3139. {
  3140. case MIDIEvents::evNoteOff: // Note Off
  3141. if(m_midiSustainActive[channel])
  3142. {
  3143. m_midiSustainBuffer[channel].push_back(midiData);
  3144. return 1;
  3145. }
  3146. [[fallthrough]];
  3147. case MIDIEvents::evNoteOn: // Note On
  3148. LimitMax(nNote, NOTE_MAX);
  3149. pModDoc->NoteOff(nNote, true);
  3150. if(event != MIDIEvents::evNoteOff)
  3151. {
  3152. nVol = CMainFrame::ApplyVolumeRelatedSettings(midiData, midiVolume);
  3153. PlayNote(nNote, 0, nVol);
  3154. }
  3155. break;
  3156. case MIDIEvents::evControllerChange: //Controller change
  3157. switch(midiByte1)
  3158. {
  3159. case MIDIEvents::MIDICC_Volume_Coarse: //Volume
  3160. midiVolume = midiByte2;
  3161. break;
  3162. case MIDIEvents::MIDICC_HoldPedal_OnOff:
  3163. m_midiSustainActive[channel] = (midiByte2 >= 0x40);
  3164. if(!m_midiSustainActive[channel])
  3165. {
  3166. // Release all notes
  3167. for(const auto offEvent : m_midiSustainBuffer[channel])
  3168. {
  3169. OnMidiMsg(offEvent, 0);
  3170. }
  3171. m_midiSustainBuffer[channel].clear();
  3172. }
  3173. break;
  3174. }
  3175. }
  3176. return 1;
  3177. }
  3178. BOOL CViewSample::PreTranslateMessage(MSG *pMsg)
  3179. {
  3180. if (pMsg)
  3181. {
  3182. //We handle keypresses before Windows has a chance to handle them (for alt etc..)
  3183. if ((pMsg->message == WM_SYSKEYUP) || (pMsg->message == WM_KEYUP) ||
  3184. (pMsg->message == WM_SYSKEYDOWN) || (pMsg->message == WM_KEYDOWN))
  3185. {
  3186. CInputHandler* ih = CMainFrame::GetInputHandler();
  3187. //Translate message manually
  3188. UINT nChar = static_cast<UINT>(pMsg->wParam);
  3189. UINT nRepCnt = LOWORD(pMsg->lParam);
  3190. UINT nFlags = HIWORD(pMsg->lParam);
  3191. KeyEventType kT = ih->GetKeyEventType(nFlags);
  3192. InputTargetContext ctx = (InputTargetContext)(kCtxViewSamples);
  3193. if (ih->KeyEvent(ctx, nChar, nRepCnt, nFlags, kT) != kcNull)
  3194. return true; // Mapped to a command, no need to pass message on.
  3195. // Handle Application (menu) key
  3196. if(pMsg->message == WM_KEYDOWN && nChar == VK_APPS)
  3197. {
  3198. int x = Util::ScalePixels(32, m_hWnd);
  3199. OnRButtonDown(0, CPoint(x, x));
  3200. }
  3201. }
  3202. }
  3203. return CModScrollView::PreTranslateMessage(pMsg);
  3204. }
  3205. LRESULT CViewSample::OnCustomKeyMsg(WPARAM wParam, LPARAM lParam)
  3206. {
  3207. CModDoc *pModDoc = GetDocument();
  3208. if(!pModDoc)
  3209. return kcNull;
  3210. CSoundFile &sndFile = pModDoc->GetSoundFile();
  3211. switch(wParam)
  3212. {
  3213. case kcSampleTrim: TrimSample(false); return wParam;
  3214. case kcSampleTrimToLoopEnd: TrimSample(true); return wParam;
  3215. case kcSampleZoomUp: OnZoomUp(); return wParam;
  3216. case kcSampleZoomDown: OnZoomDown(); return wParam;
  3217. case kcSampleZoomSelection: OnZoomOnSel(); return wParam;
  3218. case kcSampleCenterSampleStart:
  3219. case kcSampleCenterSampleEnd:
  3220. case kcSampleCenterLoopStart:
  3221. case kcSampleCenterLoopEnd:
  3222. case kcSampleCenterSustainStart:
  3223. case kcSampleCenterSustainEnd:
  3224. {
  3225. SmpLength point = 0;
  3226. ModSample &sample = sndFile.GetSample(m_nSample);
  3227. switch(wParam)
  3228. {
  3229. case kcSampleCenterSampleStart: point = 0; break;
  3230. case kcSampleCenterSampleEnd: point = sample.nLength; break;
  3231. case kcSampleCenterLoopStart: point = sample.nLoopStart; break;
  3232. case kcSampleCenterLoopEnd: point = sample.nLoopEnd; break;
  3233. case kcSampleCenterSustainStart: point = sample.nSustainStart; break;
  3234. case kcSampleCenterSustainEnd: point = sample.nSustainEnd; break;
  3235. }
  3236. if(!m_nZoom)
  3237. SendCtrlMessage(CTRLMSG_SMP_SETZOOM, 1);
  3238. ScrollToSample(point);
  3239. }
  3240. return wParam;
  3241. case kcPrevInstrument: OnPrevInstrument(); return wParam;
  3242. case kcNextInstrument: OnNextInstrument(); return wParam;
  3243. case kcEditSelectAll: OnEditSelectAll(); return wParam;
  3244. case kcSampleDelete: OnEditDelete(); return wParam;
  3245. case kcEditCut: OnEditCut(); return wParam;
  3246. case kcEditCopy: OnEditCopy(); return wParam;
  3247. case kcEditPaste: OnEditPaste(); return wParam;
  3248. case kcEditMixPasteITStyle:
  3249. case kcEditMixPaste: DoPaste(PasteMode::MixPaste); return wParam;
  3250. case kcEditPushForwardPaste: DoPaste(PasteMode::Insert); return wParam;
  3251. case kcEditUndo: OnEditUndo(); return wParam;
  3252. case kcEditRedo: OnEditRedo(); return wParam;
  3253. case kcSampleConvertPingPongLoop: OnConvertPingPongLoop(); return wParam;
  3254. case kcSampleConvertPingPongSustain: OnConvertPingPongSustain(); return wParam;
  3255. case kcSample8Bit: if(sndFile.GetSample(m_nSample).uFlags[CHN_16BIT])
  3256. On8BitConvert();
  3257. else
  3258. On16BitConvert();
  3259. return wParam;
  3260. case kcSampleMonoMix: OnMonoConvertMix(); return wParam;
  3261. case kcSampleMonoLeft: OnMonoConvertLeft(); return wParam;
  3262. case kcSampleMonoRight: OnMonoConvertRight(); return wParam;
  3263. case kcSampleMonoSplit: OnMonoConvertSplit(); return wParam;
  3264. case kcSampleReverse: PostCtrlMessage(IDC_SAMPLE_REVERSE); return wParam;
  3265. case kcSampleSilence: PostCtrlMessage(IDC_SAMPLE_SILENCE); return wParam;
  3266. case kcSampleNormalize: PostCtrlMessage(IDC_SAMPLE_NORMALIZE); return wParam;
  3267. case kcSampleAmplify: PostCtrlMessage(IDC_SAMPLE_AMPLIFY); return wParam;
  3268. case kcSampleInvert: PostCtrlMessage(IDC_SAMPLE_INVERT); return wParam;
  3269. case kcSampleSignUnsign: PostCtrlMessage(IDC_SAMPLE_SIGN_UNSIGN); return wParam;
  3270. case kcSampleRemoveDCOffset: PostCtrlMessage(IDC_SAMPLE_DCOFFSET); return wParam;
  3271. case kcSampleXFade: PostCtrlMessage(IDC_SAMPLE_XFADE); return wParam;
  3272. case kcSampleAutotune: PostCtrlMessage(IDC_SAMPLE_AUTOTUNE); return wParam;
  3273. case kcSampleQuickFade: PostCtrlMessage(IDC_SAMPLE_QUICKFADE); return wParam;
  3274. case kcSampleStereoSep: PostCtrlMessage(IDC_SAMPLE_STEREOSEPARATION); return wParam;
  3275. case kcSampleSlice: OnSampleSlice(); return wParam;
  3276. case kcSampleToggleDrawing: OnDrawingToggle(); return wParam;
  3277. case kcSampleResize: OnAddSilence(); return wParam;
  3278. case kcSampleGrid: OnChangeGridSize(); return wParam;
  3279. // Those don't seem to work.
  3280. case kcNoteOff: PlayNote(NOTE_KEYOFF); return wParam;
  3281. case kcNoteCut: PlayNote(NOTE_NOTECUT); return wParam;
  3282. }
  3283. if(wParam >= kcSampStartNotes && wParam <= kcSampEndNotes)
  3284. {
  3285. const ModCommand::NOTE note = pModDoc->GetNoteWithBaseOctave(static_cast<int>(wParam - kcSampStartNotes), 0);
  3286. if(ModCommand::IsNote(note))
  3287. {
  3288. switch(TrackerSettings::Instance().sampleEditorKeyBehaviour)
  3289. {
  3290. case seNoteOffOnKeyRestrike:
  3291. if(m_noteChannel[note - NOTE_MIN] != CHANNELINDEX_INVALID)
  3292. {
  3293. NoteOff(note);
  3294. break;
  3295. }
  3296. // Fall-through
  3297. default:
  3298. PlayNote(note);
  3299. }
  3300. return wParam;
  3301. }
  3302. } else if(wParam >= kcSampStartNoteStops && wParam <= kcSampEndNoteStops)
  3303. {
  3304. const ModCommand::NOTE note = pModDoc->GetNoteWithBaseOctave(static_cast<int>(wParam - kcSampStartNoteStops), 0);
  3305. if(ModCommand::IsNote(note))
  3306. {
  3307. switch(TrackerSettings::Instance().sampleEditorKeyBehaviour)
  3308. {
  3309. case seNoteOffOnNewKey:
  3310. m_dwStatus.reset(SMPSTATUS_KEYDOWN);
  3311. if(m_noteChannel[note - NOTE_MIN] != CHANNELINDEX_INVALID)
  3312. {
  3313. // Release sustain loop on key up
  3314. sndFile.KeyOff(sndFile.m_PlayState.Chn[m_noteChannel[note - NOTE_MIN]]);
  3315. }
  3316. break;
  3317. case seNoteOffOnKeyUp:
  3318. if(m_noteChannel[note - NOTE_MIN] != CHANNELINDEX_INVALID)
  3319. {
  3320. NoteOff(note);
  3321. }
  3322. break;
  3323. }
  3324. return wParam;
  3325. }
  3326. } else if(wParam >= kcStartSampleCues && wParam <= kcEndSampleCues)
  3327. {
  3328. const ModSample &sample = sndFile.GetSample(m_nSample);
  3329. SmpLength offset = sample.cues[wParam - kcStartSampleCues];
  3330. if(offset < sample.nLength)
  3331. PlayNote(NOTE_MIDDLEC, offset);
  3332. return wParam;
  3333. }
  3334. // Pass on to ctrl_smp
  3335. return GetControlDlg()->SendMessage(WM_MOD_KEYCOMMAND, wParam, lParam);
  3336. }
  3337. void CViewSample::OnSampleSlice()
  3338. {
  3339. CModDoc *modDoc = GetDocument();
  3340. if(modDoc == nullptr || m_nSample > modDoc->GetNumSamples())
  3341. return;
  3342. CSoundFile &sndFile = modDoc->GetSoundFile();
  3343. ModSample &sample = sndFile.GetSample(m_nSample);
  3344. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB])
  3345. return;
  3346. // Sort cue points and add two fake cue points to make things easier below...
  3347. constexpr size_t NUM_CUES = mpt::array_size<decltype(sample.cues)>::size;
  3348. std::array<SmpLength, NUM_CUES + 2> cues;
  3349. bool hasValidCues = false; // Any cues in ]0, length[
  3350. for(std::size_t i = 0; i < std::size(sample.cues); i++)
  3351. {
  3352. cues[i] = sample.cues[i];
  3353. if(cues[i] == 0 || cues[i] >= sample.nLength)
  3354. cues[i] = sample.nLength;
  3355. else
  3356. hasValidCues = true;
  3357. }
  3358. // Nothing to slice?
  3359. if(!hasValidCues)
  3360. return;
  3361. cues[NUM_CUES] = 0;
  3362. cues[NUM_CUES + 1] = sample.nLength;
  3363. std::sort(cues.begin(), cues.end());
  3364. // Now slice the sample at each cue point
  3365. for(std::size_t i = 1; i < std::size(cues) - 1; i++)
  3366. {
  3367. const SmpLength cue = cues[i];
  3368. if(cue > cues[i - 1] && cue < cues[i + 1])
  3369. {
  3370. SAMPLEINDEX nextSmp = modDoc->InsertSample();
  3371. if(nextSmp == SAMPLEINDEX_INVALID)
  3372. break;
  3373. ModSample &newSample = sndFile.GetSample(nextSmp);
  3374. newSample = sample;
  3375. newSample.nLength = cues[i + 1] - cues[i];
  3376. newSample.pData.pSample = nullptr;
  3377. sndFile.m_szNames[nextSmp] = sndFile.m_szNames[m_nSample];
  3378. if(newSample.AllocateSample() > 0)
  3379. {
  3380. Util::DeleteRange(SmpLength(0), cues[i] - SmpLength(1), newSample.nLoopStart, newSample.nLoopEnd);
  3381. memcpy(newSample.sampleb(), sample.sampleb() + cues[i] * sample.GetBytesPerSample(), newSample.nLength * sample.GetBytesPerSample());
  3382. newSample.PrecomputeLoops(sndFile, false);
  3383. if(sndFile.GetNumInstruments() > 0)
  3384. {
  3385. if(auto instr = modDoc->InsertInstrument(nextSmp); instr != INSTRUMENTINDEX_INVALID)
  3386. sndFile.Instruments[instr]->name = sndFile.m_szNames[nextSmp];
  3387. }
  3388. }
  3389. }
  3390. }
  3391. modDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_delete, "Slice Sample", cues[1], sample.nLength);
  3392. SampleEdit::ResizeSample(sample, cues[1], sndFile);
  3393. sample.PrecomputeLoops(sndFile, true);
  3394. SetModified(SampleHint().Info().Data().Names(), true, true);
  3395. modDoc->UpdateAllViews(this, SampleHint().Info().Data().Names(), this);
  3396. modDoc->UpdateAllViews(this, InstrumentHint().Info().Envelope().Names(), this);
  3397. }
  3398. void CViewSample::OnSampleInsertCuePoint()
  3399. {
  3400. CModDoc *modDoc = GetDocument();
  3401. if(modDoc == nullptr || m_nSample > modDoc->GetNumSamples())
  3402. return;
  3403. CSoundFile &sndFile = modDoc->GetSoundFile();
  3404. ModSample &sample = sndFile.GetSample(m_nSample);
  3405. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB] || m_dwMenuParam >= sample.nLength)
  3406. return;
  3407. for(auto &pt : sample.cues)
  3408. {
  3409. if(pt >= sample.nLength)
  3410. {
  3411. modDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Insert Cue Point");
  3412. pt = m_dwMenuParam;
  3413. SetModified(SampleHint().Info().Data(), true, true);
  3414. break;
  3415. }
  3416. }
  3417. }
  3418. void CViewSample::OnSampleDeleteCuePoint()
  3419. {
  3420. CModDoc *modDoc = GetDocument();
  3421. if(modDoc == nullptr || m_nSample > modDoc->GetNumSamples())
  3422. return;
  3423. CSoundFile &sndFile = modDoc->GetSoundFile();
  3424. ModSample &sample = sndFile.GetSample(m_nSample);
  3425. if(!sample.HasSampleData() || sample.uFlags[CHN_ADLIB] || m_dwMenuParam >= std::size(sample.cues))
  3426. return;
  3427. modDoc->GetSampleUndo().PrepareUndo(m_nSample, sundo_none, "Delete Cue Point");
  3428. sample.cues[m_dwMenuParam] = MAX_SAMPLE_LENGTH;
  3429. SetModified(SampleHint().Info().Data(), true, true);
  3430. }
  3431. bool CViewSample::CanZoomSelection() const
  3432. {
  3433. return GetZoomLevel(m_dwEndSel - m_dwBeginSel) <= MAX_ZOOM;
  3434. }
  3435. // Returns auto-zoom level compared to other zoom levels.
  3436. // Result is not limited to MIN_ZOOM...MAX_ZOOM range.
  3437. int CViewSample::GetZoomLevel(SmpLength length) const
  3438. {
  3439. if(m_rcClient.Width() == 0 || length == 0)
  3440. return MAX_ZOOM + 1;
  3441. // When m_nZoom > 0, 2^(m_nZoom - 1) = samplesPerPixel [1]
  3442. // With auto-zoom setting the whole sample is fitted to screen:
  3443. // ViewScreenWidthInPixels * samplesPerPixel = sampleLength (approximately) [2].
  3444. // Solve samplesPerPixel from [2], then "m_nZoom" from [1].
  3445. double zoom = static_cast<double>(length) / m_rcClient.Width();
  3446. zoom = 1 + (std::log10(zoom) / std::log10(2.0));
  3447. if(zoom <= 0) zoom -= 2;
  3448. return static_cast<int>(zoom + mpt::signum(zoom));
  3449. }
  3450. void CViewSample::DoZoom(int direction, const CPoint &zoomPoint)
  3451. {
  3452. const CSoundFile &sndFile = GetDocument()->GetSoundFile();
  3453. // zoomOrder: Biggest to smallest zoom order.
  3454. std::array<int, (-MIN_ZOOM - 1) + (MAX_ZOOM + 1)> zoomOrder;
  3455. for(int i = 2; i < -MIN_ZOOM + 1; ++i)
  3456. zoomOrder[i - 2] = MIN_ZOOM + i - 2; // -6, -5, -4, -3...
  3457. for(int i = 1; i <= MAX_ZOOM; ++i)
  3458. zoomOrder[i - 1 + (-MIN_ZOOM - 1)] = i; // 1, 2, 3...
  3459. zoomOrder.back() = 0;
  3460. const int autoZoomLevel = std::max(MIN_ZOOM, GetZoomLevel(sndFile.GetSample(m_nSample).nLength));
  3461. // Move auto-zoom index (=zero) to the right position in the zoom order according to its real zoom strength.
  3462. if (autoZoomLevel < MAX_ZOOM + 1)
  3463. {
  3464. auto p = std::find(zoomOrder.begin(), zoomOrder.end(), autoZoomLevel);
  3465. if(p != zoomOrder.end())
  3466. {
  3467. std::move(p, zoomOrder.end() - 1, p + 1);
  3468. *p = 0;
  3469. }
  3470. else
  3471. MPT_ASSERT_NOTREACHED();
  3472. }
  3473. const std::ptrdiff_t nPos = std::distance(zoomOrder.begin(), std::find(zoomOrder.begin(), zoomOrder.end(), m_nZoom));
  3474. int newZoom;
  3475. if(direction > 0 && nPos > 0) // Zoom in
  3476. newZoom = zoomOrder[nPos - 1];
  3477. else if(direction < 0 && nPos + 1 < static_cast<std::ptrdiff_t>(zoomOrder.size()))
  3478. newZoom = zoomOrder[nPos + 1];
  3479. else
  3480. return;
  3481. if(m_rcClient.PtInRect(zoomPoint))
  3482. {
  3483. SetZoom(newZoom, ScreenToSample(zoomPoint.x));
  3484. } else
  3485. {
  3486. SetZoom(newZoom);
  3487. }
  3488. SendCtrlMessage(CTRLMSG_SMP_SETZOOM, newZoom);
  3489. }
  3490. BOOL CViewSample::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
  3491. {
  3492. // Ctrl + mouse wheel: zoom control.
  3493. // One scroll direction zooms in and the other zooms out.
  3494. // This behaviour is different from what would happen if simply scrolling
  3495. // the zoom levels in the zoom combobox.
  3496. if (nFlags == MK_CONTROL && GetDocument())
  3497. {
  3498. ScreenToClient(&pt);
  3499. DoZoom(zDelta, pt);
  3500. }
  3501. return CModScrollView::OnMouseWheel(nFlags, zDelta, pt);
  3502. }
  3503. void CViewSample::OnXButtonUp(UINT nFlags, UINT nButton, CPoint point)
  3504. {
  3505. if(nButton == XBUTTON1) OnPrevInstrument();
  3506. else if(nButton == XBUTTON2) OnNextInstrument();
  3507. CModScrollView::OnXButtonUp(nFlags, nButton, point);
  3508. }
  3509. void CViewSample::OnChangeGridSize()
  3510. {
  3511. CSampleGridDlg dlg(this, m_nGridSegments, GetDocument()->GetSoundFile().GetSample(m_nSample).nLength);
  3512. if(dlg.DoModal() == IDOK)
  3513. {
  3514. m_nGridSegments = dlg.m_nSegments;
  3515. InvalidateSample(false);
  3516. }
  3517. }
  3518. void CViewSample::OnQuickFade()
  3519. {
  3520. PostCtrlMessage(IDC_SAMPLE_QUICKFADE);
  3521. }
  3522. void CViewSample::SetTimelineFormat(TimelineFormat fmt)
  3523. {
  3524. TrackerSettings::Instance().sampleEditorTimelineFormat = fmt;
  3525. UpdateScrollSize();
  3526. InvalidateTimeline();
  3527. }
  3528. void CViewSample::OnUpdateUndo(CCmdUI *pCmdUI)
  3529. {
  3530. CModDoc *pModDoc = GetDocument();
  3531. if ((pCmdUI) && (pModDoc))
  3532. {
  3533. pCmdUI->Enable(pModDoc->GetSampleUndo().CanUndo(m_nSample));
  3534. pCmdUI->SetText(CMainFrame::GetInputHandler()->GetKeyTextFromCommand(kcEditUndo, _T("Undo ") + mpt::ToCString(pModDoc->GetSoundFile().GetCharsetInternal(), pModDoc->GetSampleUndo().GetUndoName(m_nSample))));
  3535. }
  3536. }
  3537. void CViewSample::OnUpdateRedo(CCmdUI *pCmdUI)
  3538. {
  3539. CModDoc *pModDoc = GetDocument();
  3540. if ((pCmdUI) && (pModDoc))
  3541. {
  3542. pCmdUI->Enable(pModDoc->GetSampleUndo().CanRedo(m_nSample));
  3543. pCmdUI->SetText(CMainFrame::GetInputHandler()->GetKeyTextFromCommand(kcEditRedo, _T("Redo ") + mpt::ToCString(pModDoc->GetSoundFile().GetCharsetInternal(), pModDoc->GetSampleUndo().GetRedoName(m_nSample))));
  3544. }
  3545. }
  3546. INT_PTR CViewSample::OnToolHitTest(CPoint point, TOOLINFO *pTI) const
  3547. {
  3548. CString text;
  3549. CRect ncRect;
  3550. CPoint screenPoint = point;
  3551. ClientToScreen(&screenPoint);
  3552. const auto ncButton = GetNcButtonAtPoint(screenPoint, &ncRect);
  3553. int buttonID = 0;
  3554. if(ncButton != uint32_max)
  3555. {
  3556. buttonID = cLeftBarButtons[ncButton];
  3557. ScreenToClient(&ncRect);
  3558. text = LoadResourceString(buttonID);
  3559. CommandID cmd = kcNull;
  3560. switch(buttonID)
  3561. {
  3562. case ID_SAMPLE_ZOOMUP: cmd = kcSampleZoomUp; break;
  3563. case ID_SAMPLE_ZOOMDOWN: cmd = kcSampleZoomDown; break;
  3564. case ID_SAMPLE_DRAW: cmd = kcSampleToggleDrawing; break;
  3565. case ID_SAMPLE_ADDSILENCE: cmd = kcSampleResize; break;
  3566. case ID_SAMPLE_GRID: cmd = kcSampleGrid; break;
  3567. }
  3568. if(cmd != kcNull)
  3569. {
  3570. auto keyText = CMainFrame::GetInputHandler()->m_activeCommandSet->GetKeyTextFromCommand(cmd, 0);
  3571. if(!keyText.IsEmpty())
  3572. text += MPT_CFORMAT(" ({})")(keyText);
  3573. }
  3574. } else
  3575. {
  3576. const ModSample &sample = GetDocument()->GetSoundFile().GetSample(m_nSample <= GetDocument()->GetNumSamples() ? m_nSample : 0);
  3577. auto [item, pos] = PointToItem(point, &ncRect);
  3578. switch(item)
  3579. {
  3580. case HitTestItem::LoopStart:
  3581. text = _T("Loop Start");
  3582. break;
  3583. case HitTestItem::LoopEnd:
  3584. text = _T("Loop End");
  3585. break;
  3586. case HitTestItem::SustainStart:
  3587. text = _T("Sustain Start");
  3588. break;
  3589. case HitTestItem::SustainEnd:
  3590. text = _T("Sustain End");
  3591. break;
  3592. default:
  3593. if(!IsCuePoint(item))
  3594. return CModScrollView::OnToolHitTest(point, pTI);
  3595. auto cue = CuePointFromItem(item);
  3596. text = MPT_CFORMAT("Cue Point {}")(cue + 1);
  3597. }
  3598. if(pos <= sample.nLength)
  3599. text += _T(": ") + mpt::cfmt::dec(3, ',', pos);
  3600. buttonID = static_cast<int>(item) + 1;
  3601. }
  3602. pTI->hwnd = m_hWnd;
  3603. pTI->uId = buttonID;
  3604. pTI->rect = ncRect;
  3605. // MFC will free() the text
  3606. auto size = text.GetLength() + 1;
  3607. TCHAR *textP = static_cast<TCHAR *>(calloc(size, sizeof(TCHAR)));
  3608. std::copy(text.GetString(), text.GetString() + size, textP);
  3609. pTI->lpszText = textP;
  3610. return buttonID;
  3611. }
  3612. OPENMPT_NAMESPACE_END