Session.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. This file is part of QTau
  3. Copyright (C) 2013-2018 Tobias "Tomoko" Platen <tplaten@posteo.de>
  4. Copyright (C) 2013 digited <https://github.com/digited>
  5. Copyright (C) 2010-2013 HAL@ShurabaP <https://github.com/haruneko>
  6. QTau is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. SPDX-License-Identifier: GPL-3.0+
  17. */
  18. #include "Session.h"
  19. #include "Utils.h"
  20. #include <QFile>
  21. #include <QFileInfo>
  22. #include <QTextStream>
  23. #include <QStringList>
  24. #include <QtAlgorithms>
  25. #include <ustjkeys.h>
  26. #include <QJsonDocument>
  27. #include <math.h>
  28. #include "ustfile.h"
  29. #include <iostream>
  30. #include "sinsyscoreconverter.h"
  31. #include "midifile.h"
  32. #define __devloglevel__ 4
  33. qtauSession::qtauSession(QObject *parent) :
  34. qtauEventManager(parent), _docName(QStringLiteral("Untitled")), _isModified(false), _hadSavePoint(false)
  35. {
  36. _defaults[USER_AGENT] = QString("QTau Debug");
  37. _defaults[TEMPO]=120;
  38. QJsonArray ts;
  39. ts.append(4);
  40. ts.append(4);
  41. _defaults[TIME_SIGNATURE]=ts;
  42. _objectMap[-1] = _defaults;
  43. }
  44. qtauSession::~qtauSession()
  45. {
  46. }
  47. qtauEvent_NoteAddition *util_makeAddNotesEvent(QJsonArray &a)
  48. {
  49. qtauEvent_NoteAddition::noteAddVector changeset;
  50. for (int i = 0; i < a.count(); ++i)
  51. {
  52. auto o = a[i];
  53. qtauEvent_NoteAddition::noteAddData d;
  54. d.id = i+1;
  55. d.lyrics = o.toObject()[NOTE_LYRIC].toString();
  56. d.pulseLength = o.toObject()[NOTE_PULSE_LENGTH].toInt();
  57. d.pulseOffset = o.toObject()[NOTE_PULSE_OFFSET].toInt();
  58. d.keyNumber = o.toObject()[NOTE_KEY_NUMBER].toInt();
  59. //d.velocity = 100;//FIXME
  60. if(d.pulseLength==0 && d.pulseOffset==0)
  61. {
  62. //qDebug() << "dummy";
  63. continue;
  64. }
  65. QStringList keys;
  66. keys << XML_ACCENT;
  67. keys << XML_STACATTO;
  68. keys << XML_TIETYPE;
  69. keys << XML_SLURTYPE;
  70. keys << XML_SYLLABICTYPE;
  71. keys << XML_BREATH;
  72. foreach(QString key, keys)
  73. {
  74. if(o.toObject().contains(key))
  75. d.optionalElements[key] = o.toObject()[key];
  76. }
  77. //accent: ?
  78. //stacatto: use different adrs, time alignment
  79. //tietype: connect notes
  80. //slurtype: portamento handle, gsl for interpolation
  81. //syllabic, breath: not implemented yet
  82. changeset.append(d);
  83. }
  84. return new qtauEvent_NoteAddition(changeset);
  85. }
  86. bool qtauSession::loadUST(QJsonArray array)
  87. {
  88. if (!array.isEmpty())
  89. {
  90. clearHistory();
  91. auto o = array[0];
  92. if(o.toObject().contains(USER_AGENT))
  93. _objectMap[-1] = o.toObject();
  94. else
  95. _objectMap[-1] = _defaults;
  96. qtauEvent_NoteAddition *loadNotesChangeset = util_makeAddNotesEvent(array);
  97. applyEvent_NoteAdded(*loadNotesChangeset);
  98. emit onEvent(loadNotesChangeset);
  99. delete loadNotesChangeset;
  100. return true;
  101. }
  102. return false;
  103. }
  104. bool qtauSession::loadUST(QString fileName)
  105. {
  106. bool result = false;
  107. QFile ustFile(fileName);
  108. if (ustFile.open(QFile::ReadOnly))
  109. {
  110. QJsonDocument doc = QJsonDocument::fromJson(ustFile.readAll());
  111. if(doc.isArray())
  112. {
  113. // qDebug() << "lock";
  114. _docName = QFileInfo(fileName).baseName();
  115. _filePath = fileName;
  116. emit dataReloaded();
  117. result = loadUST(doc.array());
  118. if(result==false) DEVLOG_ERROR("ust failed to load");
  119. }
  120. else
  121. DEVLOG_ERROR("json document is not an array");
  122. ustFile.close();
  123. }
  124. else
  125. DEVLOG_ERROR("Could not open " + fileName);
  126. return result;
  127. }
  128. inline void qSwap(QJsonValueRef var1, QJsonValueRef var2)
  129. {
  130. QJsonValue tmp = var2;
  131. var2 = var1;
  132. var1 = tmp;
  133. }
  134. inline bool noteNumComparison(const QJsonValueRef o1, const QJsonValueRef& o2)
  135. {
  136. return o1.toObject()[NOTE_KEY_NUMBER].toInt() < o2.toObject()[NOTE_KEY_NUMBER].toInt();
  137. }
  138. inline bool pulseOffsetComparison(const QJsonValueRef o1, const QJsonValueRef& o2)
  139. {
  140. return o1.toObject()[NOTE_PULSE_OFFSET].toInt() < o2.toObject()[NOTE_PULSE_OFFSET].toInt();
  141. }
  142. void qtauSession::importUST(QString fileName)
  143. {
  144. USTFile ust;
  145. ust.readFromFile(fileName);
  146. loadUST(ust.json());
  147. }
  148. void qtauSession::ustJson(QJsonArray& ret)
  149. {
  150. foreach (const quint64 &key, _objectMap.keys())
  151. ret.append(_objectMap[key]);
  152. qStableSort(ret.begin(), ret.end(), noteNumComparison);
  153. qStableSort(ret.begin(), ret.end(), pulseOffsetComparison);
  154. }
  155. void qtauSession::setDocName(const QString &name)
  156. {
  157. if (name.isEmpty())
  158. {
  159. DEVLOG_ERROR("Shouldn't set empty doc name for session! Ignoring...")
  160. }
  161. else
  162. _docName = name;
  163. }
  164. void qtauSession::setFilePath(const QString &fp)
  165. {
  166. if (fp.isEmpty())
  167. {
  168. DEVLOG_ERROR("Shouldn't set empty filepath for session! Ignoring...")
  169. }
  170. else
  171. {
  172. _filePath = fp;
  173. _docName = QFileInfo(fp).baseName();
  174. }
  175. }
  176. //----- inner data functions -----------------------------
  177. void qtauSession::applyEvent_NoteAdded(const qtauEvent_NoteAddition &event)
  178. {
  179. const qtauEvent_NoteAddition::noteAddVector &changeset = event.getAdded();
  180. // delete event has reversed transformations
  181. bool reallyForward = (event.isForward() && !event.isDeleteEvent()) ||
  182. (!event.isForward() && event.isDeleteEvent());
  183. if (reallyForward)
  184. {
  185. foreach (const qtauEvent_NoteAddition::noteAddData &change, changeset)
  186. {
  187. //noteMap[change.id] = ust_note(change.id, change.lyrics, change.pulseOffset, change.pulseLength, change.keyNumber);
  188. QJsonObject object;
  189. object[NOTE_LYRIC] = change.lyrics;
  190. object[NOTE_PULSE_OFFSET] = change.pulseOffset;
  191. object[NOTE_PULSE_LENGTH] = change.pulseLength;
  192. object[NOTE_KEY_NUMBER] = change.keyNumber;
  193. foreach(QString key, change.optionalElements.keys())
  194. {
  195. object[key] = change.optionalElements[key];
  196. }
  197. _objectMap[change.id] = object;
  198. }
  199. }
  200. else
  201. foreach (const qtauEvent_NoteAddition::noteAddData &change, changeset)
  202. _objectMap.remove(change.id);
  203. }
  204. void qtauSession::applyEvent_NoteResized(const qtauEvent_NoteResize &event)
  205. {
  206. const qtauEvent_NoteResize::noteResizeVector &changeset = event.getResized();
  207. foreach (const qtauEvent_NoteResize::noteResizeData &change, changeset)
  208. {
  209. auto &n = _objectMap[change.id];
  210. if (event.isForward())
  211. {
  212. n[NOTE_PULSE_OFFSET] = change.offset;
  213. n[NOTE_PULSE_LENGTH] = change.length;
  214. }
  215. else
  216. {
  217. n[NOTE_PULSE_OFFSET] = change.prevOffset;
  218. n[NOTE_PULSE_LENGTH] = change.prevLength;
  219. }
  220. }
  221. }
  222. void qtauSession::applyEvent_NoteMoved(const qtauEvent_NoteMove &event)
  223. {
  224. const qtauEvent_NoteMove::noteMoveVector &changeset = event.getMoved();
  225. foreach (const qtauEvent_NoteMove::noteMoveData &change, changeset)
  226. {
  227. auto &n = _objectMap[change.id];
  228. if (event.isForward())
  229. {
  230. n[NOTE_PULSE_OFFSET] = n[NOTE_PULSE_OFFSET].toInt() + change.pulseOffDelta;
  231. n[NOTE_KEY_NUMBER] = change.keyNumber;
  232. }
  233. else
  234. {
  235. n[NOTE_PULSE_OFFSET] = n[NOTE_PULSE_OFFSET].toInt() - change.pulseOffDelta;
  236. n[NOTE_KEY_NUMBER] = change.prevKeyNumber;
  237. }
  238. }
  239. }
  240. void qtauSession::applyEvent_NoteLyrics(const qtauEvent_NoteText &event)
  241. {
  242. const qtauEvent_NoteText::noteTextVector &changeset = event.getText();
  243. foreach (const qtauEvent_NoteText::noteTextData &change, changeset)
  244. if (event.isForward()) _objectMap[change.id][NOTE_LYRIC] = change.txt;
  245. else _objectMap[change.id][NOTE_LYRIC] = change.prevTxt;
  246. }
  247. void qtauSession::applyEvent_NoteEffects(const qtauEvent_NoteEffect &/*event*/)
  248. {
  249. //FIXME: to do or not to do, that is the question
  250. //implement other undoable UTAU things
  251. }
  252. //--------- dispatcher -----------------------------
  253. void qtauSession::onUIEvent(qtauEvent *e)
  254. {
  255. if (e)
  256. {
  257. if (processEvent(e))
  258. storeEvent(e);
  259. delete e; // if it's valid it was copied on storing, and UI should only create events anyway.
  260. }
  261. }
  262. // process event is called from both program (ui input) and undo/redo in manager (stack change)
  263. bool qtauSession::processEvent(qtauEvent *e)
  264. {
  265. bool result = false;
  266. if (e)
  267. {
  268. switch (e->type())
  269. {
  270. case ENoteEvents::add:
  271. {
  272. qtauEvent_NoteAddition *ne = static_cast<qtauEvent_NoteAddition*>(e);
  273. if (ne)
  274. {
  275. applyEvent_NoteAdded(*ne);
  276. result = true;
  277. }
  278. else
  279. DEVLOG_ERROR("Session could not convert UI event to noteAdd");
  280. break;
  281. }
  282. case ENoteEvents::move:
  283. {
  284. qtauEvent_NoteMove *ne = static_cast<qtauEvent_NoteMove*>(e);
  285. if (ne)
  286. {
  287. applyEvent_NoteMoved(*ne);
  288. result = true;
  289. }
  290. else
  291. DEVLOG_ERROR("Session could not convert UI event to noteMove");
  292. break;
  293. }
  294. case ENoteEvents::resize:
  295. {
  296. qtauEvent_NoteResize *ne = static_cast<qtauEvent_NoteResize*>(e);
  297. if (ne)
  298. {
  299. applyEvent_NoteResized(*ne);
  300. result = true;
  301. }
  302. else
  303. DEVLOG_ERROR("Session could not convert UI event to noteResize");
  304. break;
  305. }
  306. case ENoteEvents::text:
  307. {
  308. qtauEvent_NoteText *ne = static_cast<qtauEvent_NoteText*>(e);
  309. if (ne)
  310. {
  311. applyEvent_NoteLyrics(*ne);
  312. result = true;
  313. }
  314. else
  315. {
  316. DEVLOG_ERROR("Session could not convert UI event to noteText");
  317. }
  318. break;
  319. }
  320. case ENoteEvents::effect:
  321. {
  322. qtauEvent_NoteEffect *ne = static_cast<qtauEvent_NoteEffect*>(e);
  323. if (ne)
  324. {
  325. applyEvent_NoteEffects(*ne);
  326. result = true;
  327. }
  328. else
  329. DEVLOG_ERROR("Session could not convert UI event to noteEffect");
  330. break;
  331. }
  332. default:
  333. DEVLOG_ERROR(QString("Session received unknown event type from UI").arg(e->type()));
  334. }
  335. }
  336. else DEVLOG_ERROR("Session can't process a zero event! Ignoring...");
  337. return result;
  338. }
  339. void qtauSession::stackChanged()
  340. {
  341. if (canUndo())
  342. _isModified = !events.top()->isSavePoint();
  343. else
  344. _isModified = _hadSavePoint;
  345. emit undoStatus(canUndo());
  346. emit redoStatus(canRedo());
  347. emit modifiedStatus(_isModified);
  348. }
  349. //Ardour is used to manage SynthesizedVocal and BackgroundAudio
  350. void qtauSession::setModified(bool m)
  351. {
  352. if (m != _isModified)
  353. {
  354. _isModified = m;
  355. emit modifiedStatus(_isModified);
  356. }
  357. }
  358. void qtauSession::setSaved()
  359. {
  360. if (canUndo())
  361. {
  362. foreach (qtauEvent *e, events)
  363. e->setSavePoint(false);
  364. if (!futureEvents.isEmpty())
  365. foreach (qtauEvent *e, futureEvents)
  366. e->setSavePoint(false);
  367. _hadSavePoint = true;
  368. events.top()->setSavePoint();
  369. setModified(false);
  370. }
  371. else
  372. DEVLOG_ERROR("Saving an empty session?");
  373. }
  374. void qtauSession::importMIDI(QString fileName)
  375. {
  376. QJsonArray ust;
  377. MidiFile f;
  378. f.loadMidi(fileName,ust);
  379. loadUST(ust);
  380. }
  381. void qtauSession::exportMIDI(QString fileName)
  382. {
  383. QJsonArray ust;
  384. ustJson(ust);
  385. MidiFile f;
  386. f.saveMidi(ust,fileName);
  387. }
  388. void qtauSession::importMusicXML(QString fileName)
  389. {
  390. sinsy::Sinsy sinsy;
  391. std::string xml = fileName.toStdString();
  392. if (!sinsy.loadScoreFromMusicXML(xml)) {
  393. std::cout << "[ERROR] failed to load score from MusicXML file : " << xml << std::endl;
  394. return ;
  395. }
  396. DEVLOG_DEBUG("valid musicxml");
  397. SinsyScoreConverter score;
  398. sinsy.toScore(score);
  399. loadUST(score.toUST());
  400. }
  401. //FIXME: connect directly to controller
  402. void qtauSession::onNewSession()
  403. {
  404. QJsonArray empty;
  405. clearHistory();
  406. _objectMap.clear();
  407. _objectMap[-1] = _defaults;
  408. _docName = "Untitled";
  409. _filePath = "";
  410. qtauEvent_NoteAddition *loadNotesChangeset = util_makeAddNotesEvent(empty);
  411. applyEvent_NoteAdded(*loadNotesChangeset);
  412. emit dataReloaded();// UPDATE text
  413. emit onEvent(loadNotesChangeset); //LOAD SCORE INTO EDITOR
  414. delete loadNotesChangeset;
  415. }
  416. // set/get proptery
  417. void qtauSession::setSingerName(QString singerName)
  418. {
  419. //qDebug() << "setSingerName";
  420. QJsonObject obj;
  421. if(_objectMap.contains(-1)) obj=_objectMap[-1];
  422. obj[SINGER_NAME] = singerName;
  423. _objectMap[-1] = obj;
  424. _isModified = true;
  425. emit modifiedStatus(_isModified);
  426. }
  427. QString qtauSession::getSingerName()
  428. {
  429. QJsonObject obj;
  430. if(_objectMap.contains(-1)) obj=_objectMap[-1];
  431. return obj[SINGER_NAME].toString();
  432. }
  433. void qtauSession::setTempoMap(QJsonArray tmap)
  434. {
  435. QJsonObject obj;
  436. if(_objectMap.contains(-1)) obj=_objectMap[-1];
  437. obj[TEMPOMAP] = tmap;
  438. _objectMap[-1] = obj;
  439. _isModified = true;
  440. emit modifiedStatus(_isModified);
  441. }
  442. QJsonArray qtauSession::getTempoMap()
  443. {
  444. QJsonObject obj;
  445. if(_objectMap.contains(-1)) obj=_objectMap[-1];
  446. return obj[TEMPOMAP].toArray();
  447. }
  448. quint64 qtauSession::getNote(QJsonObject note)
  449. {
  450. foreach(quint64 key, _objectMap.keys())
  451. {
  452. if(_objectMap[key]==note) return key;
  453. }
  454. return -1;
  455. }
  456. QString qtauSession::undoAction()
  457. {
  458. switch(events.top()->type())
  459. {
  460. case ENoteEvents::add:
  461. return "add note";
  462. case ENoteEvents::move:
  463. return "move note";
  464. case ENoteEvents::resize:
  465. return "resize note";
  466. case ENoteEvents::text:
  467. return "text change";
  468. }
  469. return "";
  470. }
  471. QString qtauSession::redoAction()
  472. {
  473. switch(futureEvents.top()->type())
  474. {
  475. case ENoteEvents::add:
  476. return "add note";
  477. case ENoteEvents::move:
  478. return "move note";
  479. case ENoteEvents::resize:
  480. return "resize note";
  481. case ENoteEvents::text:
  482. return "text change";
  483. }
  484. return "";
  485. }