Debian Codegraph @

BambooTracker/gui/pattern_editor/pattern_editor_panel.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2018 Rerrah
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include "pattern_editor_panel.hpp"
7 #include <algorithm>
8 #include <vector>
9 #include <utility>
10 #include <stdexcept>
11 #include <thread>
12 #include <unordered_map>
13 #include <numeric>
14 #include <optional>
15 #include <QPainter>
16 #include <QFontMetrics>
17 #include <QFontInfo>
18 #include <QPoint>
19 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
20 #include <QPointF>
21 #endif
22 #include <QApplication>
23 #include <QClipboard>
24 #include <QMenu>
25 #include <QAction>
26 #include <QRegularExpression>
27 #include <QMetaMethod>
28 #include <QIcon>
29 #include "midi/midi.hpp"
30 #include "command/pattern/set_effect_value_to_step_command.hpp"
31 #include "jamming.hpp"
32 #include "note.hpp"
33 #include "step.hpp"
34 #include "bamboo_tracker_defs.hpp"
35 #include "gui/dpi.hpp"
36 #include "gui/event_guard.hpp"
37 #include "gui/command/pattern/pattern_commands_qt.hpp"
38 #include "gui/effect_description.hpp"
39 #include "gui/jam_layout.hpp"
40 #include "gui/note_name_manager.hpp"
41 #include "gui/gui_utils.hpp"
42 #include "gui/command_result_message_box.hpp"
43 #include "utils.hpp"
44
45 using Dpi::scaledQPixmap;
46 using Dpi::iRatio;
47 using Dpi::scaleRect;
48
49 PatternEditorPanel::PatternEditorPanel(QWidget *parent)
50 : QWidget(parent),
51 config_(std::make_shared<Configuration>()), // Dummy
52 stepFontWidth_(0),
53 stepFontHeight_(0),
54 stepFontAscent_(0),
55 stepFontLeading_(0),
56 headerFontAscent_(0),
57 widthSpace_(0),
58 widthSpaceDbl_(0),
59 stepNumWidthCnt_(0),
60 stepNumWidth_(0),
61 stepNumBase_(0),
62 baseTrackWidth_(0),
63 toneNameWidth_(0),
64 instWidth_(0),
65 volWidth_(0),
66 effWidth_(0),
67 effIDWidth_(0),
68 effValWidth_(0),
69 tracksWidthFromLeftToEnd_(0),
70 hdMuteToggleWidth_(0),
71 hdEffCompandButtonWidth_(0),
72 headerHeight_(0),
73 hdPlusY_(0),
74 hdMinusY_(0),
75 curRowBaselineY_(0),
76 curRowY_(0),
77 visTracks_(1), // Dummy
78 rightEffn_(16), // Dummy
79 leftTrackVisIdx_(0),
80 curSongNum_(0),
81 curPos_{ 0, 0, 0, 0, },
82 hovPos_{ -1, -1, -1, -1 },
83 mousePressPos_{ -1, -1, -1, -1 },
84 mouseReleasePos_{ -1, -1, -1, -1 },
85 selLeftAbovePos_{ -1, -1, -1, -1 },
86 selRightBelowPos_{ -1, -1, -1, -1 },
87 shiftPressedPos_{ -1, -1, -1, -1 },
88 doubleClickPos_{ -1, -1, -1, -1 },
89 markerPos_{ -1, -1, -1, -1 },
90 isIgnoreToSlider_(false),
91 isIgnoreToOrder_(false),
92 isPressedPlus_(false),
93 isPressedMinus_(false),
94 entryCnt_(0),
95 selectAllState_(-1),
96 isMuteElse_(false),
97 hl1Cnt_(4),
98 hl2Cnt_(16),
99 editableStepCnt_(1),
100 viewedRowCnt_(1),
101 viewedRowsHeight_(0),
102 viewedRowOffset_(0),
103 viewedCenterY_(0),
104 viewedCenterBaseY_(0),
105 backChanged_(false),
106 textChanged_(false),
107 foreChanged_(false),
108 headerChanged_(false),
109 focusChanged_(false),
110 followModeChanged_(false),
111 hasFocussedBefore_(false),
112 stepDownCount_(0),
113 repaintable_(true),
114 repaintingCnt_(0),
115 isInitedFirstMod_(false),
116 upSc_(Qt::Key_Up, this, nullptr, nullptr, Qt::WidgetShortcut),
117 upWSSc_(Qt::SHIFT | Qt::Key_Up, this, nullptr, nullptr, Qt::WidgetShortcut),
118 dnSc_(Qt::Key_Down, this, nullptr, nullptr, Qt::WidgetShortcut),
119 dnWSSc_(Qt::SHIFT | Qt::Key_Down, this, nullptr, nullptr, Qt::WidgetShortcut),
120 pgUpSc_(Qt::Key_PageUp, this, nullptr, nullptr, Qt::WidgetShortcut),
121 pgUpWSSc_(Qt::SHIFT | Qt::Key_PageUp, this, nullptr, nullptr, Qt::WidgetShortcut),
122 pgDnSc_(Qt::Key_PageDown, this, nullptr, nullptr, Qt::WidgetShortcut),
123 pgDnWSSc_(Qt::SHIFT | Qt::Key_PageDown, this, nullptr, nullptr, Qt::WidgetShortcut),
124 homeSc_(Qt::Key_Home, this, nullptr, nullptr, Qt::WidgetShortcut),
125 homeWSSc_(Qt::SHIFT | Qt::Key_Home, this, nullptr, nullptr, Qt::WidgetShortcut),
126 endSc_(Qt::Key_End, this, nullptr, nullptr, Qt::WidgetShortcut),
127 endWSSc_(Qt::SHIFT | Qt::Key_End, this, nullptr, nullptr, Qt::WidgetShortcut),
128 hlUpSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
129 hlUpWSSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
130 hlDnSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
131 hlDnWSSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
132 ltSc_(Qt::Key_Left, this, nullptr, nullptr, Qt::WidgetShortcut),
133 ltWSSc_(Qt::SHIFT | Qt::Key_Left, this, nullptr, nullptr, Qt::WidgetShortcut),
134 rtSc_(Qt::Key_Right, this, nullptr, nullptr, Qt::WidgetShortcut),
135 rtWSSc_(Qt::SHIFT | Qt::Key_Right, this, nullptr, nullptr, Qt::WidgetShortcut),
136 keyOffSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
137 keyCutSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
138 echoBufSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
139 stepMvUpSc_(Qt::ALT | Qt::Key_Up, this, nullptr, nullptr, Qt::WidgetShortcut),
140 stepMvDnSc_(Qt::ALT | Qt::Key_Down, this, nullptr, nullptr, Qt::WidgetShortcut),
141 expandColSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut),
142 shrinkColSc_(QKeySequence(), this, nullptr, nullptr, Qt::WidgetShortcut)
143 {
144 setAttribute(Qt::WA_Hover);
145 setFocusPolicy(Qt::ClickFocus);
146 setContextMenuPolicy(Qt::CustomContextMenu);
147
148 // Initialize font
149 headerFontDef_ = [] {
150 auto font = QApplication::font();
151 font.setPointSize(10);
152 return font;
153 }();
154 headerFont_ = headerFontDef_;
155
156 stepFontDef_ = [] {
157 QFont font("Monospace", 10);
158 font.setStyleHint(QFont::TypeWriter);
159 font.setStyleStrategy(QFont::PreferMatch);
160 // Get actually used font
161 QFontInfo info(font);
162 return QFont(info.family(), info.pointSize());
163 }();
164 stepFont_ = stepFontDef_;
165
166 updateSizes();
167
168 // Track visibility
169 songStyle_.type = SongType::Standard; // Dummy
170 songStyle_.trackAttribs.push_back({ 0, SoundSource::FM, 0 }); // Dummy
171 std::iota(visTracks_.begin(), visTracks_.end(), 0);
172
173 // Shortcuts
174 auto vMoveLam = [&] (bool isShift, auto getFunc) { // For lazy evaluation
175 if (bt_->isPlaySong() && bt_->isFollowPlay()) return;
176 moveCursorToDown(getFunc());
177 checkSelectionByCursorMove(isShift);
178 };
179 auto upLam = [&] { return (editableStepCnt_ ? -editableStepCnt_ : -1); };
180 QObject::connect(&upSc_, &QShortcut::activated, this, [vMoveLam, upLam] { vMoveLam(false, upLam); });
181 QObject::connect(&upWSSc_, &QShortcut::activated, this, [vMoveLam, upLam] { vMoveLam(true, upLam); });
182 auto dnLam = [&] { return (editableStepCnt_ ? editableStepCnt_ : 1); };
183 QObject::connect(&dnSc_, &QShortcut::activated, this, [vMoveLam, dnLam] { vMoveLam(false, dnLam); });
184 QObject::connect(&dnWSSc_, &QShortcut::activated, this, [vMoveLam, dnLam] { vMoveLam(true, dnLam); });
185 auto pgUpLam = [&] { return -static_cast<int>(config_->getPageJumpLength()); };
186 QObject::connect(&pgUpSc_, &QShortcut::activated, this, [vMoveLam, pgUpLam] { vMoveLam(false, pgUpLam); });
187 QObject::connect(&pgUpWSSc_, &QShortcut::activated, this, [vMoveLam, pgUpLam] { vMoveLam(true, pgUpLam); });
188 auto pgDnLam = [&] { return static_cast<int>(config_->getPageJumpLength()); };
189 QObject::connect(&pgDnSc_, &QShortcut::activated, this, [vMoveLam, pgDnLam] { vMoveLam(false, pgDnLam); });
190 QObject::connect(&pgDnWSSc_, &QShortcut::activated, this, [vMoveLam, pgDnLam] { vMoveLam(true, pgDnLam); });
191 auto homeLam = [&] { return -curPos_.step; };
192 QObject::connect(&homeSc_, &QShortcut::activated, this, [vMoveLam, homeLam] { vMoveLam(false, homeLam); });
193 QObject::connect(&homeWSSc_, &QShortcut::activated, this, [vMoveLam, homeLam] { vMoveLam(true, homeLam); });
194 auto endLam = [&] {
195 return (static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)) - curPos_.step - 1);
196 };
197 QObject::connect(&endSc_, &QShortcut::activated, this, [vMoveLam, endLam] { vMoveLam(false, endLam); });
198 QObject::connect(&endWSSc_, &QShortcut::activated, this, [vMoveLam, endLam] { vMoveLam(true, endLam); });
199 auto hlUpLam = [&] {
200 int base;
201 if (curPos_.step) {
202 base = curPos_.step;
203 }
204 else {
205 base = static_cast<int>(bt_->getPatternSizeFromOrderNumber(
206 curSongNum_,
207 (curPos_.order) ? (curPos_.order - 1)
208 : (static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1)));
209 }
210 return ((base - 1) / hl1Cnt_ * hl1Cnt_ - base);
211 };
212 QObject::connect(&hlUpSc_, &QShortcut::activated, this, [vMoveLam, hlUpLam] { vMoveLam(false, hlUpLam); });
213 QObject::connect(&hlUpWSSc_, &QShortcut::activated, this, [vMoveLam, hlUpLam] { vMoveLam(true, hlUpLam); });
214 auto hlDnLam = [&] {
215 int next = std::min((curPos_.step / hl1Cnt_ + 1) * hl1Cnt_,
216 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)));
217 return (next - curPos_.step);
218 };
219 QObject::connect(&hlDnSc_, &QShortcut::activated, this, [vMoveLam, hlDnLam] { vMoveLam(false, hlDnLam); });
220 QObject::connect(&hlDnWSSc_, &QShortcut::activated, this, [vMoveLam, hlDnLam] { vMoveLam(true, hlDnLam); });
221 auto ltRtLam = [&] (bool isLeft, bool isShift) {
222 moveCursorToRight(isLeft ? -1 : 1);
223 checkSelectionByCursorMove(isShift);
224 };
225 QObject::connect(&ltSc_, &QShortcut::activated, this, [ltRtLam] { ltRtLam(true, false); });
226 QObject::connect(&ltWSSc_, &QShortcut::activated, this, [ltRtLam] { ltRtLam(true, true); });
227 QObject::connect(&rtSc_, &QShortcut::activated, this, [ltRtLam] { ltRtLam(false, false); });
228 QObject::connect(&rtWSSc_, &QShortcut::activated, this, [ltRtLam] { ltRtLam(false, true); });
229 QObject::connect(&keyOffSc_, &QShortcut::activated, this, [&] {
230 if (!bt_->isJamMode() && curPos_.colInTrack == 0) {
231 bt_->setStepKeyOff(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
232 comStack_.lock()->push(new SetKeyOffToStepQtCommand(this));
233 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(editableStepCnt_);
234 }
235 });
236 QObject::connect(&keyCutSc_, &QShortcut::activated, this, [&] {
237 if (!bt_->isJamMode() && curPos_.colInTrack == 0) {
238 bt_->setStepKeyCut(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
239 comStack_.lock()->push(new SetKeyCutToStepQtCommand(this));
240 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(editableStepCnt_);
241 }
242 });
243 QObject::connect(&echoBufSc_, &QShortcut::activated, this, [&] {
244 if (!bt_->isJamMode() && curPos_.colInTrack == 0) {
245 int n = bt_->getCurrentOctave();
246 if (n > 3) n = 3;
247 bt_->setEchoBufferAccess(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step, n);
248 comStack_.lock()->push(new SetEchoBufferAccessQtCommand(this));
249 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(editableStepCnt_);
250 }
251 });
252 QObject::connect(&stepMvUpSc_, &QShortcut::activated, this, [&] {
253 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !bt_->isJamMode())
254 deletePreviousStep();
255 });
256 QObject::connect(&stepMvDnSc_, &QShortcut::activated, this, [&] {
257 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !bt_->isJamMode()) {
258 insertStep();
259 moveCursorToDown(1);
260 }
261 });
262 QObject::connect(&expandColSc_, &QShortcut::activated, this, [&] {
263 onExpandEffectColumnPressed(curPos_.trackVisIdx);
264 });
265 QObject::connect(&shrinkColSc_, &QShortcut::activated, this, [&] {
266 onShrinkEffectColumnPressed(curPos_.trackVisIdx);
267 });
268 onShortcutUpdated();
269
270 // MIDI
271 midiKeyEventMethod_ = metaObject()->indexOfSlot("midiKeyEvent(uchar,uchar,uchar)");
272 Q_ASSERT(midiKeyEventMethod_ != -1);
273 MidiInterface::getInstance().installInputHandler(&midiThreadReceivedEvent, this);
274 }
275
276 PatternEditorPanel::~PatternEditorPanel()
277 {
278 MidiInterface::getInstance().uninstallInputHandler(&midiThreadReceivedEvent, this);
279 }
280
281 void PatternEditorPanel::funcResize()
282 {
283 // Recalculate center row position
284 curRowY_ = (geometry().height() + headerHeight_ - stepFontHeight_) >> 1;
285 curRowBaselineY_ = curRowY_ + stepFontAscent_ - (stepFontLeading_ >> 1);
286
287 initDisplay();
288 }
289
290 void PatternEditorPanel::updateSizes()
291 {
292 QFontMetrics metrics(stepFont_);
293 #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
294 stepFontWidth_ = metrics.horizontalAdvance('0');
295 #else
296 stepFontWidth_ = metrics.width('0');
297 #endif
298 #if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)
299 stepFontAscent_ = metrics.capHeight();
300 #else
301 stepFontAscent_ = metrics.boundingRect('X').height();
302 #endif
303 stepFontLeading_ = metrics.ascent() - stepFontAscent_ + metrics.descent() / 2;
304 stepFontHeight_ = stepFontAscent_ + stepFontLeading_;
305
306 QFontMetrics m(headerFont_);
307 headerFontAscent_ = m.ascent() + 2;
308
309 /* Width & height */
310 widthSpace_ = stepFontWidth_ / 5 * 2;
311 widthSpaceDbl_ = widthSpace_ * 2;
312 stepNumWidthCnt_ = config_->getShowRowNumberInHex() ? 2 : 3;
313 if (config_->getShowRowNumberInHex()) {
314 stepNumWidthCnt_ = 2;
315 stepNumBase_ = 16;
316 }
317 else {
318 stepNumWidthCnt_ = 3;
319 stepNumBase_ = 10;
320 }
321 stepNumWidth_ = stepFontWidth_ * stepNumWidthCnt_ + widthSpace_;
322 toneNameWidth_ = stepFontWidth_ * 3;
323 instWidth_ = stepFontWidth_ * 2;
324 volWidth_ = stepFontWidth_ * 2;
325 effIDWidth_ = stepFontWidth_ * 2;
326 effValWidth_ = stepFontWidth_ * 2;
327 effWidth_ = effIDWidth_ + effValWidth_ + widthSpaceDbl_;
328 baseTrackWidth_ = toneNameWidth_ + instWidth_ + volWidth_
329 + effIDWidth_ + effValWidth_ + widthSpaceDbl_ * 4;
330 #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
331 hdEffCompandButtonWidth_ = m.horizontalAdvance("+");
332 #else
333 hdEffCompandButtonWidth_ = m.width("+");
334 #endif
335 hdMuteToggleWidth_ = baseTrackWidth_ - hdEffCompandButtonWidth_ - stepFontWidth_ / 2 * 3;
336 headerHeight_ = m.height() * 2 + 1;
337 hdPlusY_ = headerHeight_ / 4 + m.lineSpacing() / 2 - m.leading() / 2 - m.descent();
338 hdMinusY_ = headerHeight_ / 2 + hdPlusY_;
339
340 initDisplay();
341 }
342
343 void PatternEditorPanel::initDisplay()
344 {
345 int width = geometry().width();
346 int ratio = iRatio(*this);
347
348 // Recalculate pixmap sizes
349 viewedRegionHeight_ = std::max((geometry().height() - headerHeight_), stepFontHeight_);
350 int cnt = viewedRegionHeight_ / stepFontHeight_;
351 viewedRowCnt_ = (cnt % 2) ? (cnt + 2) : (cnt + 1);
352 viewedRowsHeight_ = viewedRowCnt_ * stepFontHeight_;
353
354 viewedRowOffset_ = (viewedRowsHeight_ - viewedRegionHeight_) >> 1;
355 viewedCenterY_ = (viewedRowsHeight_ - stepFontHeight_) >> 1;
356 viewedCenterBaseY_ = viewedCenterY_ + stepFontAscent_ + (stepFontLeading_ >> 1);
357
358 completePixmap_ = scaledQPixmap(geometry().size(), ratio);
359 backPixmap_ = scaledQPixmap(width, viewedRowsHeight_, ratio);
360 textPixmap_ = scaledQPixmap(width, viewedRowsHeight_, ratio);
361 forePixmap_ = scaledQPixmap(width, viewedRowsHeight_, ratio);
362 headerPixmap_ = scaledQPixmap(width, headerHeight_, ratio);
363 }
364
365 void PatternEditorPanel::setCore(std::shared_ptr<BambooTracker> core)
366 {
367 bt_ = core;
368 }
369
370 bool PatternEditorPanel::isReadyCore() const
371 {
372 return (bt_ != nullptr);
373 }
374
375 void PatternEditorPanel::setCommandStack(std::weak_ptr<QUndoStack> stack)
376 {
377 comStack_ = stack;
378 }
379
380 void PatternEditorPanel::setConfiguration(std::shared_ptr<Configuration> config)
381 {
382 config_ = config;
383 }
384
385 void PatternEditorPanel::setColorPallete(std::shared_ptr<ColorPalette> palette)
386 {
387 palette_ = palette;
388 }
389
390 void PatternEditorPanel::waitPaintFinish()
391 {
392 while (true) {
393 if (repaintingCnt_.load())
394 std::this_thread::sleep_for(std::chrono::milliseconds(10));
395 else {
396 curPos_ = { 0, 0, 0, 0 }; // Init
397 return;
398 }
399 }
400 }
401
402 QFont PatternEditorPanel::getHeaderFont() const
403 {
404 return headerFont_;
405 }
406
407 QFont PatternEditorPanel::getRowsFont() const
408 {
409 return stepFont_;
410 }
411
412 QFont PatternEditorPanel::getDefaultHeaderFont() const
413 {
414 return headerFontDef_;
415 }
416
417 QFont PatternEditorPanel::getDefaultRowsFont() const
418 {
419 return stepFontDef_;
420 }
421
422 void PatternEditorPanel::setFonts(const QFont& headerFont, const QFont& rowsFont)
423 {
424 headerFont_ = headerFont;
425 stepFont_ = rowsFont;
426
427 updateSizes();
428 updateTracksWidthFromLeftToEnd();
429
430 redrawAll();
431 }
432
433 void PatternEditorPanel::setVisibleTracks(std::vector<int> tracks)
434 {
435 visTracks_ = tracks;
436 rightEffn_.resize(visTracks_.size());
437 std::transform(visTracks_.begin(), visTracks_.end(), rightEffn_.begin(), [&](int t) {
438 return static_cast<int>(bt_->getEffectDisplayWidth(curSongNum_, t));
439 });
440 int max = static_cast<int>(tracks.size());
441 bool cond = (max <= curPos_.trackVisIdx);
442 if (cond) curPos_.trackVisIdx = max;
443 leftTrackVisIdx_ = std::min(leftTrackVisIdx_, curPos_.trackVisIdx);
444 updateTracksWidthFromLeftToEnd();
445
446 bt_->setCurrentTrack(visTracks_.at(curPos_.trackVisIdx));
447 emit currentTrackChanged(curPos_.trackVisIdx);
448
449 if (cond) {
450 if (config_->getMoveCursorByHorizontalScroll())
451 emit hScrollBarChangeRequested(calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack));
452 else
453 emit hScrollBarChangeRequested(leftTrackVisIdx_);
454 }
455
456 redrawAll();
457 }
458
459 std::vector<int> PatternEditorPanel::getVisibleTracks() const
460 {
461 return visTracks_;
462 }
463
464 void PatternEditorPanel::redrawByPatternChanged(bool patternSizeChanged)
465 {
466 textChanged_ = true;
467
468 // When pattern size is changed, redraw all area
469 if (patternSizeChanged) {
470 backChanged_ = true;
471 foreChanged_ = true;
472 }
473
474 repaint();
475 }
476
477 void PatternEditorPanel::redrawByFocusChanged()
478 {
479 if (hasFocussedBefore_) {
480 focusChanged_ = true;
481 repaint();
482 }
483 else {
484 redrawAll();
485 hasFocussedBefore_ = true;
486 }
487 }
488
489 void PatternEditorPanel::redrawByHoverChanged()
490 {
491 headerChanged_ = true;
492 backChanged_ = true;
493 repaint();
494 }
495
496 void PatternEditorPanel::redrawByMaskChanged()
497 {
498 foreChanged_ = true;
499 headerChanged_ = true;
500 repaint();
501 }
502
503 void PatternEditorPanel::redrawPatterns()
504 {
505 backChanged_ = true;
506 textChanged_ = true;
507 foreChanged_ = true;
508 repaint();
509 }
510
511 void PatternEditorPanel::redrawAll()
512 {
513 headerChanged_ = true;
514 redrawPatterns();
515 }
516
517 void PatternEditorPanel::resetEntryCount()
518 {
519 entryCnt_ = 0;
520 }
521
522 void PatternEditorPanel::drawPattern(const QRect &rect)
523 {
524 if (repaintable_.load()) {
525 repaintable_.store(false);
526 ++repaintingCnt_; // Use module data after this line
527
528 int ratio = iRatio(*this);
529 if (rect.size() * ratio != completePixmap_.size()) { // Prevent resize event was failed
530 funcResize();
531 headerChanged_ = true;
532 backChanged_ = true;
533 textChanged_ = true;
534 foreChanged_ = true;
535 }
536
537 if (backChanged_ || textChanged_ || foreChanged_ || headerChanged_ || focusChanged_ || stepDownCount_ || followModeChanged_) {
538
539 int maxWidth = std::min(rect.width(), tracksWidthFromLeftToEnd_);
540 completePixmap_.fill(palette_->ptnBackColor);
541
542 if (!focusChanged_) {
543 if (stepDownCount_ && !followModeChanged_) {
544 quickDrawRows(maxWidth);
545 }
546 else {
547 backPixmap_.fill(Qt::transparent);
548 if (textChanged_) textPixmap_.fill(Qt::transparent);
549 if (foreChanged_) forePixmap_.fill(Qt::transparent);
550 drawRows(maxWidth);
551 }
552 drawBorders(maxWidth);
553
554 if (headerChanged_) {
555 // headerPixmap_->fill(Qt::transparent);
556 drawHeaders(maxWidth);
557 }
558 }
559
560 {
561 QPainter mergePainter(&completePixmap_);
562 QRect rowsRect(0, viewedRowOffset_, maxWidth, viewedRegionHeight_);
563 rowsRect = scaleRect(rowsRect, ratio);
564 QRect inViewRect(0, headerHeight_, maxWidth, viewedRegionHeight_);
565 mergePainter.drawPixmap(inViewRect, backPixmap_, rowsRect);
566 mergePainter.drawPixmap(inViewRect, textPixmap_, rowsRect);
567 mergePainter.drawPixmap(inViewRect, forePixmap_, rowsRect);
568 mergePainter.drawPixmap(QPoint(0, 0), headerPixmap_);
569 }
570
571 if (!hasFocus()) drawShadow();
572
573 backChanged_ = false;
574 textChanged_ = false;
575 foreChanged_ = false;
576 headerChanged_ = false;
577 focusChanged_ = false;
578 followModeChanged_ = false;
579 stepDownCount_ = 0;
580 }
581
582 --repaintingCnt_; // Used module data until this line
583 repaintable_.store(true);
584 }
585
586 QPainter completePainter(this);
587 completePainter.drawPixmap(rect, completePixmap_);
588 }
589
590 void PatternEditorPanel::drawRows(int maxWidth)
591 {
592 QPainter forePainter(&forePixmap_);
593 QPainter textPainter(&textPixmap_);
594 QPainter backPainter(&backPixmap_);
595 textPainter.setFont(stepFont_);
596
597 /* Current row */
598 // Fill row
599 backPainter.fillRect(0, viewedCenterY_, maxWidth, stepFontHeight_,
600 bt_->isJamMode() ? palette_->ptnCurStepColor : palette_->ptnCurEditStepColor);
601 // Step number
602 if (markerPos_.isEqualRows(curPos_))
603 backPainter.fillRect(0, viewedCenterY_, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
604 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(curPos_))
605 backPainter.fillRect(0, viewedCenterY_, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
606 if (textChanged_) {
607 if (curPos_.step % hl2Cnt_) {
608 textPainter.setPen(!(curPos_.step % hl2Cnt_) ? palette_->ptnHl1StepNumColor
609 : !(curPos_.step % hl1Cnt_) ? palette_->ptnHl1StepNumColor
610 : palette_->ptnDefStepNumColor);
611 }
612 else {
613 textPainter.setPen(palette_->ptnHl2StepNumColor);
614 }
615 textPainter.drawText(1, viewedCenterBaseY_, QString("%1").arg(curPos_.step, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
616 }
617 // Step data
618 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
619 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, curPos_.order, curPos_.step, x, viewedCenterBaseY_, viewedCenterY_);
620 }
621 viewedCenterPos_ = curPos_;
622
623 int stepNum, odrNum;
624 int rowY, baseY;
625 int playOdrNum = bt_->getPlayingOrderNumber();
626 int playStepNum = bt_->getPlayingStepNumber();
627
628 /* Previous rows */
629 viewedFirstPos_ = curPos_;
630 for (rowY = viewedCenterY_ - stepFontHeight_, baseY = viewedCenterBaseY_ - stepFontHeight_,
631 stepNum = curPos_.step - 1, odrNum = curPos_.order;
632 rowY >= 0;
633 rowY -= stepFontHeight_, baseY -= stepFontHeight_, --stepNum) {
634 if (stepNum == -1) {
635 if (odrNum == 0) {
636 break;
637 }
638 else if (config_->getShowPreviousNextOrders()) {
639 --odrNum;
640 stepNum = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, odrNum)) - 1;
641 }
642 else {
643 break;
644 }
645 }
646
647 QColor rowColor;
648 if (!config_->getFollowMode() && odrNum == playOdrNum && stepNum == playStepNum) {
649 rowColor = palette_->ptnPlayStepColor;
650 }
651 else {
652 rowColor = !(stepNum % hl2Cnt_) ? palette_->ptnHl2StepColor
653 : !(stepNum % hl1Cnt_) ? palette_->ptnHl1StepColor
654 : palette_->ptnDefStepColor;
655 }
656
657 // Fill row
658 backPainter.fillRect(0, rowY, maxWidth, stepFontHeight_, rowColor);
659 // Step number
660 if (markerPos_.isEqualRows(odrNum, stepNum))
661 backPainter.fillRect(0, rowY, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
662 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(odrNum, stepNum))
663 backPainter.fillRect(0, rowY, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
664 if (textChanged_) {
665 textPainter.setPen(!(stepNum % hl2Cnt_) ? palette_->ptnHl2StepNumColor
666 : !(stepNum % hl1Cnt_) ? palette_->ptnHl1StepNumColor
667 : palette_->ptnDefStepNumColor);
668 textPainter.drawText(1, baseY, QString("%1").arg(stepNum, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
669 }
670 // Step data
671 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
672 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, odrNum, stepNum, x, baseY, rowY);
673 }
674 if (foreChanged_) {
675 if (odrNum != curPos_.order) // Mask
676 forePainter.fillRect(0, rowY, maxWidth, stepFontHeight_, palette_->ptnMaskColor);
677 }
678 viewedFirstPos_.setRows(odrNum, stepNum);
679 }
680
681 int stepEnd = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order));
682
683 /* Next rows */
684 viewedLastPos_ = curPos_;
685 for (rowY = viewedCenterY_ + stepFontHeight_, baseY = viewedCenterBaseY_ + stepFontHeight_,
686 stepNum = curPos_.step + 1, odrNum = curPos_.order;
687 rowY < viewedRowsHeight_;
688 rowY += stepFontHeight_, baseY += stepFontHeight_, ++stepNum) {
689 if (stepNum == stepEnd) {
690 if (odrNum == static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1) {
691 break;
692 }
693 else if (config_->getShowPreviousNextOrders()) {
694 ++odrNum;
695 stepNum = 0;
696 stepEnd = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, odrNum));
697 }
698 else {
699 break;
700 }
701 }
702
703 QColor rowColor;
704 if (!config_->getFollowMode() && odrNum == playOdrNum && stepNum == playStepNum) {
705 rowColor = palette_->ptnPlayStepColor;
706 }
707 else {
708 rowColor = !(stepNum % hl2Cnt_) ? palette_->ptnHl2StepColor
709 : !(stepNum % hl1Cnt_) ? palette_->ptnHl1StepColor
710 : palette_->ptnDefStepColor;
711 }
712
713 // Fill row
714 backPainter.fillRect(0, rowY, maxWidth, stepFontHeight_, rowColor);
715 // Step number
716 if (markerPos_.isEqualRows(odrNum, stepNum))
717 backPainter.fillRect(0, rowY, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
718 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(odrNum, stepNum))
719 backPainter.fillRect(0, rowY, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
720 if (textChanged_) {
721 textPainter.setPen(!(stepNum % hl2Cnt_) ? palette_->ptnHl2StepNumColor
722 : !(stepNum % hl1Cnt_) ? palette_->ptnHl1StepNumColor
723 : palette_->ptnDefStepNumColor);
724 textPainter.drawText(1, baseY, QString("%1").arg(stepNum, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
725 }
726 // Step data
727 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
728 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, odrNum, stepNum, x, baseY, rowY);
729 }
730 if (foreChanged_) {
731 if (odrNum != curPos_.order) // Mask
732 forePainter.fillRect(0, rowY, maxWidth, stepFontHeight_, palette_->ptnMaskColor);
733 }
734 viewedLastPos_.setRows(odrNum, stepNum);
735 }
736 }
737
738 void PatternEditorPanel::quickDrawRows(int maxWidth)
739 {
740 int ratio = iRatio(*this);
741
742 int halfRowsCnt = viewedRowCnt_ >> 1;
743 bool repaintForeAll = (curPos_.step - stepDownCount_ < 0);
744 int shift = stepFontHeight_ * stepDownCount_;
745
746 /* Move up */
747 {
748 // QPixmap::scroll() takes physical pixels, not virtual.
749 int phShift = shift * ratio;
750 QRect srcRect(0, 0, maxWidth, viewedRowsHeight_);
751 srcRect = scaleRect(srcRect, ratio);
752
753 if (!repaintForeAll) forePixmap_.scroll(0, -phShift, srcRect);
754 textPixmap_.scroll(0, -phShift, srcRect);
755 backPixmap_.scroll(0, -phShift, srcRect);
756 }
757
758 {
759 PatternPosition fpos = calculatePositionFrom(viewedCenterPos_.order, viewedCenterPos_.step, stepDownCount_ - halfRowsCnt);
760 if (fpos.order != -1) viewedFirstPos_ = std::move(fpos);
761 }
762
763 QPainter forePainter(&forePixmap_);
764 QPainter textPainter(&textPixmap_);
765 QPainter backPainter(&backPixmap_);
766 textPainter.setFont(stepFont_);
767
768 /* Clear previous cursor row, current cursor row and last rows text and foreground */
769 int prevY = viewedCenterY_ - shift;
770 int lastY = viewedRowsHeight_ - shift;
771 textPainter.setCompositionMode(QPainter::CompositionMode_Source);
772 textPainter.fillRect(0, prevY, maxWidth, stepFontHeight_, Qt::transparent);
773 textPainter.fillRect(0, viewedCenterY_, maxWidth, stepFontHeight_, Qt::transparent);
774 textPainter.fillRect(0, lastY, maxWidth, shift, Qt::transparent);
775 textPainter.setCompositionMode(QPainter::CompositionMode_SourceOver);
776 if (!repaintForeAll) {
777 forePainter.setCompositionMode(QPainter::CompositionMode_Source);
778 forePainter.fillRect(0, prevY, maxWidth, stepFontHeight_, Qt::transparent);
779 forePainter.fillRect(0, viewedCenterY_, maxWidth, stepFontHeight_, Qt::transparent);
780 forePainter.fillRect(0, lastY, maxWidth, shift, Qt::transparent);
781 forePainter.setCompositionMode(QPainter::CompositionMode_SourceOver);
782 }
783
784 /* Redraw previous cursor step */
785 {
786 int baseY = viewedCenterBaseY_ - shift;
787 QColor rowColor = !(viewedCenterPos_.step % hl2Cnt_) ? palette_->ptnHl2StepColor
788 : !(viewedCenterPos_.step % hl1Cnt_) ? palette_->ptnHl1StepColor
789 : palette_->ptnDefStepColor;
790 // Fill row
791 backPainter.fillRect(0, prevY, maxWidth, stepFontHeight_, rowColor);
792 // Step number
793 if (markerPos_.isEqualRows(viewedCenterPos_))
794 backPainter.fillRect(0, prevY, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
795 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(viewedCenterPos_))
796 backPainter.fillRect(0, prevY, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
797 textPainter.setPen(!(viewedCenterPos_.step % hl2Cnt_) ? palette_->ptnHl2StepNumColor
798 : !(viewedCenterPos_.step % hl1Cnt_) ? palette_->ptnHl1StepNumColor
799 : palette_->ptnDefStepNumColor);
800 textPainter.drawText(1, baseY, QString("%1").arg(viewedCenterPos_.step, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
801 // Step data
802 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
803 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, viewedCenterPos_.order, viewedCenterPos_.step, x, baseY, prevY);
804 }
805 }
806
807 /* Redraw current cursor step */
808 // Fill row
809 backPainter.fillRect(0, viewedCenterY_, maxWidth, stepFontHeight_,
810 bt_->isJamMode() ? palette_->ptnCurStepColor : palette_->ptnCurEditStepColor);
811 // Step number
812 if (markerPos_.isEqualRows(curPos_))
813 backPainter.fillRect(0, viewedCenterY_, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
814 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(curPos_))
815 backPainter.fillRect(0, viewedCenterY_, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
816 if (curPos_.step % hl2Cnt_) {
817 textPainter.setPen(!(curPos_.step % hl2Cnt_) ? palette_->ptnHl1StepNumColor
818 : !(curPos_.step % hl1Cnt_) ? palette_->ptnHl1StepNumColor
819 : palette_->ptnDefStepNumColor);
820 }
821 else {
822 textPainter.setPen(palette_->ptnHl2StepNumColor);
823 }
824 textPainter.drawText(1, viewedCenterBaseY_, QString("%1").arg(curPos_.step, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
825 // Step data
826 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
827 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, curPos_.order, curPos_.step, x, viewedCenterBaseY_, viewedCenterY_);
828 }
829 viewedCenterPos_ = curPos_;
830
831 /* Draw new step at last if necessary */
832 {
833 PatternPosition bpos = calculatePositionFrom(viewedCenterPos_.order, viewedCenterPos_.step, halfRowsCnt);
834 if (!config_->getShowPreviousNextOrders() && viewedCenterPos_.order != bpos.order) {
835 // Clear row
836 backPainter.setCompositionMode(QPainter::CompositionMode_Source);
837 backPainter.fillRect(0, lastY, maxWidth, shift, Qt::transparent);
838 }
839 else {
840 int baseY = lastY + (viewedCenterBaseY_ - viewedCenterY_);
841 bpos = std::exchange(viewedLastPos_, bpos);
842 while (true) {
843 if (bpos.compareRows(viewedLastPos_) == 0) break;
844 PatternPosition tmpBpos = calculatePositionFrom(bpos.order, bpos.step, 1);
845 if (tmpBpos.order == -1) { // when viewedLastPos_.row == -1 (viewedlastPos_.row < viewedCenterPos_.row + halRowsCnt)
846 viewedLastPos_ = bpos;
847 // Clear row
848 backPainter.setCompositionMode(QPainter::CompositionMode_Source);
849 backPainter.fillRect(0, lastY, maxWidth, shift, Qt::transparent);
850 break;
851 }
852 else {
853 bpos = tmpBpos;
854 }
855
856 QColor rowColor = !(bpos.step % hl2Cnt_) ? palette_->ptnHl2StepColor
857 : !(bpos.step % hl1Cnt_) ? palette_->ptnHl1StepColor
858 : palette_->ptnDefStepColor;
859 // Fill row
860 backPainter.fillRect(0, lastY, maxWidth, stepFontHeight_, rowColor);
861 // Step number
862 if (markerPos_.isEqualRows(bpos))
863 backPainter.fillRect(0, lastY, stepNumWidth_, stepFontHeight_, palette_->ptnMarkerColor); // Paint marker
864 if (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(bpos))
865 backPainter.fillRect(0, lastY, stepNumWidth_, stepFontHeight_, palette_->ptnHovCellColor); // Paint hover
866 textPainter.setPen(!(bpos.step % hl2Cnt_) ? palette_->ptnHl2StepNumColor
867 : !(bpos.step % hl1Cnt_) ? palette_->ptnHl1StepNumColor
868 : palette_->ptnDefStepNumColor);
869 textPainter.drawText(1, baseY, QString("%1").arg(bpos.step, stepNumWidthCnt_, stepNumBase_, QChar('0')).toUpper());
870 // Step data
871 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
872 x += drawStep(forePainter, textPainter, backPainter, trackVisIdx, bpos.order, bpos.step, x, baseY, lastY);
873 }
874 if (bpos.order != curPos_.order) // Mask
875 forePainter.fillRect(0, lastY, maxWidth, stepFontHeight_, palette_->ptnMaskColor);
876
877 baseY += stepFontHeight_;
878 lastY += stepFontHeight_;
879 }
880 }
881 }
882
883 /* Redraw foreground all area if new order */
884 if (repaintForeAll) {
885 forePixmap_.fill(Qt::transparent);
886 int y = viewedCenterY_ - viewedCenterPos_.step * stepFontHeight_;
887 if (y > 0) forePainter.fillRect(0, 0, maxWidth, y, palette_->ptnMaskColor);
888 if (viewedLastPos_.order != viewedCenterPos_.order) {
889 y += static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, viewedCenterPos_.order)) * stepFontHeight_;
890 forePainter.fillRect(0, y, maxWidth, viewedRowsHeight_ - y, palette_->ptnMaskColor);
891 }
892 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
893 int w = baseTrackWidth_ + effWidth_ * rightEffn_.at(static_cast<size_t>(trackVisIdx));
894 if (foreChanged_ && bt_->isMute(visTracks_.at(trackVisIdx))) // Paint mute mask
895 forePainter.fillRect(x, 0, w, viewedRowsHeight_, palette_->ptnMaskColor);
896 x += w;
897 }
898 }
899 }
900
901 int PatternEditorPanel::drawStep(QPainter &forePainter, QPainter &textPainter, QPainter& backPainter, int trackVisIdx, int orderNum, int stepNum, int x, int baseY, int rowY)
902 {
903 int trackNum = visTracks_.at(trackVisIdx);
904 int offset = x + widthSpace_;
905 PatternPosition pos{ trackVisIdx, 0, orderNum, stepNum };
906 QColor textColor = curPos_.isEqualRows(orderNum, stepNum) ? palette_->ptnCurTextColor : palette_->ptnDefTextColor;
907 bool isHovTrack = (hovPos_.order == -2 && hovPos_.trackVisIdx == trackVisIdx);
908 bool isHovStep = (hovPos_.trackVisIdx == -2 && hovPos_.isEqualRows(orderNum, stepNum));
909 SoundSource src = songStyle_.trackAttribs[static_cast<size_t>(trackNum)].source;
910
911
912 /* Tone name */
913 if (pos == curPos_) // Paint current cell
914 backPainter.fillRect(offset - widthSpace_, rowY, toneNameWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnCurCellColor);
915 if (pos == hovPos_ || isHovTrack || isHovStep) // Paint hover
916 backPainter.fillRect(offset - widthSpace_, rowY, toneNameWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnHovCellColor);
917 if ((selLeftAbovePos_.trackVisIdx >= 0 && selLeftAbovePos_.order >= 0)
918 && isSelectedCell(trackVisIdx, 0, orderNum, stepNum)) // Paint selected
919 backPainter.fillRect(offset - widthSpace_, rowY, toneNameWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnSelCellColor);
920 if (textChanged_) {
921 int noteNum = bt_->getStepNoteNumber(curSongNum_, trackNum, orderNum, stepNum);
922 switch (noteNum) {
923 case Step::NOTE_NONE:
924 textPainter.setPen(textColor);
925 textPainter.drawText(offset, baseY, "---");
926 break;
927 case Step::NOTE_KEY_OFF:
928 {
929 int h = stepFontHeight_ / 7;
930 textPainter.fillRect(offset, rowY + stepFontHeight_ * 2 / 7, toneNameWidth_, h, palette_->ptnNoteColor);
931 textPainter.fillRect(offset, rowY + stepFontHeight_ * 4 / 7, toneNameWidth_, h, palette_->ptnNoteColor);
932 break;
933 }
934 case Step::NOTE_KEY_CUT:
935 textPainter.fillRect(offset, rowY + stepFontHeight_ * 2 / 5,
936 toneNameWidth_, stepFontHeight_ / 5, palette_->ptnNoteColor);
937 break;
938 case Step::NOTE_ECHO0:
939 textPainter.setPen(palette_->ptnNoteColor);
940 textPainter.drawText(offset + stepFontWidth_ / 2, baseY, "^0");
941 break;
942 case Step::NOTE_ECHO1:
943 textPainter.setPen(palette_->ptnNoteColor);
944 textPainter.drawText(offset + stepFontWidth_ / 2, baseY, "^1");
945 break;
946 case Step::NOTE_ECHO2:
947 textPainter.setPen(palette_->ptnNoteColor);
948 textPainter.drawText(offset + stepFontWidth_ / 2, baseY, "^2");
949 break;
950 case Step::NOTE_ECHO3:
951 textPainter.setPen(palette_->ptnNoteColor);
952 textPainter.drawText(offset + stepFontWidth_ / 2, baseY, "^3");
953 break;
954 default: // Convert tone name
955 {
956 textPainter.setPen(palette_->ptnNoteColor);
957 KeySignature::Type key = bt_->searchKeySignatureAt(curSongNum_, orderNum, stepNum);
958 textPainter.drawText(offset, baseY, NoteNameManager::getManager().getNoteString(noteNum, key));
959 break;
960 }
961 }
962 }
963 offset += toneNameWidth_ + widthSpaceDbl_;
964 pos.colInTrack = 1;
965
966 /* Instrument */
967 if (pos == curPos_) // Paint current cell
968 backPainter.fillRect(offset - widthSpace_, rowY, instWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnCurCellColor);
969 if (pos == hovPos_ || isHovTrack || isHovStep) // Paint hover
970 backPainter.fillRect(offset - widthSpace_, rowY, instWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnHovCellColor);
971 if ((selLeftAbovePos_.trackVisIdx >= 0 && selLeftAbovePos_.order >= 0)
972 && isSelectedCell(trackVisIdx, 1, orderNum, stepNum)) // Paint selected
973 backPainter.fillRect(offset - widthSpace_, rowY, instWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnSelCellColor);
974 if (textChanged_) {
975 int instNum = bt_->getStepInstrument(curSongNum_, trackNum, orderNum, stepNum);
976 if (instNum == -1) {
977 textPainter.setPen(textColor);
978 textPainter.drawText(offset, baseY, "--");
979 }
980 else {
981 std::unique_ptr<AbstractInstrument> inst = bt_->getInstrument(instNum);
982 textPainter.setPen((inst != nullptr && src == inst->getSoundSource())
983 ? palette_->ptnInstColor
984 : palette_->ptnErrorColor);
985 textPainter.drawText(offset, baseY, QString("%1").arg(instNum, 2, 16, QChar('0')).toUpper());
986 }
987 }
988 offset += instWidth_ + widthSpaceDbl_;
989 pos.colInTrack = 2;
990
991 /* Volume */
992 if (pos == curPos_) // Paint current cell
993 backPainter.fillRect(offset - widthSpace_, rowY, volWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnCurCellColor);
994 if (pos == hovPos_ || isHovTrack || isHovStep) // Paint hover
995 backPainter.fillRect(offset - widthSpace_, rowY, volWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnHovCellColor);
996 if ((selLeftAbovePos_.trackVisIdx >= 0 && selLeftAbovePos_.order >= 0)
997 && isSelectedCell(trackVisIdx, 2, orderNum, stepNum)) // Paint selected
998 backPainter.fillRect(offset - widthSpace_, rowY, volWidth_ + widthSpaceDbl_, stepFontHeight_, palette_->ptnSelCellColor);
999 if (textChanged_) {
1000 int vol = bt_->getStepVolume(curSongNum_, trackNum, orderNum, stepNum);
1001 if (vol == -1) {
1002 textPainter.setPen(textColor);
1003 textPainter.drawText(offset, baseY, "--");
1004 }
1005 else {
1006 int volLim = 0; // Dummy set
1007 switch (src) {
1008 case SoundSource::FM: volLim = bt_defs::NSTEP_FM_VOLUME ; break;
1009 case SoundSource::SSG: volLim = bt_defs::NSTEP_SSG_VOLUME; break;
1010 case SoundSource::RHYTHM: volLim = bt_defs::NSTEP_RHYTHM_VOLUME; break;
1011 case SoundSource::ADPCM: volLim = bt_defs::NSTEP_ADPCM_VOLUME; break;
1012 }
1013 textPainter.setPen((vol < volLim) ? palette_->ptnVolColor : palette_->ptnErrorColor);
1014 if (src == SoundSource::FM && vol < volLim && config_->getReverseFMVolumeOrder()) {
1015 vol = volLim - vol - 1;
1016 }
1017 textPainter.drawText(offset, baseY, QString("%1").arg(vol, 2, 16, QChar('0')).toUpper());
1018 }
1019 }
1020 offset += volWidth_ + widthSpaceDbl_;
1021 pos.colInTrack = 3;
1022
1023 /* Effect */
1024 for (int i = 0; i <= rightEffn_.at(static_cast<size_t>(trackVisIdx)); ++i) {
1025 /* Effect ID */
1026 if (pos == curPos_) // Paint current cell
1027 backPainter.fillRect(offset - widthSpace_, rowY, effIDWidth_ + widthSpace_, stepFontHeight_, palette_->ptnCurCellColor);
1028 if (pos == hovPos_ || isHovTrack || isHovStep) // Paint hover
1029 backPainter.fillRect(offset - widthSpace_, rowY, effIDWidth_ + widthSpace_, stepFontHeight_, palette_->ptnHovCellColor);
1030 if ((selLeftAbovePos_.trackVisIdx >= 0 && selLeftAbovePos_.order >= 0)
1031 && isSelectedCell(trackVisIdx, pos.colInTrack, orderNum, stepNum)) // Paint selected
1032 backPainter.fillRect(offset - widthSpace_, rowY, effIDWidth_ + widthSpace_, stepFontHeight_, palette_->ptnSelCellColor);
1033 std::string effId;
1034 QString effStr;
1035 if (textChanged_) {
1036 effId = bt_->getStepEffectID(curSongNum_, trackNum, orderNum, stepNum, i);
1037 effStr = QString::fromStdString(effId);
1038 if (effStr == "--") {
1039 textPainter.setPen(textColor);
1040 textPainter.drawText(offset, baseY, effStr);
1041 }
1042 else {
1043 textPainter.setPen(palette_->ptnEffColor);
1044 textPainter.drawText(offset, baseY, effStr);
1045 }
1046 }
1047 offset += effIDWidth_;
1048 ++pos.colInTrack;
1049
1050 /* Effect Value */
1051 if (pos == curPos_) // Paint current cell
1052 backPainter.fillRect(offset, rowY, effValWidth_ + widthSpace_, stepFontHeight_, palette_->ptnCurCellColor);
1053 if (pos == hovPos_ || isHovTrack || isHovStep) // Paint hover
1054 backPainter.fillRect(offset, rowY, effValWidth_ + widthSpace_, stepFontHeight_, palette_->ptnHovCellColor);
1055 if ((selLeftAbovePos_.trackVisIdx >= 0 && selLeftAbovePos_.order >= 0)
1056 && isSelectedCell(trackVisIdx, pos.colInTrack, orderNum, stepNum)) // Paint selected
1057 backPainter.fillRect(offset, rowY, effValWidth_ + widthSpace_, stepFontHeight_, palette_->ptnSelCellColor);
1058 if (textChanged_) {
1059 int effVal = bt_->getStepEffectValue(curSongNum_, trackNum, orderNum, stepNum, i);
1060 if (effVal == -1) {
1061 textPainter.setPen(textColor);
1062 textPainter.drawText(offset, baseY, "--");
1063 }
1064 else {
1065 textPainter.setPen(palette_->ptnEffColor);
1066 switch (effect_utils::validateEffectId(src, effId)) {
1067 case EffectType::VolumeDelay:
1068 if (src == SoundSource::FM && config_->getReverseFMVolumeOrder())
1069 effVal = effect_utils::reverseFmVolume(effVal);
1070 break;
1071 case EffectType::Brightness:
1072 if (config_->getReverseFMVolumeOrder())
1073 effVal = effect_utils::reverseFmBrightness(effVal);
1074 break;
1075 default:
1076 break;
1077 }
1078 textPainter.drawText(offset, baseY, QString("%1").arg(effVal, 2, 16, QChar('0')).toUpper());
1079 }
1080 }
1081 offset += effValWidth_ + widthSpaceDbl_;
1082 ++pos.colInTrack;
1083 }
1084
1085 if (foreChanged_ && bt_->isMute(trackNum)) // Paint mute mask
1086 forePainter.fillRect(x, rowY, offset - x - 1, stepFontHeight_, palette_->ptnMaskColor);
1087
1088 return baseTrackWidth_ + effWidth_ * rightEffn_[static_cast<size_t>(trackVisIdx)];
1089 }
1090
1091 void PatternEditorPanel::drawHeaders(int maxWidth)
1092 {
1093 QPainter painter(&headerPixmap_);
1094 painter.setFont(headerFont_);
1095
1096 painter.fillRect(0, 0, geometry().width(), headerHeight_, palette_->ptnHeaderRowColor);
1097 painter.setPen(palette_->ptnHeaderBorderColor);
1098 qreal bottomLineY = headerHeight_ - 0.5;
1099 painter.drawLine(QPointF(0., bottomLineY), QPointF(geometry().width(), bottomLineY));
1100 int lspace = stepFontWidth_ / 2;
1101 for (int x = stepNumWidth_, trackVisIdx = leftTrackVisIdx_; x < maxWidth; ++trackVisIdx) {
1102 painter.setPen(palette_->ptnHeaderBorderColor);
1103 painter.drawLine(x, 0, x, headerHeight_);
1104 int trackNum = visTracks_.at(trackVisIdx);
1105 int tw = baseTrackWidth_ + effWidth_ * rightEffn_.at(static_cast<size_t>(trackVisIdx));
1106 if (hovPos_.order == -2 && hovPos_.trackVisIdx == trackVisIdx)
1107 painter.fillRect(x, 0, tw, headerHeight_, palette_->ptnHovCellColor);
1108 int left = x + lspace;
1109 painter.setPen(palette_->ptnHeaderTextColor);
1110 const TrackAttribute& attrib = songStyle_.trackAttribs[static_cast<size_t>(trackNum)];
1111 painter.drawText(left, headerFontAscent_,
1112 gui_utils::getTrackName(songStyle_.type, attrib.source, attrib.channelInSource));
1113
1114 painter.fillRect(left, headerHeight_ - 4, hdMuteToggleWidth_, 2,
1115 bt_->isMute(trackNum) ? palette_->ptnMuteColor : palette_->ptnUnmuteColor);
1116
1117 painter.drawText(left + hdMuteToggleWidth_ + lspace, hdPlusY_, "+");
1118 painter.drawText(left + hdMuteToggleWidth_ + lspace, hdMinusY_, "-");
1119
1120 x += tw;
1121 }
1122 }
1123
1124 void PatternEditorPanel::drawBorders(int maxWidth)
1125 {
1126 QPainter painter(&backPixmap_);
1127 painter.setPen(palette_->ptnBorderColor);
1128 painter.drawLine(stepNumWidth_, 0, stepNumWidth_, backPixmap_.height());
1129 size_t trackVisIdx = static_cast<size_t>(leftTrackVisIdx_);
1130 for (int x = stepNumWidth_; trackVisIdx < rightEffn_.size(); ) {
1131 x += (baseTrackWidth_ + effWidth_ * rightEffn_.at(trackVisIdx));
1132 if (x > maxWidth) break;
1133 painter.drawLine(x, 0, x, backPixmap_.height());
1134 ++trackVisIdx;
1135 }
1136 }
1137
1138 void PatternEditorPanel::drawShadow()
1139 {
1140 QPainter painter(&completePixmap_);
1141 painter.fillRect(0, 0, geometry().width(), geometry().height(), palette_->ptnUnfocusedShadowColor);
1142 }
1143
1144 // NOTE: end >= -1
1145 int PatternEditorPanel::calculateTracksWidthWithRowNum(int beginIdx, int endIdx) const
1146 {
1147 int width = stepNumWidth_;
1148 for (int i = beginIdx; i <= endIdx; ++i) {
1149 width += (baseTrackWidth_ + effWidth_ * rightEffn_.at(static_cast<size_t>(i)));
1150 }
1151 return width;
1152 }
1153
1154 int PatternEditorPanel::calculateColNumInRow(int trackVisIdx, int colNumInTrack, bool isExpanded) const
1155 {
1156 if (isExpanded) {
1157 return trackVisIdx * 11 + colNumInTrack;
1158 }
1159 else {
1160 trackVisIdx = std::min(trackVisIdx, static_cast<int>(rightEffn_.size()));
1161 return std::accumulate(rightEffn_.begin(), rightEffn_.begin() + trackVisIdx, colNumInTrack,
1162 [](int acc, int v) { return acc + 5 + 2 * v; });
1163 }
1164 }
1165
1166 void PatternEditorPanel::moveCursorToRight(int n)
1167 {
1168 int oldTrackIdx = curPos_.trackVisIdx;
1169 int oldLeftTrackIdx = leftTrackVisIdx_;
1170
1171 curPos_.colInTrack += n;
1172 if (n > 0) {
1173 while (true) {
1174 int lim = 5 + 2 * rightEffn_.at(static_cast<size_t>(curPos_.trackVisIdx));
1175 if (curPos_.colInTrack < lim) {
1176 break;
1177 }
1178 else {
1179 if (curPos_.trackVisIdx == static_cast<int>(visTracks_.size()) - 1) {
1180 if (config_->getWarpCursor()) {
1181 curPos_.trackVisIdx = 0;
1182 }
1183 else {
1184 curPos_.colInTrack = lim - 1;
1185 break;
1186 }
1187 }
1188 else {
1189 ++curPos_.trackVisIdx;
1190 }
1191 curPos_.colInTrack -= lim;
1192 }
1193 }
1194 }
1195 else {
1196 while (true) {
1197 if (curPos_.colInTrack >= 0) {
1198 break;
1199 }
1200 else {
1201 if (!curPos_.trackVisIdx) {
1202 if (config_->getWarpCursor()) {
1203 curPos_.trackVisIdx = static_cast<int>(visTracks_.size()) - 1;
1204 }
1205 else {
1206 curPos_.colInTrack = 0;
1207 break;
1208 }
1209 }
1210 else {
1211 --curPos_.trackVisIdx;
1212 }
1213 curPos_.colInTrack += (5 + 2 * rightEffn_.at(static_cast<size_t>(curPos_.trackVisIdx)));
1214 }
1215 }
1216 }
1217 if (oldTrackIdx < curPos_.trackVisIdx) {
1218 while (calculateTracksWidthWithRowNum(leftTrackVisIdx_, curPos_.trackVisIdx) > geometry().width())
1219 ++leftTrackVisIdx_;
1220 }
1221 else {
1222 if (curPos_.trackVisIdx < leftTrackVisIdx_) leftTrackVisIdx_ = curPos_.trackVisIdx;
1223 }
1224
1225 updateTracksWidthFromLeftToEnd();
1226 entryCnt_ = 0;
1227
1228 if (curPos_.trackVisIdx != oldTrackIdx)
1229 bt_->setCurrentTrack(visTracks_.at(curPos_.trackVisIdx));
1230
1231 if (!isIgnoreToSlider_) {
1232 if (config_->getMoveCursorByHorizontalScroll()) {
1233 emit hScrollBarChangeRequested(calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack));
1234 }
1235 else if (curPos_.trackVisIdx != oldTrackIdx) {
1236 emit hScrollBarChangeRequested(leftTrackVisIdx_);
1237 }
1238 }
1239
1240 if (!isIgnoreToOrder_ && curPos_.trackVisIdx != oldTrackIdx) // Send to order list
1241 emit currentTrackChanged(curPos_.trackVisIdx);
1242
1243 // Request fore-background repaint if leftmost track is changed else request only background repaint
1244 if (leftTrackVisIdx_ != oldLeftTrackIdx) {
1245 headerChanged_ = true;
1246 foreChanged_ = true;
1247 textChanged_ = true;
1248 }
1249 backChanged_ = true;
1250 repaint();
1251 }
1252
1253 void PatternEditorPanel::moveViewToRight(int n)
1254 {
1255 leftTrackVisIdx_ += n;
1256 updateTracksWidthFromLeftToEnd();
1257
1258 // Calculate cursor position
1259 int trackIdx = curPos_.trackVisIdx + n;
1260 int col = std::min(curPos_.colInTrack,
1261 4 + 2 * rightEffn_.at(static_cast<size_t>(trackIdx)));
1262
1263 // Check visible
1264 int width = stepNumWidth_;
1265 for (int i = leftTrackVisIdx_; i <= trackIdx; ++i) {
1266 width += (baseTrackWidth_ + effWidth_ * rightEffn_.at(static_cast<size_t>(i)));
1267 if (geometry().width() < width) {
1268 trackIdx = i - 1;
1269 col = 4 + 2 * rightEffn_.at(static_cast<size_t>(trackIdx));
1270 break;
1271 }
1272 }
1273
1274 // Move cursor and repaint all
1275 headerChanged_ = true;
1276 foreChanged_ = true;
1277 textChanged_ = true;
1278 moveCursorToRight(calculateColumnDistance(curPos_.trackVisIdx, curPos_.colInTrack, trackIdx, col));
1279 }
1280
1281 void PatternEditorPanel::moveCursorToDown(int n)
1282 {
1283 int oldOdr = curPos_.order;
1284 int tmp = curPos_.step + n;
1285
1286 if (n > 0) {
1287 while (true) {
1288 int dif = tmp - static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order));
1289 if (dif < 0) {
1290 curPos_.step = tmp;
1291 break;
1292 }
1293 else {
1294 if (config_->getWarpAcrossOrders()) {
1295 if (curPos_.order == static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1) {
1296 curPos_.order = 0;
1297 }
1298 else {
1299 ++curPos_.order;
1300 }
1301 }
1302 tmp = dif;
1303 }
1304 }
1305 }
1306 else {
1307 while (true) {
1308 if (tmp < 0) {
1309 if (config_->getWarpAcrossOrders()) {
1310 if (curPos_.order == 0) {
1311 curPos_.order = static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1;
1312 }
1313 else {
1314 --curPos_.order;
1315 }
1316 }
1317 tmp += bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order);
1318 }
1319 else {
1320 curPos_.step = tmp;
1321 break;
1322 }
1323 }
1324 }
1325
1326 if (curPos_.order != oldOdr)
1327 bt_->setCurrentOrderNumber(curPos_.order);
1328 bt_->setCurrentStepNumber(curPos_.step);
1329
1330 entryCnt_ = 0;
1331
1332 if (!isIgnoreToSlider_)
1333 emit vScrollBarChangeRequested(
1334 curPos_.step, static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)) - 1);
1335
1336 if (!isIgnoreToOrder_ && curPos_.order != oldOdr) // Send to order list
1337 emit currentOrderChanged(
1338 curPos_.order, static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1);
1339
1340 backChanged_ = true;
1341 textChanged_ = true;
1342 foreChanged_ = true;
1343 repaint();
1344 }
1345
1346 int PatternEditorPanel::calculateColumnDistance(int beginTrackIdx, int beginColumn, int endTrackIdx, int endColumn, bool isExpanded) const
1347 {
1348 return (calculateColNumInRow(endTrackIdx, endColumn, isExpanded)
1349 - calculateColNumInRow(beginTrackIdx, beginColumn, isExpanded));
1350 }
1351
1352 int PatternEditorPanel::calculateStepDistance(int beginOrder, int beginStep, int endOrder, int endStep) const
1353 {
1354 int d = 0;
1355 int startOrder, startStep, stopOrder, stopStep;
1356 bool flag;
1357
1358 if (endOrder >= beginOrder) {
1359 startOrder = endOrder;
1360 startStep = endStep;
1361 stopOrder = beginOrder;
1362 stopStep = beginStep;
1363 flag = true;
1364 }
1365 else {
1366 startOrder = beginOrder;
1367 startStep = beginStep;
1368 stopOrder = endOrder;
1369 stopStep = endStep;
1370 flag = false;
1371 }
1372
1373 while (true) {
1374 if (startOrder == stopOrder) {
1375 d += (startStep - stopStep);
1376 break;
1377 }
1378 else {
1379 d += startStep;
1380 startStep = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, --startOrder));
1381 }
1382 }
1383
1384 return flag ? d : -d;
1385 }
1386
1387 PatternPosition PatternEditorPanel::calculatePositionFrom(int order, int step, int by) const
1388 {
1389 PatternPosition pos{ -1, -1, order, step + by };
1390
1391 if (by > 0) {
1392 while (true) {
1393 int dif = pos.step - static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, pos.order));
1394 if (dif < 0) {
1395 break;
1396 }
1397 else {
1398 if (pos.order == static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1) {
1399 return { -1, -1, -1, -1 };
1400 }
1401 else {
1402 ++pos.order;
1403 }
1404 pos.step = dif;
1405 }
1406 }
1407 }
1408 else {
1409 while (true) {
1410 if (pos.step < 0) {
1411 if (pos.order == 0) {
1412 return { -1, -1, -1, -1 };
1413 }
1414 else {
1415 --pos.order;
1416 }
1417 pos.step += bt_->getPatternSizeFromOrderNumber(curSongNum_, pos.order);
1418 }
1419 else {
1420 break;
1421 }
1422 }
1423 }
1424 return pos;
1425 }
1426
1427 QPoint PatternEditorPanel::calculateCurrentCursorPosition() const
1428 {
1429 int w = calculateTracksWidthWithRowNum(leftTrackVisIdx_, curPos_.trackVisIdx - 1);
1430 if (curPos_.colInTrack > 0) {
1431 w = w + toneNameWidth_ + widthSpaceDbl_;
1432 if (curPos_.colInTrack > 1) {
1433 w = w + instWidth_ + widthSpaceDbl_;
1434 if (curPos_.colInTrack > 2) {
1435 w = w + volWidth_ + widthSpaceDbl_;
1436 for (int i = 3; i < 11; ++i) {
1437 if (curPos_.colInTrack == i) break;
1438 w = w + widthSpace_ + ((i % 2) ? effIDWidth_ : effValWidth_);
1439 }
1440 }
1441 }
1442 }
1443 return QPoint(w, curRowY_);
1444 }
1445
1446 int PatternEditorPanel::getScrollableCountByTrack() const
1447 {
1448 int width = stepNumWidth_;
1449 size_t i = visTracks_.size();
1450 do {
1451 --i;
1452 width += (baseTrackWidth_ + effWidth_ * rightEffn_.at(i));
1453 if (geometry().width() < width) {
1454 return static_cast<int>(i + 1);
1455 }
1456 } while (i);
1457 return 0;
1458 }
1459
1460 void PatternEditorPanel::changeEditable()
1461 {
1462 backChanged_ = true;
1463 repaint();
1464 }
1465
1466 int PatternEditorPanel::getFullColmunSize() const
1467 {
1468 return calculateColNumInRow(static_cast<int>(visTracks_.size()) - 1, 4 + 2 * rightEffn_.back());
1469 }
1470
1471 void PatternEditorPanel::updatePositionByStepUpdate(bool isFirstUpdate, bool forceJump, bool trackChanged)
1472 {
1473 if (!forceJump && !config_->getFollowMode()) { // Repaint only background
1474 backChanged_ = true;
1475 repaint();
1476 return;
1477 }
1478
1479 if (trackChanged) {
1480 int trackVisIdx = std::distance(visTracks_.begin(), utils::find(visTracks_, bt_->getCurrentTrackAttribute().number));
1481 int oldTrackVisIdx = std::exchange(curPos_.trackVisIdx, trackVisIdx);
1482 curPos_.colInTrack = 0;
1483 if (oldTrackVisIdx < curPos_.trackVisIdx) {
1484 while (calculateTracksWidthWithRowNum(leftTrackVisIdx_, curPos_.trackVisIdx) > geometry().width()) {
1485 ++leftTrackVisIdx_;
1486 headerChanged_ = true;
1487 }
1488 }
1489 else {
1490 if (curPos_.trackVisIdx < leftTrackVisIdx_) {
1491 leftTrackVisIdx_ = curPos_.trackVisIdx;
1492 headerChanged_ = true;
1493 }
1494 }
1495
1496 updateTracksWidthFromLeftToEnd();
1497
1498 if (!isIgnoreToSlider_) {
1499 if (config_->getMoveCursorByHorizontalScroll())
1500 emit hScrollBarChangeRequested(calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack));
1501 else
1502 emit hScrollBarChangeRequested(leftTrackVisIdx_);
1503 }
1504 }
1505
1506 PatternPosition tmp = curPos_;
1507 curPos_.setRows(bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
1508 int cmp = curPos_.compareRows(tmp);
1509 if (cmp || isFirstUpdate) {
1510 emit vScrollBarChangeRequested(
1511 curPos_.step, static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)) - 1);
1512
1513 if (isFirstUpdate || (cmp < 0) || (cmp && !config_->getShowPreviousNextOrders())) {
1514 stepDownCount_ = 0; // Redraw entire area in first update
1515 }
1516 else {
1517 int d = calculateStepDistance(tmp.order, tmp.step, curPos_.order, curPos_.step);
1518 stepDownCount_ = (d < (viewedRowCnt_ >> 1)) ? d : 0;
1519 }
1520 }
1521 else if (!trackChanged) return; // Delayed call, already updated.
1522
1523 entryCnt_ = 0;
1524
1525 // If stepChanged is false, repaint all pattern
1526 foreChanged_ = true;
1527 textChanged_ = true;
1528 backChanged_ = true;
1529 repaint();
1530 }
1531
1532 void PatternEditorPanel::changeMarker()
1533 {
1534 markerPos_.setRows(bt_->getMarkerOrder(), bt_->getMarkerStep());
1535 backChanged_ = true;
1536 repaint();
1537 }
1538
1539 bool PatternEditorPanel::enterToneData(QKeyEvent* event)
1540 {
1541 int baseOct = bt_->getCurrentOctave();
1542
1543 auto modifiers = event->modifiers();
1544 if (modifiers.testFlag(Qt::NoModifier) || modifiers.testFlag(Qt::KeypadModifier)) {
1545 Qt::Key qtKey = static_cast<Qt::Key>(event->key());
1546 try {
1547 JamKey possibleJamKey = getJamKeyFromLayoutMapping(qtKey, config_);
1548 setStepKeyOn(jam_utils::makeNote(baseOct, possibleJamKey));
1549 } catch (std::invalid_argument &) {}
1550 }
1551
1552 return false;
1553 }
1554
1555 void PatternEditorPanel::setStepKeyOn(const Note& note)
1556 {
1557 bt_->setStepNote(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step, note,
1558 config_->getInstrumentMask(), config_->getVolumeMask());
1559 comStack_.lock()->push(new SetKeyOnToStepQtCommand(this));
1560 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(editableStepCnt_);
1561 }
1562
1563 bool PatternEditorPanel::enterInstrumentData(int key)
1564 {
1565 switch (key) {
1566 case Qt::Key_0: setStepInstrument(0x0); return true;
1567 case Qt::Key_1: setStepInstrument(0x1); return true;
1568 case Qt::Key_2: setStepInstrument(0x2); return true;
1569 case Qt::Key_3: setStepInstrument(0x3); return true;
1570 case Qt::Key_4: setStepInstrument(0x4); return true;
1571 case Qt::Key_5: setStepInstrument(0x5); return true;
1572 case Qt::Key_6: setStepInstrument(0x6); return true;
1573 case Qt::Key_7: setStepInstrument(0x7); return true;
1574 case Qt::Key_8: setStepInstrument(0x8); return true;
1575 case Qt::Key_9: setStepInstrument(0x9); return true;
1576 case Qt::Key_A: setStepInstrument(0xa); return true;
1577 case Qt::Key_B: setStepInstrument(0xb); return true;
1578 case Qt::Key_C: setStepInstrument(0xc); return true;
1579 case Qt::Key_D: setStepInstrument(0xd); return true;
1580 case Qt::Key_E: setStepInstrument(0xe); return true;
1581 case Qt::Key_F: setStepInstrument(0xf); return true;
1582 default: return false;
1583 }
1584 }
1585
1586 void PatternEditorPanel::setStepInstrument(int num)
1587 {
1588 int trackNum = visTracks_.at(curPos_.trackVisIdx);
1589 bt_->setStepInstrumentDigit(curSongNum_, trackNum, curPos_.order, curPos_.step, num, (entryCnt_ == 1));
1590 comStack_.lock()->push(new SetInstrumentToStepQtCommand(this, curPos_, (entryCnt_ == 1)));
1591
1592 emit instrumentEntered(
1593 bt_->getStepInstrument(curSongNum_, trackNum, curPos_.order, curPos_.step));
1594
1595 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !updateEntryCount())
1596 moveCursorToDown(editableStepCnt_);
1597 }
1598
1599 bool PatternEditorPanel::enterVolumeData(int key)
1600 {
1601 switch (key) {
1602 case Qt::Key_0: setStepVolume(0x0); return true;
1603 case Qt::Key_1: setStepVolume(0x1); return true;
1604 case Qt::Key_2: setStepVolume(0x2); return true;
1605 case Qt::Key_3: setStepVolume(0x3); return true;
1606 case Qt::Key_4: setStepVolume(0x4); return true;
1607 case Qt::Key_5: setStepVolume(0x5); return true;
1608 case Qt::Key_6: setStepVolume(0x6); return true;
1609 case Qt::Key_7: setStepVolume(0x7); return true;
1610 case Qt::Key_8: setStepVolume(0x8); return true;
1611 case Qt::Key_9: setStepVolume(0x9); return true;
1612 case Qt::Key_A: setStepVolume(0xa); return true;
1613 case Qt::Key_B: setStepVolume(0xb); return true;
1614 case Qt::Key_C: setStepVolume(0xc); return true;
1615 case Qt::Key_D: setStepVolume(0xd); return true;
1616 case Qt::Key_E: setStepVolume(0xe); return true;
1617 case Qt::Key_F: setStepVolume(0xf); return true;
1618 default: return false;
1619 }
1620 }
1621
1622 void PatternEditorPanel::setStepVolume(int volume)
1623 {
1624 int vol = bt_->setStepVolumeDigit(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step, volume, (entryCnt_ == 1));
1625 comStack_.lock()->push(new SetVolumeToStepQtCommand(this, curPos_, (entryCnt_ == 1)));
1626
1627 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !updateEntryCount())
1628 moveCursorToDown(editableStepCnt_);
1629
1630 emit volumeEntered(vol);
1631 }
1632
1633 bool PatternEditorPanel::enterEffectID(int key)
1634 {
1635 switch (key) {
1636 case Qt::Key_0: setStepEffectID("0"); return true;
1637 case Qt::Key_1: setStepEffectID("1"); return true;
1638 case Qt::Key_2: setStepEffectID("2"); return true;
1639 case Qt::Key_3: setStepEffectID("3"); return true;
1640 case Qt::Key_4: setStepEffectID("4"); return true;
1641 case Qt::Key_5: setStepEffectID("5"); return true;
1642 case Qt::Key_6: setStepEffectID("6"); return true;
1643 case Qt::Key_7: setStepEffectID("7"); return true;
1644 case Qt::Key_8: setStepEffectID("8"); return true;
1645 case Qt::Key_9: setStepEffectID("9"); return true;
1646 case Qt::Key_A: setStepEffectID("A"); return true;
1647 case Qt::Key_B: setStepEffectID("B"); return true;
1648 case Qt::Key_C: setStepEffectID("C"); return true;
1649 case Qt::Key_D: setStepEffectID("D"); return true;
1650 case Qt::Key_E: setStepEffectID("E"); return true;
1651 case Qt::Key_F: setStepEffectID("F"); return true;
1652 case Qt::Key_G: setStepEffectID("G"); return true;
1653 case Qt::Key_H: setStepEffectID("H"); return true;
1654 case Qt::Key_I: setStepEffectID("I"); return true;
1655 case Qt::Key_J: setStepEffectID("J"); return true;
1656 case Qt::Key_K: setStepEffectID("K"); return true;
1657 case Qt::Key_L: setStepEffectID("L"); return true;
1658 case Qt::Key_M: setStepEffectID("M"); return true;
1659 case Qt::Key_N: setStepEffectID("N"); return true;
1660 case Qt::Key_O: setStepEffectID("O"); return true;
1661 case Qt::Key_P: setStepEffectID("P"); return true;
1662 case Qt::Key_Q: setStepEffectID("Q"); return true;
1663 case Qt::Key_R: setStepEffectID("R"); return true;
1664 case Qt::Key_S: setStepEffectID("S"); return true;
1665 case Qt::Key_T: setStepEffectID("T"); return true;
1666 case Qt::Key_U: setStepEffectID("U"); return true;
1667 case Qt::Key_V: setStepEffectID("V"); return true;
1668 case Qt::Key_W: setStepEffectID("W"); return true;
1669 case Qt::Key_X: setStepEffectID("X"); return true;
1670 case Qt::Key_Y: setStepEffectID("Y"); return true;
1671 case Qt::Key_Z: setStepEffectID("Z"); return true;
1672 default: return false;
1673 }
1674 }
1675
1676 void PatternEditorPanel::setStepEffectID(QString str)
1677 {
1678 int curTrackNum = visTracks_.at(curPos_.trackVisIdx);
1679 bt_->setStepEffectIDCharacter(curSongNum_, curTrackNum, curPos_.order, curPos_.step,
1680 (curPos_.colInTrack - 3) / 2, str.toStdString(),
1681 config_->getFill00ToEffectValue(), (entryCnt_ == 1));
1682 comStack_.lock()->push(new SetEffectIDToStepQtCommand(this, curPos_, (entryCnt_ == 1)));
1683
1684 PatternPosition editPos = curPos_;
1685
1686 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !updateEntryCount()) {
1687 if (config_->getMoveCursorToRight()) moveCursorToRight(1);
1688 else moveCursorToDown(editableStepCnt_);
1689 }
1690
1691 // Send effect description
1692 std::string id = bt_->getStepEffectID(curSongNum_, visTracks_.at(editPos.trackVisIdx), editPos.order,
1693 editPos.step, (editPos.colInTrack - 3) / 2);
1694 SoundSource src = songStyle_.trackAttribs.at(static_cast<size_t>(curTrackNum)).source;
1695 emit effectEntered(effect_desc::getEffectFormatAndDetailString(effect_utils::validateEffectId(src, id)));
1696 }
1697
1698 bool PatternEditorPanel::enterEffectValue(int key)
1699 {
1700 switch (key) {
1701 case Qt::Key_0: setStepEffectValue(0x0); return true;
1702 case Qt::Key_1: setStepEffectValue(0x1); return true;
1703 case Qt::Key_2: setStepEffectValue(0x2); return true;
1704 case Qt::Key_3: setStepEffectValue(0x3); return true;
1705 case Qt::Key_4: setStepEffectValue(0x4); return true;
1706 case Qt::Key_5: setStepEffectValue(0x5); return true;
1707 case Qt::Key_6: setStepEffectValue(0x6); return true;
1708 case Qt::Key_7: setStepEffectValue(0x7); return true;
1709 case Qt::Key_8: setStepEffectValue(0x8); return true;
1710 case Qt::Key_9: setStepEffectValue(0x9); return true;
1711 case Qt::Key_A: setStepEffectValue(0xa); return true;
1712 case Qt::Key_B: setStepEffectValue(0xb); return true;
1713 case Qt::Key_C: setStepEffectValue(0xc); return true;
1714 case Qt::Key_D: setStepEffectValue(0xd); return true;
1715 case Qt::Key_E: setStepEffectValue(0xe); return true;
1716 case Qt::Key_F: setStepEffectValue(0xf); return true;
1717 default: return false;
1718 }
1719 }
1720
1721 void PatternEditorPanel::setStepEffectValue(int value)
1722 {
1723 int trackNum = visTracks_.at(curPos_.trackVisIdx);
1724 int n = (curPos_.colInTrack - 4) / 2;
1725 EffectDisplayControl ctrl = EffectDisplayControl::Unset;
1726 SoundSource src = songStyle_.trackAttribs[static_cast<size_t>(trackNum)].source;
1727 switch (effect_utils::validateEffectId(
1728 src,
1729 bt_->getStepEffectID(curSongNum_, trackNum, curPos_.order, curPos_.step, n))) {
1730 case EffectType::VolumeDelay:
1731 if (src == SoundSource::FM && config_->getReverseFMVolumeOrder())
1732 ctrl = EffectDisplayControl::ReverseFMVolumeDelay;
1733 break;
1734 case EffectType::Brightness:
1735 if (config_->getReverseFMVolumeOrder()) ctrl = EffectDisplayControl::ReverseFMBrightness;
1736 break;
1737 default:
1738 break;
1739 }
1740 bt_->setStepEffectValueDigit(curSongNum_, trackNum, curPos_.order, curPos_.step, n, value, ctrl, (entryCnt_ == 1));
1741 comStack_.lock()->push(new SetEffectValueToStepQtCommand(this, curPos_, (entryCnt_ == 1)));
1742
1743 if ((!bt_->isPlaySong() || !bt_->isFollowPlay()) && !updateEntryCount()) {
1744 if (config_->getMoveCursorToRight()) moveCursorToRight(1);
1745 else moveCursorToDown(editableStepCnt_);
1746 }
1747 }
1748
1749 void PatternEditorPanel::insertStep()
1750 {
1751 bt_->insertStep(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
1752 comStack_.lock()->push(new InsertStepQtCommand(this));
1753 }
1754
1755 void PatternEditorPanel::deletePreviousStep()
1756 {
1757 if (curPos_.step) {
1758 bt_->deletePreviousStep(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
1759 comStack_.lock()->push(new DeletePreviousStepQtCommand(this));
1760 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(-1);
1761 }
1762 }
1763
1764 void PatternEditorPanel::copySelectedCells()
1765 {
1766 if (selLeftAbovePos_.order == -1) return;
1767
1768 int r = visTracks_.at(selRightBelowPos_.trackVisIdx) * 11 + selRightBelowPos_.colInTrack;
1769 int l = visTracks_.at(selLeftAbovePos_.trackVisIdx) * 11 + selLeftAbovePos_.colInTrack;
1770 int w = 1 + r - l; // Real selected region width
1771 int h = 1 + calculateStepDistance(selLeftAbovePos_.order, selLeftAbovePos_.step,
1772 selRightBelowPos_.order, selRightBelowPos_.step);
1773 QString str = QString("PATTERN_COPY:%1,%2,%3,").arg(selLeftAbovePos_.colInTrack).arg(w).arg(h);
1774 // NOTE: pos.trackVisIdx, endPos.trackVisIdx indecates a real track number.
1775 PatternPosition pos = {
1776 visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
1777 selLeftAbovePos_.order, selLeftAbovePos_.step
1778 };
1779 const PatternPosition endPos = {
1780 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack,
1781 selRightBelowPos_.order, selRightBelowPos_.step
1782 };
1783 while (true) {
1784 switch (pos.colInTrack) {
1785 case 0:
1786 str += QString::number(bt_->getStepNoteNumber(curSongNum_, pos.trackVisIdx, pos.order, pos.step));
1787 break;
1788 case 1:
1789 str += QString::number(bt_->getStepInstrument(curSongNum_, pos.trackVisIdx, pos.order, pos.step));
1790 break;
1791 case 2:
1792 str += QString::number(bt_->getStepVolume(curSongNum_, pos.trackVisIdx, pos.order, pos.step));
1793 break;
1794 case 3:
1795 str += QString::fromStdString(bt_->getStepEffectID(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 0));
1796 break;
1797 case 4:
1798 str += QString::number(bt_->getStepEffectValue(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 0));
1799 break;
1800 case 5:
1801 str += QString::fromStdString(bt_->getStepEffectID(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 1));
1802 break;
1803 case 6:
1804 str += QString::number(bt_->getStepEffectValue(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 1));
1805 break;
1806 case 7:
1807 str += QString::fromStdString(bt_->getStepEffectID(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 2));
1808 break;
1809 case 8:
1810 str += QString::number(bt_->getStepEffectValue(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 2));
1811 break;
1812 case 9:
1813 str += QString::fromStdString(bt_->getStepEffectID(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 3));
1814 break;
1815 case 10:
1816 str += QString::number(bt_->getStepEffectValue(curSongNum_, pos.trackVisIdx, pos.order, pos.step, 3));
1817 break;
1818 }
1819
1820 if (pos.isEqualCols(endPos)) {
1821 if (pos.isEqualRows(endPos)) {
1822 break;
1823 }
1824 else {
1825 pos.setCols(visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack);
1826 ++pos.step;
1827 }
1828 }
1829 else {
1830 ++pos.colInTrack;
1831 pos.trackVisIdx += (pos.colInTrack / 11);
1832 pos.colInTrack %= 11;
1833 }
1834
1835 str += ",";
1836 }
1837
1838 QApplication::clipboard()->setText(str);
1839 }
1840
1841 void PatternEditorPanel::eraseSelectedCells()
1842 {
1843 if (!bt_->erasePatternCells(curSongNum_, visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
1844 selLeftAbovePos_.order, selLeftAbovePos_.step,
1845 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack, selRightBelowPos_.step)) {
1846 command_result_message_box::showCommandInvokingErrorMessageBox(window());
1847 }
1848 comStack_.lock()->push(new EraseCellsInPatternQtCommand(this));
1849 }
1850
1851 namespace
1852 {
1853 std::optional <std::pair<int, Vector2d<std::string>>> decodeTextForPatternPasting(const QString& decodedText)
1854 {
1855 static const QRegularExpression COMMAND_REGEX {
1856 R"(^PATTERN_(COPY|CUT):(?<startCol>\d+),(?<width>\d+),(?<height>\d+),(?<data>.+)$)"
1857 };
1858 const auto match = COMMAND_REGEX.match(decodedText);
1859 if (!match.hasMatch()) return std::nullopt;
1860
1861 bool isOk{};
1862 int startCol = match.captured("startCol").toInt(&isOk);
1863 if (!isOk || startCol < 0 || Step::N_COLUMN <= startCol) return std::nullopt;
1864
1865 std::size_t w = match.captured("width").toUInt();
1866 std::size_t h = match.captured("height").toUInt();
1867 if (w == 0 || h == 0) return std::nullopt;
1868
1869 QStringList data = match.captured("data").split(",");
1870 auto unmodifiedSize = data.size();
1871 data.removeAll("");
1872 if (static_cast<std::size_t>(data.size()) != w * h || data.size() != unmodifiedSize) {
1873 return std::nullopt;
1874 }
1875
1876 Vector2d<std::string> cells(h, w);
1877 for (std::size_t i = 0; i < h; ++i) {
1878 for (std::size_t j = 0; j < w; ++j) {
1879 cells[i][j] = data[i * w + j].toStdString();
1880 }
1881 }
1882
1883 return std::make_pair(startCol, std::move(cells));
1884 }
1885 }
1886
1887 void PatternEditorPanel::pasteCopiedCells(const PatternPosition& cursorPos)
1888 {
1889 bool result = [&] {
1890 const auto decoded = decodeTextForPatternPasting(QApplication::clipboard()->text());
1891 if (!decoded.has_value()) return false;
1892 auto [sCol, cells] = decoded.value();
1893
1894 PatternPosition pos = getPasteLeftAbovePosition(sCol, cursorPos, cells.columnSize());
1895 if (config_->getPasteMode() == Configuration::PasteMode::Fill && selLeftAbovePos_.order != -1) {
1896 cells = makeCopiedCellsForPasteFull(pos, cells);
1897 }
1898
1899 bool overflow = config_->getOverflowPaste();
1900 if (!bt_->pastePatternCells(
1901 curSongNum_, visTracks_.at(pos.trackVisIdx), pos.colInTrack,
1902 pos.order, pos.step, cells, overflow)) {
1903 return false;
1904 }
1905 comStack_.lock()->push(new PasteCopiedDataToPatternQtCommand(this));
1906
1907 return true;
1908 }();
1909
1910 if (!result) command_result_message_box::showCommandInvokingErrorMessageBox(window());
1911 }
1912
1913 void PatternEditorPanel::pasteMixCopiedCells(const PatternPosition& cursorPos)
1914 {
1915 bool result = [&] {
1916 const auto decoded = decodeTextForPatternPasting(QApplication::clipboard()->text());
1917 if (!decoded.has_value()) return false;
1918 auto [sCol, cells] = decoded.value();
1919
1920 PatternPosition pos = getPasteLeftAbovePosition(sCol, cursorPos, cells.columnSize());
1921 if (config_->getPasteMode() == Configuration::PasteMode::Fill && selLeftAbovePos_.order != -1) {
1922 cells = makeCopiedCellsForPasteFull(pos, cells);
1923 }
1924
1925 bool overflow = config_->getOverflowPaste();
1926 if (!bt_->pasteMixPatternCells(
1927 curSongNum_, visTracks_.at(pos.trackVisIdx), pos.colInTrack,
1928 pos.order, pos.step, cells, overflow)) {
1929 return false;
1930 }
1931 comStack_.lock()->push(new PasteMixCopiedDataToPatternQtCommand(this));
1932
1933 return true;
1934 }();
1935
1936 if (!result) command_result_message_box::showCommandInvokingErrorMessageBox(window());
1937 }
1938
1939 void PatternEditorPanel::pasteOverwriteCopiedCells(const PatternPosition& cursorPos)
1940 {
1941 bool result = [&] {
1942 const auto decoded = decodeTextForPatternPasting(QApplication::clipboard()->text());
1943 if (!decoded.has_value()) return false;
1944 auto [sCol, cells] = decoded.value();
1945
1946
1947 PatternPosition pos = getPasteLeftAbovePosition(sCol, cursorPos, cells.columnSize());
1948 if (config_->getPasteMode() == Configuration::PasteMode::Fill && selLeftAbovePos_.order != -1) {
1949 cells = makeCopiedCellsForPasteFull(pos, cells);
1950 }
1951
1952 bool overflow = config_->getOverflowPaste();
1953 if (!bt_->pasteOverwritePatternCells(
1954 curSongNum_, visTracks_.at(pos.trackVisIdx), pos.colInTrack,
1955 pos.order, pos.step, cells, overflow)) {
1956 return false;
1957 }
1958 comStack_.lock()->push(new PasteOverwriteCopiedDataToPatternQtCommand(this));
1959
1960 return true;
1961 }();
1962
1963 if (!result) command_result_message_box::showCommandInvokingErrorMessageBox(window());
1964 }
1965
1966 void PatternEditorPanel::pasteInsertCopiedCells(const PatternPosition& cursorPos)
1967 {
1968 bool result = [&] {
1969 const auto decoded = decodeTextForPatternPasting(QApplication::clipboard()->text());
1970 if (!decoded.has_value()) return false;
1971 auto [sCol, cells] = decoded.value();
1972
1973 PatternPosition pos = getPasteLeftAbovePosition(sCol, cursorPos, cells.columnSize());
1974 if (config_->getPasteMode() == Configuration::PasteMode::Fill && selLeftAbovePos_.order != -1) {
1975 cells = makeCopiedCellsForPasteFull(pos, cells);
1976 }
1977
1978 if (!bt_->pasteInsertPatternCells(
1979 curSongNum_, visTracks_.at(pos.trackVisIdx), pos.colInTrack, pos.order, pos.step, cells)) {
1980 return false;
1981 }
1982 comStack_.lock()->push(new PasteInsertCopiedDataToPatternQtCommand(this));
1983
1984 return true;
1985 }();
1986
1987 if (!result) command_result_message_box::showCommandInvokingErrorMessageBox(window());
1988 }
1989
1990 PatternPosition PatternEditorPanel::getPasteLeftAbovePosition(
1991 int pasteCol, const PatternPosition& cursorPos, size_t cellW) const
1992 {
1993 PatternPosition pos;
1994 Configuration::PasteMode mode = config_->getPasteMode();
1995 if ((mode == Configuration::PasteMode::Selection || mode == Configuration::PasteMode::Fill)
1996 && selLeftAbovePos_.colInTrack != -1) {
1997 pos = selLeftAbovePos_;
1998 pos.colInTrack = pasteCol;
1999 }
2000 else {
2001 pos = cursorPos;
2002 if (pasteCol < 3 || (pos.colInTrack - pasteCol) % 2
2003 || (Step::N_COLUMN - pos.colInTrack) < static_cast<int>(cellW)) {
2004 pos.colInTrack = pasteCol;
2005 }
2006 }
2007
2008 return pos;
2009 }
2010
2011 void PatternEditorPanel::cutSelectedCells()
2012 {
2013 if (selLeftAbovePos_.order == -1) return;
2014
2015 copySelectedCells();
2016 eraseSelectedCells();
2017 QString str = QApplication::clipboard()->text();
2018 str.replace("COPY", "CUT");
2019 QApplication::clipboard()->setText(str);
2020 }
2021
2022 Vector2d<std::string> PatternEditorPanel::makeCopiedCellsForPasteFull(
2023 const PatternPosition& laPos, const Vector2d<std::string>& cells)
2024 {
2025 int ow = cells.columnSize();
2026 int oh = cells.rowSize();
2027 int l = laPos.trackVisIdx * Step::N_COLUMN + laPos.colInTrack;
2028 int r = selRightBelowPos_.trackVisIdx * Step::N_COLUMN + selRightBelowPos_.colInTrack;
2029 int w = r - l + 1; // Real selected region width
2030 auto h = static_cast<std::size_t>(
2031 calculateStepDistance(laPos.order, laPos.step,
2032 selRightBelowPos_.order, selRightBelowPos_.step) + 1);
2033
2034 int bw = ((ow - 1) / Step::N_COLUMN + 1) * Step::N_COLUMN;
2035 std::size_t padSize = bw - ow;
2036 int lc = (laPos.colInTrack + ow) % Step::N_COLUMN;
2037
2038 std::vector<std::string> pad(padSize);
2039 for (std::size_t i = 0; i < padSize; ++i) {
2040 switch (lc) {
2041 case 3:
2042 case 5:
2043 case 7:
2044 case 9:
2045 pad[i] = "--";
2046 break;
2047 default:
2048 pad[i] = "-1";
2049 break;
2050 }
2051 lc = (lc + 1) % Step::N_COLUMN;
2052 }
2053
2054 Vector2d<std::string> newCells(h, w);
2055 for (std::size_t i = 0; i < h; ++i) {
2056 auto rowBeginIt = newCells[i].begin();
2057 for (int dw = w, p = 0; dw > 0; dw -= bw, p += bw) {
2058 int ws = std::min(ow, dw);
2059 std::copy_n(cells.at(i % oh).begin(), ws, rowBeginIt + p);
2060 std::copy_n(pad.begin(), std::min(dw - ws, static_cast<int>(padSize)), rowBeginIt + p + ws);
2061 }
2062 }
2063
2064 return newCells;
2065 }
2066
2067 void PatternEditorPanel::transposeNote(const PatternPosition& startPos, const PatternPosition& endPos, int semitone)
2068 {
2069 int beginTrackIdx = (startPos.colInTrack == 0) ? startPos.trackVisIdx : startPos.trackVisIdx + 1;
2070 if (beginTrackIdx <= endPos.trackVisIdx) {
2071 bt_->transposeNoteInPattern(curSongNum_, visTracks_.at(beginTrackIdx), startPos.order, startPos.step,
2072 visTracks_.at(endPos.trackVisIdx), endPos.step, semitone);
2073 comStack_.lock()->push(new TransposeNoteInPatternQtCommand(this));
2074 }
2075 }
2076
2077 void PatternEditorPanel::changeValuesInPattern(const PatternPosition& startPos, const PatternPosition& endPos, int value)
2078 {
2079 if (startPos.compareCols(endPos) <= 0) {
2080 bt_->changeValuesInPattern(curSongNum_, visTracks_.at(startPos.trackVisIdx), startPos.colInTrack, startPos.order, startPos.step,
2081 visTracks_.at(endPos.trackVisIdx), endPos.colInTrack, endPos.step, value);
2082 comStack_.lock()->push(new ChangeValuesInPatternQtCommand(this));
2083 }
2084 }
2085
2086 void PatternEditorPanel::toggleTrack(int trackIdx)
2087 {
2088 int trackNum = visTracks_.at(trackIdx);
2089 bt_->setTrackMuteState(trackNum, !bt_->isMute(trackNum));
2090 isMuteElse_ = false;
2091 redrawByMaskChanged();
2092 }
2093
2094 void PatternEditorPanel::soloTrack(int trackIdx)
2095 {
2096 int soloTrackNum = visTracks_.at(trackIdx);
2097 int trackCnt = static_cast<int>(songStyle_.trackAttribs.size());
2098 if (isMuteElse_) {
2099 if (bt_->isMute(soloTrackNum)) {
2100 for (int t = 0; t < trackCnt; ++t)
2101 bt_->setTrackMuteState(t, t != soloTrackNum);
2102 }
2103 else {
2104 isMuteElse_ = false;
2105 for (int t = 0; t < trackCnt; ++t)
2106 bt_->setTrackMuteState(t, false);
2107 }
2108 }
2109 else {
2110 isMuteElse_ = true;
2111 for (int t = 0; t < trackCnt; ++t)
2112 bt_->setTrackMuteState(t, (t == soloTrackNum) ? false : isMuteElse_);
2113 }
2114 redrawByMaskChanged();
2115 }
2116
2117 void PatternEditorPanel::setSelectedRectangle(const PatternPosition& start, const PatternPosition& end)
2118 {
2119 int patMax = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, end.order)) - 1;
2120 if (start.compareCols(end) > 0) {
2121 if (start.step > end.step) {
2122 selLeftAbovePos_ = end;
2123 selRightBelowPos_ = {
2124 start.trackVisIdx, start.colInTrack,
2125 end.order, (start.step > patMax) ? patMax : start.step
2126 };
2127 }
2128 else {
2129 selLeftAbovePos_ = { end.trackVisIdx, end.colInTrack, end.order, start.step };
2130 selRightBelowPos_ = { start.trackVisIdx, start.colInTrack, end.order, end.step };
2131 }
2132 }
2133 else {
2134 if (start.step > end.step) {
2135 selLeftAbovePos_ = { start.trackVisIdx, start.colInTrack, end.order, end.step };
2136 selRightBelowPos_ = {
2137 end.trackVisIdx, end.colInTrack,
2138 end.order, (start.step > patMax) ? patMax : start.step
2139 };
2140 }
2141 else {
2142 selLeftAbovePos_ = { start.trackVisIdx, start.colInTrack, end.order, start.step };
2143 selRightBelowPos_ = end;
2144 }
2145 }
2146
2147 emit selected(true);
2148
2149 backChanged_ = true;
2150 repaint();
2151 }
2152
2153 bool PatternEditorPanel::isSelectedCell(int trackVisIdx, int colNum, int orderNum, int stepNum)
2154 {
2155 PatternPosition pos{ trackVisIdx, colNum, orderNum, stepNum };
2156 return (selLeftAbovePos_.compareCols(pos) <= 0 && selRightBelowPos_.compareCols(pos) >= 0
2157 && selLeftAbovePos_.compareRows(pos) <= 0 && selRightBelowPos_.compareRows(pos) >= 0);
2158 }
2159
2160 void PatternEditorPanel::showPatternContextMenu(const PatternPosition& pos, const QPoint& point)
2161 {
2162 QMenu menu;
2163 // Leave Before Qt5.7.0 style due to windows xp
2164 QAction* undo = menu.addAction(tr("&Undo"));
2165 undo->setIcon(QIcon(":/icon/undo"));
2166 QObject::connect(undo, &QAction::triggered, this, [&]() {
2167 if (!bt_->undo()) {
2168 command_result_message_box::showCommandUndoingErrorMessageBox(this->window());
2169 return;
2170 }
2171 comStack_.lock()->undo();
2172 });
2173 QAction* redo = menu.addAction(tr("&Redo"));
2174 redo->setIcon(QIcon(":/icon/redo"));
2175 QObject::connect(redo, &QAction::triggered, this, [&]() {
2176 if (!bt_->redo()) {
2177 command_result_message_box::showCommandRedoingErrorMessageBox(this->window());
2178 return;
2179 }
2180 comStack_.lock()->redo();
2181 });
2182 menu.addSeparator();
2183 QAction* copy = menu.addAction(tr("&Copy"));
2184 copy->setIcon(QIcon(":/icon/copy"));
2185 QObject::connect(copy, &QAction::triggered, this, &PatternEditorPanel::copySelectedCells);
2186 QAction* cut = menu.addAction(tr("Cu&t"));
2187 cut->setIcon(QIcon(":/icon/cut"));
2188 QObject::connect(cut, &QAction::triggered, this, &PatternEditorPanel::cutSelectedCells);
2189 QAction* paste = menu.addAction(tr("&Paste"));
2190 paste->setIcon(QIcon(":/icon/paste"));
2191 QObject::connect(paste, &QAction::triggered, this, [&]() { pasteCopiedCells(pos); });
2192 auto pasteSp = new QMenu(tr("Paste Specia&l"));
2193 menu.addMenu(pasteSp);
2194 QAction* pasteMix = pasteSp->addAction(tr("&Mix"));
2195 QObject::connect(pasteMix, &QAction::triggered, this, [&]() { pasteMixCopiedCells(pos); });
2196 QAction* pasteOver = pasteSp->addAction(tr("&Overwrite"));
2197 QObject::connect(pasteOver, &QAction::triggered, this, [&]() { pasteOverwriteCopiedCells(pos); });
2198 QAction* pasteIns = pasteSp->addAction(tr("&Insert"));
2199 QObject::connect(pasteIns, &QAction::triggered, this, [&]() { pasteInsertCopiedCells(pos); });
2200 QAction* erase = menu.addAction(tr("&Erase"));
2201 QObject::connect(erase, &QAction::triggered, this, &PatternEditorPanel::eraseSelectedCells);
2202 QAction* select = menu.addAction(tr("Select &All"));
2203 QObject::connect(select, &QAction::triggered, this, [&]() { onSelectPressed(1); });
2204 menu.addSeparator();
2205 auto pattern = new QMenu(tr("Patter&n"));
2206 menu.addMenu(pattern);
2207 QAction* interpolate = pattern->addAction(tr("&Interpolate"));
2208 QObject::connect(interpolate, &QAction::triggered, this, &PatternEditorPanel::onInterpolatePressed);
2209 QAction* reverse = pattern->addAction(tr("&Reverse"));
2210 QObject::connect(reverse, &QAction::triggered, this, &PatternEditorPanel::onReversePressed);
2211 QAction* replace = pattern->addAction(tr("R&eplace Instrument"));
2212 QObject::connect(replace, &QAction::triggered, this, &PatternEditorPanel::onReplaceInstrumentPressed);
2213 pattern->addSeparator();
2214 QAction* expand = pattern->addAction(tr("E&xpand"));
2215 QObject::connect(expand, &QAction::triggered, this, &PatternEditorPanel::onExpandPressed);
2216 QAction* shrink = pattern->addAction(tr("S&hrink"));
2217 QObject::connect(shrink, &QAction::triggered, this, &PatternEditorPanel::onShrinkPressed);
2218 pattern->addSeparator();
2219 auto transpose = new QMenu(tr("&Transpose"));
2220 pattern->addMenu(transpose);
2221 QAction* deNote = transpose->addAction(tr("&Decrease Note"));
2222 QObject::connect(deNote, &QAction::triggered, this, [&]() { onNoteTransposePressed(-1); });
2223 QAction* inNote = transpose->addAction(tr("&Increase Note"));
2224 QObject::connect(inNote, &QAction::triggered, this, [&]() { onNoteTransposePressed(1); });
2225 QAction* deOct = transpose->addAction(tr("D&ecrease Octave"));
2226 QObject::connect(deOct, &QAction::triggered, this, [&]() { onNoteTransposePressed(-12); });
2227 QAction* inOct = transpose->addAction(tr("I&ncrease Octave"));
2228 QObject::connect(inOct, &QAction::triggered, this, [&]() { onNoteTransposePressed(12); });
2229 auto changeVals = new QMenu(tr("&Change Values"));
2230 pattern->addMenu(changeVals);
2231 QAction* fdeVal = changeVals->addAction(tr("Fine &Decrease Values"));
2232 QObject::connect(fdeVal, &QAction::triggered, this, [&]() { onChangeValuesPressed(-1); });
2233 QAction* finVal = changeVals->addAction(tr("Fine &Increase Values"));
2234 QObject::connect(finVal, &QAction::triggered, this, [&]() { onChangeValuesPressed(1); });
2235 QAction* cdeVal = changeVals->addAction(tr("Coarse D&ecrease Values"));
2236 QObject::connect(cdeVal, &QAction::triggered, this, [&]() { onChangeValuesPressed(-16); });
2237 QAction* cinVal = changeVals->addAction(tr("Coarse I&ncrease Values"));
2238 QObject::connect(cinVal, &QAction::triggered, this, [&]() { onChangeValuesPressed(16); });
2239 menu.addSeparator();
2240 QAction* toggle = menu.addAction(tr("To&ggle Track"));
2241 QObject::connect(toggle, &QAction::triggered, this, [&] { toggleTrack(pos.trackVisIdx); });
2242 QAction* solo = menu.addAction(tr("&Solo Track"));
2243 QObject::connect(solo, &QAction::triggered, this, [&] { soloTrack(pos.trackVisIdx); });
2244 menu.addSeparator();
2245 QAction* exeff = menu.addAction(tr("Expand E&ffect Column"));
2246 QObject::connect(exeff, &QAction::triggered, this, [&] { onExpandEffectColumnPressed(pos.trackVisIdx); });
2247 QAction* sheff = menu.addAction(tr("Shrin&k Effect Column"));
2248 QObject::connect(sheff, &QAction::triggered, this, [&] { onShrinkEffectColumnPressed(pos.trackVisIdx); });
2249 #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
2250 undo->setShortcutVisibleInContextMenu(true);
2251 redo->setShortcutVisibleInContextMenu(true);
2252 copy->setShortcutVisibleInContextMenu(true);
2253 cut->setShortcutVisibleInContextMenu(true);
2254 paste->setShortcutVisibleInContextMenu(true);
2255 pasteMix->setShortcutVisibleInContextMenu(true);
2256 erase->setShortcutVisibleInContextMenu(true);
2257 select->setShortcutVisibleInContextMenu(true);
2258 interpolate->setShortcutVisibleInContextMenu(true);
2259 reverse->setShortcutVisibleInContextMenu(true);
2260 replace->setShortcutVisibleInContextMenu(true);
2261 deNote->setShortcutVisibleInContextMenu(true);
2262 inNote->setShortcutVisibleInContextMenu(true);
2263 deOct->setShortcutVisibleInContextMenu(true);
2264 inOct->setShortcutVisibleInContextMenu(true);
2265 fdeVal->setShortcutVisibleInContextMenu(true);
2266 finVal->setShortcutVisibleInContextMenu(true);
2267 cdeVal->setShortcutVisibleInContextMenu(true);
2268 cinVal->setShortcutVisibleInContextMenu(true);
2269 toggle->setShortcutVisibleInContextMenu(true);
2270 solo->setShortcutVisibleInContextMenu(true);
2271 exeff->setShortcutVisibleInContextMenu(true);
2272 sheff->setShortcutVisibleInContextMenu(true);
2273 #endif
2274 auto shortcuts = config_->getShortcuts();
2275 undo->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Z));
2276 redo->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Y));
2277 undo->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Z));
2278 copy->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C));
2279 cut->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X));
2280 paste->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_V));
2281 pasteMix->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteMix)));
2282 pasteOver->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteOverwrite)));
2283 pasteIns->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteInsert)));
2284 erase->setShortcut(QKeySequence(Qt::Key_Delete));
2285 select->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectAll)));
2286 interpolate->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Interpolate)));
2287 reverse->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Reverse)));
2288 replace->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ReplaceInstrument)));
2289 expand->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ExpandPattern)));
2290 shrink->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ShrinkPattern)));
2291 deNote->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreaseNote)));
2292 inNote->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreaseNote)));
2293 deOct->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreaseOctave)));
2294 inOct->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreaseOctave)));
2295 fdeVal->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FineDecreaseValues)));
2296 finVal->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FineIncreaseValues)));
2297 cdeVal->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::CoarseDecreaseValues)));
2298 cinVal->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::CoarseIncreaseValuse)));
2299 toggle->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ToggleTrack)));
2300 solo->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SoloTrack)));
2301 exeff->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ExpandEffect)));
2302 sheff->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ShrinkEffect)));
2303
2304 if (bt_->isJamMode() || pos.order < 0 || pos.trackVisIdx < 0) {
2305 copy->setEnabled(false);
2306 cut->setEnabled(false);
2307 paste->setEnabled(false);
2308 pasteMix->setEnabled(false);
2309 pasteOver->setEnabled(false);
2310 pasteIns->setEnabled(false);
2311 erase->setEnabled(false);
2312 interpolate->setEnabled(false);
2313 reverse->setEnabled(false);
2314 replace->setEnabled(false);
2315 expand->setEnabled(false);
2316 shrink->setEnabled(false);
2317 deNote->setEnabled(false);
2318 inNote->setEnabled(false);
2319 deOct->setEnabled(false);
2320 inOct->setEnabled(false);
2321 fdeVal->setEnabled(false);
2322 finVal->setEnabled(false);
2323 cdeVal->setEnabled(false);
2324 cinVal->setEnabled(false);
2325 }
2326 else {
2327 QString clipText = QApplication::clipboard()->text();
2328 if (!clipText.startsWith("PATTERN_COPY") && !clipText.startsWith("PATTERN_CUT")) {
2329 paste->setEnabled(false);
2330 pasteMix->setEnabled(false);
2331 pasteOver->setEnabled(false);
2332 pasteIns->setEnabled(false);
2333 }
2334 if (selRightBelowPos_.order < 0
2335 || !isSelectedCell(pos.trackVisIdx, pos.colInTrack, pos.order, pos.step)) {
2336 copy->setEnabled(false);
2337 cut->setEnabled(false);
2338 erase->setEnabled(false);
2339 interpolate->setEnabled(false);
2340 reverse->setEnabled(false);
2341 replace->setEnabled(false);
2342 expand->setEnabled(false);
2343 shrink->setEnabled(false);
2344 deNote->setEnabled(false);
2345 inNote->setEnabled(false);
2346 deOct->setEnabled(false);
2347 inOct->setEnabled(false);
2348 fdeVal->setEnabled(false);
2349 finVal->setEnabled(false);
2350 cdeVal->setEnabled(false);
2351 cinVal->setEnabled(false);
2352 }
2353 }
2354 if (!comStack_.lock()->canUndo()) {
2355 undo->setEnabled(false);
2356 }
2357 if (!comStack_.lock()->canRedo()) {
2358 redo->setEnabled(false);
2359 }
2360 if (pos.trackVisIdx < 0) {
2361 toggle->setEnabled(false);
2362 solo->setEnabled(false);
2363 exeff->setEnabled(false);
2364 sheff->setEnabled(false);
2365 }
2366
2367 menu.exec(mapToGlobal(point));
2368 }
2369
2370 /********** Slots **********/
2371 void PatternEditorPanel::onHScrollBarChanged(int num)
2372 {
2373 Ui::EventGuard eg(isIgnoreToSlider_);
2374
2375 // Skip if position has already changed in panel
2376 if (config_->getMoveCursorByHorizontalScroll()) {
2377 if (int dif = num - calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack))
2378 moveCursorToRight(dif);
2379 }
2380 else {
2381 if (int dif = num - leftTrackVisIdx_)
2382 moveViewToRight(dif);
2383 }
2384 }
2385
2386 void PatternEditorPanel::onVScrollBarChanged(int num)
2387 {
2388 Ui::EventGuard eg(isIgnoreToSlider_);
2389
2390 // Skip if position has already changed in panel
2391 if (int dif = num - curPos_.step) moveCursorToDown(dif);
2392 }
2393
2394 void PatternEditorPanel::onOrderListCurrentTrackChanged(int idx)
2395 {
2396 Ui::EventGuard eg(isIgnoreToOrder_);
2397
2398 int dif = calculateColumnDistance(curPos_.trackVisIdx, curPos_.colInTrack, idx, 0);
2399 moveCursorToRight(dif);
2400 }
2401
2402 void PatternEditorPanel::onOrderListCurrentOrderChanged(int num)
2403 {
2404 Ui::EventGuard eg(isIgnoreToOrder_);
2405
2406 int step = std::min(curPos_.step, static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, num)) - 1);
2407 int dif = calculateStepDistance(curPos_.order, curPos_.step, num, step);
2408 moveCursorToDown(dif);
2409 }
2410
2411 void PatternEditorPanel::onOrderListEdited()
2412 {
2413 // Reset position memory
2414 hovPos_ = { -1, -1, -1, -1 };
2415 mousePressPos_ = { -1, -1, -1, -1 };
2416 mouseReleasePos_ = { -1, -1, -1, -1 };
2417 selLeftAbovePos_ = { -1, -1, -1, -1 };
2418 selRightBelowPos_ = { -1, -1, -1, -1 };
2419 shiftPressedPos_ = { -1, -1, -1, -1 };
2420 selectAllState_ = -1;
2421 emit selected(false);
2422
2423 redrawByPatternChanged(true);
2424 }
2425
2426 void PatternEditorPanel::onDefaultPatternSizeChanged()
2427 {
2428 // Check pattern size
2429 int end = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order));
2430 if (curPos_.step >= end) curPos_.step = end - 1;
2431
2432 redrawByPatternChanged(true);
2433 }
2434
2435 void PatternEditorPanel::onShortcutUpdated()
2436 {
2437 auto shortcuts = config_->getShortcuts();
2438
2439 hlUpSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PrevHighlighted)));
2440 hlUpWSSc_.setKey(gui_utils::strToKeySeq("Shift+" + shortcuts.at(Configuration::ShortcutAction::PrevHighlighted)));
2441 hlDnSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::NextHighlighted)));
2442 hlDnWSSc_.setKey(gui_utils::strToKeySeq("Shift+" + shortcuts.at(Configuration::ShortcutAction::NextHighlighted)));
2443 keyOffSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::KeyOff)));
2444 keyCutSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::KeyCut)));
2445 echoBufSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::EchoBuffer)));
2446 expandColSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ExpandEffect)));
2447 shrinkColSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ShrinkEffect)));
2448 }
2449
2450 void PatternEditorPanel::setPatternHighlight1Count(int count)
2451 {
2452 hl1Cnt_ = count;
2453
2454 backChanged_ = true;
2455 textChanged_ = true;
2456 repaint();
2457 }
2458
2459 void PatternEditorPanel::setPatternHighlight2Count(int count)
2460 {
2461 hl2Cnt_ = count;
2462
2463 backChanged_ = true;
2464 textChanged_ = true;
2465 repaint();
2466 }
2467
2468 void PatternEditorPanel::setEditableStep(int n)
2469 {
2470 editableStepCnt_ = n;
2471 }
2472
2473 void PatternEditorPanel::onSongLoaded()
2474 {
2475 // NOTE: Temporary fix for https://github.com/BambooTracker/BambooTracker/issues/276
2476 isInitedFirstMod_.store(true);
2477
2478 // Initialize cursor position
2479 curSongNum_ = bt_->getCurrentSongNumber();
2480 SongType prevType = songStyle_.type;
2481 songStyle_ = bt_->getSongStyle(curSongNum_);
2482 visTracks_ = gui_utils::adaptVisibleTrackList(visTracks_, prevType, songStyle_.type);
2483 rightEffn_.resize(visTracks_.size());
2484 std::transform(visTracks_.begin(), visTracks_.end(), rightEffn_.begin(), [&](int t) {
2485 return static_cast<int>(bt_->getEffectDisplayWidth(curSongNum_, t));
2486 });
2487 curPos_ = {
2488 visTracks_.front(),
2489 0,
2490 bt_->getCurrentOrderNumber(),
2491 bt_->getCurrentStepNumber()
2492 };
2493 // Set cursor to the most lest-placed visible track
2494 if (visTracks_.front() != bt_->getCurrentTrackAttribute().number) {
2495 bt_->setCurrentTrack(visTracks_.front());
2496 }
2497 leftTrackVisIdx_ = 0;
2498 updateTracksWidthFromLeftToEnd();
2499
2500 hovPos_ = { -1, -1, -1, -1 };
2501 mousePressPos_ = { -1, -1, -1, -1 };
2502 mouseReleasePos_ = { -1, -1, -1, -1 };
2503 selLeftAbovePos_ = { -1, -1, -1, -1 };
2504 selRightBelowPos_ = { -1, -1, -1, -1 };
2505 shiftPressedPos_ = { -1, -1, -1, -1 };
2506 markerPos_ = { -1, -1, -1, -1 };
2507 entryCnt_ = 0;
2508 selectAllState_ = -1;
2509 emit selected(false);
2510
2511 redrawAll();
2512 }
2513
2514 void PatternEditorPanel::onDeletePressed()
2515 {
2516 if (bt_->isJamMode()) return;
2517
2518 if (selLeftAbovePos_.order != -1) { // Delete region
2519 eraseSelectedCells();
2520 }
2521 else {
2522 switch (curPos_.colInTrack) {
2523 case 0:
2524 bt_->eraseStepNote(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
2525 comStack_.lock()->push(new EraseStepQtCommand(this));
2526 break;
2527 case 1:
2528 bt_->eraseStepInstrument(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
2529 comStack_.lock()->push(new EraseInstrumentInStepQtCommand(this));
2530 break;
2531 case 2:
2532 bt_->eraseStepVolume(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step);
2533 comStack_.lock()->push(new EraseVolumeInStepQtCommand(this));
2534 break;
2535 case 3:
2536 case 5:
2537 case 7:
2538 case 9:
2539 bt_->eraseStepEffect(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step,
2540 (curPos_.colInTrack - 3) / 2);
2541 comStack_.lock()->push(new EraseEffectInStepQtCommand(this));
2542 break;
2543 case 4:
2544 case 6:
2545 case 8:
2546 case 10:
2547 bt_->eraseStepEffectValue(curSongNum_, visTracks_.at(curPos_.trackVisIdx), curPos_.order, curPos_.step,
2548 (curPos_.colInTrack - 4) / 2);
2549 comStack_.lock()->push(new EraseEffectValueInStepQtCommand(this));
2550 break;
2551 }
2552 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(editableStepCnt_);
2553 }
2554 }
2555
2556 void PatternEditorPanel::onPastePressed()
2557 {
2558 if (!bt_->isJamMode()) pasteCopiedCells(curPos_);
2559 }
2560
2561 void PatternEditorPanel::onPasteMixPressed()
2562 {
2563 if (!bt_->isJamMode()) pasteMixCopiedCells(curPos_);
2564 }
2565
2566 void PatternEditorPanel::onPasteOverwritePressed()
2567 {
2568 if (!bt_->isJamMode()) pasteOverwriteCopiedCells(curPos_);
2569 }
2570
2571 void PatternEditorPanel::onPasteInsertPressed()
2572 {
2573 if (!bt_->isJamMode()) pasteInsertCopiedCells(curPos_);
2574 }
2575
2576 void PatternEditorPanel::onSelectPressed(int type)
2577 {
2578 switch (type) {
2579 case 0: // None
2580 {
2581 selLeftAbovePos_ = { -1, -1, -1, -1 };
2582 selRightBelowPos_ = { -1, -1, -1, -1 };
2583 selectAllState_ = -1;
2584 emit selected(false);
2585 backChanged_ = true;
2586 repaint();
2587 break;
2588 }
2589 case 1: // All
2590 {
2591 selectAllState_ = (selectAllState_ + 1) % 2;
2592 int max = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)) - 1;
2593 PatternPosition start, end;
2594 if (selectAllState_) {
2595 start = { 0, 0, curPos_.order, 0 };
2596 end = { static_cast<int>(visTracks_.size() - 1), 10, curPos_.order, max };
2597 }
2598 else {
2599 start = { curPos_.trackVisIdx, 0, curPos_.order, 0 };
2600 end = { curPos_.trackVisIdx, 10, curPos_.order, max };
2601 }
2602 setSelectedRectangle(start, end);
2603 break;
2604 }
2605 case 2: // Row
2606 {
2607 selectAllState_ = -1;
2608 PatternPosition start = { 0, 0, curPos_.order, curPos_.step };
2609 PatternPosition end = { static_cast<int>(visTracks_.size() - 1), 10, curPos_.order, curPos_.step };
2610 setSelectedRectangle(start, end);
2611 break;
2612 }
2613 case 3: // Column
2614 {
2615 selectAllState_ = -1;
2616 PatternPosition start = { curPos_.trackVisIdx, curPos_.colInTrack, curPos_.order, 0 };
2617 PatternPosition end = {
2618 curPos_.trackVisIdx,
2619 curPos_.colInTrack,
2620 curPos_.order,
2621 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order) - 1)
2622 };
2623 setSelectedRectangle(start, end);
2624 break;
2625 }
2626 case 4: // Pattern
2627 {
2628 selectAllState_ = -1;
2629 PatternPosition start = { curPos_.trackVisIdx, 0, curPos_.order, 0 };
2630 PatternPosition end = {
2631 curPos_.trackVisIdx,
2632 10,
2633 curPos_.order,
2634 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order) - 1)
2635 };
2636 setSelectedRectangle(start, end);
2637 break;
2638 }
2639 case 5: // Order
2640 {
2641 selectAllState_ = -1;
2642 PatternPosition start = { 0, 0, curPos_.order, 0 };
2643 PatternPosition end = {
2644 static_cast<int>(visTracks_.size() - 1),
2645 10,
2646 curPos_.order,
2647 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order) - 1)
2648 };
2649 setSelectedRectangle(start, end);
2650 break;
2651 }
2652 }
2653 }
2654
2655 void PatternEditorPanel::onNoteTransposePressed(int semitone)
2656 {
2657 if (bt_->isJamMode()) return;
2658
2659 if (selLeftAbovePos_.order != -1)
2660 transposeNote(selLeftAbovePos_, selRightBelowPos_, semitone);
2661 else
2662 transposeNote(curPos_, curPos_, semitone);
2663 }
2664
2665 void PatternEditorPanel::onToggleTrackPressed()
2666 {
2667 toggleTrack(curPos_.trackVisIdx);
2668 }
2669
2670 void PatternEditorPanel::onSoloTrackPressed()
2671 {
2672 soloTrack(curPos_.trackVisIdx);
2673 }
2674
2675 void PatternEditorPanel::onUnmuteAllPressed()
2676 {
2677 int trackCnt = static_cast<int>(songStyle_.trackAttribs.size());
2678 for (int t = 0; t < trackCnt; ++t)
2679 bt_->setTrackMuteState(t, false);
2680 isMuteElse_ = false;
2681 redrawByMaskChanged();
2682 }
2683
2684 void PatternEditorPanel::onExpandPressed()
2685 {
2686 if (selLeftAbovePos_.order == -1) return;
2687
2688 bt_->expandPattern(curSongNum_, visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
2689 selLeftAbovePos_.order, selLeftAbovePos_.step,
2690 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack, selRightBelowPos_.step);
2691 comStack_.lock()->push(new ExpandPatternQtCommand(this));
2692 }
2693
2694 void PatternEditorPanel::onShrinkPressed()
2695 {
2696 if (selLeftAbovePos_.order == -1) return;
2697
2698 bt_->shrinkPattern(curSongNum_, visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
2699 selLeftAbovePos_.order, selLeftAbovePos_.step,
2700 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack, selRightBelowPos_.step);
2701 comStack_.lock()->push(new ShrinkPatternQtCommand(this));
2702 }
2703
2704 void PatternEditorPanel::onInterpolatePressed()
2705 {
2706 if (selLeftAbovePos_.order == -1) return;
2707
2708 bt_->interpolatePattern(curSongNum_, visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
2709 selLeftAbovePos_.order, selLeftAbovePos_.step,
2710 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack, selRightBelowPos_.step);
2711 comStack_.lock()->push(new InterpolatePatternQtCommand(this));
2712 }
2713
2714 void PatternEditorPanel::onReversePressed()
2715 {
2716 if (selLeftAbovePos_.order == -1) return;
2717
2718 bt_->reversePattern(curSongNum_, visTracks_.at(selLeftAbovePos_.trackVisIdx), selLeftAbovePos_.colInTrack,
2719 selLeftAbovePos_.order, selLeftAbovePos_.step,
2720 visTracks_.at(selRightBelowPos_.trackVisIdx), selRightBelowPos_.colInTrack, selRightBelowPos_.step);
2721 comStack_.lock()->push(new ReversePatternQtCommand(this));
2722 }
2723
2724 void PatternEditorPanel::onReplaceInstrumentPressed()
2725 {
2726 if (selLeftAbovePos_.order == -1) return;
2727
2728 int curInst = bt_->getCurrentInstrumentNumber();
2729 if (curInst == -1) return;
2730
2731 int beginTrackIdx = (selLeftAbovePos_.colInTrack < 2) ? selLeftAbovePos_.trackVisIdx : (selLeftAbovePos_.trackVisIdx + 1);
2732 int endTrackIdx = (selRightBelowPos_.colInTrack == 0) ? (selRightBelowPos_.trackVisIdx - 1) : selRightBelowPos_.trackVisIdx;
2733 if (beginTrackIdx <= endTrackIdx) {
2734 bt_->replaceInstrumentInPattern(curSongNum_,
2735 visTracks_.at(beginTrackIdx), selLeftAbovePos_.order, selLeftAbovePos_.step,
2736 visTracks_.at(endTrackIdx), selRightBelowPos_.step, curInst);
2737 comStack_.lock()->push(new ReplaceInstrumentInPatternQtCommand(this));
2738 }
2739 }
2740
2741 void PatternEditorPanel::onExpandEffectColumnPressed(int trackVisIdx)
2742 {
2743 size_t ti = static_cast<size_t>(trackVisIdx);
2744 if (rightEffn_.at(ti) == 3) return;
2745 bt_->setEffectDisplayWidth(curSongNum_, visTracks_.at(trackVisIdx), static_cast<size_t>(++rightEffn_[ti]));
2746 updateTracksWidthFromLeftToEnd();
2747
2748 if (config_->getMoveCursorByHorizontalScroll()) {
2749 emit effectColsCompanded(calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack), getFullColmunSize());
2750 }
2751 else {
2752 emit effectColsCompanded(leftTrackVisIdx_, getScrollableCountByTrack());
2753 }
2754
2755 redrawAll();
2756 }
2757
2758 void PatternEditorPanel::onShrinkEffectColumnPressed(int trackVisIdx)
2759 {
2760 size_t ti = static_cast<size_t>(trackVisIdx);
2761 if (rightEffn_.at(ti) == 0) return;
2762 bt_->setEffectDisplayWidth(curSongNum_, visTracks_.at(trackVisIdx), static_cast<size_t>(--rightEffn_[ti]));
2763 updateTracksWidthFromLeftToEnd();
2764
2765 if (config_->getMoveCursorByHorizontalScroll()) {
2766 emit effectColsCompanded(calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack), getFullColmunSize());
2767 }
2768 else {
2769 emit effectColsCompanded(leftTrackVisIdx_, getScrollableCountByTrack());
2770 }
2771
2772 redrawAll();
2773 }
2774
2775 void PatternEditorPanel::onFollowModeChanged()
2776 {
2777 curPos_.setRows(bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
2778
2779 emit vScrollBarChangeRequested(
2780 curPos_.step, static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order)) - 1);
2781
2782 // Force redraw all area
2783 followModeChanged_ = true;
2784 redrawPatterns();
2785 }
2786
2787 void PatternEditorPanel::onChangeValuesPressed(int value)
2788 {
2789 if (bt_->isJamMode()) return;
2790
2791 if (selLeftAbovePos_.order != -1)
2792 changeValuesInPattern(selLeftAbovePos_, selRightBelowPos_, value);
2793 else
2794 changeValuesInPattern(curPos_, curPos_, value);
2795 }
2796
2797 void PatternEditorPanel::onPlayStepPressed()
2798 {
2799 moveCursorToDown(1);
2800 }
2801
2802 /********** Events **********/
2803 bool PatternEditorPanel::event(QEvent *event)
2804 {
2805 switch (event->type()) {
2806 case QEvent::KeyPress:
2807 return keyPressed(dynamic_cast<QKeyEvent*>(event));
2808 case QEvent::KeyRelease:
2809 return keyReleased(dynamic_cast<QKeyEvent*>(event));
2810 case QEvent::HoverMove:
2811 return mouseHoverd(dynamic_cast<QHoverEvent*>(event));
2812 default:
2813 return QWidget::event(event);
2814 }
2815 }
2816
2817 bool PatternEditorPanel::keyPressed(QKeyEvent *event)
2818 {
2819 /* General Keys */
2820 switch (event->key()) {
2821 case Qt::Key_Shift:
2822 shiftPressedPos_ = curPos_;
2823 return true;
2824 case Qt::Key_Tab:
2825 if (curPos_.trackVisIdx == static_cast<int>(visTracks_.size()) - 1) {
2826 if (config_->getWarpCursor())
2827 moveCursorToRight(-calculateColNumInRow(curPos_.trackVisIdx, curPos_.colInTrack));
2828 }
2829 else {
2830 moveCursorToRight(5 + 2 * rightEffn_[static_cast<size_t>(curPos_.trackVisIdx)] - curPos_.colInTrack);
2831 }
2832 return true;
2833 case Qt::Key_Backtab:
2834 if (curPos_.trackVisIdx == 0) {
2835 if (config_->getWarpCursor())
2836 moveCursorToRight(getFullColmunSize() - 1);
2837 }
2838 else {
2839 moveCursorToRight(-5 - 2 * rightEffn_[static_cast<size_t>(curPos_.trackVisIdx) - 1] - curPos_.colInTrack);
2840 }
2841 return true;
2842 case Qt::Key_Insert:
2843 if (bt_->isJamMode()) {
2844 return false;
2845 }
2846 else {
2847 insertStep();
2848 return true;
2849 }
2850 case Qt::Key_Backspace:
2851 if (bt_->isJamMode()) {
2852 return false;
2853 }
2854 else {
2855 deletePreviousStep();
2856 return true;
2857 }
2858 case Qt::Key_Menu:
2859 {
2860 QPoint point = calculateCurrentCursorPosition();
2861 point.setX(point.x() + 24);
2862 point.setY(point.y() - 16);
2863 showPatternContextMenu(curPos_, point);
2864 return true;
2865 }
2866 default:
2867 if (!bt_->isJamMode()) {
2868 // Pattern edit
2869 if (!config_->getKeyRepetition() && event->isAutoRepeat()) return false;
2870 switch (curPos_.colInTrack) {
2871 case 0:
2872 return enterToneData(event);
2873 case 1:
2874 {
2875 auto modifiers = event->modifiers();
2876 if (modifiers.testFlag(Qt::NoModifier) || modifiers.testFlag(Qt::KeypadModifier))
2877 return enterInstrumentData(event->key());
2878 break;
2879 }
2880 case 2:
2881 {
2882 auto modifiers = event->modifiers();
2883 if (modifiers.testFlag(Qt::NoModifier) || modifiers.testFlag(Qt::KeypadModifier))
2884 return enterVolumeData(event->key());
2885 break;
2886 }
2887 case 3:
2888 case 5:
2889 case 7:
2890 case 9:
2891 {
2892 auto modifiers = event->modifiers();
2893 if (modifiers.testFlag(Qt::NoModifier) || modifiers.testFlag(Qt::KeypadModifier))
2894 return enterEffectID(event->key());
2895 break;
2896 }
2897 case 4:
2898 case 6:
2899 case 8:
2900 case 10:
2901 {
2902 auto modifiers = event->modifiers();
2903 if (modifiers.testFlag(Qt::NoModifier) || modifiers.testFlag(Qt::KeypadModifier))
2904 return enterEffectValue(event->key());
2905 break;
2906 }
2907 }
2908 }
2909 return false;
2910 }
2911 }
2912
2913 bool PatternEditorPanel::keyReleased(QKeyEvent* event)
2914 {
2915 switch (event->key()) {
2916 case Qt::Key_Shift:
2917 shiftPressedPos_ = { -1, -1, -1, -1 };
2918 return true;
2919 default:
2920 return false;
2921 }
2922 }
2923
2924 void PatternEditorPanel::paintEvent(QPaintEvent *event)
2925 {
2926 if (bt_ && isInitedFirstMod_.load()) {
2927 // Check the cursor position and clamp it if neccesary.
2928 int odrSize = static_cast<int>(bt_->getOrderSize(curSongNum_));
2929 if (curPos_.order >= odrSize) {
2930 curPos_.setRows(odrSize - 1, 0);
2931 }
2932 else {
2933 int patternSize = bt_->getPatternSizeFromOrderNumber(curSongNum_, curPos_.order);
2934 if (curPos_.step >= patternSize) {
2935 curPos_.step = patternSize - 1;
2936 }
2937 }
2938
2939 const QRect& area = event->rect();
2940 if (area.x() == 0 && area.y() == 0) {
2941 drawPattern(area);
2942 }
2943 else {
2944 drawPattern(rect());
2945 }
2946 }
2947 }
2948
2949 void PatternEditorPanel::resizeEvent(QResizeEvent *event)
2950 {
2951 QWidget::resizeEvent(event);
2952 funcResize();
2953 redrawAll();
2954 }
2955
2956 void PatternEditorPanel::mousePressEvent(QMouseEvent* event)
2957 {
2958 mousePressPos_ = hovPos_;
2959 doubleClickPos_ = mousePressPos_;
2960 mouseReleasePos_ = { -1, -1, -1, -1 };
2961 isPressedPlus_ = false;
2962 isPressedMinus_ = false;
2963
2964 if (event->button() == Qt::LeftButton) {
2965 if (mousePressPos_.order == -2 && mousePressPos_.trackVisIdx >= 0) {
2966 int w = calculateTracksWidthWithRowNum(leftTrackVisIdx_, mousePressPos_.trackVisIdx - 1)
2967 + hdMuteToggleWidth_ + stepFontWidth_ / 2;
2968 if (w < event->pos().x() && event->pos().x() < w + hdEffCompandButtonWidth_ + stepFontWidth_) {
2969 if (event->pos().y() < headerHeight_ / 2) isPressedPlus_ = true;
2970 else isPressedMinus_ = true;
2971 }
2972 }
2973 selLeftAbovePos_ = { -1, -1, -1, -1 };
2974 selRightBelowPos_ = { -1, -1, -1, -1 };
2975 selectAllState_ = -1;
2976 emit selected(false);
2977 }
2978 }
2979
2980 void PatternEditorPanel::mouseMoveEvent(QMouseEvent* event)
2981 {
2982 if (event->buttons() & Qt::LeftButton) {
2983 if (mousePressPos_.trackVisIdx < 0 || mousePressPos_.order < 0) return; // Start point is out of range
2984
2985 if (hovPos_.trackVisIdx >= 0 && hovPos_.order >= 0) {
2986 setSelectedRectangle(mousePressPos_, hovPos_);
2987 }
2988
2989 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
2990 QPointF pos = event->position();
2991 #else
2992 QPoint pos = event->pos();
2993 #endif
2994 if (pos.x() < stepNumWidth_ && leftTrackVisIdx_ > 0) {
2995 if (config_->getMoveCursorByHorizontalScroll()) {
2996 moveCursorToRight(-(5 + 2 * rightEffn_.at(static_cast<size_t>(leftTrackVisIdx_) - 1)));
2997 }
2998 else {
2999 moveViewToRight(-1);
3000 }
3001 }
3002 else if (pos.x() > geometry().width() - stepNumWidth_ && hovPos_.trackVisIdx != -1) {
3003 if (config_->getMoveCursorByHorizontalScroll()) {
3004 moveCursorToRight(5 + 2 * rightEffn_.at(static_cast<size_t>(leftTrackVisIdx_)));
3005 }
3006 else {
3007 moveViewToRight(1);
3008 }
3009 }
3010 if (pos.y() < headerHeight_ + stepFontHeight_) {
3011 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(-1);
3012 }
3013 else if (pos.y() > geometry().height() - stepFontHeight_) {
3014 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(1);
3015 }
3016 }
3017 }
3018
3019 void PatternEditorPanel::mouseReleaseEvent(QMouseEvent* event)
3020 {
3021 mouseReleasePos_ = hovPos_;
3022
3023 switch (event->button()) {
3024 case Qt::LeftButton:
3025 if (mousePressPos_ == mouseReleasePos_) { // Jump cell
3026 if (hovPos_.order >= 0 && hovPos_.step >= 0
3027 && hovPos_.trackVisIdx >= 0 && hovPos_.colInTrack >= 0) {
3028 int horDif = calculateColumnDistance(curPos_.trackVisIdx, curPos_.colInTrack,
3029 hovPos_.trackVisIdx, hovPos_.colInTrack);
3030 int verDif = calculateStepDistance(curPos_.order, curPos_.step,
3031 hovPos_.order, hovPos_.step);
3032 moveCursorToRight(horDif);
3033 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) moveCursorToDown(verDif);
3034 }
3035 else if (hovPos_.order == -2 && hovPos_.trackVisIdx >= 0) { // Header
3036 if (isPressedPlus_) {
3037 onExpandEffectColumnPressed(hovPos_.trackVisIdx);
3038 }
3039 else if (isPressedMinus_) {
3040 onShrinkEffectColumnPressed(hovPos_.trackVisIdx);
3041 }
3042 else {
3043 toggleTrack(hovPos_.trackVisIdx);
3044 int horDif = calculateColumnDistance(curPos_.trackVisIdx, curPos_.colInTrack,
3045 hovPos_.trackVisIdx, 0);
3046 moveCursorToRight(horDif);
3047 }
3048 }
3049 else if (hovPos_.trackVisIdx == -2 && hovPos_.order >= 0 && hovPos_.step >= 0) { // Step number
3050 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) {
3051 int verDif = calculateStepDistance(curPos_.order, curPos_.step,
3052 hovPos_.order, hovPos_.step);
3053 moveCursorToDown(verDif);
3054 }
3055 }
3056 }
3057 break;
3058
3059 case Qt::RightButton: // Show context menu
3060 {
3061 if (mousePressPos_.order == -2) { // Header
3062 QMenu menu;
3063 // Leave Before Qt5.7.0 style due to windows xp
3064 QAction* toggle = menu.addAction(tr("To&ggle Track"));
3065 QObject::connect(toggle, &QAction::triggered, this, [&] { toggleTrack(mousePressPos_.trackVisIdx); });
3066 QAction* solo = menu.addAction(tr("&Solo Track"));
3067 QObject::connect(solo, &QAction::triggered, this, [&] { soloTrack(mousePressPos_.trackVisIdx); });
3068 QAction* unmute = menu.addAction(tr("&Unmute All Tracks"));
3069 QObject::connect(unmute, &QAction::triggered, this, &PatternEditorPanel::onUnmuteAllPressed);
3070 #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
3071 toggle->setShortcutVisibleInContextMenu(true);
3072 solo->setShortcutVisibleInContextMenu(true);
3073 #endif
3074 auto shortcuts = config_->getShortcuts();
3075 toggle->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ToggleTrack)));
3076 solo->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SoloTrack)));
3077 if (mousePressPos_.trackVisIdx < 0) {
3078 toggle->setEnabled(false);
3079 solo->setEnabled(false);
3080 unmute->setEnabled(false);
3081 }
3082 menu.exec(mapToGlobal(event->pos()));
3083 }
3084 else { // Pattern
3085 showPatternContextMenu(mousePressPos_, event->pos());
3086 }
3087
3088 break;
3089 }
3090
3091 case Qt::XButton1:
3092 {
3093 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) {
3094 int order = curPos_.order - 1;
3095 if (order < 0) order = static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1;
3096 int step = std::min(
3097 curPos_.step,
3098 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, order)) - 1);
3099 int d = calculateStepDistance(curPos_.order, curPos_.step, order, step);
3100 moveCursorToDown(d);
3101 }
3102 break;
3103 }
3104
3105 case Qt::XButton2:
3106 {
3107 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) {
3108 int order = curPos_.order + 1;
3109 if (static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1 < order) order = 0;
3110 int step = std::min(
3111 curPos_.step,
3112 static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, order)) - 1);
3113 int d = calculateStepDistance(curPos_.order, curPos_.step, order, step);
3114 moveCursorToDown(d);
3115 }
3116 break;
3117 }
3118
3119 default:
3120 break;
3121 }
3122
3123 mousePressPos_ = { -1, -1, -1, -1 };
3124 mouseReleasePos_ = { -1, -1, -1, -1 };
3125 }
3126
3127 void PatternEditorPanel::mouseDoubleClickEvent(QMouseEvent* event)
3128 {
3129 if (event->button() == Qt::LeftButton) {
3130 if (doubleClickPos_.order >= 0) {
3131 if (!config_->getDontSelectOnDoubleClick()) {
3132 if (doubleClickPos_.trackVisIdx >= 0) {
3133 onSelectPressed(4);
3134 return;
3135 }
3136 else if (doubleClickPos_.trackVisIdx == -2) {
3137 onSelectPressed(5);
3138 return;
3139 }
3140 }
3141 }
3142 else if (doubleClickPos_.order == -2) {
3143 if (doubleClickPos_.trackVisIdx >= 0 && !isPressedPlus_ && !isPressedMinus_) {
3144 bool flag = true;
3145 int trackCnt = static_cast<int>(songStyle_.trackAttribs.size());
3146 int clickedNum = visTracks_.at(doubleClickPos_.trackVisIdx);
3147 for (int t = 0; t < trackCnt; ++t) {
3148 if (t != clickedNum) flag &= bt_->isMute(t);
3149 }
3150 if (flag) onUnmuteAllPressed();
3151 else soloTrack(doubleClickPos_.trackVisIdx);
3152 return;
3153 }
3154 }
3155 }
3156
3157 // Else
3158 mousePressEvent(event);
3159 }
3160
3161 bool PatternEditorPanel::mouseHoverd(QHoverEvent *event)
3162 {
3163 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
3164 QPointF pos = event->position();
3165 #else
3166 QPoint pos = event->pos();
3167 #endif
3168 PatternPosition oldPos = hovPos_;
3169
3170 // Detect Step
3171 if (pos.y() <= headerHeight_) {
3172 // Track header
3173 hovPos_.setRows(-2, -2);
3174 }
3175 else {
3176 if (pos.y() < curRowY_) {
3177 int tmpOdr = curPos_.order;
3178 int tmpStep = curPos_.step + static_cast<int>(std::ceil((pos.y() - curRowY_) / stepFontHeight_)) - 1;
3179 while (true) {
3180 if (tmpStep < 0) {
3181 if (tmpOdr == 0) {
3182 hovPos_.setRows(-1, -1);
3183 break;
3184 }
3185 else {
3186 tmpStep += bt_->getPatternSizeFromOrderNumber(curSongNum_, --tmpOdr);
3187 }
3188 }
3189 else {
3190 hovPos_.setRows(tmpOdr, tmpStep);
3191 break;
3192 }
3193 }
3194 }
3195 else {
3196 int tmpOdr = curPos_.order;
3197 int tmpStep = curPos_.step + static_cast<int>(std::floor((pos.y() - curRowY_) / stepFontHeight_));
3198 while (true) {
3199 int endStep = static_cast<int>(bt_->getPatternSizeFromOrderNumber(curSongNum_, tmpOdr));
3200 if (tmpStep < endStep) {
3201 hovPos_.setRows(tmpOdr, tmpStep);
3202 break;
3203 }
3204 else {
3205 if (tmpOdr == static_cast<int>(bt_->getOrderSize(curSongNum_)) - 1) {
3206 hovPos_.setRows(-1, -1);
3207 break;
3208 }
3209 else {
3210 ++tmpOdr;
3211 tmpStep -= endStep;
3212 }
3213 }
3214 }
3215 }
3216 }
3217
3218 // Detect column
3219 if (pos.x() <= stepNumWidth_) {
3220 // Row number
3221 hovPos_.setCols(-2, -2);
3222 }
3223 else {
3224 int tmpWidth = stepNumWidth_;
3225 for (int i = leftTrackVisIdx_; ; ) {
3226 tmpWidth += (toneNameWidth_ + widthSpaceDbl_);
3227 if (pos.x() <= tmpWidth) {
3228 hovPos_.setCols(i, 0);
3229 break;
3230 }
3231 tmpWidth += (instWidth_ + widthSpaceDbl_);
3232 if (pos.x() <= tmpWidth) {
3233 hovPos_.setCols(i, 1);
3234 break;
3235 }
3236 tmpWidth += (volWidth_ + widthSpaceDbl_);
3237 if (pos.x() <= tmpWidth) {
3238 hovPos_.setCols(i, 2);
3239 break;
3240 }
3241 bool flag = false;
3242 for (int j = 0; j <= rightEffn_.at(static_cast<size_t>(i)); ++j) {
3243 tmpWidth += (effIDWidth_ + widthSpace_);
3244 if (pos.x() <= tmpWidth) {
3245 hovPos_.setCols(i, 3 + 2 * j);
3246 flag = true;
3247 break;
3248 }
3249 tmpWidth += (effValWidth_ + widthSpace_);
3250 if (pos.x() <= tmpWidth) {
3251 hovPos_.setCols(i, 4 + 2 * j);
3252 flag = true;
3253 break;
3254 }
3255 }
3256 if (flag) break;
3257 ++i;
3258
3259 if (i == static_cast<int>(visTracks_.size())) {
3260 hovPos_.setCols(-1, -1);
3261 break;
3262 }
3263 }
3264 }
3265
3266 if (hovPos_ != oldPos) redrawByHoverChanged();
3267
3268 return true;
3269 }
3270
3271 void PatternEditorPanel::wheelEvent(QWheelEvent *event)
3272 {
3273 if (bt_->isPlaySong() && bt_->isFollowPlay()) return;
3274 int cnt = event->angleDelta().y() / 120;
3275 if (event->modifiers().testFlag(Qt::ControlModifier)) {
3276 onNoteTransposePressed(cnt);
3277 }
3278 else if (event->modifiers().testFlag(Qt::ShiftModifier)) {
3279 onChangeValuesPressed(cnt);
3280 }
3281 else {
3282 moveCursorToDown(-cnt);
3283 }
3284 }
3285
3286 void PatternEditorPanel::leaveEvent(QEvent*)
3287 {
3288 // Clear mouse hover selection
3289 hovPos_ = { -1, -1, -1, -1 };
3290 }
3291
3292 void PatternEditorPanel::midiThreadReceivedEvent(double delay, const uint8_t *msg, size_t len, void *userData)
3293 {
3294 PatternEditorPanel *self = reinterpret_cast<PatternEditorPanel *>(userData);
3295
3296 Q_UNUSED(delay)
3297
3298 // Note-On/Note-Off
3299 if (len == 3 && (msg[0] & 0xe0) == 0x80) {
3300 uint8_t status = msg[0];
3301 uint8_t key = msg[1];
3302 uint8_t velocity = msg[2];
3303 QMetaMethod method = self->metaObject()->method(self->midiKeyEventMethod_);
3304 method.invoke(self, Qt::QueuedConnection,
3305 Q_ARG(uchar, status), Q_ARG(uchar, key), Q_ARG(uchar, velocity));
3306 }
3307 }
3308
3309 void PatternEditorPanel::midiKeyEvent(uchar status, uchar key, uchar velocity)
3310 {
3311 if (!bt_->isJamMode()) {
3312 bool release = ((status & 0xf0) == 0x80) || velocity == 0;
3313 if (!release) {
3314 setStepKeyOn(Note(static_cast<int>(key) - 12));
3315 }
3316 }
3317 }