Debian Codegraph @

BambooTracker/gui/mainwindow.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2018 Rerrah
3 * SPDX-License-Identifier: MIT
4 */
5
6 #include "mainwindow.hpp"
7 #include "ui_mainwindow.h"
8 #include <algorithm>
9 #include <unordered_map>
10 #include <array>
11 #include <numeric>
12 #include <QString>
13 #include <QClipboard>
14 #include <QMenu>
15 #include <QAction>
16 #include <QDialog>
17 #include <QFileDialog>
18 #include <QFile>
19 #include <QFileInfo>
20 #include <QMimeData>
21 #include <QProgressDialog>
22 #include <QRect>
23 #include <QMetaMethod>
24 #include <QScreen>
25 #include <QComboBox>
26 #include <QToolButton>
27 #include <QSignalBlocker>
28 #include <QTextCodec>
29 #include <QVariant>
30 #include "jamming.hpp"
31 #include "song.hpp"
32 #include "track.hpp"
33 #include "instrument.hpp"
34 #include "bank.hpp"
35 #include "io/io_file_type.hpp"
36 #include "io/module_io.hpp"
37 #include "io/instrument_io.hpp"
38 #include "io/bank_io.hpp"
39 #include "io/binary_container.hpp"
40 #include "io/wav_container.hpp"
41 #include "version.hpp"
42 #include "gui/command/instrument/instrument_commands_qt.hpp"
43 #include "gui/instrument_editor/fm_instrument_editor.hpp"
44 #include "gui/instrument_editor/ssg_instrument_editor.hpp"
45 #include "gui/instrument_editor/adpcm_instrument_editor.hpp"
46 #include "gui/instrument_editor/adpcm_drumkit_editor.hpp"
47 #include "gui/module_properties_dialog.hpp"
48 #include "gui/groove_settings_dialog.hpp"
49 #include "gui/configuration_dialog.hpp"
50 #include "gui/wave_export_settings_dialog.hpp"
51 #include "gui/vgm_export_settings_dialog.hpp"
52 #include "gui/instrument_selection_dialog.hpp"
53 #include "gui/s98_export_settings_dialog.hpp"
54 #include "gui/configuration_handler.hpp"
55 #include "gui/jam_layout.hpp"
56 #include "gui/wheel_spin_box.hpp"
57 #include "chip/scci/scci_wrapper.hpp"
58 #include "chip/c86ctl/c86ctl_wrapper.hpp"
59 #include "midi/midi.hpp"
60 #include "audio/audio_stream_rtaudio.hpp"
61 #include "enum_hash.hpp"
62 #include "gui/go_to_dialog.hpp"
63 #include "gui/transpose_song_dialog.hpp"
64 #include "gui/swap_tracks_dialog.hpp"
65 #include "gui/hide_tracks_dialog.hpp"
66 #include "gui/file_io_error_message_box.hpp"
67 #include "gui/note_name_manager.hpp"
68 #include "gui/gui_utils.hpp"
69 #include "gui/command_result_message_box.hpp"
70 #include "utils.hpp"
71
72 namespace
73 {
74 const std::unordered_map<Configuration::ToolbarPosition, Qt::ToolBarArea> TB_POS_ = {
75 { Configuration::ToolbarPosition::TopPosition, Qt::TopToolBarArea },
76 { Configuration::ToolbarPosition::BottomPosition, Qt::BottomToolBarArea },
77 { Configuration::ToolbarPosition::LeftPosition, Qt::LeftToolBarArea },
78 { Configuration::ToolbarPosition::RightPosition, Qt::RightToolBarArea }
79 };
80
81 constexpr int STATUS_DISPLAY_TIMEOUT = 0;
82 }
83
84 ModuleSaveCheckDialog::ModuleSaveCheckDialog(const std::string& name, QWidget* parent) :
85 QMessageBox(QMessageBox::Warning, "BambooTracker", "",
86 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, parent)
87 {
88 setText(tr("Save changes to %1?").arg(name.empty() ? tr("Untitled") : gui_utils::utf8ToQString(name)));
89 }
90
91 MainWindow::MainWindow(std::weak_ptr<Configuration> config, QString filePath, bool isFirstLaunch, QWidget *parent) :
92 QMainWindow(parent),
93 ui(new Ui::MainWindow),
94 config_(config),
95 palette_(std::make_shared<ColorPalette>()),
96 bt_(std::make_shared<BambooTracker>(config)),
97 comStack_(std::make_shared<QUndoStack>(this)),
98 fileHistory_(std::make_shared<FileHistory>()),
99 scciDll_(std::make_shared<QLibrary>("scci")),
100 c86ctlDll_(std::make_shared<QLibrary>("c86ctl")),
101 instDialogMan_(std::make_shared<InstrumentEditorManager>()),
102 renamingInstItem_(nullptr),
103 renamingInstEdit_(nullptr),
104 isModifiedForNotCommand_(false),
105 hasLockedWigets_(false),
106 isEditedPattern_(true),
107 isEditedOrder_(false),
108 isEditedInstList_(false),
109 isSelectedPattern_(false),
110 isSelectedOrder_(false),
111 hasShownOnce_(false),
112 firstViewUpdateRequest_(false),
113 octUpSc_(nullptr),
114 octDownSc_(nullptr),
115 focusPtnSc_(this),
116 focusOdrSc_(this),
117 focusInstSc_(this),
118 playAndStopSc_(nullptr),
119 playStepSc_(nullptr),
120 goPrevOdrSc_(nullptr),
121 goNextOdrSc_(nullptr),
122 prevInstSc_(nullptr),
123 nextInstSc_(nullptr),
124 incPtnSizeSc_(nullptr),
125 decPtnSizeSc_(nullptr),
126 incEditStepSc_(nullptr),
127 decEditStepSc_(nullptr),
128 prevSongSc_(nullptr),
129 nextSongSc_(nullptr),
130 jamVolUpSc_(nullptr),
131 jamVolDownSc_(nullptr),
132 bankJamMidiCtrl_(false)
133 {
134 ui->setupUi(this);
135
136 if (config.lock()->getMainWindowX() == -1) { // When unset
137 QRect rec = geometry();
138 rec.moveCenter(QGuiApplication::screens().at(0)->geometry().center());
139 setGeometry(rec);
140 config.lock()->setMainWindowX(x());
141 config.lock()->setMainWindowY(y());
142 }
143 else {
144 move(config.lock()->getMainWindowX(), config.lock()->getMainWindowY());
145 }
146 if (isFirstLaunch) {
147 const QHash<QString, NoteNotationSystem> defNoteSysMap = {
148 { "English", NoteNotationSystem::ENGLISH },
149 { "German", NoteNotationSystem::GERMAN }
150 };
151 //: Set the name of suitable notation system (English or German)
152 config.lock()->setNotationSystem(defNoteSysMap[tr("English", "Default notation system")]);
153 }
154 resize(config.lock()->getMainWindowWidth(), config.lock()->getMainWindowHeight());
155 if (config.lock()->getMainWindowMaximized()) showMaximized();
156 ui->action_Status_Bar->setChecked(config.lock()->getVisibleStatusBar());
157 ui->statusBar->setVisible(config.lock()->getVisibleStatusBar());
158 ui->actionFollow_Mode->setChecked(config.lock()->getFollowMode());
159 ui->action_Instrument_Mask->setChecked(config.lock()->getInstrumentMask());
160 ui->action_Volume_Mask->setChecked(config.lock()->getVolumeMask());
161 ui->action_Wave_View->setChecked(config.lock()->getVisibleWaveView());
162 ui->waveVisual->setVisible(config.lock()->getVisibleWaveView());
163 bt_->setFollowPlay(config.lock()->getFollowMode());
164 NoteNameManager::getManager().setNotationSystem(config.lock()->getNotationSystem());
165 ui->patternEditor->setConfiguration(config_.lock());
166 ui->orderList->setConfiguration(config_.lock());
167 updateFonts();
168 ui->orderList->setHorizontalScrollMode(config.lock()->getMoveCursorByHorizontalScroll(), false);
169 ui->patternEditor->setHorizontalScrollMode(config.lock()->getMoveCursorByHorizontalScroll(), false);
170 ui->patternEditor->setCore(bt_);
171 ui->orderList->setCore(bt_);
172 io::loadPalette(palette_.get());
173 ui->patternEditor->setColorPallete(palette_);
174 ui->orderList->setColorPallete(palette_);
175 updateInstrumentListColors();
176 ui->waveVisual->setColorPalette(palette_);
177
178 /* Command stack */
179 QObject::connect(comStack_.get(), &QUndoStack::indexChanged,
180 this, [&](int idx) {
181 setWindowModified(idx || isModifiedForNotCommand_);
182 ui->actionUndo->setEnabled(comStack_->canUndo());
183 ui->actionRedo->setEnabled(comStack_->canRedo());
184 });
185
186 /* File history */
187 io::loadFileHistory(fileHistory_);
188 for (size_t i = 0; i < fileHistory_->size(); ++i) {
189 // Leave Before Qt5.7.0 style due to windows xp
190 QAction* action = ui->menu_Recent_Files->addAction(QString("&%1 %2").arg(i + 1).arg(fileHistory_->at(i)));
191 action->setData(fileHistory_->at(i));
192 }
193 QObject::connect(ui->menu_Recent_Files, &QMenu::triggered, this, [&](QAction* action) {
194 if (action != ui->actionClear) {
195 if (isWindowModified()) {
196 switch (ModuleSaveCheckDialog(bt_->getModuleTitle(), this).exec()) {
197 case QMessageBox::Yes:
198 if (!on_actionSave_triggered()) return;
199 break;
200 case QMessageBox::No:
201 break;
202 case QMessageBox::Cancel:
203 return;
204 default:
205 break;
206 }
207 }
208 openModule(action->data().toString());
209 }
210 });
211
212 /* Menus */
213 pasteModeGroup_ = std::make_unique<QActionGroup>(this);
214 pasteModeGroup_->addAction(ui->action_Cursor);
215 QObject::connect(ui->action_Cursor, &QAction::triggered, this, [&](bool checked) {
216 if (checked) config_.lock()->setPasteMode(Configuration::PasteMode::Cursor);
217 });
218 pasteModeGroup_->addAction(ui->action_Selection);
219 QObject::connect(ui->action_Selection, &QAction::triggered, this, [&](bool checked) {
220 if (checked) config_.lock()->setPasteMode(Configuration::PasteMode::Selection);
221 });
222 pasteModeGroup_->addAction(ui->action_Fill);
223 QObject::connect(ui->action_Fill, &QAction::triggered, this, [&](bool checked) {
224 if (checked) config_.lock()->setPasteMode(Configuration::PasteMode::Fill);
225 });
226 switch (config.lock()->getPasteMode()) {
227 case Configuration::PasteMode::Cursor: ui->action_Cursor->setChecked(true); break;
228 case Configuration::PasteMode::Selection: ui->action_Selection->setChecked(true); break;
229 case Configuration::PasteMode::Fill: ui->action_Fill->setChecked(true); break;
230 }
231
232 /* Tool bars */
233 {
234 auto genSB = [](int value, int min, int max, int minW) {
235 auto sb = new WheelSpinBox();
236 sb->setMinimum(min);
237 sb->setMaximum(max);
238 sb->setValue(value);
239 sb->setMinimumWidth(minW);
240 sb->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
241 return sb;
242 };
243
244 /* Octave */
245 auto octLab = new QLabel(tr("Octave"));
246 octLab->setMargin(6);
247 ui->subToolBar->addWidget(octLab);
248 octave_ = genSB(bt_->getCurrentOctave(), 0, 7, 40);
249 // Leave Before Qt5.7.0 style due to windows xp
250 QObject::connect(octave_, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
251 this, [&](int octave) {
252 bt_->setCurrentOctave(octave);
253 statusOctave_->setText(tr("Octave: %1").arg(octave));
254 });
255 ui->subToolBar->addWidget(octave_);
256
257 /* Volume */
258 auto volLab = new QLabel(tr("Volume"));
259 volLab->setMargin(6);
260 ui->subToolBar->addWidget(volLab);
261 volume_ = [value = bt_->getCurrentVolume(), genSB] {
262 auto sb = genSB(value, 0, 255, 40);
263 sb->setDisplayIntegerBase(16);
264 QFont font = sb->font();
265 font.setCapitalization(QFont::AllUppercase);
266 sb->setFont(font);
267 return sb;
268 }();
269 // Leave Before Qt5.7.0 style due to windows xp
270 QObject::connect(volume_, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
271 this, [&](int volume) { bt_->setCurrentVolume(volume); });
272 ui->subToolBar->addWidget(volume_);
273
274 ui->subToolBar->addSeparator();
275
276 /* Follow mode */
277 ui->subToolBar->addAction(ui->actionFollow_Mode);
278
279 ui->subToolBar->addSeparator();
280
281 /* Step highlight 1st */
282 auto hlLab1 = new QLabel(tr("Step highlight 1st"));
283 hlLab1->setMargin(6);
284 ui->subToolBar->addWidget(hlLab1);
285 highlight1_ = genSB(8, 1, 256, 50);
286 // Leave Before Qt5.7.0 style due to windows xp
287 QObject::connect(highlight1_, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
288 this, [&](int count) {
289 bt_->setModuleStepHighlight1Distance(static_cast<size_t>(count));
290 ui->patternEditor->setPatternHighlight1Count(count);
291 });
292 ui->subToolBar->addWidget(highlight1_);
293
294 /* Step highlight 2nd */
295 auto hlLab2 = new QLabel(tr("2nd"));
296 hlLab2->setMargin(6);
297 ui->subToolBar->addWidget(hlLab2);
298 highlight2_ = genSB(8, 1, 256, 50);
299 highlight2_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
300 // Leave Before Qt5.7.0 style due to windows xp
301 QObject::connect(highlight2_, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
302 this, [&](int count) {
303 bt_->setModuleStepHighlight2Distance(static_cast<size_t>(count));
304 ui->patternEditor->setPatternHighlight2Count(count);
305 });
306 ui->subToolBar->addWidget(highlight2_);
307
308 ui->subToolBar->addSeparator();
309
310 auto& mainTbConfig = config.lock()->getMainToolbarConfiguration();
311 if (mainTbConfig.getPosition() == Configuration::ToolbarPosition::FloatPorition) {
312 ui->mainToolBar->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
313 ui->mainToolBar->move(mainTbConfig.getX(), mainTbConfig.getY());
314 }
315 else {
316 addToolBar(TB_POS_.at(mainTbConfig.getPosition()), ui->mainToolBar);
317 }
318 auto& subTbConfig = config.lock()->getSubToolbarConfiguration();
319 if (subTbConfig.getPosition() == Configuration::ToolbarPosition::FloatPorition) {
320 ui->subToolBar->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
321 ui->subToolBar->move(subTbConfig.getX(), subTbConfig.getY());
322 }
323 else {
324 auto pos = TB_POS_.at(subTbConfig.getPosition());
325 if (subTbConfig.getNumber()) {
326 if (subTbConfig.hasBreakBefore()) addToolBarBreak(pos);
327 addToolBar(pos, ui->subToolBar);
328 }
329 else {
330 if (mainTbConfig.getPosition() == subTbConfig.getPosition()) {
331 insertToolBar(ui->mainToolBar, ui->subToolBar);
332 if (mainTbConfig.hasBreakBefore()) insertToolBarBreak(ui->mainToolBar);
333 }
334 else {
335 addToolBar(pos, ui->subToolBar);
336 }
337 }
338 }
339 ui->action_Toolbar->setChecked(config.lock()->getVisibleToolbar());
340 ui->mainToolBar->setVisible(config.lock()->getVisibleToolbar());
341 ui->subToolBar->setVisible(config.lock()->getVisibleToolbar());
342 }
343
344 /* Splitter */
345 ui->splitter->setStretchFactor(0, 0);
346 ui->splitter->setStretchFactor(1, 1);
347
348 /* Module settings */
349 QObject::connect(ui->modTitleLineEdit, &QLineEdit::textEdited,
350 this, [&](const QString& str) {
351 bt_->setModuleTitle(str.toUtf8().toStdString());
352 setModifiedTrue();
353 setWindowTitle();
354 });
355 QObject::connect(ui->authorLineEdit, &QLineEdit::textEdited,
356 this, [&](const QString& str) {
357 bt_->setModuleAuthor(str.toUtf8().toStdString());
358 setModifiedTrue();
359 });
360 QObject::connect(ui->copyrightLineEdit, &QLineEdit::textEdited,
361 this, [&](const QString& str) {
362 bt_->setModuleCopyright(str.toUtf8().toStdString());
363 setModifiedTrue();
364 });
365
366 /* Edit settings */
367 // Leave Before Qt5.7.0 style due to windows xp
368 QObject::connect(ui->editableStepSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
369 this, [&](int n) {
370 ui->patternEditor->setEditableStep(n);
371 config_.lock()->setEditableStep(static_cast<size_t>(n));
372 });
373 ui->editableStepSpinBox->setValue(static_cast<int>(config.lock()->getEditableStep()));
374 ui->patternEditor->setEditableStep(static_cast<int>(config.lock()->getEditableStep()));
375
376 ui->keyRepeatCheckBox->setCheckState(config.lock()->getKeyRepetition() ? Qt::Checked : Qt::Unchecked);
377
378 /* Song */
379 // Leave Before Qt5.7.0 style due to windows xp
380 QObject::connect(ui->songComboBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
381 this, [&](int num) {
382 if (num == -1) return;
383 freezeViews();
384 if (!tickTimerForRealChip_) {
385 try {
386 stream_->stop();
387 }
388 catch (std::exception& e) {
389 showStreamFailedDialog(e.what());
390 }
391 }
392 bt_->setCurrentSongNumber(num);
393 loadSong();
394 if (!tickTimerForRealChip_) {
395 try {
396 stream_->start();
397 }
398 catch (std::exception& e) {
399 showStreamFailedDialog(e.what());
400 }
401 }
402 });
403
404 /* Song settings */
405 // Leave Before Qt5.7.0 style due to windows xp
406 QObject::connect(ui->tempoSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
407 this, [&](int tempo) {
408 int curSong = bt_->getCurrentSongNumber();
409 if (tempo != bt_->getSongTempo(curSong)) {
410 bt_->setSongTempo(curSong, tempo);
411 setModifiedTrue();
412 }
413 });
414 // Leave Before Qt5.7.0 style due to windows xp
415 QObject::connect(ui->speedSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
416 this, [&](int speed) {
417 int curSong = bt_->getCurrentSongNumber();
418 if (speed != bt_->getSongSpeed(curSong)) {
419 bt_->setSongSpeed(curSong, speed);
420 setModifiedTrue();
421 }
422 });
423 // Leave Before Qt5.7.0 style due to windows xp
424 QObject::connect(ui->patternSizeSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
425 this, [&](int size) {
426 bt_->setDefaultPatternSize(bt_->getCurrentSongNumber(), static_cast<size_t>(size));
427 ui->patternEditor->onDefaultPatternSizeChanged();
428 setModifiedTrue();
429 });
430 // Leave Before Qt5.7.0 style due to windows xp
431 QObject::connect(ui->grooveSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
432 this, [&](int n) {
433 bt_->setSongGroove(bt_->getCurrentSongNumber(), n);
434 setModifiedTrue();
435 });
436
437 /* Instrument list */
438 auto instToolBar = [&] {
439 auto subMenu = [](const QList<QAction*>& actions) {
440 auto menu = new QMenu();
441 menu->addActions(actions);
442 auto btn = new QToolButton();
443 btn->setPopupMode(QToolButton::MenuButtonPopup);
444 btn->setMenu(menu);
445 btn->setDefaultAction(actions.front());
446 return btn;
447 };
448 auto tb = new QToolBar();
449 tb->setIconSize(QSize(16, 16));
450 tb->addWidget(subMenu({ ui->actionNew_Instrument, ui->actionNew_Drumki_t }));
451 tb->addActions({ ui->actionRemove_Instrument, ui->actionClone_Instrument });
452 tb->addSeparator();
453 tb->addWidget(subMenu({ ui->actionLoad_From_File, ui->actionImport_From_Bank_File }));
454 tb->addWidget(subMenu({ ui->actionSave_To_File, ui->actionExport_To_Bank_File }));
455 tb->addSeparator();
456 tb->addAction(ui->actionEdit);
457 tb->addSeparator();
458 tb->addAction(ui->actionRename_Instrument);
459 return tb;
460 }();
461 ui->instrumentListGroupBox->layout()->addWidget(instToolBar);
462 ui->instrumentList->installEventFilter(this);
463 QObject::connect(ui->instrumentList, &DropDetectListWidget::itemDroppedAtItemIndex,
464 this, &MainWindow::swapInstruments);
465
466 /* Pattern editor */
467 ui->patternEditor->setCommandStack(comStack_);
468 ui->patternEditor->installEventFilter(this);
469 QObject::connect(ui->patternEditor, &PatternEditor::currentTrackChanged,
470 ui->orderList, &OrderListEditor::onPatternEditorCurrentTrackChanged);
471 QObject::connect(ui->patternEditor, &PatternEditor::currentOrderChanged,
472 ui->orderList, &OrderListEditor::onPatternEditorCurrentOrderChanged);
473 QObject::connect(ui->patternEditor, &PatternEditor::focusIn,
474 this, &MainWindow::updateMenuByPattern);
475 QObject::connect(ui->patternEditor, &PatternEditor::selected,
476 this, &MainWindow::updateMenuByPatternSelection);
477 QObject::connect(ui->patternEditor, &PatternEditor::instrumentEntered,
478 this, [&](int num) {
479 auto list = ui->instrumentList;
480 if (num != -1) {
481 for (int i = 0; i < list->count(); ++i) {
482 if (list->item(i)->data(Qt::UserRole).toInt() == num) {
483 list->setCurrentRow(i);
484 return ;
485 }
486 }
487 }
488 });
489 QObject::connect(ui->patternEditor, &PatternEditor::volumeEntered,
490 this, [&](int volume) { volume_->setValue(volume); });
491 QObject::connect(ui->patternEditor, &PatternEditor::effectEntered,
492 this, [&](QString text) { ui->statusBar->showMessage(text, STATUS_DISPLAY_TIMEOUT); });
493 QObject::connect(ui->patternEditor, &PatternEditor::currentTrackChanged,
494 this, &MainWindow::onCurrentTrackChanged);
495
496 /* Order List */
497 ui->orderList->setCommandStack(comStack_);
498 ui->orderList->installEventFilter(this);
499 QObject::connect(ui->orderList, &OrderListEditor::currentTrackChanged,
500 ui->patternEditor, &PatternEditor::onOrderListCurrentTrackChanged);
501 QObject::connect(ui->orderList, &OrderListEditor::currentOrderChanged,
502 ui->patternEditor, &PatternEditor::onOrderListCrrentOrderChanged);
503 QObject::connect(ui->orderList, &OrderListEditor::orderEdited,
504 ui->patternEditor, &PatternEditor::onOrderListEdited);
505 QObject::connect(ui->orderList, &OrderListEditor::focusIn,
506 this, &MainWindow::updateMenuByOrder);
507 QObject::connect(ui->orderList, &OrderListEditor::selected,
508 this, &MainWindow::updateMenuByOrderSelection);
509 QObject::connect(ui->orderList, &OrderListEditor::currentTrackChanged,
510 this, &MainWindow::onCurrentTrackChanged);
511
512 /* Wave view */
513 visualTimer_.reset(new QTimer);
514 QObject::connect(visualTimer_.get(), &QTimer::timeout, this, &MainWindow::updateVisuals);
515 if (config.lock()->getVisibleWaveView())
516 visualTimer_->start(static_cast<int>(std::round(1000. / config.lock()->getWaveViewFrameRate())));
517
518 /* Status bar */
519 statusStyle_ = new QLabel(ui->statusBar);
520 statusStyle_->setAlignment(Qt::AlignTrailing | Qt::AlignVCenter);
521 statusInst_ = new QLabel(ui->statusBar);
522 statusInst_->setFixedWidth(110);
523 statusInst_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
524 statusOctave_ = new QLabel(ui->statusBar);
525 statusOctave_->setFixedWidth(90);
526 statusOctave_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
527 statusIntr_ = new QLabel(ui->statusBar);
528 statusIntr_->setFixedWidth(50);
529 statusIntr_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
530 statusMixer_ = new QLabel(ui->statusBar);
531 statusMixer_->setFixedWidth(200);
532 statusMixer_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
533 statusBpm_ = new QLabel(ui->statusBar);
534 statusBpm_->setFixedWidth(90);
535 statusBpm_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
536 statusPlayPos_ = new QLabel(ui->statusBar);
537 statusPlayPos_->setFixedWidth(40);
538 statusPlayPos_->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);
539 ui->statusBar->addPermanentWidget(statusStyle_);
540 ui->statusBar->addPermanentWidget(statusInst_);
541 ui->statusBar->addPermanentWidget(statusOctave_);
542 ui->statusBar->addPermanentWidget(statusIntr_);
543 ui->statusBar->addPermanentWidget(statusMixer_);
544 ui->statusBar->addPermanentWidget(statusBpm_);
545 ui->statusBar->addPermanentWidget(statusPlayPos_);
546 statusOctave_->setText(tr("Octave: %1").arg(bt_->getCurrentOctave()));
547 statusIntr_->setText(QString::number(bt_->getModuleTickFrequency()) + QString("Hz"));
548 ui->statusBar->showMessage(tr("Welcome to BambooTracker v%1!").arg(QString::fromStdString(Version::ofApplicationInString())),
549 STATUS_DISPLAY_TIMEOUT);
550
551 /* Bookmark */
552 bmManForm_ = std::make_unique<BookmarkManagerForm>(bt_, config_.lock()->getShowRowNumberInHex());
553 auto posJumpFunc = [&](int order, int step) {
554 if (bt_->isPlaySong()) return;
555 int song = bt_->getCurrentSongNumber();
556 if (static_cast<int>(bt_->getOrderSize(song)) <= order) return;
557 if (static_cast<int>(bt_->getPatternSizeFromOrderNumber(song, order)) <= step) return;
558 bt_->setCurrentOrderNumber(order);
559 bt_->setCurrentStepNumber(step);
560 ui->orderList->updatePositionByPositionJump();
561 ui->patternEditor->updatepositionByPositionJump();
562 activateWindow();
563 };
564 QObject::connect(bmManForm_.get(), &BookmarkManagerForm::positionJumpRequested, this, posJumpFunc);
565 QObject::connect(bmManForm_.get(), &BookmarkManagerForm::modified, this, &MainWindow::setModifiedTrue);
566
567 /* Key signature */
568 ksManForm_ = std::make_unique<KeySignatureManagerForm>(bt_, config_.lock()->getShowRowNumberInHex());
569 QObject::connect(ksManForm_.get(), &KeySignatureManagerForm::positionJumpRequested, this, posJumpFunc);
570 QObject::connect(ksManForm_.get(), &KeySignatureManagerForm::modified, this, [&] {
571 ui->patternEditor->onPatternDataGlobalChanged();
572 setModifiedTrue();
573 });
574
575 /* Shortcuts */
576 {
577 auto linkShortcut = [&](QAction* ptr) {
578 ptr->setShortcutContext(Qt::WidgetWithChildrenShortcut);
579 ui->orderList->addAction(ptr);
580 ui->patternEditor->addAction(ptr);
581 };
582
583 linkShortcut(&octUpSc_);
584 QObject::connect(&octUpSc_, &QAction::triggered, this, [&] { changeOctave(true); });
585 linkShortcut(&octDownSc_);
586 QObject::connect(&octDownSc_, &QAction::triggered, this, [&] { changeOctave(false); });
587 QObject::connect(&focusPtnSc_, &QShortcut::activated, this, [&] { ui->patternEditor->setFocus(); });
588 QObject::connect(&focusOdrSc_, &QShortcut::activated, this, [&] { ui->orderList->setFocus(); });
589 QObject::connect(&focusInstSc_, &QShortcut::activated, this, [&] {
590 ui->instrumentList->setFocus();
591 updateMenuByInstrumentList();
592 });
593 auto playLinkShortcut = [&](QAction* ptr) {
594 ptr->setShortcutContext(Qt::WidgetShortcut);
595 ui->instrumentList->addAction(ptr);
596 ui->orderList->addActionToPanel(ptr);
597 ui->patternEditor->addActionToPanel(ptr);
598 };
599 playLinkShortcut(ui->actionPlay);
600 playLinkShortcut(&playAndStopSc_);
601 QObject::connect(&playAndStopSc_, &QAction::triggered, this, [&] {
602 if (bt_->isPlaySong()) stopPlaySong();
603 else startPlaySong();
604 });
605 playLinkShortcut(&playStepSc_);
606 QObject::connect(&playStepSc_, &QAction::triggered, this, &MainWindow::playStep);
607 playLinkShortcut(ui->actionPlay_From_Start);
608 playLinkShortcut(ui->actionPlay_Pattern);
609 playLinkShortcut(ui->actionPlay_From_Cursor);
610 playLinkShortcut(ui->actionPlay_From_Marker);
611 playLinkShortcut(ui->actionStop);
612 instAddSc_ = std::make_unique<QShortcut>(Qt::Key_Insert, ui->instrumentList,
613 nullptr, nullptr, Qt::WidgetShortcut);
614 QObject::connect(instAddSc_.get(), &QShortcut::activated, this, &MainWindow::addInstrument);
615 linkShortcut(&goPrevOdrSc_);
616 QObject::connect(&goPrevOdrSc_, &QAction::triggered, this, [&] {
617 ui->orderList->onGoOrderRequested(false);
618 });
619 linkShortcut(&goNextOdrSc_);
620 QObject::connect(&goNextOdrSc_, &QAction::triggered, this, [&] {
621 ui->orderList->onGoOrderRequested(true);
622 });
623 linkShortcut(&prevInstSc_);
624 QObject::connect(&prevInstSc_, &QAction::triggered, this, [&] {
625 if (ui->instrumentList->count()) {
626 int row = ui->instrumentList->currentRow();
627 if (row == -1) ui->instrumentList->setCurrentRow(0);
628 else if (row > 0) ui->instrumentList->setCurrentRow(row - 1);
629 }
630 });
631 linkShortcut(&nextInstSc_);
632 QObject::connect(&nextInstSc_, &QAction::triggered, this, [&] {
633 int cnt = ui->instrumentList->count();
634 if (cnt) {
635 int row = ui->instrumentList->currentRow();
636 if (row == -1) ui->instrumentList->setCurrentRow(cnt - 1);
637 else if (row < cnt - 1) ui->instrumentList->setCurrentRow(row + 1);
638 }
639 });
640 linkShortcut(&incPtnSizeSc_);
641 QObject::connect(&incPtnSizeSc_, &QAction::triggered, this, [&] {
642 ui->patternSizeSpinBox->setValue(ui->patternSizeSpinBox->value() + 1);
643 });
644 linkShortcut(&decPtnSizeSc_);
645 QObject::connect(&decPtnSizeSc_, &QAction::triggered, this, [&] {
646 ui->patternSizeSpinBox->setValue(ui->patternSizeSpinBox->value() - 1);
647 });
648 linkShortcut(&incEditStepSc_);
649 QObject::connect(&incEditStepSc_, &QAction::triggered, this, [&] {
650 ui->editableStepSpinBox->setValue(ui->editableStepSpinBox->value() + 1);
651 });
652 linkShortcut(&decEditStepSc_);
653 QObject::connect(&decEditStepSc_, &QAction::triggered, this, [&] {
654 ui->editableStepSpinBox->setValue(ui->editableStepSpinBox->value() - 1);
655 });
656 linkShortcut(&prevSongSc_);
657 QObject::connect(&prevSongSc_, &QAction::triggered, this, [&] {
658 if (ui->songComboBox->isEnabled()) {
659 ui->songComboBox->setCurrentIndex(std::max(ui->songComboBox->currentIndex() - 1, 0));
660 }
661 });
662 linkShortcut(&nextSongSc_);
663 QObject::connect(&nextSongSc_, &QAction::triggered, this, [&] {
664 if (ui->songComboBox->isEnabled()) {
665 ui->songComboBox->setCurrentIndex(std::min(ui->songComboBox->currentIndex() + 1,
666 ui->songComboBox->count() - 1));
667 }
668 });
669 linkShortcut(&jamVolUpSc_);
670 QObject::connect(&jamVolUpSc_, &QAction::triggered, this, [&] {
671 volume_->setValue(volume_->value() + 1);
672 });
673 linkShortcut(&jamVolDownSc_);
674 QObject::connect(&jamVolDownSc_, &QAction::triggered, this, [&] {
675 volume_->setValue(volume_->value() - 1);
676 });
677 setShortcuts();
678 }
679
680 /* Clipboard */
681 QObject::connect(QApplication::clipboard(), &QClipboard::dataChanged,
682 this, [&]() {
683 if (isEditedOrder_) updateMenuByOrder();
684 else if (isEditedPattern_) updateMenuByPattern();
685 });
686
687 /* Welcome dialog */
688 {
689 const QString text =
690 "<h2 style='text-align: center;'>" + tr("Welcome to BambooTracker!") + "</h2>" +
691 "<div style='text-align: center;'>"
692 "<img src=':/icon/app_icon' width=128 height=128>"
693 "</div>"
694 "<h3>" + tr("Don't know where to start?") + "</h3>" +
695 "<p>" + tr("Check the demo modules and instruments included "
696 "with your download of BambooTracker.") + "</p>" +
697 "<h3>" + tr("Need a list of effects and shortcuts?") + "</h3>" +
698 "<p>" + tr("Check the Help menu at the top of the window.") + "</p>" +
699 "<h3>" + tr("Still lost?") + "</h3>" +
700 "<p>" + tr("The README.md has a link to our Discord server.") + "</p>" +
701 "<h3>" + tr("Think you've found a bug? Missing a feature?") + "</h3>" +
702 "<p>" + tr("BambooTracker is still in development, bugs and missing "
703 "features are to be expected. So we need your help!") +
704 "<ul style='margin-left: 16px; -qt-list-indent: 0;'>" +
705 //: %1 is the link to the issue submission page in GitHub.
706 "<li>" + tr("Please report any bugs you find and requests and features "
707 "you'd like to see on our Discord server or our bug tracker (%1).")
708 .arg("<a href=\"https://github.com/BambooTracker/BambooTracker/issues/new/choose\">"
709 "https://github.com/BambooTracker/BambooTracker/issues/new/choose</a>") + "</li>" +
710 "<li>" + tr("If you're a developer yourself or would like to start being one, "
711 "consider contributing to the project yourself. "
712 "Any help would be appreciated!") + "</li>" +
713 "</ul></p>";
714 welcomeDialog_ = std::make_unique<QMessageBox>(QMessageBox::NoIcon, tr("Welcome"), text, QMessageBox::Ok, this);
715 welcomeDialog_->setWindowModality(Qt::ApplicationModal);
716 welcomeDialog_->setWindowFlags(welcomeDialog_->windowFlags() & ~Qt::WindowContextHelpButtonHint);
717 welcomeDialog_->setTextFormat(Qt::RichText);
718 if (isFirstLaunch) on_action_Welcome_triggered();
719 }
720
721 /* MIDI */
722 setMidiConfiguration();
723 midiKeyEventMethod_ = metaObject()->indexOfSlot("midiKeyEvent(uchar,uchar,uchar)");
724 Q_ASSERT(midiKeyEventMethod_ != -1);
725 midiProgramEventMethod_ = metaObject()->indexOfSlot("midiProgramEvent(uchar,uchar)");
726 Q_ASSERT(midiProgramEventMethod_ != -1);
727 MidiInterface::getInstance().installInputHandler(&midiThreadReceivedEvent, this);
728
729 /* Audio stream */
730 stream_ = std::make_shared<AudioStreamRtAudio>();
731 stream_->setTickUpdateCallback(+[](void* cbPtr) -> int {
732 auto bt = reinterpret_cast<BambooTracker*>(cbPtr);
733 return bt->streamCountUp();
734 }, bt_.get());
735 stream_->setGenerateCallback(+[](int16_t* container, size_t nSamples, void* cbPtr) {
736 auto bt = reinterpret_cast<BambooTracker*>(cbPtr);
737 return bt->getStreamSamples(container, nSamples);
738 }, bt_.get());
739 QObject::connect(stream_.get(), &AudioStream::streamInterrupted, this, &MainWindow::onNewTickSignaled);
740 QObject::connect(stream_.get(), &AudioStream::streamErrorInCallback,
741 this, [&](const QVariant&) {
742 QMessageBox::critical(this, tr("Error"), tr("An error occurred in the audio playback.\n"
743 "Please change the settings in the configuration."));
744 });
745 QString audioApi = gui_utils::utf8ToQString(config.lock()->getSoundAPI());
746 if (isFirstLaunch) {
747 try {
748 bool streamState = false;
749 QString streamErr;
750 for (const QString& audioApi : stream_->getAvailableBackends()) {
751 config.lock()->setSoundAPI(audioApi.toUtf8().toStdString());
752 QString audioDevice = stream_->getDefaultOutputDevice(audioApi);
753 config.lock()->setSoundDevice(audioDevice.toUtf8().toStdString());
754 streamState = stream_->initialize(
755 static_cast<uint32_t>(bt_->getStreamRate()),
756 static_cast<uint32_t>(bt_->getStreamDuration()),
757 bt_->getModuleTickFrequency(), audioApi, audioDevice, &streamErr);
758 if (streamState) break;
759 }
760 if (streamState) {
761 uint32_t sr = stream_->getStreamRate();
762 if (config.lock()->getSampleRate() != sr) {
763 showStreamRateWarningDialog(sr);
764 bt_->setStreamRate(sr);
765 }
766 }
767 else {
768 showStreamFailedDialog(streamErr);
769 }
770 }
771 catch (std::exception& e) {
772 showStreamFailedDialog(e.what());
773 }
774 }
775 else { // Ordinary launch
776 bool savedApiExists = false;
777 const std::vector<QString> audioApis = stream_->getAvailableBackends();
778 for (const QString& api : audioApis) {
779 if (api.toUtf8().toStdString() == config.lock()->getSoundAPI()) {
780 savedApiExists = true;
781 break;
782 }
783 }
784 if (!savedApiExists) {
785 audioApi = audioApis.front();
786 config.lock()->setSoundAPI(audioApi.toUtf8().toStdString());
787 }
788 QString audioDevice = gui_utils::utf8ToQString(config.lock()->getSoundDevice());
789 bool savedDeviceExists = false;
790 for (const QString& device : stream_->getAvailableDevices(audioApi)) {
791 if (device.toUtf8().toStdString() == config.lock()->getSoundDevice()) {
792 savedDeviceExists = true;
793 break;
794 }
795 }
796 if (!savedDeviceExists) {
797 audioDevice = stream_->getDefaultOutputDevice(audioApi);
798 config.lock()->setSoundDevice(audioDevice.toUtf8().toStdString());
799 }
800 try {
801 QString streamErr;
802 bool streamState = stream_->initialize(
803 static_cast<uint32_t>(bt_->getStreamRate()),
804 static_cast<uint32_t>(bt_->getStreamDuration()),
805 bt_->getModuleTickFrequency(), audioApi, audioDevice, &streamErr);
806 if (streamState) {
807 uint32_t sr = stream_->getStreamRate();
808 if (config.lock()->getSampleRate() != sr) {
809 showStreamRateWarningDialog(sr);
810 bt_->setStreamRate(sr);
811 }
812 }
813 else {
814 showStreamFailedDialog(streamErr);
815 }
816 }
817 catch (std::exception& e) {
818 showStreamFailedDialog(e.what());
819 }
820 }
821 RealChipInterfaceType intf = config.lock()->getRealChipInterface();
822 if (intf != RealChipInterfaceType::NONE) {
823 tickTimerForRealChip_ = std::make_unique<PreciseTimer>();
824 tickTimerForRealChip_->setInterval(1000000 / bt_->getModuleTickFrequency());
825 tickEventMethod_ = metaObject()->indexOfSlot("onNewTickSignaledRealChip()");
826 Q_ASSERT(tickEventMethod_ != -1);
827 tickTimerForRealChip_->setFunction([&]{
828 QMetaMethod method = this->metaObject()->method(this->tickEventMethod_);
829 method.invoke(this, Qt::QueuedConnection);
830 });
831
832 setRealChipInterface(intf);
833
834 tickTimerForRealChip_->start();
835 }
836
837 /* Load module */
838 if (filePath.isEmpty()) {
839 loadModule();
840 setInitialSelectedInstrument();
841 assignADPCMSamples();
842 if (!tickTimerForRealChip_) {
843 try {
844 stream_->start();
845 }
846 catch (std::exception& e) {
847 showStreamFailedDialog(e.what());
848 }
849 }
850 }
851 else {
852 openModule(QFileInfo(filePath).absoluteFilePath()); // If use emulation, stream starts
853 }
854 }
855
856 MainWindow::~MainWindow()
857 {
858 MidiInterface::getInstance().uninstallInputHandler(&midiThreadReceivedEvent, this);
859 stream_->shutdown();
860 }
861
862 void MainWindow::onApplicationStateChanged(Qt::ApplicationState state)
863 {
864 switch (state) {
865 case Qt::ApplicationHidden:
866 case Qt::ApplicationInactive:
867 if (bt_) bt_->jamkeyOffAll();
868 break;
869 default:
870 break;
871 }
872 }
873
874 bool MainWindow::eventFilter(QObject* watched, QEvent* event)
875 {
876 if (auto fmForm = qobject_cast<FmInstrumentEditor*>(watched)) {
877 // Change current instrument by activating FM editor
878 if (event->type() == QEvent::WindowActivate) {
879 int row = findRowFromInstrumentList(fmForm->getInstrumentNumber());
880 ui->instrumentList->setCurrentRow(row);
881 }
882 else if (event->type() == QEvent::Resize) {
883 config_.lock()->setInstrumentFMWindowWidth(fmForm->width());
884 config_.lock()->setInstrumentFMWindowHeight(fmForm->height());
885 }
886 return false;
887 }
888
889 if (auto ssgForm = qobject_cast<SsgInstrumentEditor*>(watched)) {
890 // Change current instrument by activating SSG editor
891 if (event->type() == QEvent::WindowActivate) {
892 int row = findRowFromInstrumentList(ssgForm->getInstrumentNumber());
893 ui->instrumentList->setCurrentRow(row);
894 }
895 else if (event->type() == QEvent::Resize) {
896 config_.lock()->setInstrumentSSGWindowWidth(ssgForm->width());
897 config_.lock()->setInstrumentSSGWindowHeight(ssgForm->height());
898 }
899 return false;
900 }
901
902 if (auto adpcmForm = qobject_cast<AdpcmInstrumentEditor*>(watched)) {
903 // Change current instrument by activating ADPCM editor
904 if (event->type() == QEvent::WindowActivate) {
905 int row = findRowFromInstrumentList(adpcmForm->getInstrumentNumber());
906 ui->instrumentList->setCurrentRow(row);
907 }
908 else if (event->type() == QEvent::Resize) {
909 config_.lock()->setInstrumentADPCMWindowWidth(adpcmForm->width());
910 config_.lock()->setInstrumentADPCMWindowHeight(adpcmForm->height());
911 }
912 return false;
913 }
914
915 if (auto kitForm = qobject_cast<AdpcmDrumkitEditor*>(watched)) {
916 // Change current instrument by activating drumkit editor
917 if (event->type() == QEvent::WindowActivate) {
918 int row = findRowFromInstrumentList(kitForm->getInstrumentNumber());
919 ui->instrumentList->setCurrentRow(row);
920 }
921 else if (event->type() == QEvent::Resize) {
922 config_.lock()->setInstrumentDrumkitWindowWidth(kitForm->width());
923 config_.lock()->setInstrumentDrumkitWindowHeight(kitForm->height());
924 }
925 return false;
926 }
927
928 if (watched == ui->instrumentList) {
929 if (event->type() == QEvent::FocusIn) updateMenuByInstrumentList();
930 return false;
931 }
932
933 if (watched == renamingInstEdit_) {
934 if (event->type() == QEvent::FocusOut) finishRenamingInstrument();
935 return false;
936 }
937
938 return false;
939 }
940
941 void MainWindow::showEvent(QShowEvent*)
942 {
943 if (!hasShownOnce_) {
944 int y = config_.lock()->getMainWindowVerticalSplit();
945 if (y == -1) {
946 config_.lock()->setMainWindowVerticalSplit(ui->splitter->sizes().at(0));
947 }
948 else {
949 ui->splitter->setSizes({ y, ui->splitter->height() - ui->splitter->handleWidth() - y });
950 }
951 hasShownOnce_ = true;
952 }
953 }
954
955 void MainWindow::keyPressEvent(QKeyEvent *event)
956 {
957 if (!event->isAutoRepeat()) {
958 // Musical keyboard
959 Qt::Key qtKey = static_cast<Qt::Key>(event->key());
960 try {
961 bt_->jamKeyOn(getJamKeyFromLayoutMapping(qtKey, config_),
962 !config_.lock()->getFixJammingVolume());
963 } catch (std::invalid_argument&) {}
964 }
965 }
966
967 void MainWindow::keyReleaseEvent(QKeyEvent *event)
968 {
969 int key = event->key();
970
971 if (!event->isAutoRepeat()) {
972 // Musical keyboard
973 Qt::Key qtKey = static_cast<Qt::Key>(key);
974 try {
975 bt_->jamKeyOff(getJamKeyFromLayoutMapping(qtKey, config_));
976 } catch (std::invalid_argument&) {}
977 }
978 }
979
980 void MainWindow::dragEnterEvent(QDragEnterEvent* event)
981 {
982 auto mime = event->mimeData();
983 if (mime->hasUrls()) {
984 const auto urls = mime->urls();
985 for (auto& url : urls) {
986 const std::string ext = QFileInfo(url.toLocalFile()).suffix().toLower().toStdString();
987 if (io::ModuleIO::getInstance().testLoadableFormat(ext)
988 || io::BankIO::getInstance().testLoadableFormat(ext)) {
989 if (urls.size() == 1) event->acceptProposedAction();
990 }
991 if (io::InstrumentIO::getInstance().testLoadableFormat(ext)) {
992 continue;
993 }
994 return;
995 }
996 if (!urls.empty()) event->acceptProposedAction(); // For instruments
997 }
998 }
999
1000 void MainWindow::dropEvent(QDropEvent* event)
1001 {
1002 const auto urls = event->mimeData()->urls();
1003 for (const auto& url : urls) {
1004 const QString file = url.toLocalFile();
1005 const std::string ext = QFileInfo(file).suffix().toLower().toStdString();
1006 if (io::ModuleIO::getInstance().testLoadableFormat(ext)) {
1007 if (isWindowModified()) {
1008 switch (ModuleSaveCheckDialog(bt_->getModuleTitle(), this).exec()) {
1009 case QMessageBox::Yes:
1010 if (!on_actionSave_triggered()) return;
1011 break;
1012 case QMessageBox::No:
1013 break;
1014 case QMessageBox::Cancel:
1015 return;
1016 default:
1017 break;
1018 }
1019 }
1020
1021 bt_->stopPlaySong();
1022 lockWidgets(false);
1023
1024 openModule(file);
1025 return;
1026 }
1027 else if (io::InstrumentIO::getInstance().testLoadableFormat(ext)) {
1028 funcLoadInstrument(file);
1029 }
1030 if (io::BankIO::getInstance().testLoadableFormat(ext)) {
1031 funcImportInstrumentsFromBank(file);
1032 return;
1033 }
1034 }
1035 }
1036
1037 void MainWindow::resizeEvent(QResizeEvent* event)
1038 {
1039 QWidget::resizeEvent(event);
1040
1041 if (!isMaximized()) { // Check previous size
1042 config_.lock()->setMainWindowWidth(event->oldSize().width());
1043 config_.lock()->setMainWindowHeight(event->oldSize().height());
1044 }
1045 }
1046
1047 void MainWindow::moveEvent(QMoveEvent* event)
1048 {
1049 QWidget::moveEvent(event);
1050
1051 if (!isMaximized()) { // Check previous position
1052 config_.lock()->setMainWindowX(event->oldPos().x());
1053 config_.lock()->setMainWindowY(event->oldPos().y());
1054 }
1055 }
1056
1057 void MainWindow::closeEvent(QCloseEvent *event)
1058 {
1059 if (isWindowModified()) {
1060 switch (ModuleSaveCheckDialog(bt_->getModuleTitle(), this).exec()) {
1061 case QMessageBox::Yes:
1062 if (!on_actionSave_triggered()) {
1063 event->ignore();
1064 return;
1065 }
1066 break;
1067 case QMessageBox::No:
1068 break;
1069 case QMessageBox::Cancel:
1070 event->ignore();
1071 return;
1072 default:
1073 break;
1074 }
1075 }
1076
1077 if (isMaximized()) {
1078 config_.lock()->setMainWindowMaximized(true);
1079 }
1080 else {
1081 config_.lock()->setMainWindowMaximized(false);
1082 config_.lock()->setMainWindowWidth(width());
1083 config_.lock()->setMainWindowHeight(height());
1084 config_.lock()->setMainWindowX(x());
1085 config_.lock()->setMainWindowY(y());
1086 }
1087 config_.lock()->setMainWindowVerticalSplit(ui->splitter->sizes().at(0));
1088
1089 auto& mainTbConfig = config_.lock()->getMainToolbarConfiguration();
1090 auto& subTbConfig = config_.lock()->getSubToolbarConfiguration();
1091 auto mainTbArea = toolBarArea(ui->mainToolBar);
1092 auto subTbArea = toolBarArea(ui->subToolBar);
1093 if (ui->mainToolBar->isFloating()) {
1094 mainTbConfig.setPosition(Configuration::ToolbarPosition::FloatPorition);
1095 mainTbConfig.setX(ui->mainToolBar->x());
1096 mainTbConfig.setY(ui->mainToolBar->y());
1097 }
1098 else {
1099 mainTbConfig.setPosition(utils::findMapValue(TB_POS_, mainTbArea)->first);
1100 mainTbConfig.setNumber(0);
1101 mainTbConfig.setBreakBefore(false);
1102 }
1103 if (ui->subToolBar->isFloating()) {
1104 subTbConfig.setPosition(Configuration::ToolbarPosition::FloatPorition);
1105 subTbConfig.setX(ui->subToolBar->x());
1106 subTbConfig.setY(ui->subToolBar->y());
1107 }
1108 else {
1109 subTbConfig.setPosition(utils::findMapValue(TB_POS_, mainTbArea)->first);
1110 subTbConfig.setNumber(0);
1111 subTbConfig.setBreakBefore(false);
1112 }
1113 if (mainTbArea == subTbArea) {
1114 auto mainPos = ui->mainToolBar->pos();
1115 auto subPos = ui->subToolBar->pos();
1116 switch (mainTbArea) {
1117 case Qt::TopToolBarArea:
1118 {
1119 if (mainPos.x() == subPos.x()) {
1120 bool cond = (mainPos.y() < subPos.y());
1121 mainTbConfig.setNumber(cond ? 0 : 1);
1122 mainTbConfig.setBreakBefore(!cond);
1123 subTbConfig.setNumber(cond ? 1 : 0);
1124 subTbConfig.setBreakBefore(cond);
1125 }
1126 else {
1127 bool cond = (mainPos.x() < subPos.x());
1128 mainTbConfig.setNumber(cond ? 0 : 1);
1129 mainTbConfig.setBreakBefore(false);
1130 subTbConfig.setNumber(cond ? 1 : 0);
1131 subTbConfig.setBreakBefore(false);
1132 }
1133 break;
1134 }
1135 case Qt::BottomToolBarArea:
1136 {
1137 if (mainPos.x() == subPos.x()) {
1138 bool cond = (subPos.y() < mainPos.y());
1139 mainTbConfig.setNumber(cond ? 0 : 1);
1140 mainTbConfig.setBreakBefore(!cond);
1141 subTbConfig.setNumber(cond ? 1 : 0);
1142 subTbConfig.setBreakBefore(cond);
1143 }
1144 else {
1145 bool cond = (mainPos.x() < subPos.x());
1146 mainTbConfig.setNumber(cond ? 0 : 1);
1147 mainTbConfig.setBreakBefore(false);
1148 subTbConfig.setNumber(cond ? 1 : 0);
1149 subTbConfig.setBreakBefore(false);
1150 }
1151 break;
1152 }
1153 case Qt::LeftToolBarArea:
1154 {
1155 if (mainPos.x() == subPos.x()) {
1156 bool cond = (mainPos.y() < subPos.y());
1157 mainTbConfig.setNumber(cond ? 0 : 1);
1158 mainTbConfig.setBreakBefore(false);
1159 subTbConfig.setNumber(cond ? 1 : 0);
1160 subTbConfig.setBreakBefore(false);
1161 }
1162 else {
1163 bool cond = (mainPos.x() < subPos.x());
1164 mainTbConfig.setNumber(cond ? 0 : 1);
1165 mainTbConfig.setBreakBefore(!cond);
1166 subTbConfig.setNumber(cond ? 1 : 0);
1167 subTbConfig.setBreakBefore(cond);
1168 }
1169 break;
1170 }
1171 case Qt::RightToolBarArea:
1172 {
1173 if (mainPos.x() == subPos.x()) {
1174 bool cond = (mainPos.y() < subPos.y());
1175 mainTbConfig.setNumber(cond ? 0 : 1);
1176 mainTbConfig.setBreakBefore(false);
1177 subTbConfig.setNumber(cond ? 1 : 0);
1178 subTbConfig.setBreakBefore(false);
1179 }
1180 else {
1181 bool cond = (subPos.x() < mainPos.x());
1182 mainTbConfig.setNumber(cond ? 0 : 1);
1183 mainTbConfig.setBreakBefore(!cond);
1184 subTbConfig.setNumber(cond ? 1 : 0);
1185 subTbConfig.setBreakBefore(cond);
1186 }
1187 break;
1188 }
1189 default:
1190 break;
1191 }
1192 }
1193 config_.lock()->setVisibleToolbar(ui->mainToolBar->isVisible());
1194 config_.lock()->setVisibleStatusBar(ui->statusBar->isVisible());
1195 config_.lock()->setFollowMode(bt_->isFollowPlay());
1196
1197 instDialogMan_->removeAll();
1198
1199 io::saveFileHistory(fileHistory_);
1200
1201 bmManForm_->close();
1202 ksManForm_->close();
1203
1204 event->accept();
1205 }
1206
1207 void MainWindow::freezeViews()
1208 {
1209 ui->orderList->freeze();
1210 ui->patternEditor->freeze();
1211 }
1212
1213 void MainWindow::unfreezeViews()
1214 {
1215 ui->orderList->unfreeze();
1216 ui->patternEditor->unfreeze();
1217 }
1218
1219 void MainWindow::setShortcuts()
1220 {
1221 auto shortcuts = config_.lock()->getShortcuts();
1222 octUpSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::OctaveUp)));
1223 octDownSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::OctaveDown)));
1224 focusPtnSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FocusOnPattern)));
1225 focusOdrSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FocusOnOrder)));
1226 focusInstSc_.setKey(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FocusOnInstrument)));
1227 playAndStopSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayAndStop)));
1228 ui->actionPlay->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Play)));
1229 ui->actionPlay_From_Start->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayFromStart)));
1230 ui->actionPlay_Pattern->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayPattern)));
1231 ui->actionPlay_From_Cursor->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayFromCursor)));
1232 ui->actionPlay_From_Marker->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayFromMarker)));
1233 playStepSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PlayStep)));
1234 ui->actionStop->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Stop)));
1235 ui->actionEdit_Mode->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ToggleEditJam)));
1236 ui->actionSet_Ro_w_Marker->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SetMarker)));
1237 ui->actionMix->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteMix)));
1238 ui->actionOverwrite->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteOverwrite)));
1239 ui->action_Insert->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PasteInsert)));
1240 ui->actionAll->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectAll)));
1241 ui->actionNone->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Deselect)));
1242 ui->actionRow->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectRow)));
1243 ui->actionColumn->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectColumn)));
1244 ui->actionPattern->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectColumn)));
1245 ui->actionOrder->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SelectOrder)));
1246 ui->action_Go_To->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::GoToStep)));
1247 ui->actionToggle_Track->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ToggleTrack)));
1248 ui->actionSolo_Track->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::SoloTrack)));
1249 ui->actionInterpolate->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::Interpolate)));
1250 goPrevOdrSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::GoToPrevOrder)));
1251 goNextOdrSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::GoToNextOrder)));
1252 ui->action_Toggle_Bookmark->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ToggleBookmark)));
1253 ui->action_Previous_Bookmark->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PrevBookmark)));
1254 ui->action_Next_Bookmark->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::NextBookmark)));
1255 ui->actionDecrease_Note->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreaseNote)));
1256 ui->actionIncrease_Note->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreaseNote)));
1257 ui->actionDecrease_Octave->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreaseOctave)));
1258 ui->actionIncrease_Octave->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreaseOctave)));
1259 prevInstSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PrevInstrument)));
1260 nextInstSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::NextInstrument)));
1261 ui->action_Instrument_Mask->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::MaskInstrument)));
1262 ui->action_Volume_Mask->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::MaskVolume)));
1263 ui->actionEdit->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::EditInstrument)));
1264 ui->actionFollow_Mode->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FollowMode)));
1265 ui->actionDuplicate_Order->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DuplicateOrder)));
1266 ui->actionClone_Patterns->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ClonePatterns)));
1267 ui->actionClone_Order->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::CloneOrder)));
1268 ui->actionReplace_Instrument->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ReplaceInstrument)));
1269 ui->actionExpand->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ExpandPattern)));
1270 ui->actionShrink->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::ShrinkPattern)));
1271 ui->actionFine_Decrease_Values->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FineDecreaseValues)));
1272 ui->actionFine_Increase_Values->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::FineIncreaseValues)));
1273 ui->actionCoarse_D_ecrease_Values->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::CoarseDecreaseValues)));
1274 ui->actionCoarse_I_ncrease_Values->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::CoarseIncreaseValuse)));
1275 incPtnSizeSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreasePatternSize)));
1276 decPtnSizeSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreasePatternSize)));
1277 incEditStepSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::IncreaseEditStep)));
1278 decEditStepSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DecreaseEditStep)));
1279 ui->action_Effect_List->setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::DisplayEffectList)));
1280 prevSongSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::PreviousSong)));
1281 nextSongSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::NextSong)));
1282 jamVolUpSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::JamVolumeUp)));
1283 jamVolDownSc_.setShortcut(gui_utils::strToKeySeq(shortcuts.at(Configuration::ShortcutAction::JamVolumeDown)));
1284
1285 ui->orderList->onShortcutUpdated();
1286 ui->patternEditor->onShortcutUpdated();
1287 }
1288
1289 void MainWindow::updateInstrumentListColors()
1290 {
1291 ui->instrumentList->setStyleSheet(
1292 QString("QListWidget { color: %1; background: %2; }")
1293 .arg(palette_->ilistTextColor.name(QColor::HexArgb),
1294 palette_->ilistBackColor.name(QColor::HexArgb))
1295 + QString("QListWidget::item:hover { color: %1; background: %2; }")
1296 .arg(palette_->ilistTextColor.name(QColor::HexArgb),
1297 palette_->ilistHovBackColor.name(QColor::HexArgb))
1298 + QString("QListWidget::item:selected { color: %1; background: %2; }")
1299 .arg(palette_->ilistTextColor.name(QColor::HexArgb),
1300 palette_->ilistSelBackColor.name(QColor::HexArgb))
1301 + QString("QListWidget::item:selected:hover { color: %1; background: %2; }")
1302 .arg(palette_->ilistTextColor.name(QColor::HexArgb),
1303 palette_->ilistHovSelBackColor.name(QColor::HexArgb)));
1304 }
1305
1306 void MainWindow::setOrderListGroupMaximumWidth()
1307 {
1308 ui->orderListGroupBox->setMaximumWidth(
1309 ui->orderListGroupBox->contentsMargins().left()
1310 + ui->orderListGroupBox->layout()->contentsMargins().left()
1311 + ui->orderList->maximumWidth()
1312 + ui->orderListGroupBox->layout()->contentsMargins().right()
1313 + ui->orderListGroupBox->contentsMargins().right());
1314 }
1315
1316 /********** MIDI **********/
1317 void MainWindow::midiThreadReceivedEvent(double delay, const uint8_t *msg, size_t len, void *userData)
1318 {
1319 MainWindow *self = reinterpret_cast<MainWindow *>(userData);
1320
1321 Q_UNUSED(delay)
1322
1323 // Note-On/Note-Off
1324 if (len == 3 && (msg[0] & 0xe0) == 0x80) {
1325 uint8_t status = msg[0];
1326 uint8_t key = msg[1];
1327 uint8_t velocity = msg[2];
1328 QMetaMethod method = self->metaObject()->method(self->midiKeyEventMethod_);
1329 method.invoke(self, Qt::QueuedConnection,
1330 Q_ARG(uchar, status), Q_ARG(uchar, key), Q_ARG(uchar, velocity));
1331 }
1332 // Program change
1333 else if (len == 2 && (msg[0] & 0xf0) == 0xc0) {
1334 uint8_t status = msg[0];
1335 uint8_t program = msg[1];
1336 QMetaMethod method = self->metaObject()->method(self->midiProgramEventMethod_);
1337 method.invoke(self, Qt::QueuedConnection,
1338 Q_ARG(uchar, status), Q_ARG(uchar, program));
1339 }
1340 }
1341
1342 void MainWindow::midiKeyEvent(uchar status, uchar key, uchar velocity)
1343 {
1344 bool release = ((status & 0xf0) == 0x80) || velocity == 0;
1345 int k = static_cast<int>(key) - 12;
1346
1347 octave_->setValue(k / 12);
1348
1349 if (importBankDialog_) {
1350 if (bankJamMidiCtrl_.load()) return;
1351 importBankDialog_->onJamKeyOffByMidi(k);
1352 if (!release) importBankDialog_->onJamKeyOnByMidi(k);
1353 return;
1354 }
1355
1356 int n = instDialogMan_->getActivatedEditorIndex();
1357 if (n == -1) {
1358 bt_->jamKeyOff(k); // possibility to recover on stuck note
1359 if (!release) bt_->jamKeyOn(k, !config_.lock()->getFixJammingVolume());
1360 }
1361 else {
1362 SoundSource src = bt_->getInstrument(n)->getSoundSource();
1363 bt_->jamKeyOffForced(k, src); // possibility to recover on stuck note
1364 if (!release) bt_->jamKeyOnForced(k, src, !config_.lock()->getFixJammingVolume());
1365 }
1366 }
1367
1368 void MainWindow::midiProgramEvent(uchar status, uchar program)
1369 {
1370 Q_UNUSED(status)
1371 int row = findRowFromInstrumentList(program);
1372 ui->instrumentList->setCurrentRow(row);
1373 }
1374
1375 /********** Instrument list **********/
1376 void MainWindow::addInstrument()
1377 {
1378 SoundSource src = bt_->getCurrentTrackAttribute().source;
1379 switch (src) {
1380 case SoundSource::FM:
1381 case SoundSource::SSG:
1382 case SoundSource::ADPCM:
1383 {
1384 std::unordered_map<SoundSource, InstrumentType> map = {
1385 { SoundSource::FM, InstrumentType::FM },
1386 { SoundSource::SSG, InstrumentType::SSG },
1387 { SoundSource::ADPCM, InstrumentType::ADPCM },
1388 };
1389 auto& list = ui->instrumentList;
1390
1391 int num = bt_->findFirstFreeInstrumentNumber();
1392 if (num == -1) return; // Maximum count check
1393
1394 QString name = tr("Instrument %1").arg(num);
1395 bt_->addInstrument(num, map.at(src), name.toUtf8().toStdString());
1396
1397 comStack_->push(new AddInstrumentQtCommand(
1398 list, num, name, map.at(src), instDialogMan_, this,
1399 config_.lock()->getWriteOnlyUsedSamples()));
1400 ui->instrumentList->setCurrentRow(num);
1401 break;
1402 }
1403 case SoundSource::RHYTHM:
1404 break;
1405 }
1406 }
1407
1408 void MainWindow::addDrumkit()
1409 {
1410 auto& list = ui->instrumentList;
1411
1412 int num = bt_->findFirstFreeInstrumentNumber();
1413 if (num == -1) return; // Maximum count check
1414
1415 QString name = tr("Instrument %1").arg(num);
1416 bt_->addInstrument(num, InstrumentType::Drumkit, name.toUtf8().toStdString());
1417
1418 comStack_->push(new AddInstrumentQtCommand(
1419 list, num, name, InstrumentType::Drumkit, instDialogMan_, this,
1420 config_.lock()->getWriteOnlyUsedSamples()));
1421 ui->instrumentList->setCurrentRow(num);
1422 }
1423
1424 void MainWindow::removeInstrument(int row)
1425 {
1426 if (row < 0) return;
1427
1428 auto& list = ui->instrumentList;
1429 int num = list->item(row)->data(Qt::UserRole).toInt();
1430
1431 auto inst = bt_->getInstrument(num);
1432
1433 bool updateRequest = false;
1434 if (config_.lock()->getWriteOnlyUsedSamples()){
1435 if (inst->getSoundSource() == SoundSource::ADPCM) {
1436 size_t size = bt_->getSampleADPCMUsers(dynamic_cast<InstrumentADPCM*>(
1437 inst.get())->getSampleNumber()).size();
1438 if (size == 1) updateRequest = true;
1439 }
1440 }
1441
1442 bt_->removeInstrument(num);
1443
1444 // Cancel renaming instrument
1445 if (list->item(row) == renamingInstItem_) {
1446 list->removeItemWidget(renamingInstItem_);
1447 renamingInstItem_ = nullptr;
1448 renamingInstEdit_ = nullptr;
1449 }
1450
1451 comStack_->push(new RemoveInstrumentQtCommand(list, num, row, gui_utils::utf8ToQString(inst->getName()),
1452 inst->getType(), instDialogMan_, this, updateRequest));
1453 }
1454
1455 void MainWindow::openInstrumentEditor()
1456 {
1457 auto item = ui->instrumentList->currentItem();
1458 int num = item->data(Qt::UserRole).toInt();
1459
1460 if (!instDialogMan_->hasShownEditor(num)) {
1461 // Create editor
1462 InstrumentEditor* editor;
1463 auto inst = bt_->getInstrument(num);
1464
1465 switch (inst->getType()) {
1466 case InstrumentType::FM:
1467 {
1468 auto fmEditor = new FmInstrumentEditor(num, this);
1469 editor = fmEditor;
1470 fmEditor->setCore(bt_);
1471 fmEditor->setConfiguration(config_.lock());
1472 fmEditor->setColorPalette(palette_);
1473 fmEditor->resize(config_.lock()->getInstrumentFMWindowWidth(),
1474 config_.lock()->getInstrumentFMWindowHeight());
1475
1476 QObject::connect(fmEditor, &FmInstrumentEditor::envelopeNumberChanged,
1477 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMEnvelopeNumberChanged);
1478 QObject::connect(fmEditor, &FmInstrumentEditor::envelopeParameterChanged,
1479 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMEnvelopeParameterChanged);
1480 QObject::connect(fmEditor, &FmInstrumentEditor::lfoNumberChanged,
1481 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMLFONumberChanged);
1482 QObject::connect(fmEditor, &FmInstrumentEditor::lfoParameterChanged,
1483 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMLFOParameterChanged);
1484 QObject::connect(fmEditor, &FmInstrumentEditor::operatorSequenceNumberChanged,
1485 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMOperatorSequenceNumberChanged);
1486 QObject::connect(fmEditor, &FmInstrumentEditor::operatorSequenceParameterChanged,
1487 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMOperatorSequenceParameterChanged);
1488 QObject::connect(fmEditor, &FmInstrumentEditor::arpeggioNumberChanged,
1489 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMArpeggioNumberChanged);
1490 QObject::connect(fmEditor, &FmInstrumentEditor::arpeggioParameterChanged,
1491 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMArpeggioParameterChanged);
1492 QObject::connect(fmEditor, &FmInstrumentEditor::pitchNumberChanged,
1493 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMPitchNumberChanged);
1494 QObject::connect(fmEditor, &FmInstrumentEditor::pitchParameterChanged,
1495 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentFMPitchParameterChanged);
1496 QObject::connect(fmEditor, &FmInstrumentEditor::jamKeyOnEvent,
1497 this, [&](JamKey key) {
1498 bt_->jamKeyOnForced(key, SoundSource::FM, !config_.lock()->getFixJammingVolume());
1499 }, Qt::DirectConnection);
1500 QObject::connect(fmEditor, &FmInstrumentEditor::jamKeyOffEvent,
1501 this, [&](JamKey key) { bt_->jamKeyOffForced(key, SoundSource::FM); },
1502 Qt::DirectConnection);
1503 QObject::connect(fmEditor, &FmInstrumentEditor::modified,
1504 this, &MainWindow::setModifiedTrue);
1505
1506 fmEditor->installEventFilter(this);
1507
1508 instDialogMan_->onInstrumentFMEnvelopeNumberChanged();
1509 instDialogMan_->onInstrumentFMLFONumberChanged();
1510 instDialogMan_->onInstrumentFMOperatorSequenceNumberChanged();
1511 instDialogMan_->onInstrumentFMArpeggioNumberChanged();
1512 instDialogMan_->onInstrumentFMPitchNumberChanged();
1513 break;
1514 }
1515 case InstrumentType::SSG:
1516 {
1517 auto ssgEditor = new SsgInstrumentEditor(num, this);
1518 editor = ssgEditor;
1519 ssgEditor->setCore(bt_);
1520 ssgEditor->setConfiguration(config_.lock());
1521 ssgEditor->setColorPalette(palette_);
1522 ssgEditor->resize(config_.lock()->getInstrumentSSGWindowWidth(),
1523 config_.lock()->getInstrumentSSGWindowHeight());
1524
1525 QObject::connect(ssgEditor, &SsgInstrumentEditor::waveformNumberChanged,
1526 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGWaveformNumberChanged);
1527 QObject::connect(ssgEditor, &SsgInstrumentEditor::waveformParameterChanged,
1528 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGWaveformParameterChanged);
1529 QObject::connect(ssgEditor, &SsgInstrumentEditor::toneNoiseNumberChanged,
1530 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGToneNoiseNumberChanged);
1531 QObject::connect(ssgEditor, &SsgInstrumentEditor::toneNoiseParameterChanged,
1532 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGToneNoiseParameterChanged);
1533 QObject::connect(ssgEditor, &SsgInstrumentEditor::envelopeNumberChanged,
1534 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGEnvelopeNumberChanged);
1535 QObject::connect(ssgEditor, &SsgInstrumentEditor::envelopeParameterChanged,
1536 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGEnvelopeParameterChanged);
1537 QObject::connect(ssgEditor, &SsgInstrumentEditor::arpeggioNumberChanged,
1538 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGArpeggioNumberChanged);
1539 QObject::connect(ssgEditor, &SsgInstrumentEditor::arpeggioParameterChanged,
1540 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGArpeggioParameterChanged);
1541 QObject::connect(ssgEditor, &SsgInstrumentEditor::pitchNumberChanged,
1542 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGPitchNumberChanged);
1543 QObject::connect(ssgEditor, &SsgInstrumentEditor::pitchParameterChanged,
1544 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentSSGPitchParameterChanged);
1545 QObject::connect(ssgEditor, &SsgInstrumentEditor::jamKeyOnEvent,
1546 this, [&](JamKey key) {
1547 bt_->jamKeyOnForced(key, SoundSource::SSG, !config_.lock()->getFixJammingVolume());
1548 }, Qt::DirectConnection);
1549 QObject::connect(ssgEditor, &SsgInstrumentEditor::jamKeyOffEvent,
1550 this, [&](JamKey key) { bt_->jamKeyOffForced(key, SoundSource::SSG); }
1551 , Qt::DirectConnection);
1552 QObject::connect(ssgEditor, &SsgInstrumentEditor::modified,
1553 this, &MainWindow::setModifiedTrue);
1554
1555 ssgEditor->installEventFilter(this);
1556
1557 instDialogMan_->onInstrumentSSGWaveformNumberChanged();
1558 instDialogMan_->onInstrumentSSGToneNoiseNumberChanged();
1559 instDialogMan_->onInstrumentSSGEnvelopeNumberChanged();
1560 instDialogMan_->onInstrumentSSGArpeggioNumberChanged();
1561 instDialogMan_->onInstrumentSSGPitchNumberChanged();
1562 break;
1563 }
1564 case InstrumentType::ADPCM:
1565 {
1566 auto adpcmEditor = new AdpcmInstrumentEditor(num, this);
1567 editor = adpcmEditor;
1568 adpcmEditor->setCore(bt_);
1569 adpcmEditor->setConfiguration(config_.lock());
1570 adpcmEditor->setColorPalette(palette_);
1571 adpcmEditor->resize(config_.lock()->getInstrumentADPCMWindowWidth(),
1572 config_.lock()->getInstrumentADPCMWindowHeight());
1573
1574 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::sampleNumberChanged,
1575 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleNumberChanged);
1576 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::sampleParameterChanged,
1577 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleParameterChanged);
1578 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::sampleAssignRequested,
1579 this, &MainWindow::assignADPCMSamples);
1580 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::sampleMemoryChanged,
1581 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleMemoryUpdated);
1582 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::envelopeNumberChanged,
1583 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMEnvelopeNumberChanged);
1584 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::envelopeParameterChanged,
1585 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMEnvelopeParameterChanged);
1586 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::arpeggioNumberChanged,
1587 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMArpeggioNumberChanged);
1588 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::arpeggioParameterChanged,
1589 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMArpeggioParameterChanged);
1590 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::pitchNumberChanged,
1591 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMPitchNumberChanged);
1592 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::pitchParameterChanged,
1593 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMPitchParameterChanged);
1594 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::jamKeyOnEvent,
1595 this, [&](JamKey key) {
1596 bt_->jamKeyOnForced(key, SoundSource::ADPCM, !config_.lock()->getFixJammingVolume());
1597 }, Qt::DirectConnection);
1598 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::jamKeyOffEvent,
1599 this, [&](JamKey key) { bt_->jamKeyOffForced(key, SoundSource::ADPCM); },
1600 Qt::DirectConnection);
1601 QObject::connect(adpcmEditor, &AdpcmInstrumentEditor::modified,
1602 this, &MainWindow::setModifiedTrue);
1603
1604 adpcmEditor->installEventFilter(this);
1605
1606 instDialogMan_->onInstrumentADPCMSampleNumberChanged();
1607 instDialogMan_->onInstrumentADPCMEnvelopeNumberChanged();
1608 instDialogMan_->onInstrumentADPCMArpeggioNumberChanged();
1609 instDialogMan_->onInstrumentADPCMPitchNumberChanged();
1610 break;
1611 }
1612 case InstrumentType::Drumkit:
1613 {
1614 auto kitEditor = new AdpcmDrumkitEditor(num, this);
1615 editor = kitEditor;
1616 kitEditor->setCore(bt_);
1617 kitEditor->setConfiguration(config_.lock());
1618 kitEditor->setColorPalette(palette_);
1619 kitEditor->resize(config_.lock()->getInstrumentDrumkitWindowWidth(),
1620 config_.lock()->getInstrumentDrumkitWindowHeight());
1621
1622 QObject::connect(kitEditor, &AdpcmDrumkitEditor::sampleNumberChanged,
1623 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleNumberChanged);
1624 QObject::connect(kitEditor, &AdpcmDrumkitEditor::sampleParameterChanged,
1625 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleParameterChanged);
1626 QObject::connect(kitEditor, &AdpcmDrumkitEditor::sampleAssignRequested,
1627 this, &MainWindow::assignADPCMSamples);
1628 QObject::connect(kitEditor, &AdpcmDrumkitEditor::sampleMemoryChanged,
1629 instDialogMan_.get(), &InstrumentEditorManager::onInstrumentADPCMSampleMemoryUpdated);
1630 QObject::connect(kitEditor, &AdpcmDrumkitEditor::jamKeyOnEvent,
1631 this, [&](JamKey key) {
1632 bt_->jamKeyOnForced(key, SoundSource::ADPCM, !config_.lock()->getFixJammingVolume());
1633 }, Qt::DirectConnection);
1634 QObject::connect(kitEditor, &AdpcmDrumkitEditor::jamKeyOffEvent,
1635 this, [&](JamKey key) { bt_->jamKeyOffForced(key, SoundSource::ADPCM); },
1636 Qt::DirectConnection);
1637 QObject::connect(kitEditor, &AdpcmDrumkitEditor::modified,
1638 this, &MainWindow::setModifiedTrue);
1639
1640 kitEditor->installEventFilter(this);
1641
1642 instDialogMan_->onInstrumentADPCMSampleNumberChanged();
1643 break;
1644 }
1645 default:
1646 throw std::invalid_argument("Invalid instrument type");
1647 }
1648
1649 editor->addActions({ &octUpSc_, &octDownSc_, &jamVolUpSc_, &jamVolDownSc_ });
1650
1651 instDialogMan_->add(num, editor);
1652 }
1653
1654 instDialogMan_->showEditor(num);
1655 }
1656
1657 int MainWindow::findRowFromInstrumentList(int instNum)
1658 {
1659 auto& list = ui->instrumentList;
1660 int row = 0;
1661 for (; row < list->count(); ++row) {
1662 auto item = list->item(row);
1663 if (item->data(Qt::UserRole).toInt() == instNum) break;
1664 }
1665 return row;
1666 }
1667
1668 void MainWindow::renameInstrument()
1669 {
1670 auto list = ui->instrumentList;
1671 auto item = list->currentItem();
1672 // Finish current edit
1673 if (item == renamingInstItem_) {
1674 finishRenamingInstrument();
1675 return;
1676 }
1677 else if (renamingInstItem_) {
1678 finishRenamingInstrument();
1679 }
1680 renamingInstItem_ = item;
1681
1682 int num = item->data(Qt::UserRole).toInt();
1683 renamingInstEdit_ = new QLineEdit(gui_utils::utf8ToQString(bt_->getInstrument(num)->getName()));
1684 QObject::connect(renamingInstEdit_, &QLineEdit::editingFinished, this, &MainWindow::finishRenamingInstrument);
1685 renamingInstEdit_->installEventFilter(this);
1686 ui->instrumentList->setItemWidget(item, renamingInstEdit_);
1687 renamingInstEdit_->selectAll();
1688 renamingInstEdit_->setFocus();
1689 }
1690
1691 void MainWindow::finishRenamingInstrument()
1692 {
1693 if (!renamingInstItem_ || !renamingInstEdit_) return;
1694 bool hasFocus = renamingInstEdit_->hasFocus();
1695 auto list = ui->instrumentList;
1696 int num = renamingInstItem_->data(Qt::UserRole).toInt();
1697 int row = findRowFromInstrumentList(num);
1698 auto oldName = gui_utils::utf8ToQString(bt_->getInstrument(num)->getName());
1699 QString newName = renamingInstEdit_->text();
1700 list->removeItemWidget(renamingInstItem_);
1701 if (newName != oldName) {
1702 bt_->setInstrumentName(num, newName.toUtf8().toStdString());
1703 comStack_->push(new ChangeInstrumentNameQtCommand(list, num, row, instDialogMan_, oldName, newName));
1704 }
1705 renamingInstItem_ = nullptr;
1706 renamingInstEdit_ = nullptr;
1707 if (hasFocus) ui->instrumentList->setFocus();
1708 }
1709
1710 void MainWindow::cloneInstrument()
1711 {
1712 int num = bt_->findFirstFreeInstrumentNumber();
1713 if (num == -1) return;
1714
1715 int refNum = ui->instrumentList->currentItem()->data(Qt::UserRole).toInt();
1716 // KEEP CODE ORDER //
1717 bt_->cloneInstrument(num, refNum);
1718 auto inst = bt_->getInstrument(num);
1719 comStack_->push(new CloneInstrumentQtCommand(ui->instrumentList, num, inst->getType(),
1720 gui_utils::utf8ToQString(inst->getName()), instDialogMan_));
1721 //----------//
1722 }
1723
1724 void MainWindow::deepCloneInstrument()
1725 {
1726 int num = bt_->findFirstFreeInstrumentNumber();
1727 if (num == -1) return;
1728
1729 int refNum = ui->instrumentList->currentItem()->data(Qt::UserRole).toInt();
1730 // KEEP CODE ORDER //
1731 bt_->deepCloneInstrument(num, refNum);
1732 auto inst = bt_->getInstrument(num);
1733 comStack_->push(new DeepCloneInstrumentQtCommand(
1734 ui->instrumentList, num, inst->getType(), gui_utils::utf8ToQString(inst->getName()),
1735 instDialogMan_, this, config_.lock()->getWriteOnlyUsedSamples()));
1736 //----------//
1737 }
1738
1739 void MainWindow::loadInstrument()
1740 {
1741 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
1742 std::vector<std::string> orgFilters = io::InstrumentIO::getInstance().getLoadFilter();
1743 QStringList filters;
1744 std::transform(orgFilters.begin(), orgFilters.end(), std::back_inserter(filters),
1745 [](const std::string& f) { return QString::fromStdString(f); });
1746 QString selectedFilter = filters.at(config_.lock()->getInstrumentOpenFormat());
1747 const QStringList files = QFileDialog::getOpenFileNames(this, tr("Open instrument"), (dir.isEmpty() ? "./" : dir),
1748 filters.join(";;"), &selectedFilter
1749 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
1750 , QFileDialog::DontUseNativeDialog
1751 #endif
1752 );
1753 if (files.empty()) return;
1754
1755 int index = std::distance(filters.begin(), utils::find(filters, selectedFilter));
1756 config_.lock()->setInstrumentOpenFormat(index);
1757
1758 for (const QString& file : files) funcLoadInstrument(file);
1759 }
1760
1761 void MainWindow::funcLoadInstrument(QString file)
1762 {
1763 int n = bt_->findFirstFreeInstrumentNumber();
1764 if (n == -1) {
1765 FileIOErrorMessageBox(file, true, io::FileType::Inst,
1766 tr("The number of instruments has reached the upper limit."), this).exec();
1767 return;
1768 }
1769
1770 try {
1771 io::BinaryContainer container;
1772 {
1773 QFile fp(file);
1774 if (!fp.open(QIODevice::ReadOnly)) {
1775 FileIOErrorMessageBox::openError(file, true, io::FileType::Inst, this);
1776 return;
1777 }
1778 QByteArray&& array = fp.readAll();
1779 fp.close();
1780 std::move(array.begin(), array.end(), std::back_inserter(container));
1781 }
1782 bt_->loadInstrument(container, file.toStdString(), n);
1783
1784 auto inst = bt_->getInstrument(n);
1785 comStack_->push(new AddInstrumentQtCommand(
1786 ui->instrumentList, n, gui_utils::utf8ToQString(inst->getName()), inst->getType(),
1787 instDialogMan_, this, config_.lock()->getWriteOnlyUsedSamples()));
1788 ui->instrumentList->setCurrentRow(n);
1789 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
1790 }
1791 catch (io::FileIOError& e) {
1792 FileIOErrorMessageBox(file, true, e, this).exec();
1793 }
1794 catch (std::exception& e) {
1795 FileIOErrorMessageBox(file, true, io::FileType::Inst, QString(e.what()), this).exec();
1796 }
1797 }
1798
1799 void MainWindow::saveInstrument()
1800 {
1801 int n = ui->instrumentList->currentItem()->data(Qt::UserRole).toInt();
1802 QString name = gui_utils::utf8ToQString(bt_->getInstrument(n)->getName());
1803
1804 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
1805 std::vector<std::string> orgFilters = io::InstrumentIO::getInstance().getSaveFilter();
1806 QStringList filters;
1807 std::transform(orgFilters.begin(), orgFilters.end(), std::back_inserter(filters),
1808 [](const std::string& f) { return QString::fromStdString(f); });
1809 QString defaultFilter = filters.front(); // bti
1810 QString file = QFileDialog::getSaveFileName(
1811 this, tr("Save instrument"),
1812 QString("%1/%2.bti").arg(dir.isEmpty() ? "." : dir, name),
1813 filters.join(";;"), &defaultFilter
1814 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
1815 , QFileDialog::DontUseNativeDialog
1816 #endif
1817 );
1818 if (file.isNull()) return;
1819 if (!file.endsWith(".bti")) file += ".bti"; // For linux
1820
1821 try {
1822 QByteArray bytes;
1823 {
1824 io::BinaryContainer container;
1825 bt_->saveInstrument(container, n);
1826 bytes.reserve(container.size());
1827 std::move(container.begin(), container.end(), std::back_inserter(bytes));
1828 }
1829 QFile fp(file);
1830 if (!fp.open(QIODevice::WriteOnly)) {
1831 FileIOErrorMessageBox::openError(file, false, io::FileType::Inst, this);
1832 return;
1833 }
1834 fp.write(bytes);
1835 fp.close();
1836
1837 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
1838 }
1839 catch (io::FileIOError& e) {
1840 FileIOErrorMessageBox(file, false, e, this).exec();
1841 }
1842 catch (std::exception& e) {
1843 FileIOErrorMessageBox(file, false, io::FileType::Inst, QString(e.what()), this).exec();
1844 }
1845 }
1846
1847 void MainWindow::importInstrumentsFromBank()
1848 {
1849 stopPlaySong();
1850
1851 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
1852 std::vector<std::string> orgFilters = io::BankIO::getInstance().getLoadFilter();
1853 QStringList filters;
1854 std::transform(orgFilters.begin(), orgFilters.end(), std::back_inserter(filters),
1855 [](const std::string& f) { return QString::fromStdString(f); });
1856 QString selectedFilter = filters.at(config_.lock()->getBankOpenFormat());
1857 QString file = QFileDialog::getOpenFileName(this, tr("Open bank"), (dir.isEmpty() ? "./" : dir),
1858 filters.join(";;"), &selectedFilter
1859 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
1860 , QFileDialog::DontUseNativeDialog
1861 #endif
1862 );
1863 if (file.isNull()) return;
1864
1865 int index = std::distance(filters.begin(), utils::find(filters, selectedFilter));
1866 config_.lock()->setBankOpenFormat(index);
1867
1868 funcImportInstrumentsFromBank(file);
1869 }
1870
1871 void MainWindow::funcImportInstrumentsFromBank(QString file)
1872 {
1873 stopPlaySong();
1874
1875 std::unique_ptr<AbstractBank> bank;
1876 try {
1877 io::BinaryContainer container;
1878 {
1879 QFile fp(file);
1880 if (!fp.open(QIODevice::ReadOnly)) {
1881 FileIOErrorMessageBox::openError(file, true, io::FileType::Bank, this);
1882 return;
1883 }
1884 QByteArray&& array = fp.readAll();
1885 fp.close();
1886 std::move(array.begin(), array.end(), std::back_inserter(container));
1887 }
1888
1889 bank.reset(io::BankIO::getInstance().loadBank(container, file.toStdString()));
1890 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
1891 }
1892 catch (io::FileIOError& e) {
1893 FileIOErrorMessageBox(file, true, e, this).exec();
1894 return;
1895 }
1896 catch (std::exception& e) {
1897 FileIOErrorMessageBox(file, true, io::FileType::Bank, QString(e.what()), this).exec();
1898 return;
1899 }
1900
1901 // Change text codec
1902 if (auto ff = dynamic_cast<FfBank*>(bank.get())) {
1903 QTextCodec* codec = QTextCodec::codecForName("Shift-JIS");
1904 for (size_t i = 0; i < ff->getNumInstruments(); ++i) {
1905 std::string sjis = ff->getInstrumentName(i);
1906 std::string utf8 = codec->toUnicode(sjis.c_str(), sjis.length()).toStdString();
1907 ff->setInstrumentName(i, utf8);
1908 }
1909 }
1910 else if (auto mu88 = dynamic_cast<Mucom88Bank*>(bank.get())) {
1911 QTextCodec* codec = QTextCodec::codecForName("Shift-JIS");
1912 for (size_t i = 0; i < mu88->getNumInstruments(); ++i) {
1913 std::string sjis = mu88->getInstrumentName(i);
1914 std::string utf8 = codec->toUnicode(sjis.c_str(), sjis.length()).toStdString();
1915 mu88->setInstrumentName(i, utf8);
1916 }
1917 }
1918
1919 size_t jamId = 128; // Dummy
1920 std::shared_ptr<AbstractInstrument> jamInst;
1921 importBankDialog_ = std::make_unique<InstrumentSelectionDialog>(*bank, tr("Select instruments to load:"), config_, this);
1922 auto bankMan = std::make_shared<InstrumentsManager>(true);
1923 auto updateInst = [&] (size_t id) {
1924 if (id != jamId) {
1925 bankJamMidiCtrl_.store(true);
1926 jamId = id;
1927 bankMan->clearAll();
1928 jamInst.reset(bank->loadInstrument(id, bankMan, 0));
1929 jamInst->setNumber(128); // Special number
1930 std::unordered_map<int, std::array<size_t, 2>> sampNums;
1931 bt_->assignADPCMBeforeForcedJamKeyOn(jamInst, sampNums);
1932 for (const auto& pairs : sampNums) {
1933 bankMan->setSampleADPCMStartAddress(pairs.first, pairs.second[0]);
1934 bankMan->setSampleADPCMStopAddress(pairs.first, pairs.second[1]);
1935 }
1936 bankJamMidiCtrl_.store(false);
1937 }
1938 };
1939 QObject::connect(importBankDialog_.get(), &InstrumentSelectionDialog::jamKeyOnEvent,
1940 this, [&](size_t id, JamKey key) {
1941 updateInst(id);
1942 bt_->jamKeyOnForced(key, jamInst->getSoundSource(),
1943 !config_.lock()->getFixJammingVolume(), jamInst);
1944 },
1945 Qt::DirectConnection);
1946 QObject::connect(importBankDialog_.get(), &InstrumentSelectionDialog::jamKeyOnMidiEvent,
1947 this, [&](size_t id, int key) {
1948 updateInst(id);
1949 bt_->jamKeyOnForced(key, jamInst->getSoundSource(),
1950 !config_.lock()->getFixJammingVolume(), jamInst);
1951 },
1952 Qt::DirectConnection);
1953 QObject::connect(importBankDialog_.get(), &InstrumentSelectionDialog::jamKeyOffEvent,
1954 this, [&](JamKey key) { bt_->jamKeyOffForced(key, jamInst->getSoundSource()); },
1955 Qt::DirectConnection);
1956 QObject::connect(importBankDialog_.get(), &InstrumentSelectionDialog::jamKeyOffMidiEvent,
1957 this, [&](int key) { if (jamInst) bt_->jamKeyOffForced(key, jamInst->getSoundSource()); },
1958 Qt::DirectConnection);
1959 importBankDialog_->addActions({ &octUpSc_, &octDownSc_ });
1960
1961 if (importBankDialog_->exec() != QDialog::Accepted) {
1962 assignADPCMSamples(); // Restore
1963 importBankDialog_.reset();
1964 return;
1965 }
1966
1967 const QVector<size_t> selection = importBankDialog_->currentInstrumentSelection();
1968 importBankDialog_.reset();
1969 if (selection.empty()) return;
1970
1971 try {
1972 bool sampleRestoreRequested = false;
1973 int lastNum = ui->instrumentList->currentRow();
1974 for (const size_t& index : selection) {
1975 int n = bt_->findFirstFreeInstrumentNumber();
1976 if (n == -1){
1977 FileIOErrorMessageBox(file, true, io::FileType::Inst,
1978 tr("The number of instruments has reached the upper limit."), this).exec();
1979 ui->instrumentList->setCurrentRow(lastNum);
1980 return;
1981 }
1982
1983 bt_->importInstrument(*bank, index, n);
1984
1985 auto inst = bt_->getInstrument(n);
1986 comStack_->push(new AddInstrumentQtCommand(
1987 ui->instrumentList, n, gui_utils::utf8ToQString(inst->getName()),
1988 inst->getType(), instDialogMan_, this, config_.lock()->getWriteOnlyUsedSamples(), true));
1989 lastNum = n;
1990
1991 sampleRestoreRequested |= (inst->getSoundSource() == SoundSource::ADPCM);
1992 }
1993 ui->instrumentList->setCurrentRow(lastNum);
1994
1995 if (sampleRestoreRequested) assignADPCMSamples(); // Store only once
1996 }
1997 catch (io::FileIOError& e) {
1998 FileIOErrorMessageBox(file, true, e, this).exec();
1999 }
2000 catch (std::exception& e) {
2001 FileIOErrorMessageBox(file, true, io::FileType::Bank, QString(e.what()), this).exec();
2002 }
2003 }
2004
2005 void MainWindow::exportInstrumentsToBank()
2006 {
2007 std::vector<int> ids = bt_->getInstrumentIndices();
2008 std::shared_ptr<BtBank> bank(std::make_shared<BtBank>(ids, bt_->getInstrumentNames()));
2009
2010 InstrumentSelectionDialog dlg(*bank, tr("Select instruments to save:"), config_, this);
2011
2012 if (dlg.exec() != QDialog::Accepted)
2013 return;
2014
2015 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
2016 std::vector<std::string> orgFilters = io::BankIO::getInstance().getSaveFilter();
2017 QStringList filters;
2018 std::transform(orgFilters.begin(), orgFilters.end(), std::back_inserter(filters),
2019 [](const std::string& f) { return QString::fromStdString(f); });
2020 QString defaultFilter = filters.front(); // btb
2021 QString file = QFileDialog::getSaveFileName(this, tr("Save bank"), (dir.isEmpty() ? "./" : dir),
2022 filters.join(";;"), &defaultFilter
2023 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
2024 , QFileDialog::DontUseNativeDialog
2025 #endif
2026 );
2027 if (file.isNull()) return;
2028
2029 QVector<size_t> selection = dlg.currentInstrumentSelection();
2030 if (selection.empty()) return;
2031 std::vector<int> sel;
2032 std::transform(selection.begin(), selection.end(), std::back_inserter(sel),
2033 [&ids](size_t i) { return ids.at(i); });
2034 std::sort(sel.begin(), sel.end());
2035
2036 try {
2037 QByteArray bytes;
2038 {
2039 io::BinaryContainer container;
2040 bt_->exportInstruments(container, sel);
2041 bytes.reserve(container.size());
2042 std::move(container.begin(), container.end(), std::back_inserter(bytes));
2043 }
2044 QFile fp(file);
2045 if (!fp.open(QIODevice::WriteOnly)) {
2046 FileIOErrorMessageBox::openError(file, false, io::FileType::Bank, this);
2047 return;
2048 }fp.write(bytes);
2049 fp.close();
2050
2051 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
2052 }
2053 catch (io::FileIOError& e) {
2054 FileIOErrorMessageBox(file, false, e, this).exec();
2055 }
2056 catch (std::exception& e) {
2057 FileIOErrorMessageBox(file, false, io::FileType::Bank, QString(e.what()), this).exec();
2058 }
2059 }
2060
2061 void MainWindow::swapInstruments(int row1, int row2)
2062 {
2063 if (row1 == row2) return;
2064
2065 // KEEP CODE ORDER //
2066 int num1 = ui->instrumentList->item(row1)->data(Qt::UserRole).toInt();
2067 int num2 = ui->instrumentList->item(row2)->data(Qt::UserRole).toInt();
2068 QString name1 = gui_utils::utf8ToQString(bt_->getInstrument(num1)->getName());
2069 QString name2 = gui_utils::utf8ToQString(bt_->getInstrument(num2)->getName());
2070
2071 bt_->swapInstruments(num1, num2, config_.lock()->getReflectInstrumentNumberChange());
2072 comStack_->push(new SwapInstrumentsQtCommand(
2073 ui->instrumentList, row1, row2, name1, name2, instDialogMan_, ui->patternEditor));
2074 //----------//
2075 }
2076
2077 /********** Undo-Redo **********/
2078 void MainWindow::undo()
2079 {
2080 if (!bt_->undo()) {
2081 command_result_message_box::showCommandUndoingErrorMessageBox(this);
2082 return;
2083 }
2084 comStack_->undo();
2085 }
2086
2087 void MainWindow::redo()
2088 {
2089 if (!bt_->redo()) {
2090 command_result_message_box::showCommandRedoingErrorMessageBox(this);
2091 return;
2092 }
2093 comStack_->redo();
2094 }
2095
2096 /********** Load data **********/
2097 void MainWindow::loadModule()
2098 {
2099 instDialogMan_->removeAll();
2100 ui->instrumentList->clear();
2101 on_instrumentList_itemSelectionChanged();
2102
2103 ui->modTitleLineEdit->setText(gui_utils::utf8ToQString(bt_->getModuleTitle()));
2104 ui->modTitleLineEdit->setCursorPosition(0);
2105 ui->authorLineEdit->setText(gui_utils::utf8ToQString(bt_->getModuleAuthor()));
2106 ui->authorLineEdit->setCursorPosition(0);
2107 ui->copyrightLineEdit->setText(gui_utils::utf8ToQString(bt_->getModuleCopyright()));
2108 ui->copyrightLineEdit->setCursorPosition(0);
2109 {
2110 QSignalBlocker blocker(ui->songComboBox); // Prevent duplicated call "loadSong"
2111 ui->songComboBox->clear();
2112 for (size_t i = 0; i < bt_->getSongCount(); ++i) {
2113 QString title = gui_utils::utf8ToQString(bt_->getSongTitle(static_cast<int>(i)));
2114 if (title.isEmpty()) title = tr("Untitled");
2115 ui->songComboBox->addItem(QString("#%1 %2").arg(i).arg(title));
2116 }
2117 }
2118 highlight1_->setValue(static_cast<int>(bt_->getModuleStepHighlight1Distance()));
2119 highlight2_->setValue(static_cast<int>(bt_->getModuleStepHighlight2Distance()));
2120
2121 for (auto& idx : bt_->getInstrumentIndices()) {
2122 auto inst = bt_->getInstrument(idx);
2123 comStack_->push(new AddInstrumentQtCommand(
2124 ui->instrumentList, idx, gui_utils::utf8ToQString(inst->getName()), inst->getType(),
2125 instDialogMan_, this, config_.lock()->getWriteOnlyUsedSamples(), true));
2126 }
2127
2128 isSavedModBefore_ = false;
2129
2130 loadSong();
2131
2132 // Set tick frequency
2133 stream_->setInterruption(bt_->getModuleTickFrequency());
2134 if (tickTimerForRealChip_) tickTimerForRealChip_->setInterval(1000000 / bt_->getModuleTickFrequency());
2135 statusIntr_->setText(QString::number(bt_->getModuleTickFrequency()) + QString("Hz"));
2136
2137 // Set mixer
2138 QString text;
2139 switch (bt_->getModuleMixerType()) {
2140 case MixerType::UNSPECIFIED:
2141 bt_->setMasterVolumeFM(config_.lock()->getMixerVolumeFM());
2142 bt_->setMasterVolumeSSG(config_.lock()->getMixerVolumeSSG());
2143 text = tr("-");
2144 break;
2145 case MixerType::CUSTOM:
2146 bt_->setMasterVolumeFM(bt_->getModuleCustomMixerFMLevel());
2147 bt_->setMasterVolumeSSG(bt_->getModuleCustomMixerSSGLevel());
2148 text = tr("Custom");
2149 break;
2150 case MixerType::PC_9821_PC_9801_86:
2151 bt_->setMasterVolumeFM(0);
2152 bt_->setMasterVolumeSSG(-5.5);
2153 text = tr("PC-9821 with PC-9801-86");
2154 break;
2155 case MixerType::PC_9821_SPEAK_BOARD:
2156 bt_->setMasterVolumeFM(0);
2157 bt_->setMasterVolumeSSG(-3.0);
2158 text = tr("PC-9821 with Speak Board");
2159 break;
2160 case MixerType::PC_8801_VA2:
2161 bt_->setMasterVolumeFM(0);
2162 bt_->setMasterVolumeSSG(1.5);
2163 text = tr("PC-88VA2");
2164 break;
2165 case MixerType::PC_8801_MKII_SR:
2166 bt_->setMasterVolumeFM(0);
2167 bt_->setMasterVolumeSSG(2.5);
2168 text = tr("NEC PC-8801mkIISR");
2169 break;
2170 }
2171 statusMixer_->setText(text);
2172
2173 // Set comment
2174 if (commentDialog_) commentDialog_->setComment(gui_utils::utf8ToQString(bt_->getModuleComment()));
2175
2176 // Clear records
2177 QApplication::clipboard()->clear();
2178 comStack_->clear();
2179 bt_->clearCommandHistory();
2180 }
2181
2182 void MainWindow::openModule(const QString& file)
2183 {
2184 try {
2185 freezeViews();
2186 if (tickTimerForRealChip_) tickTimerForRealChip_->stop();
2187 else {
2188 try {
2189 stream_->stop();
2190 }
2191 catch (std::exception& e) {
2192 showStreamFailedDialog(e.what());
2193 }
2194 }
2195
2196 QFile fp(file);
2197 if (fp.open(QIODevice::ReadOnly)) {
2198 io::BinaryContainer container;
2199 {
2200 QByteArray&& array = fp.readAll();
2201 fp.close();
2202 std::move(array.begin(), array.end(), std::back_inserter(container));
2203 }
2204
2205 bt_->loadModule(container);
2206 bt_->setModulePath(file.toStdString());
2207
2208 loadModule();
2209
2210 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
2211 changeFileHistory(file);
2212
2213 goto AFTER_MOD_LOADING; // Skip error handling section
2214 }
2215 else {
2216 FileIOErrorMessageBox::openError(file, true, io::FileType::Mod, this);
2217 }
2218 }
2219 catch (std::exception& e) {
2220 if (auto ef = dynamic_cast<io::FileIOError*>(&e)) {
2221 FileIOErrorMessageBox(file, true, *ef, this).exec();
2222 }
2223 else {
2224 FileIOErrorMessageBox(file, true, io::FileType::Mod, QString(e.what()), this).exec();
2225 }
2226 }
2227
2228 // Init module as a plain when something is wrong
2229 freezeViews();
2230 bt_->makeNewModule();
2231 loadModule();
2232
2233 AFTER_MOD_LOADING: // Post process of module loading
2234 isModifiedForNotCommand_ = false;
2235 setWindowModified(false);
2236 if (tickTimerForRealChip_) tickTimerForRealChip_->start();
2237 else {
2238 try {
2239 stream_->start();
2240 }
2241 catch (std::exception& e) {
2242 showStreamFailedDialog(e.what());
2243 }
2244 }
2245
2246 setInitialSelectedInstrument();
2247 assignADPCMSamples();
2248 }
2249
2250 void MainWindow::loadSong()
2251 {
2252 // Init position
2253 int songCnt = static_cast<int>(bt_->getSongCount());
2254 if (ui->songComboBox->currentIndex() >= songCnt)
2255 bt_->setCurrentSongNumber(songCnt - 1);
2256 else
2257 bt_->setCurrentSongNumber(bt_->getCurrentSongNumber());
2258 bt_->setCurrentOrderNumber(0);
2259 bt_->setCurrentTrack(0);
2260 bt_->setCurrentStepNumber(0);
2261
2262 // Init ui
2263 ui->orderList->onSongLoaded();
2264 setOrderListGroupMaximumWidth();
2265 ui->patternEditor->onSongLoaded();
2266 unfreezeViews();
2267
2268 int curSong = bt_->getCurrentSongNumber();
2269 ui->songComboBox->setCurrentIndex(curSong);
2270 ui->tempoSpinBox->setValue(bt_->getSongTempo(curSong));
2271 ui->speedSpinBox->setValue(bt_->getSongSpeed(curSong));
2272 ui->patternSizeSpinBox->setValue(static_cast<int>(bt_->getDefaultPatternSize(curSong)));
2273 ui->grooveSpinBox->setValue(bt_->getSongGroove(curSong));
2274 ui->grooveSpinBox->setMaximum(static_cast<int>(bt_->getGrooveCount()) - 1);
2275 if (bt_->isUsedTempoInSong(curSong)) {
2276 ui->tempoSpinBox->setEnabled(true);
2277 ui->speedSpinBox->setEnabled(true);
2278 ui->grooveCheckBox->setChecked(false);
2279 ui->grooveSpinBox->setEnabled(false);
2280 }
2281 else {
2282 ui->tempoSpinBox->setEnabled(false);
2283 ui->speedSpinBox->setEnabled(false);
2284 ui->grooveCheckBox->setChecked(true);
2285 ui->grooveSpinBox->setEnabled(true);
2286 }
2287 onCurrentTrackChanged();
2288
2289 setWindowTitle();
2290 switch (bt_->getSongStyle(bt_->getCurrentSongNumber()).type) {
2291 case SongType::Standard: statusStyle_->setText(tr("Standard")); break;
2292 case SongType::FM3chExpanded: statusStyle_->setText(tr("FM3ch expanded")); break;
2293 }
2294 statusPlayPos_->setText(config_.lock()->getShowRowNumberInHex() ? "00/00" : "000/000");
2295
2296 bmManForm_->onCurrentSongNumberChanged();
2297 ksManForm_->onCurrentSongNumberChanged();
2298
2299 // Update track visibility
2300 std::vector<int> visTracks;
2301 int all = static_cast<int>(bt_->getSongStyle(curSong).trackAttribs.size());
2302 for (int i = 0; i < all; ++i) {
2303 if (bt_->isVisibleTrack(curSong, i)) visTracks.push_back(i);
2304 }
2305 ui->orderList->setVisibleTracks(visTracks);
2306 setOrderListGroupMaximumWidth();
2307 ui->patternEditor->setVisibleTracks(visTracks);
2308 }
2309
2310 void MainWindow::assignADPCMSamples()
2311 {
2312 bt_->stopPlaySong();
2313 lockWidgets(false);
2314 if (tickTimerForRealChip_) tickTimerForRealChip_->stop();
2315 else {
2316 try {
2317 stream_->stop();
2318 }
2319 catch (std::exception& e) {
2320 showStreamFailedDialog(e.what());
2321 }
2322 }
2323
2324 bool isStoredAll = bt_->assignSampleADPCMRawSamples(); // Mutex register
2325 instDialogMan_->onInstrumentADPCMSampleMemoryUpdated();
2326
2327 if (!isStoredAll) {
2328 QMessageBox::warning(this, tr("Warning"),
2329 tr("Insufficient memory size to load ADPCM samples. Please delete the unused samples."));
2330 }
2331
2332 if (tickTimerForRealChip_) tickTimerForRealChip_->start();
2333 else {
2334 try {
2335 stream_->start();
2336 }
2337 catch (std::exception& e) {
2338 showStreamFailedDialog(e.what());
2339 }
2340 }
2341 }
2342
2343 /********** Play song **********/
2344 void MainWindow::startPlaySong()
2345 {
2346 bt_->startPlaySong();
2347 lockWidgets(true);
2348 firstViewUpdateRequest_ = true;
2349 }
2350
2351 void MainWindow::startPlayFromStart()
2352 {
2353 bt_->startPlayFromStart();
2354 lockWidgets(true);
2355 firstViewUpdateRequest_ = true;
2356 }
2357
2358 void MainWindow::startPlayPattern()
2359 {
2360 bt_->startPlayPattern();
2361 lockWidgets(true);
2362 firstViewUpdateRequest_ = true;
2363 }
2364
2365 void MainWindow::startPlayFromCurrentStep()
2366 {
2367 bt_->startPlayFromCurrentStep();
2368 lockWidgets(true);
2369 firstViewUpdateRequest_ = true;
2370 }
2371
2372 void MainWindow::startPlayFromMarker()
2373 {
2374 if (bt_->startPlayFromMarker()) {
2375 lockWidgets(true);
2376 firstViewUpdateRequest_ = true;
2377 }
2378 }
2379
2380 void MainWindow::playStep()
2381 {
2382 if (!bt_->isPlaySong()) {
2383 bt_->playStep();
2384 firstViewUpdateRequest_ = true;
2385 ui->patternEditor->onPlayStepPressed();
2386 }
2387 }
2388
2389 void MainWindow::stopPlaySong()
2390 {
2391 bt_->stopPlaySong();
2392 lockWidgets(false);
2393 ui->patternEditor->onStoppedPlaySong();
2394 ui->orderList->onStoppedPlaySong();
2395 }
2396
2397 void MainWindow::lockWidgets(bool isLock)
2398 {
2399 hasLockedWigets_ = isLock;
2400 ui->songComboBox->setEnabled(!isLock);
2401 }
2402
2403 /********** Octave change **********/
2404 void MainWindow::changeOctave(bool upFlag)
2405 {
2406 if (upFlag) octave_->stepUp();
2407 else octave_->stepDown();
2408
2409 statusOctave_->setText(tr("Octave: %1").arg(bt_->getCurrentOctave()));
2410 }
2411
2412 /********** Configuration change **********/
2413 void MainWindow::changeConfiguration()
2414 {
2415 // Real chip interface
2416 bool streamState = false;
2417 RealChipInterfaceType intf = config_.lock()->getRealChipInterface();
2418 if (intf == RealChipInterfaceType::NONE) {
2419 tickTimerForRealChip_.reset();
2420 bt_->connectToRealChip(RealChipInterfaceType::NONE);
2421
2422 try {
2423 QString streamErr;
2424 streamState = stream_->initialize(
2425 config_.lock()->getSampleRate(),
2426 config_.lock()->getBufferLength(),
2427 bt_->getModuleTickFrequency(),
2428 gui_utils::utf8ToQString(config_.lock()->getSoundAPI()),
2429 gui_utils::utf8ToQString(config_.lock()->getSoundDevice()),
2430 &streamErr);
2431 if (!streamState) showStreamFailedDialog(streamErr);
2432 }
2433 catch (std::exception& e) {
2434 showStreamFailedDialog(e.what());
2435 }
2436
2437 try {
2438 stream_->start();
2439 }
2440 catch (std::exception& e) {
2441 showStreamFailedDialog(e.what());
2442 }
2443 }
2444 else {
2445 try {
2446 stream_->stop();
2447 }
2448 catch (std::exception& e) {
2449 showStreamFailedDialog(e.what());
2450 }
2451
2452 if (tickTimerForRealChip_) {
2453 tickTimerForRealChip_->stop();
2454 }
2455 else {
2456 tickTimerForRealChip_ = std::make_unique<PreciseTimer>();
2457 tickTimerForRealChip_->setInterval(1000000 / bt_->getModuleTickFrequency());
2458 tickEventMethod_ = metaObject()->indexOfSlot("onNewTickSignaledRealChip()");
2459 Q_ASSERT(tickEventMethod_ != -1);
2460 tickTimerForRealChip_->setFunction([&]{
2461 QMetaMethod method = this->metaObject()->method(this->tickEventMethod_);
2462 method.invoke(this, Qt::QueuedConnection);
2463 });
2464 }
2465
2466 setRealChipInterface(intf);
2467
2468 tickTimerForRealChip_->start();
2469 }
2470
2471 setMidiConfiguration();
2472 NoteNameManager::getManager().setNotationSystem(config_.lock()->getNotationSystem());
2473 updateFonts();
2474 ui->orderList->setHorizontalScrollMode(config_.lock()->getMoveCursorByHorizontalScroll());
2475 ui->patternEditor->setHorizontalScrollMode(config_.lock()->getMoveCursorByHorizontalScroll());
2476 instDialogMan_->updateByConfiguration();
2477
2478 bt_->changeConfiguration(config_);
2479
2480 if (streamState) {
2481 uint32_t sr = stream_->getStreamRate();
2482 if (config_.lock()->getSampleRate() != sr) {
2483 showStreamRateWarningDialog(sr);
2484 bt_->setStreamRate(sr);
2485 }
2486 }
2487
2488 setShortcuts();
2489 updateInstrumentListColors();
2490 bmManForm_->onConfigurationChanged(config_.lock()->getShowRowNumberInHex());
2491 ksManForm_->onConfigurationChanged(config_.lock()->getShowRowNumberInHex());
2492
2493 visualTimer_->stop();
2494 visualTimer_->start(static_cast<int>(std::round(1000. / config_.lock()->getWaveViewFrameRate())));
2495
2496 update();
2497 }
2498
2499 void MainWindow::setRealChipInterface(RealChipInterfaceType intf)
2500 {
2501 if (intf == bt_->getRealChipInterfaceType()) return;
2502
2503 if (isWindowModified()
2504 && QMessageBox::warning(this, tr("Warning"),
2505 tr("The module has been changed. Do you want to save it?"),
2506 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
2507 on_actionSave_As_triggered();
2508 }
2509
2510 struct Pair
2511 {
2512 std::weak_ptr<QLibrary> lib;
2513 const char* symbol;
2514 };
2515 static std::unordered_map<RealChipInterfaceType, Pair> RCI_DIC = {
2516 { RealChipInterfaceType::SCCI, { scciDll_, "getSoundInterfaceManager" } },
2517 { RealChipInterfaceType::C86CTL, { c86ctlDll_, "CreateInstance" } }
2518 };
2519
2520 auto& dll = RCI_DIC.at(intf).lib;
2521 dll.lock()->load();
2522 if (dll.lock()->isLoaded())
2523 bt_->connectToRealChip(intf, new RealChipInterfaceGeneratorFunc(dll.lock()->resolve(RCI_DIC[intf].symbol)));
2524 else
2525 bt_->connectToRealChip(RealChipInterfaceType::NONE);
2526
2527 bt_->assignSampleADPCMRawSamples(); // Mutex register
2528 instDialogMan_->onInstrumentADPCMSampleMemoryUpdated();
2529 }
2530
2531 void MainWindow::setMidiConfiguration()
2532 {
2533 MidiInterface &midiIntf = MidiInterface::getInstance();
2534 std::string midiApi = config_.lock()->getMidiAPI();
2535 std::string midiInPortName = config_.lock()->getMidiInputPort();
2536
2537 if (config_.lock()->getMidiEnabled()) {
2538 std::string errDetail;
2539 if (midiApi.empty()) {
2540 config_.lock()->setMidiEnabled(false);
2541 midiIntf.switchApi(""); // Clear
2542 }
2543 else {
2544 if (!midiIntf.isAvailableApi(midiApi)) {
2545 showMidiFailedDialog("Invalid API name.");
2546 midiIntf.switchApi(""); // Clear
2547 return;
2548 }
2549 if (midiIntf.switchApi(midiApi, &errDetail)) {
2550 bool resPort = true;
2551 if (!midiInPortName.empty())
2552 resPort = midiIntf.openInputPortByName(midiInPortName, &errDetail);
2553 else if (midiIntf.supportsVirtualPort())
2554 resPort = midiIntf.openInputPort(~0u, &errDetail);
2555 else
2556 config_.lock()->setMidiEnabled(false);
2557 if (!resPort) {
2558 showMidiFailedDialog(QString::fromStdString(errDetail));
2559 midiIntf.switchApi(""); // Clear
2560 }
2561 }
2562 else {
2563 showMidiFailedDialog(QString::fromStdString(errDetail));
2564 midiIntf.switchApi(""); // Clear
2565 }
2566 }
2567 }
2568 }
2569
2570 void MainWindow::updateFonts()
2571 {
2572 QFont ptnHeader, ptnRows, odrHeader, odrRows;
2573
2574 if (!ptnHeader.fromString(gui_utils::utf8ToQString(config_.lock()->getPatternEditorHeaderFont()))) {
2575 ptnHeader = ui->patternEditor->getDefaultHeaderFont();
2576 config_.lock()->setPatternEditorHeaderFont(ptnHeader.toString().toUtf8().toStdString());
2577 }
2578 if (!ptnRows.fromString(gui_utils::utf8ToQString(config_.lock()->getPatternEditorRowsFont()))) {
2579 ptnRows = ui->patternEditor->getDefaultRowsFont();
2580 config_.lock()->setPatternEditorRowsFont(ptnRows.toString().toUtf8().toStdString());
2581 }
2582 if (!odrHeader.fromString(gui_utils::utf8ToQString(config_.lock()->getOrderListHeaderFont()))) {
2583 odrHeader = ui->orderList->getDefaultHeaderFont();
2584 config_.lock()->setOrderListHeaderFont(odrHeader.toString().toUtf8().toStdString());
2585 }
2586 if (!odrRows.fromString(gui_utils::utf8ToQString(config_.lock()->getOrderListRowsFont()))) {
2587 odrRows = ui->orderList->getDefaultRowsFont();
2588 config_.lock()->setOrderListRowsFont(odrRows.toString().toUtf8().toStdString());
2589 }
2590
2591 ui->patternEditor->setFonts(ptnHeader, ptnRows);
2592 ui->orderList->setFonts(odrHeader, odrRows);
2593 }
2594
2595 /********** History change **********/
2596 void MainWindow::changeFileHistory(QString file)
2597 {
2598 fileHistory_->addFile(file);
2599 for (int i = ui->menu_Recent_Files->actions().count() - 1; 1 < i; --i)
2600 ui->menu_Recent_Files->removeAction(ui->menu_Recent_Files->actions().at(i));
2601 for (size_t i = 0; i < fileHistory_->size(); ++i) {
2602 // Leave Before Qt5.7.0 style due to windows xp
2603 QAction* action = ui->menu_Recent_Files->addAction(QString("&%1 %2").arg(i + 1).arg(fileHistory_->at(i)));
2604 action->setData(fileHistory_->at(i));
2605 }
2606 }
2607
2608 /********** Backup **********/
2609 bool MainWindow::backupModule(QString srcFile)
2610 {
2611 if (!isSavedModBefore_ && config_.lock()->getBackupModules()) {
2612 bool err = false;
2613 QString backup = srcFile + ".bak";
2614 if (QFile::exists(backup)) err = !QFile::remove(backup);
2615 if (err || !QFile::copy(srcFile, backup)) {
2616 QMessageBox::critical(this, tr("Error"), tr("Failed to backup module."));
2617 return false;
2618 }
2619 }
2620 return true;
2621 }
2622
2623 /******************************/
2624 void MainWindow::setWindowTitle()
2625 {
2626 int n = bt_->getCurrentSongNumber();
2627 QString filePath = QString::fromStdString(bt_->getModulePath());
2628 QString fileName = filePath.isEmpty() ? tr("Untitled") : QFileInfo(filePath).fileName();
2629 QString songTitle = gui_utils::utf8ToQString(bt_->getSongTitle(n));
2630 if (songTitle.isEmpty()) songTitle = tr("Untitled");
2631 QMainWindow::setWindowTitle(QString("%1[*] [#%2 %3] - BambooTracker")
2632 .arg(fileName, QString::number(n), songTitle));
2633 }
2634
2635 void MainWindow::setModifiedTrue()
2636 {
2637 isModifiedForNotCommand_ = true;
2638 setWindowModified(true);
2639 }
2640
2641 void MainWindow::setInitialSelectedInstrument()
2642 {
2643 if (bt_->getInstrumentIndices().empty()) {
2644 bt_->setCurrentInstrument(-1);
2645 statusInst_->setText(tr("No instrument"));
2646 }
2647 else {
2648 ui->instrumentList->setCurrentRow(0);
2649 }
2650 }
2651
2652 QString MainWindow::getModuleFileBaseName() const
2653 {
2654 auto filePathStd = bt_->getModulePath();
2655 QString filePath = QString::fromStdString(filePathStd);
2656 return (filePath.isEmpty() ? tr("Untitled") : QFileInfo(filePath).completeBaseName());
2657 }
2658
2659 /******************************/
2660 /********** Instrument list events **********/
2661 void MainWindow::on_instrumentList_customContextMenuRequested(const QPoint &pos)
2662 {
2663 auto& list = ui->instrumentList;
2664 QPoint globalPos = list->mapToGlobal(pos);
2665 QMenu menu;
2666
2667 // Leave Before Qt5.7.0 style due to windows xp
2668 menu.addActions({ ui->actionNew_Instrument, ui->actionNew_Drumki_t, ui->actionRemove_Instrument });
2669 menu.addSeparator();
2670 menu.addAction(ui->actionRename_Instrument);
2671 menu.addSeparator();
2672 menu.addActions({ ui->actionClone_Instrument, ui->actionDeep_Clone_Instrument });
2673 menu.addSeparator();
2674 menu.addActions({ ui->actionLoad_From_File, ui->actionSave_To_File });
2675 menu.addSeparator();
2676 menu.addActions({ ui->actionImport_From_Bank_File, ui->actionExport_To_Bank_File });
2677 menu.addSeparator();
2678 menu.addAction(ui->actionEdit);
2679
2680 menu.exec(globalPos);
2681 }
2682
2683 void MainWindow::on_instrumentList_itemDoubleClicked(QListWidgetItem *)
2684 {
2685 openInstrumentEditor();
2686 }
2687
2688 void MainWindow::on_instrumentList_itemSelectionChanged()
2689 {
2690 int num = (ui->instrumentList->currentRow() == -1)
2691 ? -1
2692 : ui->instrumentList->currentItem()->data(Qt::UserRole).toInt();
2693 bt_->setCurrentInstrument(num);
2694
2695 if (num == -1) statusInst_->setText(tr("No instrument"));
2696 else statusInst_->setText(
2697 tr("Instrument: %1").arg(QString("%1").arg(num, 2, 16, QChar('0')).toUpper()));
2698
2699 bool canAdd = (bt_->findFirstFreeInstrumentNumber() != -1);
2700 ui->actionLoad_From_File->setEnabled(canAdd);
2701 ui->actionImport_From_Bank_File->setEnabled(canAdd);
2702
2703 bool isSelected = (num != -1);
2704 ui->actionRemove_Instrument->setEnabled(isSelected);
2705 ui->actionClone_Instrument->setEnabled(isSelected);
2706 ui->actionDeep_Clone_Instrument->setEnabled(isSelected);
2707 ui->actionSave_To_File->setEnabled(isSelected);
2708 ui->actionExport_To_Bank_File->setEnabled(isSelected);
2709 ui->actionRename_Instrument->setEnabled(isSelected);
2710 ui->actionEdit->setEnabled(isSelected);
2711 }
2712
2713 void MainWindow::on_grooveCheckBox_stateChanged(int arg1)
2714 {
2715 if (arg1 == Qt::Checked) {
2716 ui->tempoSpinBox->setEnabled(false);
2717 ui->speedSpinBox->setEnabled(false);
2718 ui->grooveSpinBox->setEnabled(true);
2719 bt_->toggleTempoOrGrooveInSong(bt_->getCurrentSongNumber(), false);
2720 }
2721 else {
2722 ui->tempoSpinBox->setEnabled(true);
2723 ui->speedSpinBox->setEnabled(true);
2724 ui->grooveSpinBox->setEnabled(false);
2725 bt_->toggleTempoOrGrooveInSong(bt_->getCurrentSongNumber(), true);
2726 }
2727
2728 setModifiedTrue();
2729 }
2730
2731 void MainWindow::on_actionExit_triggered()
2732 {
2733 close();
2734 }
2735
2736 void MainWindow::on_actionUndo_triggered()
2737 {
2738 undo();
2739 }
2740
2741 void MainWindow::on_actionRedo_triggered()
2742 {
2743 redo();
2744 }
2745
2746 void MainWindow::on_actionCut_triggered()
2747 {
2748 if (isEditedPattern_) ui->patternEditor->cutSelectedCells();
2749 }
2750
2751 void MainWindow::on_actionCopy_triggered()
2752 {
2753 if (isEditedPattern_) ui->patternEditor->copySelectedCells();
2754 else if (isEditedOrder_) ui->orderList->copySelectedCells();
2755 }
2756
2757 void MainWindow::on_actionPaste_triggered()
2758 {
2759 if (isEditedPattern_) ui->patternEditor->onPastePressed();
2760 else if (isEditedOrder_) ui->orderList->onPastePressed();
2761 }
2762
2763 void MainWindow::on_actionDelete_triggered()
2764 {
2765 if (isEditedPattern_) ui->patternEditor->onDeletePressed();
2766 else if (isEditedOrder_) ui->orderList->deleteOrder();
2767 else if (isEditedInstList_) on_actionRemove_Instrument_triggered();
2768 }
2769
2770 void MainWindow::updateMenuByPattern()
2771 {
2772 isEditedPattern_ = true;
2773 isEditedOrder_ = false;
2774 isEditedInstList_ = false;
2775
2776 if (bt_->isJamMode()) {
2777 // Edit
2778 ui->actionPaste->setEnabled(false);
2779 ui->actionMix->setEnabled(false);
2780 ui->actionOverwrite->setEnabled(false);
2781 ui->action_Insert->setEnabled(false);
2782 ui->actionDelete->setEnabled(false);
2783 // Pattern
2784 ui->actionInterpolate->setEnabled(false);
2785 ui->actionReverse->setEnabled(false);
2786 ui->actionReplace_Instrument->setEnabled(false);
2787 ui->actionExpand->setEnabled(false);
2788 ui->actionShrink->setEnabled(false);
2789 ui->actionDecrease_Note->setEnabled(false);
2790 ui->actionIncrease_Note->setEnabled(false);
2791 ui->actionDecrease_Octave->setEnabled(false);
2792 ui->actionIncrease_Octave->setEnabled(false);
2793 ui->actionFine_Decrease_Values->setEnabled(false);
2794 ui->actionFine_Increase_Values->setEnabled(false);
2795 ui->actionCoarse_D_ecrease_Values->setEnabled(false);
2796 ui->actionCoarse_I_ncrease_Values->setEnabled(false);
2797 }
2798 else {
2799 // Edit
2800 bool enabled = QApplication::clipboard()->text().startsWith("PATTERN_");
2801 ui->actionPaste->setEnabled(enabled);
2802 ui->actionMix->setEnabled(enabled);
2803 ui->actionOverwrite->setEnabled(enabled);
2804 ui->action_Insert->setEnabled(enabled);
2805 ui->actionDelete->setEnabled(true);
2806 // Pattern
2807 ui->actionInterpolate->setEnabled(isSelectedPattern_);
2808 ui->actionReverse->setEnabled(isSelectedPattern_);
2809 ui->actionReplace_Instrument->setEnabled(
2810 isSelectedPattern_ && ui->instrumentList->currentRow() != -1);
2811 ui->actionExpand->setEnabled(isSelectedPattern_);
2812 ui->actionShrink->setEnabled(isSelectedPattern_);
2813 ui->actionDecrease_Note->setEnabled(true);
2814 ui->actionIncrease_Note->setEnabled(true);
2815 ui->actionDecrease_Octave->setEnabled(true);
2816 ui->actionIncrease_Octave->setEnabled(true);
2817 ui->actionFine_Decrease_Values->setEnabled(true);
2818 ui->actionFine_Increase_Values->setEnabled(true);
2819 ui->actionCoarse_D_ecrease_Values->setEnabled(true);
2820 ui->actionCoarse_I_ncrease_Values->setEnabled(true);
2821 }
2822
2823 updateMenuByPatternSelection(isSelectedPattern_);
2824 }
2825
2826 void MainWindow::updateMenuByOrder()
2827 {
2828 isEditedPattern_ = false;
2829 isEditedOrder_ = true;
2830 isEditedInstList_ = false;
2831
2832 // Edit
2833 bool enabled = QApplication::clipboard()->text().startsWith("ORDER_");
2834 ui->actionCut->setEnabled(false);
2835 ui->actionPaste->setEnabled(enabled);
2836 ui->actionMix->setEnabled(false);
2837 ui->actionOverwrite->setEnabled(false);
2838 ui->action_Insert->setEnabled(false);
2839 ui->actionDelete->setEnabled(true);
2840 // Song
2841 bool canAdd = bt_->canAddNewOrder(bt_->getCurrentSongNumber());
2842 ui->actionInsert_Order->setEnabled(canAdd);
2843 //ui->actionRemove_Order->setEnabled(true);
2844 ui->actionDuplicate_Order->setEnabled(canAdd);
2845 //ui->actionMove_Order_Up->setEnabled(true);
2846 //ui->actionMove_Order_Down->setEnabled(true);
2847 ui->actionClone_Patterns->setEnabled(canAdd);
2848 ui->actionClone_Order->setEnabled(canAdd);
2849 // Pattern
2850 ui->actionInterpolate->setEnabled(false);
2851 ui->actionReverse->setEnabled(false);
2852 ui->actionReplace_Instrument->setEnabled(false);
2853 ui->actionExpand->setEnabled(false);
2854 ui->actionShrink->setEnabled(false);
2855 ui->actionDecrease_Note->setEnabled(false);
2856 ui->actionIncrease_Note->setEnabled(false);
2857 ui->actionDecrease_Octave->setEnabled(false);
2858 ui->actionIncrease_Octave->setEnabled(false);
2859 ui->actionFine_Decrease_Values->setEnabled(false);
2860 ui->actionFine_Increase_Values->setEnabled(false);
2861 ui->actionCoarse_D_ecrease_Values->setEnabled(false);
2862 ui->actionCoarse_I_ncrease_Values->setEnabled(false);
2863
2864 updateMenuByOrderSelection(isSelectedOrder_);
2865 }
2866
2867 void MainWindow::onCurrentTrackChanged()
2868 {
2869 SoundSource src = bt_->getCurrentTrackAttribute().source;
2870 bool space = (bt_->findFirstFreeInstrumentNumber() != -1);
2871 ui->actionNew_Instrument->setEnabled((src != SoundSource::RHYTHM) && space);
2872 ui->actionNew_Drumki_t->setEnabled((src == SoundSource::ADPCM) && space);
2873 }
2874
2875 void MainWindow::updateMenuByInstrumentList()
2876 {
2877 isEditedPattern_ = false;
2878 isEditedOrder_ = false;
2879 isEditedInstList_ = true;
2880
2881 // Edit
2882 ui->actionPaste->setEnabled(false);
2883 ui->actionMix->setEnabled(false);
2884 ui->actionOverwrite->setEnabled(false);
2885 ui->action_Insert->setEnabled(false);
2886 ui->actionDelete->setEnabled(true);
2887
2888 // Pattern
2889 ui->actionInterpolate->setEnabled(false);
2890 ui->actionReverse->setEnabled(false);
2891 ui->actionReplace_Instrument->setEnabled(false);
2892 ui->actionExpand->setEnabled(false);
2893 ui->actionShrink->setEnabled(false);
2894 ui->actionDecrease_Note->setEnabled(false);
2895 ui->actionIncrease_Note->setEnabled(false);
2896 ui->actionDecrease_Octave->setEnabled(false);
2897 ui->actionIncrease_Octave->setEnabled(false);
2898 ui->actionFine_Decrease_Values->setEnabled(false);
2899 ui->actionFine_Increase_Values->setEnabled(false);
2900 ui->actionCoarse_D_ecrease_Values->setEnabled(false);
2901 ui->actionCoarse_I_ncrease_Values->setEnabled(false);
2902 }
2903
2904 void MainWindow::updateMenuByPatternSelection(bool isSelected)
2905 {
2906 isSelectedPattern_ = isSelected;
2907
2908 if (bt_->isJamMode()) {
2909 // Edit
2910 ui->actionCopy->setEnabled(false);
2911 ui->actionCut->setEnabled(false);
2912 // Pattern
2913 ui->actionInterpolate->setEnabled(false);
2914 ui->actionReverse->setEnabled(false);
2915 ui->actionReplace_Instrument->setEnabled(false);
2916 ui->actionExpand->setEnabled(false);
2917 ui->actionShrink->setEnabled(false);
2918 }
2919 else {
2920 // Edit
2921 ui->actionCopy->setEnabled(isSelected);
2922 ui->actionCut->setEnabled(isEditedPattern_ ? isSelected : false);
2923 // Pattern
2924 bool enabled = (isEditedPattern_ && isEditedPattern_) ? isSelected : false;
2925 ui->actionInterpolate->setEnabled(enabled);
2926 ui->actionReverse->setEnabled(enabled);
2927 ui->actionReplace_Instrument->setEnabled(
2928 enabled && ui->instrumentList->currentRow() != -1);
2929 ui->actionExpand->setEnabled(enabled);
2930 ui->actionShrink->setEnabled(enabled);
2931 }
2932 }
2933
2934 void MainWindow::updateMenuByOrderSelection(bool isSelected)
2935 {
2936 isSelectedOrder_ = isSelected;
2937
2938 // Edit
2939 ui->actionCopy->setEnabled(isSelected);
2940 }
2941
2942 void MainWindow::on_actionAll_triggered()
2943 {
2944 if (isEditedPattern_) ui->patternEditor->onSelectPressed(1);
2945 else if (isEditedOrder_) ui->orderList->onSelectPressed(1);
2946 }
2947
2948 void MainWindow::on_actionNone_triggered()
2949 {
2950 if (isEditedPattern_) ui->patternEditor->onSelectPressed(0);
2951 else if (isEditedOrder_) ui->orderList->onSelectPressed(0);
2952 }
2953
2954 void MainWindow::on_actionDecrease_Note_triggered()
2955 {
2956 if (isEditedPattern_) ui->patternEditor->onTransposePressed(false, false);
2957 }
2958
2959 void MainWindow::on_actionIncrease_Note_triggered()
2960 {
2961 if (isEditedPattern_) ui->patternEditor->onTransposePressed(false, true);
2962 }
2963
2964 void MainWindow::on_actionDecrease_Octave_triggered()
2965 {
2966 if (isEditedPattern_) ui->patternEditor->onTransposePressed(true, false);
2967 }
2968
2969 void MainWindow::on_actionIncrease_Octave_triggered()
2970 {
2971 if (isEditedPattern_) ui->patternEditor->onTransposePressed(true, true);
2972 }
2973
2974 void MainWindow::on_actionInsert_Order_triggered()
2975 {
2976 ui->orderList->insertOrderBelow();
2977 }
2978
2979 void MainWindow::on_actionRemove_Order_triggered()
2980 {
2981 ui->orderList->deleteOrder();
2982 }
2983
2984 void MainWindow::on_actionModule_Properties_triggered()
2985 {
2986 ModulePropertiesDialog dialog(bt_, config_.lock()->getMixerVolumeFM(), config_.lock()->getMixerVolumeSSG(), this);
2987 if (dialog.exec() == QDialog::Accepted
2988 && showUndoResetWarningDialog(tr("Do you want to change song properties?"))) {
2989 int instRow = ui->instrumentList->currentRow();
2990 bt_->stopPlaySong();
2991 lockWidgets(false);
2992 dialog.onAccepted();
2993 freezeViews();
2994 if (!tickTimerForRealChip_) {
2995 try {
2996 stream_->stop();
2997 }
2998 catch (std::exception& e) {
2999 showStreamFailedDialog(e.what());
3000 }
3001 }
3002 loadModule();
3003 setModifiedTrue();
3004 setWindowTitle();
3005 ui->instrumentList->setCurrentRow(instRow);
3006 if (!tickTimerForRealChip_) {
3007 try {
3008 stream_->start();
3009 }
3010 catch (std::exception& e) {
3011 showStreamFailedDialog(e.what());
3012 }
3013 }
3014 assignADPCMSamples();
3015 }
3016 }
3017
3018 void MainWindow::on_actionNew_Instrument_triggered()
3019 {
3020 addInstrument();
3021 }
3022
3023 void MainWindow::on_actionRemove_Instrument_triggered()
3024 {
3025 removeInstrument(ui->instrumentList->currentRow());
3026 }
3027
3028 void MainWindow::on_actionClone_Instrument_triggered()
3029 {
3030 cloneInstrument();
3031 }
3032
3033 void MainWindow::on_actionDeep_Clone_Instrument_triggered()
3034 {
3035 deepCloneInstrument();
3036 }
3037
3038 void MainWindow::on_actionEdit_triggered()
3039 {
3040 openInstrumentEditor();
3041 }
3042
3043 void MainWindow::on_actionPlay_triggered()
3044 {
3045 startPlaySong();
3046 }
3047
3048 void MainWindow::on_actionPlay_Pattern_triggered()
3049 {
3050 startPlayPattern();
3051 }
3052
3053 void MainWindow::on_actionPlay_From_Start_triggered()
3054 {
3055 startPlayFromStart();
3056 }
3057
3058 void MainWindow::on_actionPlay_From_Cursor_triggered()
3059 {
3060 startPlayFromCurrentStep();
3061 }
3062
3063 void MainWindow::on_actionStop_triggered()
3064 {
3065 stopPlaySong();
3066 }
3067
3068 void MainWindow::on_actionEdit_Mode_triggered()
3069 {
3070 bt_->toggleJamMode();
3071 ui->orderList->changeEditable();
3072 ui->patternEditor->changeEditable();
3073
3074 if (isEditedOrder_) updateMenuByOrder();
3075 else if (isEditedPattern_) updateMenuByPattern();
3076
3077 bool editable = !bt_->isJamMode();
3078 ui->statusBar->showMessage(editable ? tr("Change to edit mode") : tr("Change to jam mode"), STATUS_DISPLAY_TIMEOUT);
3079 ui->action_Toggle_Bookmark->setEnabled(editable);
3080 }
3081
3082 void MainWindow::on_actionToggle_Track_triggered()
3083 {
3084 ui->patternEditor->onToggleTrackPressed();
3085 }
3086
3087 void MainWindow::on_actionSolo_Track_triggered()
3088 {
3089 ui->patternEditor->onSoloTrackPressed();
3090 }
3091
3092 void MainWindow::on_actionKill_Sound_triggered()
3093 {
3094 bt_->killSound();
3095 }
3096
3097 void MainWindow::on_actionAbout_triggered()
3098 {
3099 static const QString APP_NAME = "BambooTracker v" + QString::fromStdString(Version::ofApplicationInString());
3100 static const QString APP_DESC = tr("YM2608 Music Tracker");
3101 static constexpr char COPY[] = "Copyright (C) 2018 Rerrah";
3102 static const QString WEB = tr("Web:")
3103 + R"( <a href="https://bambootracker.github.io/BambooTracker/">https://bambootracker.github.io/BambooTracker/</a>)";
3104
3105 static const QString LICENSE = tr("This software is licensed under the GNU General Public License v2.0 or later.");
3106 static const QString SOURCE = tr("Source is available at:");
3107 static const QString REPO = R"(<a href="https://github.com/BambooTracker/BambooTracker">https://github.com/BambooTracker/BambooTracker</a>)";
3108
3109 static const QString LIB_HEAD = tr("Libraries:");
3110 static const QString CONTRIBUTORS = tr("Also see changelog which lists contributors.");
3111 static const QString ACKNOWLEGEMENT = tr("Thank you to everyone who reports bugs, makes suggestions, and contributes to this project!");
3112
3113 static const QStringList LIBS = {
3114 tr("blip_buf by (C) Shay Green (LGPL v2.1)"),
3115 #ifdef USE_REAL_CHIP
3116 tr("C86CTL by (C) honet (BSD 3-Clause)"),
3117 #endif
3118 tr("emu2149 by (C) Mitsutaka Okazaki (MIT License)"),
3119 tr("fmopn by (C) Tatsuyuki Satoh, Jarek Burczynski, ValleyBell (GPL v2+)"),
3120 tr("libOPNMIDI by (C) Vitaly Novichkov (MIT License part)"),
3121 tr("Nuked OPN-MOD by (C) Alexey Khokholov (Nuke.YKT), Jean Pierre Cimalando (LGPL v2.1+)"),
3122 tr("Qt (GPL v2+ or LGPL v3)"),
3123 tr("RtAudio by (C) Gary P. Scavone (RtAudio License)"),
3124 tr("RtMidi by (C) Gary P. Scavone (RtMidi License)"),
3125 #ifdef USE_REAL_CHIP
3126 tr("SCCI by (C) gasshi (SCCI License)"),
3127 #endif
3128 tr("Silk icons by (C) Mark James (CC BY 2.5 or 3.0)"),
3129 tr("ymdeltat by (C) Tatsuyuki Satoh, Jarek Burczynski, ValleyBell (GPL v2+)"),
3130 tr("ymfm by (C) Aaron Giles (BSD 3-Clause)")
3131 };
3132
3133 static const QString FORMATTED_TEXT =
3134 "<h2>" + APP_NAME + "</h2>"
3135 "<p><strong>" + APP_DESC + "</strong></p>"
3136 "<p><b>" + COPY + "</b></p>"
3137 "<p>" + WEB + "</p>"
3138 "<p>" + LICENSE + "<br>"
3139 + SOURCE + "<br>" + REPO + "</p>"
3140 "<hr>"
3141 "<p>" + LIB_HEAD + "<ul style='margin-left: 16px; -qt-list-indent: 0;'>"
3142 + (QStringList { "" } + LIBS).join("<li>") + "</li>"
3143 + "</ul></p>"
3144 "<p>" + CONTRIBUTORS + "<br>"
3145 + ACKNOWLEGEMENT +"</p>";
3146
3147 QMessageBox dialog(QMessageBox::NoIcon, tr("About"), FORMATTED_TEXT, QMessageBox::Ok, this);
3148 dialog.setTextFormat(Qt::RichText);
3149 dialog.setIconPixmap(QIcon(":/icon/app_icon").pixmap(QSize(44, 44)));
3150 dialog.exec();
3151 }
3152
3153 void MainWindow::on_actionFollow_Mode_triggered()
3154 {
3155 bt_->setFollowPlay(ui->actionFollow_Mode->isChecked());
3156 config_.lock()->setFollowMode(ui->actionFollow_Mode->isChecked());
3157
3158 ui->orderList->onFollowModeChanged();
3159 ui->patternEditor->onFollowModeChanged();
3160 }
3161
3162 void MainWindow::on_actionGroove_Settings_triggered()
3163 {
3164 std::vector<std::vector<int>> seqs(bt_->getGrooveCount());
3165 std::generate(seqs.begin(), seqs.end(), [&, i = 0]() mutable { return bt_->getGroove(i++); });
3166
3167 GrooveSettingsDialog dialog(this);
3168 dialog.setGrooveSquences(seqs);
3169 if (dialog.exec() == QDialog::Accepted) {
3170 bt_->stopPlaySong();
3171 lockWidgets(false);
3172 bt_->setGrooves(dialog.getGrooveSequences());
3173 ui->grooveSpinBox->setMaximum(static_cast<int>(bt_->getGrooveCount()) - 1);
3174 setModifiedTrue();
3175 }
3176 }
3177
3178 void MainWindow::on_actionConfiguration_triggered()
3179 {
3180 ConfigurationDialog dialog(config_.lock(), palette_, stream_, this);
3181 QObject::connect(&dialog, &ConfigurationDialog::applyPressed, this, &MainWindow::changeConfiguration);
3182
3183 if (dialog.exec() == QDialog::Accepted) {
3184 changeConfiguration();
3185 io::saveConfiguration(config_.lock());
3186 io::savePalette(palette_.get());
3187 }
3188 }
3189
3190 void MainWindow::on_actionExpand_triggered()
3191 {
3192 ui->patternEditor->onExpandPressed();
3193 }
3194
3195 void MainWindow::on_actionShrink_triggered()
3196 {
3197 ui->patternEditor->onShrinkPressed();
3198 }
3199
3200 void MainWindow::on_actionDuplicate_Order_triggered()
3201 {
3202 ui->orderList->onDuplicatePressed();
3203 }
3204
3205 void MainWindow::on_actionMove_Order_Up_triggered()
3206 {
3207 ui->orderList->onMoveOrderPressed(true);
3208 }
3209
3210 void MainWindow::on_actionMove_Order_Down_triggered()
3211 {
3212 ui->orderList->onMoveOrderPressed(false);
3213 }
3214
3215 void MainWindow::on_actionClone_Patterns_triggered()
3216 {
3217 ui->orderList->onClonePatternsPressed();
3218 }
3219
3220 void MainWindow::on_actionClone_Order_triggered()
3221 {
3222 ui->orderList->onCloneOrderPressed();
3223 }
3224
3225 void MainWindow::on_actionNew_triggered()
3226 {
3227 if (isWindowModified()) {
3228 switch (ModuleSaveCheckDialog(bt_->getModuleTitle(), this).exec()) {
3229 case QMessageBox::Yes:
3230 if (!on_actionSave_triggered()) return;
3231 break;
3232 case QMessageBox::No:
3233 break;
3234 case QMessageBox::Cancel:
3235 default:
3236 return;
3237 }
3238 }
3239
3240 bt_->stopPlaySong();
3241 lockWidgets(false);
3242 freezeViews();
3243 if (!tickTimerForRealChip_) {
3244 try {
3245 stream_->stop();
3246 }
3247 catch (std::exception& e) {
3248 showStreamFailedDialog(e.what());
3249 }
3250 }
3251
3252 bt_->makeNewModule();
3253 loadModule();
3254 setInitialSelectedInstrument();
3255 isModifiedForNotCommand_ = false;
3256 setWindowModified(false);
3257 if (!tickTimerForRealChip_) {
3258 try {
3259 stream_->start();
3260 }
3261 catch (std::exception& e) {
3262 showStreamFailedDialog(e.what());
3263 }
3264 }
3265 assignADPCMSamples();
3266 }
3267
3268 void MainWindow::on_actionComments_triggered()
3269 {
3270 if (commentDialog_) {
3271 if (commentDialog_->isVisible()) commentDialog_->activateWindow();
3272 else commentDialog_->show();
3273 }
3274 else {
3275 commentDialog_ = std::make_unique<CommentEditDialog>(gui_utils::utf8ToQString(bt_->getModuleComment()), this);
3276 commentDialog_->show();
3277 QObject::connect(commentDialog_.get(), &CommentEditDialog::commentChanged,
3278 this, [&](const QString text) {
3279 bt_->setModuleComment(text.toUtf8().toStdString());
3280 setModifiedTrue();
3281 });
3282 }
3283 }
3284
3285 bool MainWindow::on_actionSave_triggered()
3286 {
3287 auto path = QString::fromStdString(bt_->getModulePath());
3288 if (!path.isEmpty() && QFileInfo::exists(path) && QFileInfo(path).isFile()) {
3289 if (!backupModule(path)) return false;
3290
3291 try {
3292 QByteArray bytes;
3293 {
3294 io::BinaryContainer container;
3295 bt_->saveModule(container);
3296 bytes.reserve(container.size());
3297 std::move(container.begin(), container.end(), std::back_inserter(bytes));
3298 }
3299 QFile fp(path);
3300 if (!fp.open(QIODevice::WriteOnly)) {
3301 FileIOErrorMessageBox::openError(path, false, io::FileType::Mod, this);
3302 return false;
3303 }
3304 fp.write(bytes);
3305 fp.close();
3306
3307 isModifiedForNotCommand_ = false;
3308 isSavedModBefore_ = true;
3309 setWindowModified(false);
3310 setWindowTitle();
3311 return true;
3312 }
3313 catch (io::FileIOError& e) {
3314 FileIOErrorMessageBox(path, false, e, this).exec();
3315 return false;
3316 }
3317 catch (std::exception& e) {
3318 FileIOErrorMessageBox(path, false, io::FileType::Mod, QString(e.what()), this).exec();
3319 return false;
3320 }
3321 }
3322 else {
3323 return on_actionSave_As_triggered();
3324 }
3325 }
3326
3327 bool MainWindow::on_actionSave_As_triggered()
3328 {
3329 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
3330 QString file = QFileDialog::getSaveFileName(
3331 this, tr("Save module"),
3332 QString("%1/%2.btm").arg(dir.isEmpty() ? "." : dir, getModuleFileBaseName()),
3333 tr("BambooTracker module (*.btm)") + ";;" + tr("All files (*)"), nullptr
3334 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
3335 , QFileDialog::DontUseNativeDialog
3336 #endif
3337 );
3338 if (file.isNull()) return false;
3339 if (!file.endsWith(".btm")) file += ".btm"; // For linux
3340
3341 if (QFile::exists(file)) { // Backup if the module already exists
3342 if (!backupModule(file)) return false;
3343 }
3344
3345 bt_->setModulePath(file.toStdString());
3346 try {
3347 QByteArray bytes;
3348 {
3349 io::BinaryContainer container;
3350 bt_->saveModule(container);
3351 bytes.reserve(container.size());
3352 std::move(container.begin(), container.end(), std::back_inserter(bytes));
3353 }
3354
3355 QFile fp(file);
3356 if (!fp.open(QIODevice::WriteOnly)) {
3357 FileIOErrorMessageBox::openError(file, false, io::FileType::Mod, this);
3358 return false;
3359 }
3360 fp.write(bytes);
3361 fp.close();
3362
3363 isModifiedForNotCommand_ = false;
3364 isSavedModBefore_ = true;
3365 setWindowModified(false);
3366 setWindowTitle();
3367 config_.lock()->setWorkingDirectory(QFileInfo(file).dir().path().toStdString());
3368 changeFileHistory(file);
3369 return true;
3370 }
3371 catch (io::FileIOError& e) {
3372 FileIOErrorMessageBox(file, false, e, this).exec();
3373 return false;
3374 }
3375 catch (std::exception& e) {
3376 FileIOErrorMessageBox(file, false, io::FileType::Mod, QString(e.what()), this).exec();
3377 return false;
3378 }
3379 }
3380
3381 void MainWindow::on_actionOpen_triggered()
3382 {
3383 if (isWindowModified()) {
3384 switch (ModuleSaveCheckDialog(bt_->getModuleTitle(), this).exec()) {
3385 case QMessageBox::Yes:
3386 if (!on_actionSave_triggered()) return;
3387 break;
3388 case QMessageBox::No:
3389 break;
3390 case QMessageBox::Cancel:
3391 return;
3392 default:
3393 break;
3394 }
3395 }
3396
3397 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
3398 QString file = QFileDialog::getOpenFileName(this, tr("Open module"), (dir.isEmpty() ? "./" : dir),
3399 tr("BambooTracker module (*.btm)") + ";;" + tr("All files (*)"), nullptr
3400 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
3401 , QFileDialog::DontUseNativeDialog
3402 #endif
3403 );
3404 if (file.isNull()) return;
3405
3406 bt_->stopPlaySong();
3407 lockWidgets(false);
3408
3409 openModule(file);
3410 }
3411
3412 void MainWindow::on_actionLoad_From_File_triggered()
3413 {
3414 loadInstrument();
3415 }
3416
3417 void MainWindow::on_actionSave_To_File_triggered()
3418 {
3419 saveInstrument();
3420 }
3421
3422 void MainWindow::on_actionImport_From_Bank_File_triggered()
3423 {
3424 importInstrumentsFromBank();
3425 }
3426
3427 void MainWindow::on_actionInterpolate_triggered()
3428 {
3429 ui->patternEditor->onInterpolatePressed();
3430 }
3431
3432 void MainWindow::on_actionReverse_triggered()
3433 {
3434 ui->patternEditor->onReversePressed();
3435 }
3436
3437 void MainWindow::on_actionReplace_Instrument_triggered()
3438 {
3439 ui->patternEditor->onReplaceInstrumentPressed();
3440 }
3441
3442 void MainWindow::on_actionRow_triggered()
3443 {
3444 if (isEditedPattern_) ui->patternEditor->onSelectPressed(2);
3445 else if (isEditedOrder_) ui->orderList->onSelectPressed(2);
3446 }
3447
3448 void MainWindow::on_actionColumn_triggered()
3449 {
3450 if (isEditedPattern_) ui->patternEditor->onSelectPressed(3);
3451 else if (isEditedOrder_) ui->orderList->onSelectPressed(3);
3452 }
3453
3454 void MainWindow::on_actionPattern_triggered()
3455 {
3456 if (isEditedPattern_) ui->patternEditor->onSelectPressed(4);
3457 else if (isEditedOrder_) ui->orderList->onSelectPressed(4);
3458 }
3459
3460 void MainWindow::on_actionOrder_triggered()
3461 {
3462 if (isEditedPattern_) ui->patternEditor->onSelectPressed(5);
3463 else if (isEditedOrder_) ui->orderList->onSelectPressed(5);
3464 }
3465
3466 void MainWindow::on_actionRemove_Unused_Instruments_triggered()
3467 {
3468 if (showUndoResetWarningDialog(tr("Do you want to remove all unused instruments?"))) {
3469 bt_->stopPlaySong();
3470 lockWidgets(false);
3471
3472 auto list = ui->instrumentList;
3473 for (auto& n : bt_->getUnusedInstrumentIndices()) {
3474 for (int i = 0; i < list->count(); ++i) {
3475 if (list->item(i)->data(Qt::UserRole).toInt() == n) {
3476 removeInstrument(i);
3477 }
3478 }
3479 }
3480 bt_->clearUnusedInstrumentProperties();
3481 bt_->clearCommandHistory();
3482 comStack_->clear();
3483 setModifiedTrue();
3484 }
3485 }
3486
3487 void MainWindow::on_actionRemove_Unused_Patterns_triggered()
3488 {
3489 if (showUndoResetWarningDialog(tr("Do you want to remove all unused patterns?"))) {
3490 bt_->stopPlaySong();
3491 lockWidgets(false);
3492
3493 bt_->clearUnusedPatterns();
3494 bt_->clearCommandHistory();
3495 comStack_->clear();
3496 setModifiedTrue();
3497 }
3498 }
3499
3500 void MainWindow::on_actionWAV_triggered()
3501 {
3502 // Record current mute states
3503 const auto& style = bt_->getSongStyle(bt_->getCurrentSongNumber());
3504 const auto& attribs = style.trackAttribs;
3505 std::vector<bool> muteStates(attribs.size());
3506 std::vector<int> unmuteTracks;
3507 for (size_t i = 0; i < attribs.size(); ++i) {
3508 muteStates[i] = bt_->isMute(attribs[i].number);
3509 if (!muteStates[i]) unmuteTracks.push_back(static_cast<int>(i));
3510 }
3511
3512 unmuteTracks = gui_utils::adaptVisibleTrackList(unmuteTracks, style.type, SongType::Standard);
3513 WaveExportSettingsDialog dialog(unmuteTracks, this);
3514 if (dialog.exec() != QDialog::Accepted) return;
3515
3516 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
3517 QString path = QFileDialog::getSaveFileName(
3518 this, tr("Export to WAV"),
3519 QString("%1/%2.wav").arg(dir.isEmpty() ? "." : dir, getModuleFileBaseName()),
3520 tr("WAV signed 16-bit PCM (*.wav)") + ";;" + tr("All files (*)"), nullptr
3521 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
3522 , QFileDialog::DontUseNativeDialog
3523 #endif
3524 );
3525 if (path.isNull()) return;
3526 if (!path.endsWith(".wav")) path += ".wav"; // For linux
3527 QString exDir = QFileInfo(path).dir().path();
3528
3529 int max = static_cast<int>(bt_->getTotalStepCount(
3530 bt_->getCurrentSongNumber(), static_cast<size_t>(dialog.getLoopCount()))) + 3;
3531 QProgressDialog progress("", tr("Cancel"), 0, max, this);
3532 progress.setWindowModality(Qt::ApplicationModal);
3533 progress.setWindowFlags(progress.windowFlags()
3534 & ~Qt::WindowContextHelpButtonHint
3535 & ~Qt::WindowCloseButtonHint);
3536 auto bar = [&progress] {
3537 QApplication::processEvents();
3538 progress.setValue(progress.value() + 1);
3539 return progress.wasCanceled();
3540 };
3541
3542 unmuteTracks = dialog.getSoloExportTracks();
3543 unmuteTracks.insert(unmuteTracks.begin(), -1);
3544
3545 bt_->stopPlaySong();
3546 lockWidgets(false);
3547
3548 try {
3549 stream_->stop();
3550 }
3551 catch (std::exception& e) {
3552 showStreamFailedDialog(e.what());
3553 }
3554
3555 for (size_t i = 0; i < unmuteTracks.size(); ++i) {
3556 int curTrack = unmuteTracks[i];
3557 QString text, name;
3558 if (curTrack == -1) text = tr("Export to WAV"); // Mixed all
3559 else {
3560 if (curTrack < 6) name = gui_utils::getTrackName(SongType::Standard, SoundSource::FM, curTrack);
3561 else if (curTrack < 9) name = gui_utils::getTrackName(SongType::Standard, SoundSource::SSG, curTrack - 6);
3562 else if (curTrack < 15) name = gui_utils::getTrackName(SongType::Standard, SoundSource::RHYTHM, curTrack - 9);
3563 else name = gui_utils::getTrackName(SongType::Standard, SoundSource::ADPCM, 0);
3564 text = tr("Export %1 to WAV").arg(name);
3565 }
3566 progress.setLabelText(text);
3567 progress.setValue(0);
3568 progress.open();
3569
3570 // Update mute states
3571 if (i == 1) {
3572 for (const TrackAttribute& attrib : attribs)
3573 bt_->setTrackMuteState(attrib.number, attrib.number != unmuteTracks[i]);
3574 }
3575 else if (i > 1) {
3576 int prevTrack = unmuteTracks[i - 1];
3577 if (style.type == SongType::FM3chExpanded) {
3578 if (prevTrack == 2) {
3579 bt_->setTrackMuteState(2, true);
3580 bt_->setTrackMuteState(3, true);
3581 bt_->setTrackMuteState(4, true);
3582 bt_->setTrackMuteState(5, true);
3583 }
3584 else if (prevTrack < 2) {
3585 bt_->setTrackMuteState(prevTrack, true);
3586 }
3587 else {
3588 bt_->setTrackMuteState(prevTrack + 3, true);
3589 }
3590 if (curTrack == 2) {
3591 bt_->setTrackMuteState(2, false);
3592 bt_->setTrackMuteState(3, false);
3593 bt_->setTrackMuteState(4, false);
3594 bt_->setTrackMuteState(5, false);
3595 }
3596 else if (curTrack < 2) {
3597 bt_->setTrackMuteState(curTrack, false);
3598 }
3599 else {
3600 bt_->setTrackMuteState(curTrack + 3, false);
3601 }
3602 }
3603 else {
3604 bt_->setTrackMuteState(prevTrack, true);
3605 bt_->setTrackMuteState(curTrack, false);
3606 }
3607 }
3608
3609 try {
3610 QByteArray bytes;
3611 {
3612 const uint32_t rate = static_cast<uint32_t>(dialog.getSampleRate());
3613 const uint16_t nCh = 2;
3614 const int loopCnt = dialog.getLoopCount();
3615 io::WavContainer container(rate, nCh, 16);
3616 if (!bt_->exportToWav(container, loopCnt, bar))
3617 break; // Jump if cancelled
3618 bytes.reserve(container.size());
3619 std::move(container.begin(), container.end(), std::back_inserter(bytes));
3620 }
3621
3622 if (curTrack > -1) path = QString("%1/%2 - %3.wav").arg(exDir).arg(curTrack + 1, 2, 10, QChar('0')).arg(name);
3623 QFile fp(path);
3624 if (!fp.open(QIODevice::WriteOnly)) {
3625 FileIOErrorMessageBox::openError(path, false, io::FileType::WAV, this);
3626 break; // Jump to post process
3627 }
3628 fp.write(bytes);
3629 fp.close();
3630 bar();
3631
3632 config_.lock()->setWorkingDirectory(QFileInfo(path).dir().path().toStdString());
3633 }
3634 catch (io::FileIOError& e) {
3635 FileIOErrorMessageBox(path, false, e, this).exec();
3636 break;
3637 }
3638 catch (std::exception& e) {
3639 FileIOErrorMessageBox(path, false, io::FileType::WAV, QString(e.what()), this).exec();
3640 break;
3641 }
3642 }
3643
3644 // Restore states
3645 for (size_t i = 0 ; i < attribs.size(); ++i) {
3646 bt_->setTrackMuteState(attribs[i].number, muteStates[i]);
3647 }
3648
3649 try {
3650 stream_->start();
3651 }
3652 catch (std::exception& e) {
3653 showStreamFailedDialog(e.what());
3654 }
3655 }
3656
3657 void MainWindow::on_actionVGM_triggered()
3658 {
3659 VgmExportSettingsDialog dialog(this);
3660 if (dialog.exec() != QDialog::Accepted) return;
3661 io::GD3Tag tag = dialog.getGD3Tag();
3662
3663 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
3664 QString path = QFileDialog::getSaveFileName(
3665 this, tr("Export to VGM"),
3666 QString("%1/%2.vgm").arg(dir.isEmpty() ? "." : dir, getModuleFileBaseName()),
3667 tr("VGM file (*.vgm)") + ";;" + tr("All files (*)"), nullptr
3668 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
3669 , QFileDialog::DontUseNativeDialog
3670 #endif
3671 );
3672 if (path.isNull()) return;
3673 if (!path.endsWith(".vgm")) path += ".vgm"; // For linux
3674
3675 int max = static_cast<int>(bt_->getTotalStepCount(bt_->getCurrentSongNumber(), 1)) + 3;
3676 QProgressDialog progress(tr("Export to VGM"), tr("Cancel"), 0, max, this);
3677 progress.setValue(0);
3678 progress.setWindowFlags(progress.windowFlags()
3679 & ~Qt::WindowContextHelpButtonHint
3680 & ~Qt::WindowCloseButtonHint);
3681 progress.setWindowModality(Qt::ApplicationModal);
3682 progress.open();
3683
3684 bt_->stopPlaySong();
3685 lockWidgets(false);
3686
3687 try {
3688 stream_->stop();
3689 }
3690 catch (std::exception& e) {
3691 showStreamFailedDialog(e.what());
3692 }
3693
3694 try {
3695 auto bar = [&progress]() -> bool {
3696 QApplication::processEvents();
3697 progress.setValue(progress.value() + 1);
3698 return progress.wasCanceled();
3699 };
3700
3701 QByteArray bytes;
3702 {
3703 io::BinaryContainer container;
3704 if (!bt_->exportToVgm(container, dialog.getExportTarget(), dialog.enabledGD3(), tag, dialog.isEnabledMix(), dialog.getGain(), bar))
3705 goto AFTER_VGM_WRITE; // Jump if cancelled
3706 bytes.reserve(container.size());
3707 std::move(container.begin(), container.end(), std::back_inserter(bytes));
3708 }
3709 QFile fp(path);
3710 if (!fp.open(QIODevice::WriteOnly)) {
3711 FileIOErrorMessageBox::openError(path, false, io::FileType::VGM, this);
3712 goto AFTER_VGM_WRITE; // Jump if cancelled
3713 }
3714 fp.write(bytes);
3715 fp.close();
3716 bar();
3717
3718 config_.lock()->setWorkingDirectory(QFileInfo(path).dir().path().toStdString());
3719 }
3720 catch (io::FileIOError& e) {
3721 FileIOErrorMessageBox(path, false, e, this).exec();
3722 }
3723 catch (std::exception& e) {
3724 FileIOErrorMessageBox(path, false, io::FileType::VGM, QString(e.what()), this).exec();
3725 }
3726
3727 AFTER_VGM_WRITE:
3728 try {
3729 stream_->start();
3730 }
3731 catch (std::exception& e) {
3732 showStreamFailedDialog(e.what());
3733 }
3734 }
3735
3736 void MainWindow::on_actionS98_triggered()
3737 {
3738 S98ExportSettingsDialog dialog(this);
3739 if (dialog.exec() != QDialog::Accepted) return;
3740 io::S98Tag tag = dialog.getS98Tag();
3741
3742 QString dir = QString::fromStdString(config_.lock()->getWorkingDirectory());
3743 QString path = QFileDialog::getSaveFileName(
3744 this, tr("Export to S98"),
3745 QString("%1/%2.s98").arg(dir.isEmpty() ? "." : dir, getModuleFileBaseName()),
3746 tr("S98 file (*.s98)") + ";;" + tr("All files (*)"), nullptr
3747 #if defined(Q_OS_LINUX) || (defined(Q_OS_BSD4) && !defined(Q_OS_DARWIN))
3748 , QFileDialog::DontUseNativeDialog
3749 #endif
3750 );
3751 if (path.isNull()) return;
3752 if (!path.endsWith(".s98")) path += ".s98"; // For linux
3753
3754 int max = static_cast<int>(bt_->getTotalStepCount(bt_->getCurrentSongNumber(), 1)) + 3;
3755 QProgressDialog progress(tr("Export to S98"), tr("Cancel"), 0, max, this);
3756 progress.setValue(0);
3757 progress.setWindowFlags(progress.windowFlags()
3758 & ~Qt::WindowContextHelpButtonHint
3759 & ~Qt::WindowCloseButtonHint);
3760 progress.setWindowModality(Qt::ApplicationModal);
3761 progress.open();
3762
3763 bt_->stopPlaySong();
3764 lockWidgets(false);
3765
3766 try {
3767 stream_->stop();
3768 }
3769 catch (std::exception& e) {
3770 showStreamFailedDialog(e.what());
3771 }
3772
3773 try {
3774 auto bar = [&progress]() -> bool {
3775 QApplication::processEvents();
3776 progress.setValue(progress.value() + 1);
3777 return progress.wasCanceled();
3778 };
3779
3780 QByteArray bytes;
3781 {
3782 io::BinaryContainer container;
3783 if (!bt_->exportToS98(container, dialog.getExportTarget(), dialog.enabledTag(),
3784 tag, dialog.getResolution(), bar))
3785 goto AFTER_S98_WRITE; // Jump if cancelled
3786 bytes.reserve(container.size());
3787 std::move(container.begin(), container.end(), std::back_inserter(bytes));
3788 }
3789
3790 QFile fp(path);
3791 if (!fp.open(QIODevice::WriteOnly)) {
3792 FileIOErrorMessageBox::openError(path, false, io::FileType::S98, this);
3793 goto AFTER_S98_WRITE; // Jump to post process
3794 }
3795 fp.write(bytes);
3796 fp.close();
3797 bar();
3798
3799 config_.lock()->setWorkingDirectory(QFileInfo(path).dir().path().toStdString());
3800 }
3801 catch (io::FileIOError& e) {
3802 FileIOErrorMessageBox(path, false, e, this).exec();
3803 }
3804 catch (std::exception& e) {
3805 FileIOErrorMessageBox(path, false, io::FileType::S98, QString(e.what()), this).exec();
3806 }
3807
3808 AFTER_S98_WRITE:
3809 try {
3810 stream_->start();
3811 }
3812 catch (std::exception& e) {
3813 showStreamFailedDialog(e.what());
3814 }
3815 }
3816
3817 void MainWindow::on_actionMix_triggered()
3818 {
3819 if (isEditedPattern_) ui->patternEditor->onPasteMixPressed();
3820 }
3821
3822 void MainWindow::on_actionOverwrite_triggered()
3823 {
3824 if (isEditedPattern_) ui->patternEditor->onPasteOverwritePressed();
3825 }
3826
3827 void MainWindow::onNewTickSignaledRealChip()
3828 {
3829 onNewTickSignaled(bt_->streamCountUp());
3830 }
3831
3832 void MainWindow::onNewTickSignaled(int state)
3833 {
3834 if (!state) { // New step
3835 int order = bt_->getPlayingOrderNumber();
3836 if (order > -1) { // Playing
3837 if (isVisible() && !isMinimized()) {
3838 ui->orderList->updatePositionByOrderUpdate(firstViewUpdateRequest_);
3839 ui->patternEditor->updatePositionByStepUpdate(firstViewUpdateRequest_);
3840 firstViewUpdateRequest_ = false;
3841 }
3842
3843 int width, base;
3844 if (config_.lock()->getShowRowNumberInHex()) {
3845 width = 2;
3846 base = 16;
3847 }
3848 else {
3849 width = 3;
3850 base = 10;
3851 }
3852 statusPlayPos_->setText(
3853 QString("%1/%2")
3854 .arg(order, width, base, QChar('0'))
3855 .arg(bt_->getPlayingStepNumber(), width, base, QChar('0')).toUpper());
3856 }
3857 }
3858 else if (state == -1) {
3859 if (hasLockedWigets_) lockWidgets(false);
3860 }
3861
3862 // Update BPM status
3863 if (bt_->getStreamGrooveEnabled()) {
3864 statusBpm_->setText(tr("Groove"));
3865 }
3866 else {
3867 // BPM = tempo * 6 / speed * 4 / 1st highlight
3868 double bpm = 24.0 * bt_->getStreamTempo() / bt_->getStreamSpeed() / highlight1_->value();
3869 statusBpm_->setText(QString::number(bpm, 'f', 2) + QString(" BPM"));
3870 }
3871 }
3872
3873 void MainWindow::on_actionClear_triggered()
3874 {
3875 fileHistory_->clearHistory();
3876 for (int i = ui->menu_Recent_Files->actions().count() - 1; 1 < i; --i)
3877 ui->menu_Recent_Files->removeAction(ui->menu_Recent_Files->actions().at(i));
3878 }
3879
3880 void MainWindow::on_keyRepeatCheckBox_stateChanged(int arg1)
3881 {
3882 config_.lock()->setKeyRepetition(arg1 == Qt::Checked);
3883 }
3884
3885 void MainWindow::updateVisuals()
3886 {
3887 int16_t wave[2 * bt_defs::OUTPUT_HISTORY_SIZE];
3888 bt_->getOutputHistory(wave);
3889
3890 ui->waveVisual->setStereoSamples(wave, bt_defs::OUTPUT_HISTORY_SIZE);
3891 }
3892
3893 void MainWindow::on_action_Effect_List_triggered()
3894 {
3895 if (effListDialog_) {
3896 if (effListDialog_->isVisible()) effListDialog_->activateWindow();
3897 else effListDialog_->show();
3898 }
3899 else {
3900 effListDialog_ = std::make_unique<EffectListDialog>(this);
3901 effListDialog_->show();
3902 }
3903 }
3904
3905 void MainWindow::on_actionShortcuts_triggered()
3906 {
3907 if (shortcutsDialog_) {
3908 if (shortcutsDialog_->isVisible()) shortcutsDialog_->activateWindow();
3909 else shortcutsDialog_->show();
3910 }
3911 else {
3912 shortcutsDialog_ = std::make_unique<KeyboardShortcutListDialog>(this);
3913 shortcutsDialog_->show();
3914 }
3915 }
3916
3917 void MainWindow::on_actionExport_To_Bank_File_triggered()
3918 {
3919 exportInstrumentsToBank();
3920 }
3921
3922 void MainWindow::on_actionRemove_Duplicate_Instruments_triggered()
3923 {
3924 if (showUndoResetWarningDialog(tr("Do you want to remove all duplicate instruments?"))) {
3925 bt_->stopPlaySong();
3926 lockWidgets(false);
3927
3928 std::unordered_map<int, int> rplMap = bt_->replaceDuplicateInstrumentsInPatterns();
3929 auto list = ui->instrumentList;
3930 for (auto& pairs : rplMap) {
3931 for (int j = 0; j < list->count(); ++j) {
3932 if (list->item(j)->data(Qt::UserRole).toInt() == pairs.first)
3933 removeInstrument(j);
3934 }
3935 }
3936 bt_->clearUnusedInstrumentProperties();
3937 bt_->clearCommandHistory();
3938 comStack_->clear();
3939 ui->patternEditor->onDuplicateInstrumentsRemoved();
3940 setModifiedTrue();
3941 }
3942 }
3943
3944 void MainWindow::on_actionRename_Instrument_triggered()
3945 {
3946 renameInstrument();
3947 }
3948
3949 void MainWindow::on_action_Bookmark_Manager_triggered()
3950 {
3951 if (bmManForm_->isVisible()) bmManForm_->activateWindow();
3952 else bmManForm_->show();
3953 }
3954
3955 void MainWindow::on_actionFine_Decrease_Values_triggered()
3956 {
3957 if (isEditedPattern_) ui->patternEditor->onChangeValuesPressed(false, false);
3958 }
3959
3960 void MainWindow::on_actionFine_Increase_Values_triggered()
3961 {
3962 if (isEditedPattern_) ui->patternEditor->onChangeValuesPressed(false, true);
3963 }
3964
3965 void MainWindow::on_actionCoarse_D_ecrease_Values_triggered()
3966 {
3967 if (isEditedPattern_) ui->patternEditor->onChangeValuesPressed(true, false);
3968 }
3969
3970 void MainWindow::on_actionCoarse_I_ncrease_Values_triggered()
3971 {
3972 if (isEditedPattern_) ui->patternEditor->onChangeValuesPressed(true, true);
3973 }
3974
3975 void MainWindow::on_action_Toggle_Bookmark_triggered()
3976 {
3977 bmManForm_->onBookmarkToggleRequested(bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
3978 }
3979
3980 void MainWindow::on_action_Next_Bookmark_triggered()
3981 {
3982 bmManForm_->onBookmarkJumpRequested(true, bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
3983 }
3984
3985 void MainWindow::on_action_Previous_Bookmark_triggered()
3986 {
3987 bmManForm_->onBookmarkJumpRequested(false, bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
3988 }
3989
3990 void MainWindow::on_action_Instrument_Mask_triggered()
3991 {
3992 config_.lock()->setInstrumentMask(ui->action_Instrument_Mask->isChecked());
3993 }
3994
3995 void MainWindow::on_action_Volume_Mask_triggered()
3996 {
3997 config_.lock()->setVolumeMask(ui->action_Volume_Mask->isChecked());
3998 }
3999
4000 void MainWindow::on_actionSet_Ro_w_Marker_triggered()
4001 {
4002 bt_->setMarker(bt_->getCurrentOrderNumber(), bt_->getCurrentStepNumber());
4003 ui->patternEditor->changeMarker();
4004 }
4005
4006 void MainWindow::on_actionPlay_From_Marker_triggered()
4007 {
4008 startPlayFromMarker();
4009 }
4010
4011 void MainWindow::on_action_Go_To_triggered()
4012 {
4013 GoToDialog dialog(bt_, this);
4014 if (dialog.exec() == QDialog::Accepted) {
4015 if (!bt_->isPlaySong() || !bt_->isFollowPlay()) {
4016 bt_->setCurrentOrderNumber(dialog.getOrder());
4017 bt_->setCurrentStepNumber(dialog.getStep());
4018 bt_->setCurrentTrack(dialog.getTrack());
4019 ui->orderList->updatePositionByPositionJump(true);
4020 ui->patternEditor->updatepositionByPositionJump(true);
4021 }
4022 }
4023 }
4024
4025 void MainWindow::on_actionRemove_Unused_ADPCM_Samples_triggered()
4026 {
4027 if (showUndoResetWarningDialog(tr("Do you want to remove all unused ADPCM samples?"))) {
4028 bt_->stopPlaySong();
4029 lockWidgets(false);
4030
4031 bt_->clearUnusedADPCMSamples();
4032 assignADPCMSamples();
4033 bt_->clearCommandHistory();
4034 comStack_->clear();
4035 setModifiedTrue();
4036 }
4037 }
4038
4039 void MainWindow::on_action_Status_Bar_triggered()
4040 {
4041 ui->statusBar->setVisible(ui->action_Status_Bar->isChecked());
4042 }
4043
4044 void MainWindow::on_action_Toolbar_triggered()
4045 {
4046 bool visible = ui->action_Toolbar->isChecked();
4047 ui->mainToolBar->setVisible(visible);
4048 ui->subToolBar->setVisible(visible);
4049 }
4050
4051 void MainWindow::on_actionNew_Drumki_t_triggered()
4052 {
4053 addDrumkit();
4054 }
4055
4056 void MainWindow::on_action_Wave_View_triggered(bool checked)
4057 {
4058 config_.lock()->setVisibleWaveView(checked);
4059 ui->waveVisual->setVisible(checked);
4060 if (checked)
4061 visualTimer_->start(static_cast<int>(std::round(1000. / config_.lock()->getWaveViewFrameRate())));
4062 else
4063 visualTimer_->stop();
4064 }
4065
4066 void MainWindow::on_action_Transpose_Song_triggered()
4067 {
4068 TransposeSongDialog dialog(this);
4069 if (dialog.exec() == QDialog::Accepted) {
4070 if (showUndoResetWarningDialog(tr("Do you want to transpose a song?"))) {
4071 bt_->stopPlaySong();
4072 lockWidgets(false);
4073
4074 bt_->transposeSong(bt_->getCurrentSongNumber(),
4075 dialog.getTransposeSemitones(), dialog.getExcludeInstruments());
4076 ui->patternEditor->onPatternDataGlobalChanged();
4077
4078 bt_->clearCommandHistory();
4079 comStack_->clear();
4080 setModifiedTrue();
4081 }
4082 }
4083 }
4084
4085 void MainWindow::on_action_Swap_Tracks_triggered()
4086 {
4087 SwapTracksDialog dialog(bt_->getSongStyle(bt_->getCurrentSongNumber()), this);
4088 if (dialog.exec() == QDialog::Accepted) {
4089 int track1 = dialog.getTrack1();
4090 int track2 = dialog.getTrack2();
4091 if ((track1 != track2) && showUndoResetWarningDialog(tr("Do you want to swap tracks?"))) {
4092 bt_->stopPlaySong();
4093 lockWidgets(false);
4094
4095 bt_->swapTracks(bt_->getCurrentSongNumber(), track1, track2);
4096 ui->orderList->onOrderDataGlobalChanged();
4097 ui->patternEditor->onPatternDataGlobalChanged();
4098
4099 bt_->clearCommandHistory();
4100 comStack_->clear();
4101 setModifiedTrue();
4102 }
4103 }
4104 }
4105
4106 void MainWindow::on_action_Insert_triggered()
4107 {
4108 if (isEditedPattern_) ui->patternEditor->onPasteInsertPressed();
4109 }
4110
4111 void MainWindow::on_action_Hide_Tracks_triggered()
4112 {
4113 HideTracksDialog dialog(bt_->getSongStyle(bt_->getCurrentSongNumber()),
4114 ui->patternEditor->getVisibleTracks(), this);
4115 if (dialog.exec() == QDialog::Accepted) {
4116 std::vector<int> visTracks = dialog.getVisibleTracks();
4117 ui->orderList->setVisibleTracks(visTracks);
4118 setOrderListGroupMaximumWidth();
4119 ui->patternEditor->setVisibleTracks(visTracks);
4120
4121 int song = bt_->getCurrentSongNumber();
4122 int all = static_cast<int>(bt_->getSongStyle(song).trackAttribs.size());
4123 for (int i = 0; i < all; ++i) {
4124 if (std::any_of(visTracks.begin(), visTracks.end(), [i](int n) { return i == n; })) {
4125 bt_->setTrackVisibility(song, i, true);
4126 }
4127 else {
4128 bt_->setTrackVisibility(song, i, false);
4129 if (config_.lock()->getMuteHiddenTracks()) {
4130 bt_->setTrackMuteState(i, true);
4131 }
4132 }
4133 }
4134
4135 setModifiedTrue();
4136 }
4137 }
4138
4139 void MainWindow::on_action_Estimate_Song_Length_triggered()
4140 {
4141 double time = bt_->estimateSongLength(bt_->getCurrentSongNumber());
4142 int seconds = static_cast<int>(std::round(time));
4143 QMessageBox dialog;
4144 dialog.setIcon(QMessageBox::Information);
4145 dialog.setText(tr("Approximate song length: %1m%2s")
4146 .arg(seconds / 60).arg(seconds % 60, 2, 10, QChar('0')));
4147 dialog.exec();
4148 }
4149
4150 void MainWindow::on_action_Key_Signature_Manager_triggered()
4151 {
4152 if (ksManForm_->isVisible()) ksManForm_->activateWindow();
4153 else ksManForm_->show();
4154 }
4155
4156 void MainWindow::on_action_Welcome_triggered()
4157 {
4158 welcomeDialog_->open();
4159 }