Debian Codegraph @

Source/Controllers/KitController.cpp

raw
1 /*
2 * KitController.cpp
3 *
4 * Created on: 19 Nov 2016
5 * Author: jeremy
6 */
7
8 #include "../Util/ErrorHandler.h"
9 #include "KitController.h"
10
11 #include <gtkmm/entry.h>
12 #include <gtkmm/messagedialog.h>
13 #include <gtkmm/filechooserdialog.h>
14 #include <gtkmm/checkbutton.h>
15
16 #include <functional>
17 #include <algorithm>
18 #include <string>
19 #include <stdexcept>
20 #include <filesystem>
21 #include <iostream>
22
23 using namespace eXaDrumsApi;
24 using namespace Widgets;
25 using namespace Util;
26 using namespace Errors;
27
28 namespace fs = std::filesystem;
29
30 namespace Controllers
31 {
32
33 KitController::KitController(Glib::RefPtr<Gtk::Builder> builder, std::shared_ptr<eXaDrums>& drumKit, bool isRoot)
34 : builder(builder), drumKit(drumKit), isRoot(isRoot)
35 {
36
37 numInstrumentsToCreate = 0;
38 instrumentToModify = -1;
39
40 std::string dataFolder(drumKit->GetDataLocation());
41
42 this->kitCreator = std::make_unique<KitCreator>(dataFolder.c_str());
43
44
45 Gtk::Button* instrumentConfigOkay = nullptr;
46 Gtk::Button* instrumentConfigCancel = nullptr;
47 Gtk::Button* instrumentSelectSave = nullptr;
48 Gtk::Button* instrumentSelectCancel = nullptr;
49 Gtk::Button* addInstrument = nullptr;
50 Gtk::Button* kitNameCancel = nullptr;
51 Gtk::Button* KitNameOk = nullptr;
52 Gtk::Button* soundChooserCancel = nullptr;
53 Gtk::Button* soundChooserOkay = nullptr;
54 Gtk::Button* recorderCancel = nullptr;
55 Gtk::Button* recorderSave = nullptr;
56 Gtk::Button* recorderExportCancel = nullptr;
57 Gtk::Button* recorderExportOK = nullptr;
58
59 Gtk::FileChooserDialog* soundChooser = nullptr;
60
61 Gtk::ComboBoxText* instrumentConfig_Type = nullptr;
62
63
64 // Get all widgets
65 {
66 // Buttons
67 builder->get_widget("PlayButton", playButton);
68 builder->get_widget("RecordButton", recordButton);
69 builder->get_widget("DeleteDrumKitButton", deleteKitButton);
70 builder->get_widget("AddDrumKitButton", addDrumKitButton);
71 builder->get_widget("KitPreferencesButton", kitPreferencesButton);
72 builder->get_widget("InstrumentConfigOkay", instrumentConfigOkay);
73 builder->get_widget("InstrumentConfigCancel", instrumentConfigCancel);
74 builder->get_widget("ISAdd", addInstrument);
75 builder->get_widget("ISSave", instrumentSelectSave);
76 builder->get_widget("ISCancel", instrumentSelectCancel);
77 builder->get_widget("KitNameCancel", kitNameCancel);
78 builder->get_widget("KitNameOk", KitNameOk);
79 builder->get_widget("SoundChooserCancel", soundChooserCancel);
80 builder->get_widget("SoundChooserOkay", soundChooserOkay);
81 builder->get_widget("RecorderCancel", recorderCancel);
82 builder->get_widget("RecorderSave", recorderSave);
83 builder->get_widget("RecorderExportCancel", recorderExportCancel);
84 builder->get_widget("RecorderExportOK", recorderExportOK);
85
86 builder->get_widget("SoundChooser", soundChooser);
87
88
89 // Lists
90 builder->get_widget("KitsList", kitsList);
91
92 // Faders' box
93 builder->get_widget("FadersSaveButton", saveFaders);
94 builder->get_widget("FadersList", fadersList);
95
96 // Virtual kit
97 builder->get_widget("VirtualPadsList", virtualPadsList);
98
99 // Comboboxes
100 builder->get_widget("InstrumentConfig_Type", instrumentConfig_Type);
101
102
103 // Windows
104 builder->get_widget("NewKitNameWindow", newKitWindow);
105 builder->get_widget("InstrumentConfigWindow", instrumentConfigWindow);
106 builder->get_widget("InstrumentSeclectWindow", instrumentSeclectWindow);
107 builder->get_widget("RecorderWindow", recorderWindow);
108 builder->get_widget("RecorderExportWindow", recorderExportWindow);
109 builder->get_widget("VirtualPadWindow", virtualPadWindow);
110
111 }
112
113 // Populate Kits list
114 CreateKitsList();
115
116 // Add faders
117 UpdateFaders();
118 saveFaders->set_sensitive(false);
119
120 // Create virtual kit
121 UpdateVirtualKit();
122
123 // Load current kit
124 drumKit->SelectKit(GetCurrentKitId());
125
126 // Connect signals
127 {
128 playButton->signal_clicked().connect([&] { PlayDrums(); });
129 recordButton->signal_toggled().connect([&] { EnableRecording(); });
130 saveFaders->signal_clicked().connect([&] { SaveFaders(); });
131 deleteKitButton->signal_clicked().connect([&] { DeleteKitDialog(); });
132 addDrumKitButton->signal_clicked().connect([&] { AddNewKitWindow(); });
133 kitPreferencesButton->signal_clicked().connect([&] { ShowInstrumentSelectWindow(); });
134 instrumentConfigOkay->signal_clicked().connect([&] { ValidateInstrumentData(); });
135 instrumentConfigCancel->signal_clicked().connect([&] { CancelInstrumentModif(); });
136 instrumentSelectSave->signal_clicked().connect([&] { SaveKitPreferences(); instrumentSeclectWindow->hide(); });
137 instrumentSelectCancel->signal_clicked().connect([&] { instrumentSeclectWindow->hide(); });
138 addInstrument->signal_clicked().connect([&] { AddInstrumentToSelectedKit(); });
139 kitNameCancel->signal_clicked().connect([&] { newKitWindow->hide(); });
140 KitNameOk->signal_clicked().connect([&] { ValidateKitData(); });
141 soundChooserCancel->signal_clicked().connect([=] { soundChooser->hide(); });
142 soundChooserOkay->signal_clicked().connect([&] { ChangeInstrumentSound(); });
143 recorderCancel->signal_clicked().connect([&] { recorderWindow->hide(); });
144 recorderSave->signal_clicked().connect([&] { RecorderExport(); });
145 recorderExportCancel->signal_clicked().connect([&] { recorderExportWindow->hide(); });
146 recorderExportOK->signal_clicked().connect([&] { recorderWindow->show(); });
147
148 // Comboboxes
149 instrumentConfig_Type->signal_changed().connect([&] { ChangeInstrumentType(); });
150
151 // Kits list
152 kitsList->signal_changed().connect([&]
153 {
154 if(!isModifyingKit)
155 {
156 ChangeKit();
157 }
158 });
159
160 // Windows
161 virtualPadWindow->signal_key_press_event().connect([&](GdkEventKey* e)
162 {
163 for(const auto& v : virtualPads)
164 {
165 v->PlaySound(e->keyval);
166 }
167
168 return false;
169 }, false);
170
171 recorderWindow->signal_key_press_event().connect([&](GdkEventKey* e)
172 {
173 if(e->keyval == GDK_KEY_Return || e->keyval == GDK_KEY_KP_Enter)
174 {
175 RecorderExport();
176 }
177 else if(e->keyval == GDK_KEY_Escape)
178 {
179 recorderWindow->hide();
180 }
181 return false;
182 }, false);
183
184 }
185
186 return;
187 }
188
189 KitController::~KitController()
190 {
191
192 // Delete all pointers (dialogs and windows)
193 delete newKitWindow;
194 delete instrumentConfigWindow;
195 delete instrumentSeclectWindow;
196 delete recorderWindow;
197
198 return;
199 }
200
201
202 // Private Methods
203
204
205 void KitController::CreateKitsList()
206 {
207
208 // Retrieve kits names
209 std::vector<std::string> kitsNames = drumKit->GetKitsNames();
210
211 // Add kits to the list
212 for(std::size_t i = 0; i < kitsNames.size(); i++)
213 {
214 kitsList->insert(i, kitsNames[i]);
215 }
216 // Set default kit
217 kitsList->set_active(0);
218
219 return;
220 }
221
222 int KitController::GetCurrentKitId() const
223 {
224
225 int currentKitId = kitsList->get_active_row_number();
226
227 return currentKitId;
228 }
229
230 void KitController::DeleteKitDialog()
231 {
232
233
234 Gtk::MessageDialog d("Are you sure you want to delete the current drum kit?", false, Gtk::MessageType::MESSAGE_QUESTION, Gtk::ButtonsType::BUTTONS_YES_NO);
235 d.set_title("Delete Kit");
236
237 // Get answer
238 int answer = d.run();
239
240 // Check answer
241 switch(answer)
242 {
243 case Gtk::ResponseType::RESPONSE_NO: break;
244 case Gtk::ResponseType::RESPONSE_YES: this->DeleteKit(GetCurrentKitId()); break;
245 default: break;
246 }
247
248 return;
249 }
250
251 void KitController::DeleteKit(int id)
252 {
253
254 int numKits = drumKit->GetNumKits();
255
256 // Can't delete if only one kit
257 if(numKits > 1)
258 {
259 // Stop module if started
260 if(drumKit->IsStarted())
261 {
262 PlayDrums();
263 }
264
265 // Delete kit
266 try
267 {
268 drumKit->DeleteKit(id);
269 }
270 catch(const Exception& e)
271 {
272 errorDialog(e);
273 return;
274 }
275
276 // Remove kit from list
277 this->isModifyingKit = true;
278 kitsList->set_active(-1);
279 kitsList->remove_text(id);
280 this->isModifyingKit = false;
281
282 kitsList->set_active(std::max(0, id - 1));
283
284 }
285 else
286 {
287 Errors::errorDialog({"Cannot delete drum kit.", errorType::error_type_error});
288 }
289
290 return;
291 }
292
293 void KitController::AddNewKit()
294 {
295
296 if(drumKit->IsStarted())
297 {
298 try
299 {
300 PlayDrums();
301 }
302 catch(const Exception& e)
303 {
304 errorDialog(e);
305 return;
306 }
307 }
308
309
310 // Retrieve kits names
311 std::vector<std::string> oldKitsNames = drumKit->GetKitsNames();
312
313 // Reload kits
314 drumKit->ReloadKits();
315
316 // Retrieve kits names
317 std::vector<std::string> newkitsNames = drumKit->GetKitsNames();
318
319 if(newkitsNames.size() == oldKitsNames.size() + 1)
320 {
321 const auto newOldKit = std::mismatch(oldKitsNames.cbegin(), oldKitsNames.cend(), newkitsNames.cbegin());
322
323 if(newOldKit.second != newkitsNames.end())
324 {
325 // Get new kit's name and position in the list
326 std::string newKitName = *(newOldKit.second);
327 int pos = std::distance(newkitsNames.cbegin(), newOldKit.second);
328
329 // Insert new kit into list, and activate it
330 kitsList->insert(pos, newKitName);
331 kitsList->set_active(pos);
332 }
333 }
334
335 // Set new kit
336 ChangeKit();
337
338 return;
339 }
340
341 void KitController::KitAdded()
342 {
343 Errors::errorDialog({"A new drum kit has been added.", errorType::error_type_other});
344 return;
345 }
346
347 void KitController::EnableRecording()
348 {
349 bool isRecording = this->recordButton->get_active();
350
351
352 drumKit->EnableRecording(isRecording);
353
354 if(!isRecording)
355 {
356 recorderExportWindow->show();
357 }
358 }
359
360 void KitController::RecorderExport()
361 {
362 recorderExportWindow->hide();
363 const std::string fileName = recorderWindow->get_filename();
364
365 Gtk::CheckButton* exportRawCheckbox = nullptr;
366 builder->get_widget("ExportRawCheckbox", exportRawCheckbox);
367
368 const auto isExportRaw = exportRawCheckbox->get_active();
369
370 try
371 {
372 const auto path = fs::path{fileName};
373 if(path.filename().string().length() <= 3)
374 {
375 throw Exception("File name is too short.", error_type_warning);
376 }
377
378 std::string wavFileName = fileName;
379 if(path.extension() != ".wav")
380 {
381 wavFileName += ".wav";
382 }
383
384 drumKit->RecorderExportPCM(wavFileName);
385
386 if(isExportRaw)
387 {
388 drumKit->RecorderExport(fileName + ".xml");
389 }
390
391 drumKit->RecorderPurgeTempFile();
392
393 }
394 catch(const Exception& e)
395 {
396 errorDialog(e);
397 return;
398 }
399
400 recorderWindow->hide();
401 }
402
403 void KitController::PlayDrums()
404 {
405
406 if(drumKit->IsStarted())
407 {
408 this->playButton->set_property("label", Gtk::StockID("gtk-media-play"));
409
410 if(drumKit->IsSensorVirtual())
411 {
412 virtualPadWindow->hide();
413 }
414
415
416 drumKit->Stop();
417 }
418 else
419 {
420 this->playButton->set_property("label", Gtk::StockID("gtk-media-stop"));
421
422 if(drumKit->IsSensorVirtual())
423 {
424 virtualPadWindow->show();
425 }
426
427 if(drumKit->IsSensorSpi() && !isRoot)
428 {
429 Errors::errorDialog({"Using SPI sensors may require superuser privileges.", errorType::error_type_other});
430 }
431
432 try
433 {
434 drumKit->Start();
435 }
436 catch(const Exception& e)
437 {
438 errorDialog(e);
439 return;
440 }
441 }
442
443 return;
444 }
445
446 void KitController::ChangeKit()
447 {
448
449 bool started = drumKit->IsStarted();
450
451 // Stop module if started
452 if(started)
453 {
454 try
455 {
456 drumKit->Stop();
457 }
458 catch(const Exception& e)
459 {
460 errorDialog(e);
461 return;
462 }
463 }
464
465
466 // Load new kit or exit if it doesn't exist
467 try
468 {
469 const auto kitId = GetCurrentKitId();
470 drumKit->SelectKit(kitId);
471 }
472 catch(const Exception& e)
473 {
474 Errors::errorDialog(e);
475 return;
476 }
477
478 // Update faders
479 this->UpdateFaders();
480 saveFaders->set_sensitive(false);
481
482 // Update virtual kit
483 UpdateVirtualKit();
484
485 // Restart module if needed
486 if(started)
487 {
488 try
489 {
490 drumKit->Start();
491 }
492 catch(const Exception& e)
493 {
494 errorDialog(e);
495 }
496 }
497
498 return;
499 }
500
501 void KitController::SetInstrumentVolume(FaderPtr& fader) const
502 {
503
504 try
505 {
506 drumKit->SetInstrumentVolume(fader->GetInstrumentId(), fader->GetValue());
507 }
508 catch(const Exception& e)
509 {
510 errorDialog(e);
511 return;
512 }
513
514 saveFaders->set_sensitive(true);
515
516 return;
517 }
518
519
520 void KitController::SaveFaders() const
521 {
522
523 try
524 {
525 SaveKitConfig();
526 }
527 catch(const Exception& e)
528 {
529 errorDialog(e);
530 return;
531 }
532
533
534 // Disable button
535 saveFaders->set_sensitive(false);
536
537 return;
538 }
539
540 void KitController::UpdateFaders()
541 {
542
543 // Remove existing faders
544 std::for_each(faders.begin(), faders.end(), [](FaderPtr& fader) { fader.reset(); });
545 faders.clear();
546
547 std::vector<std::string> instNames = drumKit->GetInstrumentsNames();
548 for(std::size_t i = 0; i < instNames.size(); i++)
549 {
550 std::string name(instNames[i]);
551 int volume = GetInstrumentVolume(i);
552
553 FaderPtr fader(new Fader(name, i, volume));
554
555 faders.emplace_back(std::move(fader));
556 }
557
558 // Add all faders to GUI
559 std::for_each(faders.cbegin(), faders.cend(), [&](const FaderPtr& f){ this->fadersList->add(*f); });
560
561 // Connect faders signals
562 for(FaderPtr& fader : faders)
563 {
564 fader->GetScale().signal_value_changed().connect([&] { SetInstrumentVolume(fader); });
565 }
566
567 return;
568 }
569
570 void KitController::UpdateVirtualKit()
571 {
572 // Remove current virtual pads
573 std::for_each(virtualPads.begin(), virtualPads.end(), [](VirtualPadPtr& vpad) { vpad.reset(); });
574 virtualPads.clear();
575
576 auto const instNames = drumKit->GetInstrumentsNames();
577 auto const max = static_cast<short>(std::pow(2, drumKit->GetSensorsResolution())/2 - 1);
578
579 // Add new virtual pads
580 for(size_t i = 0; i < instNames.size(); i++)
581 {
582 auto trigsIds = drumKit->GetInstrumentTriggersIds(i);
583 std::vector<std::function<void()>> soundTriggers(trigsIds.size());
584
585 std::transform(trigsIds.begin(), trigsIds.end(), soundTriggers.begin(), [&, max] (int trigId)
586 {
587 return [&, trigId, max] () -> void { drumKit->SetTriggerSensorValue(trigId, max); };
588 });
589
590 VirtualPadPtr vpad(new VirtualPad(instNames[i], std::move(soundTriggers)));
591 virtualPads.emplace_back(std::move(vpad));
592 }
593
594 std::for_each(virtualPads.begin(), virtualPads.end(), [&](const VirtualPadPtr& vpad) { this->virtualPadsList->add(*vpad); });
595
596 }
597
598
599 void KitController::AddNewKitWindow()
600 {
601
602 newKitWindow->show();
603 // ShowKeyboard();
604
605 return;
606 }
607
608 void KitController::ModifyInstrument(int i)
609 {
610
611 // Get instrument name
612 std::vector<std::string> instrumentsNames = kitCreator->GetInstrumentsNames();
613
614 if(static_cast<std::size_t>(i) >= instrumentsNames.size())
615 {
616 errorDialog("This instrument does not exist.", error_type_error);
617 return;
618 }
619
620 std::string instrumentName = instrumentsNames[i];
621
622 // Get instrument type
623 std::string instrumentType = kitCreator->GetInstrumentType(i);
624
625 // Get instrument triggers
626 std::vector<int> instrumentTriggersIds = kitCreator->GetInstrumentTriggersIds(i);
627 std::vector<std::string> instrumentLocations = kitCreator->GetInstrumentTriggersLocations(i);
628
629 // Get instrument sounds
630 std::vector<std::string> instrumentSoundsTypes = kitCreator->GetInstrumentSoundsTypes(i);
631 std::vector<std::string> instrumentSoundsLocs = kitCreator->GetInstrumentSoundsLocs(i);
632 std::vector<uint8_t> instrumentNotes = kitCreator->GetInstrumentSoundsNotes(i);
633
634 // Get widgets
635 Gtk::ComboBoxText* instrumentConfig_Type = nullptr;
636 Gtk::Entry* instrumentConfig_Name = nullptr;
637
638 builder->get_widget("InstrumentConfig_Type", instrumentConfig_Type);
639 builder->get_widget("InstrumentConfig_Name", instrumentConfig_Name);
640
641 // Set widgets values
642
643 // Set instrument name
644 instrumentConfig_Name->set_text(instrumentName);
645
646 // Create vector of instruments types
647 std::vector<std::string> instrumentTypes = kitCreator->GetInstrumentsTypes();
648
649 // Populate instrument config window
650 {
651
652 std::string text = instrumentConfig_Type->get_active_text();
653 if(text.empty())
654 {
655
656 // Populate only if not already done
657
658 for(std::size_t i = 0; i < instrumentTypes.size(); i++)
659 {
660 instrumentConfig_Type->insert(i, instrumentTypes[i]);
661 }
662
663 // Set default instrument and call ChangeInstrumentType() method
664 instrumentConfig_Type->set_active(0);
665 }
666
667 }
668
669 instrumentConfig_Type->set_active_text(instrumentType);
670
671 for(std::size_t i = 0; i < triggersIdsAndLocations.size(); i++)
672 {
673 auto& t = triggersIdsAndLocations[i];
674
675 t->SetTriggerId(instrumentTriggersIds[i]);
676 t->SetTriggerLoc(instrumentLocations[i]);
677 }
678
679 for(std::size_t i = 0; i < soundsTypesAndPaths.size(); i++)
680 {
681 auto& s = soundsTypesAndPaths[i];
682
683 s->SetSoundType(instrumentSoundsTypes[i]);
684 s->SetSound(instrumentSoundsLocs[i]);
685 s->SetMidiNote(instrumentNotes[i]);
686 }
687
688 // Keep track of the instrument id
689 instrumentToModify = i;
690
691 // Show window
692 instrumentConfigWindow->show();
693
694 return;
695 }
696
697 void KitController::RemoveInstrument(std::size_t i)
698 {
699
700 if(instrumentsSelectors.size() > 1)
701 {
702 Gtk::MessageDialog d("Are you sure you want to remove this instrument (this modification will be saved and cannot be undone)?", false, Gtk::MessageType::MESSAGE_WARNING, Gtk::ButtonsType::BUTTONS_YES_NO);
703 d.set_title("Remove Instrument");
704
705 // Get answer
706 int answer = d.run();
707
708 // Check answer
709 switch(answer)
710 {
711 case Gtk::ResponseType::RESPONSE_NO: return;
712 case Gtk::ResponseType::RESPONSE_YES: break;
713 default: return;
714 }
715
716 // Load current kit into the kit creator for modifications
717 try
718 {
719 std::string kitLocation = drumKit->GetKitDataFileName();
720 kitCreator->CreateFromModel(kitLocation.c_str());
721 }
722 catch(const Exception& e)
723 {
724 errorDialog(e);
725 }
726
727 kitCreator->RemoveInstrument(i);
728
729 // Remove instrument from GUI
730 if(i < instrumentsSelectors.size())
731 {
732 instrumentsSelectors[i].reset();
733 instrumentsSelectors.erase(instrumentsSelectors.begin() + i);
734 }
735
736 try
737 {
738 std::string kitLocation = drumKit->GetKitDataFileName();
739 kitCreator->SaveKit(kitLocation.c_str());
740 }
741 catch(const Exception& e)
742 {
743 errorDialog(e);
744 }
745
746 SaveKitPreferences();
747 }
748
749 return;
750 }
751
752
753 void KitController::AddInstrumentToSelectedKit()
754 {
755
756 this->isModifyingKit = true;
757 kitCreator->SaveKit();
758 kitCreator->CreateNewKit();
759
760 // Load current kit into the kit creator for modifications
761 try
762 {
763 std::string kitLocation = drumKit->GetKitDataFileName();
764 kitCreator->CreateFromModel(kitLocation.c_str());
765 }
766 catch(const Exception& e)
767 {
768 errorDialog(e);
769 return;
770 }
771
772 int numInstruments = kitCreator->GetNumInstruments();
773 this->numInstrumentsToCreate = numInstruments + 1;
774
775 AddInstrumentToKit();
776 }
777
778
779 void KitController::AddInstrumentToKit()
780 {
781
782 int numInstruments = kitCreator->GetNumInstruments();
783
784 if(numInstruments < this->numInstrumentsToCreate)
785 {
786
787 // Retrieve data
788 std::string instrumentName = "Instrument " + std::to_string(numInstruments + 1);
789
790 // Retrieve window's widgets
791 Gtk::Entry* instrumentConfig_Name = nullptr;
792 Gtk::ComboBoxText* instrumentConfig_Type = nullptr;
793
794 // Get widgets
795 builder->get_widget("InstrumentConfig_Name", instrumentConfig_Name);
796 builder->get_widget("InstrumentConfig_Type", instrumentConfig_Type);
797
798
799 // Create vector of instruments types
800 std::vector<std::string> instrumentTypes = kitCreator->GetInstrumentsTypes();
801
802 // Populate instrument config window
803 {
804
805 // Populate only if not already done
806
807 std::string text = instrumentConfig_Type->get_active_text();
808
809 if(text.empty())
810 {
811 for(std::size_t i = 0; i < instrumentTypes.size(); i++)
812 {
813 instrumentConfig_Type->insert(i, instrumentTypes[i]);
814 }
815
816 // Set default instrument and call ChangeInstrumentType() method
817 instrumentConfig_Type->set_active(0);
818 }
819
820 }
821
822 instrumentConfig_Name->set_text(instrumentName);
823
824
825 // Show window
826 instrumentConfigWindow->show();
827
828 }
829 else if(numInstruments == this->numInstrumentsToCreate && numInstruments != 0)
830 {
831 // All instruments have been added, save kit.
832 kitCreator->SaveKit();
833 instrumentConfigWindow->hide();
834
835 AddNewKit();
836
837 if(!this->isModifyingKit)
838 {
839 KitAdded();
840 kitCreator->CreateNewKit();
841 this->numInstrumentsToCreate = 0;
842 }
843 else
844 {
845 ShowInstrumentSelectWindow();
846 }
847
848
849 if(this->isModifyingKit)
850 this->isModifyingKit = false;
851
852 }
853 else
854 {
855 errorDialog("Cannot create a new instrument.", error_type_warning);
856 }
857
858 return;
859 }
860
861 void KitController::ChangeInstrumentType()
862 {
863
864 Gtk::ComboBoxText* instrumentConfig_Type = nullptr;
865 Gtk::Box* instrumentConfig_TriggersBox = nullptr;
866 Gtk::Box* instrumentConfig_SoundsBox = nullptr;
867
868 builder->get_widget("InstrumentConfig_Type", instrumentConfig_Type);
869 builder->get_widget("InstrumentConfig_TriggersBox", instrumentConfig_TriggersBox);
870 builder->get_widget("InstrumentConfig_SoundsBox", instrumentConfig_SoundsBox);
871
872 /*if(instrumentConfig_Type->get_active_text() == nullptr)
873 {
874 errorDialog("Instrument type is undefined.", error_type_warning);
875 return;
876 }*/
877
878 std::string text = instrumentConfig_Type->get_active_text();
879 if(text.empty())
880 {
881
882 const auto instrumentTypes = kitCreator->GetInstrumentsTypes();
883 // Populate only if not already done
884
885 for(std::size_t i = 0; i < instrumentTypes.size(); i++)
886 {
887 instrumentConfig_Type->insert(i, instrumentTypes[i]);
888 }
889
890 // Set default instrument and call ChangeInstrumentType() method
891 instrumentConfig_Type->set_active(0);
892 }
893
894 std::string instrumentType = instrumentConfig_Type->get_active_text();
895
896 // Retrieve triggers locations
897 std::vector<std::string> triggersLocations = kitCreator->GetTriggersLocations(instrumentType);
898
899 // Retrieve sounds types
900 std::vector<std::string> soundsTypes = kitCreator->GetSoundsTypes(instrumentType);
901
902 // Retrieve sounds files
903 // std::vector<std::string> soundsFiles = kitCreator->GetSoundsFiles();
904
905 // Create tirggers ids and locations
906 {
907
908 std::vector<int> triggersIds = kitCreator->GetTriggersIds();
909
910 std::for_each(triggersIdsAndLocations.begin(), triggersIdsAndLocations.end(), [](TriggerIdAndLocationPtr& t) { t.reset(); });
911 triggersIdsAndLocations.clear();
912
913 for(std::size_t i = 0; i < triggersLocations.size(); i++)
914 {
915 triggersIdsAndLocations.push_back(std::make_shared<TriggerIdAndLocation>(triggersLocations, triggersIds));
916 }
917
918 std::for_each(triggersIdsAndLocations.cbegin(), triggersIdsAndLocations.cend(), [&](const TriggerIdAndLocationPtr& t){ instrumentConfig_TriggersBox->add(*t); });
919 }
920
921 // Create sounds types and paths
922 {
923
924 std::for_each(soundsTypesAndPaths.begin(), soundsTypesAndPaths.end(), [](SoundTypeAndPathPtr& t) { t.reset(); });
925 soundsTypesAndPaths.clear();
926
927 Gtk::FileChooserDialog* soundChooser = nullptr;
928 this->builder->get_widget("SoundChooser", soundChooser);
929
930 for(std::size_t i = 0; i < soundsTypes.size(); i++)
931 {
932 soundsTypesAndPaths.push_back(std::make_shared<SoundTypeAndPath>(soundsTypes, drumKit->GetDataLocation(), soundChooser));
933 }
934
935 // Add sounds types to window
936 std::for_each(soundsTypesAndPaths.cbegin(), soundsTypesAndPaths.cend(), [&](const SoundTypeAndPathPtr& t){ instrumentConfig_SoundsBox->add(*t); });
937
938 }
939
940 return;
941 }
942
943 void KitController::CancelInstrumentModif()
944 {
945
946 if(this->numInstrumentsToCreate != 0)
947 {
948 kitCreator->CreateNewKit();
949 }
950
951 this->numInstrumentsToCreate = 0;
952
953 this->instrumentConfigWindow->hide();
954
955 return;
956 }
957
958 void KitController::ValidateInstrumentData()
959 {
960
961 Gtk::Entry* instrumentConfig_Name = nullptr;
962 Gtk::ComboBoxText* instrumentConfig_Type = nullptr;
963
964 builder->get_widget("InstrumentConfig_Name", instrumentConfig_Name);
965 builder->get_widget("InstrumentConfig_Type", instrumentConfig_Type);
966
967 // Get instrument name
968 std::string instrumentName = instrumentConfig_Name->get_text(); // TODO: find out if these things can return nullptr
969 // Get instrument type
970 std::string instrumentType = instrumentConfig_Type->get_entry_text();
971
972 // Check if we are modifying or adding an instrument
973 bool isModif = (numInstrumentsToCreate == 0);
974
975 if(isModif)
976 {
977
978 // Get instrument id
979 int id = instrumentToModify;
980
981 // Modify instrument
982 {
983 // Retrieve triggers ids and locations
984 std::vector<std::pair<int, std::string>> trigIdsAndLocs;
985 for(const auto& t : triggersIdsAndLocations)
986 {
987 trigIdsAndLocs.push_back({t->GetTriggerId(), t->GetTriggerLoc()});
988 }
989
990 // Retrieve sounds types and locations
991 std::vector<std::pair<std::string, std::string>> sndTypesAndLocs;
992 std::vector<uint8_t> soundsNotes;
993 for(const auto& s : soundsTypesAndPaths)
994 {
995 sndTypesAndLocs.push_back({s->GetSoundType(), s->GetSound()});
996 soundsNotes.push_back(s->GetMidiNote());
997 }
998
999 // Change instrument name
1000 kitCreator->SetInstrumentName(id, instrumentName.c_str());
1001
1002 // Change instrument type
1003 kitCreator->SetInstrumentType(id, instrumentType.c_str());
1004
1005 // Modify triggers ids and locations
1006 kitCreator->SetInstrumentTriggersIdsAndLocs(id, trigIdsAndLocs);
1007
1008 // Modify sounds
1009 kitCreator->SetInstrumentSoundsTypesAndLocs(id, sndTypesAndLocs);
1010 kitCreator->SetInstrumentSoundsNotes(id, soundsNotes);
1011
1012
1013 // Change instrument name on the kit config window
1014 instrumentsSelectors[id]->SetInstrumentName(instrumentName);
1015
1016 instrumentConfigWindow->hide();
1017
1018 // Save kit
1019 //kitCreator->SaveKit();
1020
1021 }
1022
1023 // We're done, so we disable instrument modification
1024 instrumentToModify = -1;
1025 }
1026 else
1027 {
1028
1029 // Create instrument
1030 kitCreator->CreateNewInstrument();
1031 kitCreator->SetInstrumentVolume(1.0f);
1032 try
1033 {
1034 kitCreator->SetInstrumentName(instrumentName.c_str());
1035 }
1036 catch(const Exception& e)
1037 {
1038 kitCreator->RemoveLastInstrument();
1039 Errors::errorDialog(e);
1040 return;
1041 }
1042
1043 kitCreator->SetInstrumentType(instrumentType.c_str());
1044
1045 // Add instrument sounds
1046 for(const auto& sound : soundsTypesAndPaths)
1047 {
1048 std::string soundType = sound->GetSoundType();
1049 std::string soundFile = sound->GetSound();
1050
1051 const auto soundPath = fs::path{drumKit->GetDataLocation() + "SoundBank/" + soundFile};
1052 const auto extension = soundPath.extension().string();
1053
1054 if(!fs::exists(soundPath) || extension != ".wav")
1055 {
1056 kitCreator->RemoveLastInstrument();
1057 Errors::errorDialog("Invalid sound file. Only '.wav' files are allowed.", error_type_error);
1058 return;
1059 }
1060 kitCreator->AddInstrumentSound(soundFile.c_str(), soundType.c_str());
1061 }
1062
1063 // Add instrument triggers
1064 for(const auto& trigger : triggersIdsAndLocations)
1065 {
1066 int id = trigger->GetTriggerId();
1067 std::string location = trigger->GetTriggerLoc();
1068
1069 kitCreator->AddInstrumentTrigger(id, location.c_str());
1070 }
1071
1072 kitCreator->AddInstrumentToKit();
1073
1074
1075 AddInstrumentToKit();
1076 }
1077
1078 return;
1079 }
1080
1081 void KitController::ValidateKitData()
1082 {
1083
1084 Gtk::Entry* kitNameEntry = nullptr;
1085 Gtk::Entry* numInstrumentsEntry = nullptr;
1086
1087
1088 builder->get_widget("KitNameEntry", kitNameEntry);
1089 builder->get_widget("NumInstrumentsEntry", numInstrumentsEntry);
1090
1091 std::string kitName = kitNameEntry->get_text();
1092
1093 // Check kit name
1094 std::vector<std::string> kitsNames = drumKit->GetKitsNames();
1095 auto it = std::find(kitsNames.cbegin(), kitsNames.cend(), kitName);
1096 if(it != kitsNames.cend())
1097 {
1098 errorDialog("A drum kit with the same name already exists.", error_type_error);
1099 return;
1100 }
1101
1102 if(kitName.length() < 3)
1103 {
1104 errorDialog("Kit's name must be at least 3 characters long.", error_type_error);
1105 return;
1106 }
1107
1108 int numInstruments;
1109 try
1110 {
1111 numInstruments = std::stoi(numInstrumentsEntry->get_text());
1112 }
1113 catch(const std::invalid_argument&)
1114 {
1115 // Return to invalidate the entry
1116 return;
1117 }
1118
1119 this->numInstrumentsToCreate = numInstruments;
1120
1121 // Create kit
1122 kitCreator->CreateNewKit();
1123 kitCreator->SetKitName(kitName.c_str());
1124
1125 // Hide window
1126 this->newKitWindow->hide();
1127 // HideKeyboard();
1128
1129 ChangeInstrumentType();
1130 AddInstrumentToKit();
1131
1132 return;
1133 }
1134
1135 void KitController::ShowInstrumentSelectWindow()
1136 {
1137
1138
1139 Gtk::Entry* kitNameEntry = nullptr;
1140 Gtk::Box* instrumentsBox = nullptr;
1141
1142 builder->get_widget("ISKitName", kitNameEntry);
1143 builder->get_widget("ISListBox", instrumentsBox);
1144
1145 kitNameEntry->set_text(kitsList->get_active_text());
1146
1147 // Load current kit into the kit creator for modifications
1148 try
1149 {
1150 std::string kitLocation = drumKit->GetKitDataFileName();
1151 kitCreator->CreateFromModel(kitLocation.c_str());
1152 }
1153 catch(const Exception& e)
1154 {
1155 errorDialog(e);
1156 return;
1157 }
1158
1159 // Get kit's instruments
1160 std::vector<std::string> instrumentsNames = kitCreator->GetInstrumentsNames();
1161
1162 // Reset instruments selectors
1163 std::for_each(instrumentsSelectors.begin(), instrumentsSelectors.end(), [](InstrumentSelectorPtr& i) { i.reset(); });
1164 instrumentsSelectors.clear();
1165
1166 // Create new instruments selectors
1167 std::transform(instrumentsNames.cbegin(), instrumentsNames.cend(), std::back_inserter(instrumentsSelectors), [](const std::string& name)
1168 {
1169 return std::make_shared<InstrumentSelector>(name);
1170 });
1171
1172 // Add selectors to window
1173 for(const auto& i : instrumentsSelectors)
1174 {
1175 instrumentsBox->add(*i);
1176 }
1177
1178 // Connect signals
1179 for(std::size_t i = 0; i < instrumentsSelectors.size(); i++)
1180 {
1181 auto& is = instrumentsSelectors[i];
1182 is->GetPreferencesButton().signal_clicked().connect([=, this] { ModifyInstrument(i); });
1183 is->GetDeleteButton().signal_clicked().connect([=, this] { RemoveInstrument(i); });
1184 }
1185
1186 instrumentSeclectWindow->show();
1187
1188 return;
1189 }
1190
1191 void KitController::SaveKitPreferences()
1192 {
1193
1194 // Get kit name
1195 Gtk::Entry* kitName = nullptr;
1196 builder->get_widget("ISKitName", kitName);
1197 std::string name = kitName->get_text(); // TODO: make sure this won't return nullptr, or handle it
1198
1199 // Set kit name
1200 kitCreator->SetKitName(name.c_str());
1201
1202 // Save kit parameters to file
1203 kitCreator->SaveKit();
1204
1205 // Reload kits
1206 {
1207
1208 bool isStarted = drumKit->IsStarted();
1209 // Stop module
1210 if(isStarted)
1211 {
1212 try
1213 {
1214 PlayDrums();
1215 }
1216 catch(const Exception& e)
1217 {
1218 errorDialog(e);
1219 return;
1220 }
1221
1222 }
1223
1224 // Reload kits
1225 try
1226 {
1227 drumKit->ReloadKits();
1228 }
1229 catch(const Exception& e)
1230 {
1231 errorDialog(e);
1232 return;
1233 }
1234
1235 if(name != kitsList->get_active_text())
1236 {
1237 kitsList->get_active()->set_value(0, name);
1238
1239 isModifyingKit = true;
1240 kitsList->set_active(-1);
1241 isModifyingKit = false;
1242
1243 kitsList->set_active_text(name);
1244 }
1245
1246 // Set active kit
1247 ChangeKit();
1248
1249 if(isStarted)
1250 {
1251 try
1252 {
1253 PlayDrums();
1254 }
1255 catch(const Exception& e)
1256 {
1257 errorDialog(e);
1258 return;
1259 }
1260 }
1261
1262 }
1263
1264 return;
1265 }
1266
1267 void KitController::ChangeInstrumentSound()
1268 {
1269
1270 // Retrieve soundChooser
1271 Gtk::FileChooserDialog* soundChooser = nullptr;
1272 this->builder->get_widget("SoundChooser", soundChooser);
1273
1274 // Get new sound's path
1275 std::string folder = soundChooser->get_filename();
1276
1277 // Find which sound's been modified
1278 auto itSound = std::find_if(soundsTypesAndPaths.begin(), soundsTypesAndPaths.end(), [](auto& s) { return s->GetChangingSound(); });
1279
1280 if(itSound == soundsTypesAndPaths.cend())
1281 {
1282 return;
1283 }
1284
1285 // Get path relative to the sound bank's folder
1286 std::string soundLoc;
1287 {
1288
1289 std::string parentFolder("SoundBank");
1290 auto pos = folder.find(parentFolder);
1291
1292 // If the path is invalid
1293 if(pos == std::string::npos)
1294 {
1295 // Close sound chooser
1296 soundChooser->hide();
1297 return;
1298 }
1299
1300 soundLoc = folder.substr(pos + parentFolder.size() + 1);
1301
1302 }
1303
1304 // Set new sound
1305 itSound->get()->SetSound(soundLoc);
1306 itSound->get()->SetSoundChanged();
1307
1308 // Close sound chooser
1309 soundChooser->hide();
1310
1311 return;
1312
1313 }
1314
1315 void KitController::ShowKeyboard()
1316 {
1317 HideKeyboard();
1318 //std::system("onboard --size=800x160 -x 0 -y 280 &");
1319 return;
1320 }
1321
1322 void KitController::HideKeyboard()
1323 {
1324
1325 //std::system("killall onboard");
1326 return;
1327 }
1328
1329
1330
1331 } /* namespace Gui */