-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmusiclibrary.cpp
More file actions
389 lines (352 loc) · 16.1 KB
/
musiclibrary.cpp
File metadata and controls
389 lines (352 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Copyright 2023 by Linwood Ferguson, licensed under GNU GPLv3
#include <QPainter>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QHeaderView>
#include <QScroller>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>
#include <QEvent>
#include <QTableWidgetItem>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QComboBox>
#include <QListView>
#include "musiclibrary.h"
#include "mainwindow.h"
#include "oursettings.h"
#include "piconstants.h"
#include <cassert>
musicLibrary::musicLibrary(QWidget *parent, MainWindow* mp) : QWidget(parent)
{
// Isolate specific librarydetails in this class so we could switch to different
// calling process, also isolate formatting and population of the widget here.
// This widget (i.e. "this") is persistent and created once. Some items are persisted
// and available publically (e.g. the dropdown, which implicitly holds all playlists).
// The playLists class uses these, isolating the actual database part to this routine
// to hopefully make it easier if a different library database is used.
ourParent = parent;
mParent = mp;
calibreMusicTag = mParent->ourSettingsPtr->getSetting("calibreMusicTag").toString();
calibrePath = mParent->ourSettingsPtr->getSetting("calibrePath").toString();
calibreDatabase = mParent->ourSettingsPtr->getSetting("calibreDatabase").toString();
calibreListPrefix = mParent->ourSettingsPtr->getSetting("calibreListPrefix").toString();
forceOnboardKeyboard = mParent->ourSettingsPtr->getSetting("forceOnboardKeyboard").toBool();
ActiveListIndex = 0; // Default for start -- choices are persisted against subsequent hide/show iterations.
m_db = NULL; // Be sure we know if it's been created. We open/close it a lot, but do not delete it until this routine is deleted
qDebug() << "in constructor with path " << calibrePath << " and file " << calibreDatabase;
// Create widgets and layouts
baseLayout = new QVBoxLayout(this);
search = new QWidget(this);
searchLayout = new QHBoxLayout(search);
prompt = new QLabel(search);
searchBox = new QLineEdit(search);
dropdown= new QComboBox(search);
listDropdown = new QListView(dropdown);
dropdown->setView(listDropdown);
libTable = new QTableWidget(this);
// Arrange the widgets
this->setLayout(baseLayout);
baseLayout->addWidget(search);
baseLayout->addWidget(libTable);
search->setLayout(searchLayout);
searchLayout->addWidget(prompt);
searchLayout->addWidget(searchBox);
searchLayout->addWidget(dropdown);
prompt->setFont(QFont("Arial",16,1));
prompt->setText("Search for:");
searchBox->setMinimumWidth(300); // Looks dumb if too short, but also if too long
searchBox->setMaximumWidth(300);
searchBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
searchBox->setAlignment(Qt::AlignLeft);
searchLayout->setAlignment(Qt::AlignLeft);
libTable->setSelectionBehavior(QAbstractItemView::SelectRows);
libTable->setSelectionMode(QAbstractItemView::SingleSelection);
libTable->verticalHeader()->hide();
libTable->setAlternatingRowColors(true);
libTable->setSortingEnabled(true);
libTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // this makes the table read-only so you don't accidentally end up editing inside a cell.
QScroller::grabGesture(libTable,QScroller::LeftMouseButtonGesture); // so a touch-drag will work, otherwise need two finger drag
libTable->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
libTable->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
libTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(libTable, SIGNAL(cellClicked(int,int)), this, SLOT(onChosen(int,int)));
connect(searchBox, SIGNAL(textChanged(QString)), this, SLOT(filterTable(QString)));
m_db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"));
m_db->setDatabaseName(calibrePath + "/" + calibreDatabase);
screenLoaded=false;
lastTimeSelected = QTime::currentTime();
}
musicLibrary::~musicLibrary()
{
qDebug() << "in destructor";
DELETE_LOG(m_db);
}
void musicLibrary::loadPlayLists()
{
// Get a list of playlists and set it to active if we already had chosen it
// Must have database open to call
// These need to stay loaded as they are used in a separate widget (and indeed may be forced into a reload by it)
qDebug() << "Entered";
dropdown->clear();
QSqlQuery queryLists;
QString sql = "select id, name from tags where name like '" + calibreListPrefix + "%' order by name;";
queryLists.exec(sql);
checkSqlError("Executed tag query " + sql, queryLists.lastError());
dropdown->addItem("All items",0);
while(queryLists.next())
{
qDebug()<<"read tags, id=" << queryLists.record().field(0).value().toInt() << ", value=" << queryLists.record().field(1).value().toString();
dropdown->addItem(queryLists.record().field(1).value().toString().replace(calibreListPrefix,""),queryLists.record().field(0).value().toInt());
}
ActiveListIndex = dropdown->findText(ActiveList); // We have to look it up in case they list changed so index may change
if(ActiveListIndex == -1) ActiveListIndex = 0; // If the current active disappeareed reset to all
dropdown->setCurrentIndex(ActiveListIndex);
}
void musicLibrary::loadBooks()
{
// Must have database open to call
qDebug() << "Entered";
lastRowSelected=-1; // None selected (yet)
libTable->setRowCount(0);
searchBox->setText(""); // Start fresh search each time
QSqlQuery queryBooks;
QString sql =
"select b.id as BookID, b.sort as Title, coalesce(max(s.name),'') as Collection, b.author_sort as Author, b.path || '/' || d.name || '.' || lower(d.format) as Path, group_concat(t2.name,',') as tags "
"from books b "
"inner join books_tags_link btl on btl.book = b.id "
"inner join tags t on t.id = btl.tag "
"inner join data d on d.book = b.id and d.format = 'PDF' " +
(
ActiveListIndex == 0 ? "" :
( "inner join books_tags_link btl3 on btl3.book = b.id "
"inner join tags t3 on t3.id = btl3.tag and t3.name = '" + calibreListPrefix + ActiveList + "' "
)
) +
"left join books_series_link bsl on bsl.book = b.id "
"left join series s on s.id=bsl.series "
"left join books_tags_link btl2 on btl2.book=b.id "
"left join tags t2 on t2.id=btl2.tag and t2.name not like 'musicList%' and t2.name <> 'music' "
"where t.name = '" + calibreMusicTag + "' "
"group by b.id, b.sort, b.author_sort, b.path, d.name "
"order by b.sort;";
queryBooks.exec(sql);
checkSqlError("Executed book query " + sql, queryBooks.lastError());
QSqlRecord rec = queryBooks.record();
libTable->setFont(QFont("Arial",10,0,false));
libTable->setColumnCount(rec.count());
// First run through the columns and code appropriately in the table, hiding some fields, remembering position
for(int field = 0; field < rec.count(); field++)
{
libTable->setHorizontalHeaderItem(field, new QTableWidgetItem(rec.fieldName(field)));
if(rec.fieldName(field)=="BookID")
{
libTable->setColumnHidden(field,true);
columnForID=field;
}
if(rec.fieldName(field)=="Path") // Remember where we put this
{
libTable->setColumnHidden(field,true);
columnForPath=field;
}
if(rec.fieldName(field)=="Title")
{
columnForTitle=field; // And remember this one
}
}
int row=0;
while(queryBooks.next())
{
libTable->setRowCount(row+1);
for(int field=0; field < rec.count(); field++)
{
libTable->setItem(row,field,new QTableWidgetItem(queryBooks.record().field(field).value().toString()));
if(rec.fieldName(field)=="Title") libTable->item(row,field)->setFont(QFont("Arial",14,1,false)); // Do something to make this proportional to some constant???
}
row++;
}
libTable->resizeColumnsToContents();
qDebug() << "Completed by book retrieval and build of table";
}
void musicLibrary::showEvent(QShowEvent *e)
{
qDebug() << "Entered";
(void)e;
if(!screenLoaded) // don't redo unless we need to
{
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
loadPlayLists();
loadBooks();
m_db->close();
}
connect(dropdown,SIGNAL(currentIndexChanged(int)),this,SLOT(changeList(int)));
searchBox->installEventFilter(this); // So we can catch keystrokes and do as-you-type filter
screenLoaded=true;
}
void musicLibrary::hideEvent(QHideEvent *e)
{
// Note we have just hidden it, the contents stays the same.
qDebug() << "Entered";
(void)e;
disconnect(dropdown,SIGNAL(currentIndexChanged(int)),this,SLOT(changeList(int))); // Need this so we don't signal when we reload it or use it from other routines
searchBox->removeEventFilter(this); // So we can catch keystrokes and do as-you-type filter
}
void musicLibrary::changeList(int newListIndex)
{
qDebug() << "Entered";
ActiveListIndex = newListIndex;
ActiveList = dropdown->itemText(ActiveListIndex);
qDebug() << "Entered with " << newListIndex << " which is " << ActiveList;
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
loadBooks();
m_db->close();
}
void musicLibrary::checkSqlError(QString stage, QSqlError err) // Aborts on error
{
if(err.databaseText()!="" || err.driverText()!="")
{
qDebug() << stage << " resulted in error " << err;
assert(err.databaseText()=="" || err.driverText()=="");
}
}
void musicLibrary::onChosen(int row, int column)
{
QTime nowTime = QTime::currentTime();
qDebug() << "Entered";
if( (lastRowSelected == row) && (lastTimeSelected.secsTo(nowTime) <= 2 ) )
{
qDebug() << "doubleclicked on row " << row << " which looks like a duplicate within 2 seconds so ignoring.";
return;
}
lastTimeSelected = nowTime;
// Move these to local items since the following are going to disappear
pathSelected = calibrePath + "/" + libTable->item(row,columnForPath)->text();
titleSelected = libTable->item(row,columnForTitle)->text();
qDebug() << "doubleclicked on row " << row << " column " << column << ", value=" << pathSelected;
lastRowSelected = row;
bookIDSelected = libTable->item(row,columnForID)->text().toInt();
emit songSelected(pathSelected, titleSelected);
}
void musicLibrary::filterTable(QString filter)
{
bool match;
qDebug() << tr("Filtering for string '%1'").arg(filter);
libTable->setUpdatesEnabled(false);
for(int row = 0; row < libTable->rowCount(); row++)
{
if(filter=="") match=true; // With no filter show everything (but go through loop in case it was previously hidden)
else
{ // see if any not-hidden field matches and show
match = false;
for(int col = 0; col < libTable->columnCount(); col++)
if (columnForPath != col && columnForID != col && libTable->item(row,col)->text().contains(filter,Qt::CaseInsensitive))
{
match = true;
break;
}
}
if(match) libTable->showRow(row);
else libTable->hideRow(row);
}
libTable->setUpdatesEnabled(true);
}
void musicLibrary::showKeyboard()
{
if(!forceOnboardKeyboard) return;
qDebug() << "Firing show keyboard";
QDBusMessage show = QDBusMessage::createMethodCall("org.onboard.Onboard","/org/onboard/Onboard/Keyboard","org.onboard.Onboard.Keyboard","Show");
QDBusConnection::sessionBus().send(show);
}
void musicLibrary::hideKeyboard()
{
if(!forceOnboardKeyboard) return;
qDebug() << "Firing hide keyboard";
QDBusMessage show = QDBusMessage::createMethodCall("org.onboard.Onboard","/org/onboard/Onboard/Keyboard","org.onboard.Onboard.Keyboard","Hide");
QDBusConnection::sessionBus().send(show);
}
bool musicLibrary::eventFilter(QObject *object, QEvent *event)
{
// This is a kludge because Onboard does not work in auto-hide mode with QT, it flashes in and out
// This forces it in when the seaerch is active, and forces it out when not.
if(event->type() == QEvent::FocusIn && object == searchBox) showKeyboard();
else if(event->type() == QEvent::FocusOut && object == searchBox) hideKeyboard();
return false;
}
void musicLibrary::paintEvent(QPaintEvent *) // Allows style sheets to apply in some way
{
QStyleOption opt;
opt.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
bool musicLibrary::bookInList(int tag)
{
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
QSqlQuery queryList;
QString sql =
"select count(*) as Presence "
"from books_tags_link btl "
"where btl.book = " + QString::number(bookIDSelected) + " and btl.tag = " + QString::number(tag) + ";";
queryList.exec(sql);
checkSqlError("Executed book/tag query " + sql, queryList.lastError());
assert(queryList.next());
bool ret = queryList.record().field(0).value().toBool();
m_db->close();
qDebug() << "Checked tag id " << tag << " for book " << bookIDSelected << " and returning " << ret;
return ret;
}
QString musicLibrary::addBookToList(int index)
{
// This aborts if we can't open the database but returns other errors back to the caller (or blank for none)
qDebug() << "Request to add book " << bookIDSelected << " to tag id " << dropdown->itemData(index).toInt() << " which is " << dropdown->itemText(index);
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
QSqlQuery insert;
QString sql = "insert into books_tags_link(tag, book) values (" + QString::number(dropdown->itemData(index).toInt()) + "," + QString::number(bookIDSelected) + ");";
insert.exec(sql);
QString result = insert.lastError().databaseText() + " / " + insert.lastError().driverText();
m_db->close();
return (result == " / " ? "" : result);
}
QString musicLibrary::removeBookFromList(int index)
{
// This aborts if we can't open the database but returns other errors back to the caller (or blank for none)
qDebug() << "Request to remove book " << bookIDSelected << " to tag id " << dropdown->itemData(index).toInt() << " which is " << dropdown->itemText(index);
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
QSqlQuery del;
QString sql = "delete from books_tags_link where tag = " + QString::number(dropdown->itemData(index).toInt()) + " and book = " + QString::number(bookIDSelected) + ";";
del.exec(sql);
QString result = del.lastError().databaseText() + " / " + del.lastError().driverText();
m_db->close();
changeList(ActiveListIndex);
return (result == " / " ? "" : result);
}
QString musicLibrary::addNewList(QString name)
{
// This aborts if we can't open the database but returns other errors back to the caller (or blank for none)
qDebug() << "Request to insert new playList " << name;
m_db->open();
checkSqlError("Opening SQL database " + m_db->databaseName(), m_db->lastError());
QSqlQuery insert;
QString sql = "insert into tags (name) values('" + name + "')";
insert.exec(sql);
QString result = insert.lastError().databaseText() + " / " + insert.lastError().driverText();
if(result == " / ") // If no error then also add the current book to it
{
qint32 rowid = insert.lastInsertId().toInt();
sql = "insert into books_tags_link(tag, book) values (" + QString::number(rowid) + "," + QString::number(bookIDSelected) + ");";
insert.exec(sql);
result = insert.lastError().databaseText() + " / " + insert.lastError().driverText();
loadPlayLists(); // Need to reload since we added one -- this does not change active list though
}
m_db->close();
return (result == " / " ? "" : result);
}