-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomiclist.cpp
823 lines (686 loc) · 26 KB
/
comiclist.cpp
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/*SDOC:**********************************************************************
File: comiclist.cpp
Action: Implementation of the ComicList object.
Copyright © 2009, Ian Prest
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************:EDOC*/
#include "stdafx.h"
#include "comiclist.h"
/////////////////////////////////////////////////////////////////////////////
// ComicDataModel class
/////////////////////////////////////////////////////////////////////////////
class ComicDataModel : public QSqlQueryModel
{
public:
enum ColumnIds { colIssueId, colOrderBy, colNumber, colId, colOwned, colDate, colCondition, colPrice, colStore, colUserId, colNotes, colSalePrice };
enum ItemStatus { statusNone, statusOwned, statusWanted, statusOrdered, statusSold, statusForSale, statusUntracked };
static QString columnNameDb[];
static QString columnNameUi[];
ComicDataModel(int seriesId, bool showOwned, bool showWanted, bool showSold, bool showUntracked, QObject *parent = 0);
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
ItemStatus rowStatus( const QModelIndex &index ) const;
bool setDataInternal(const QModelIndex &index, const QVariant &value, int role);
void refreshView(const QItemSelectionRange range);
private:
QVariant eval(const QString& str) const;
QVariant evalExpression(const QChar* str, int &pos) const;
QVariant evalTerm(const QChar* str, int &pos) const;
QVariant evalFactor(const QChar* str, int &pos) const;
};
// These must be kept synchronized with the ComicDataModel::columnIds enum
QString ComicDataModel::columnNameDb[] =
{
"%2%1.id", // colIssueId
"CAST(%1.number AS INTEGER) AS sort_by", // colOrderBy
"%1.number", // colNumber
"document.comics.id", // colId
"document.comics.owned", // colOwned
"%1.publication_date", // colDate
"document.comics.condition", // colCondition
"document.comics.price", // colPrice
"document.comics.store", // colStore
"document.comics.user_id", // colUserId
"document.comics.notes", // colNotes
"document.comics.sold_price", // colSoldPrice
};
QString ComicDataModel::columnNameUi[] =
{
"Issue", // colIssueId
QObject::tr("Sort"), // colOrderBy
QObject::tr("Number"), // colNumber
"Id", // colId
"", // colOwned
QObject::tr("Date"), // colDate
QObject::tr("Condition"), // colCondition
QObject::tr("Price Paid"), // colPrice
QObject::tr("Store"), // colStore
QObject::tr("Id"), // colUserId
QObject::tr("Notes"), // colNotes
QObject::tr("Sale Price"), // colSoldPrice
};
/*SDOC:**********************************************************************
Name: ComicDataModel::ComicDataModel
Action: Constructs the data model & populates it with initial data
**********************************************************************:EDOC*/
ComicDataModel::ComicDataModel(int seriesId, bool showOwned, bool showWanted, bool showSold, bool showUntracked, QObject *parent)
: QSqlQueryModel(parent)
{
// Build a list of column names
QStringList dbNames, dbNamesCustom;
for(int i = 0; i < _countof(columnNameDb); ++i)
{
dbNames.push_back(columnNameDb[i].arg("issues",""));
dbNamesCustom.push_back(columnNameDb[i].arg("document.custom_issues","-"));
}
// Prepare & execute the query
QString conditions;
if( showOwned && showWanted && showSold) conditions = "";
else if( showOwned && showWanted && !showSold) conditions = "AND (document.comics.owned = 'true' OR document.comics.sold_price IS NULL)";
else if( showOwned && !showWanted && showSold) conditions = "AND (document.comics.owned = 'true' OR document.comics.sold_price IS NOT NULL)";
else if( showOwned && !showWanted && !showSold) conditions = "AND document.comics.owned = 'true'";
else if(!showOwned && showWanted && showSold) conditions = "AND document.comics.owned = 'false'";
else if(!showOwned && showWanted && !showSold) conditions = "AND document.comics.owned = 'false' AND document.comics.sold_price IS NULL";
else if(!showOwned && !showWanted && showSold) conditions = "AND document.comics.owned = 'false' AND document.comics.sold_price IS NOT NULL";
else if(!showOwned && !showWanted && !showSold) conditions = "AND document.comics.id = 0";
QString sql1 = QString("SELECT %1 "
"FROM issues "
"%4 JOIN document.comics ON issues.id = document.comics.issue_id "
"WHERE issues.series_id = %2 %3 ")
.arg(dbNames.join(", "))
.arg(seriesId)
.arg(conditions)
.arg(showUntracked ? "LEFT" : "INNER");
QString sql2 = QString("SELECT %1 "
"FROM document.custom_issues "
"%4 JOIN document.comics ON -document.custom_issues.id = document.comics.issue_id "
"WHERE document.custom_issues.series_id = %2 %3 ")
.arg(dbNamesCustom.join(", "))
.arg(seriesId)
.arg(conditions)
.arg(showUntracked ? "LEFT" : "INNER");
QString sql = sql1 + QString(" UNION ") + sql2 + " ORDER BY sort_by, number;";
setQuery(sql);
// Set up the UI names for each column
for(int i = 0; i < _countof(columnNameUi); ++i)
setHeaderData(i, Qt::Horizontal, columnNameUi[i]);
}
/*SDOC:**********************************************************************
Name: ComicDataModel::flags
Action: Return editability flags for each column
**********************************************************************:EDOC*/
Qt::ItemFlags ComicDataModel::flags(const QModelIndex &index) const
{
switch(index.column())
{
case colOwned:
return QSqlQueryModel::flags(index) | Qt::ItemIsUserCheckable;
case colCondition:
case colPrice:
case colStore:
case colUserId:
case colNotes:
return QSqlQueryModel::flags(index) | Qt::ItemIsEditable;
default:
return QSqlQueryModel::flags(index);
}
}
/*SDOC:**********************************************************************
Name: ComicDataModel::rowStatus
Action: Return status of the comic pointed to by index
**********************************************************************:EDOC*/
ComicDataModel::ItemStatus ComicDataModel::rowStatus( const QModelIndex &index ) const
{
// Test to see if the issue is untracked; this trumps all other considerations
if(QSqlQueryModel::data(index.sibling(index.row(),colId)).isNull())
return statusUntracked;
// Test to see if the issue is marked as owned (checked)
if(QSqlQueryModel::data(index.sibling(index.row(),colOwned)).toBool())
{
// Issue is checked; possibly owned or for-sale
if(!QSqlQueryModel::data(index.sibling(index.row(),colSalePrice)).isNull())
return statusForSale;
return statusOwned;
}
else
{
// Issue is unchecked; possibly wanted, sold, or on-order
if(!QSqlQueryModel::data(index.sibling(index.row(),colSalePrice)).isNull())
return statusSold;
if(!QSqlQueryModel::data(index.sibling(index.row(),colPrice)).isNull())
return statusOrdered;
return statusWanted;
}
return statusNone;
}
/*SDOC:**********************************************************************
Name: ComicDataModel::data
Action: Retrieve the data for each cell
**********************************************************************:EDOC*/
QVariant ComicDataModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::BackgroundRole || role == Qt::ForegroundRole)
{
switch(rowStatus(index))
{
case statusUntracked:
if(role == Qt::BackgroundRole) return QColor(255,224,224); // red
break;
case statusWanted:
if(role == Qt::BackgroundRole) return QColor(224,224,255); // blue
break;
case statusOrdered:
if(role == Qt::BackgroundRole) return QColor(224,255,224); // green
break;
case statusSold:
if(role == Qt::ForegroundRole) return QColor(128,128,128); // grey foreground
break;
case statusForSale:
if(role == Qt::ForegroundRole) return QColor(255,0,0); // red foreground
break;
}
}
switch(index.column())
{
// For the "owned" column, we show a checbox instead of the string value
case colOwned:
switch(role)
{
case Qt::CheckStateRole:
return QSqlQueryModel::data(index).toBool() ? Qt::Checked : Qt::Unchecked;
case Qt::DisplayRole:
return QString();
}
break;
// For the "price" column, we show the DOUBLE value as currency
case colPrice:
switch(role)
{
case Qt::TextAlignmentRole:
return Qt::AlignRight;
case Qt::DisplayRole:
{
QVariant value = QSqlQueryModel::data(index, role);
if(!value.isNull())
return QString("$%1").arg(eval(value.toString()).toDouble(),0,'f',2);
}
}
break;
}
// Use the default behaviour
return QSqlQueryModel::data(index, role);
}
/*SDOC:**********************************************************************
Name: ComicDataModel::setData
ComicDataModel::setDataInternal
Action: Called in response to a user-edit; sets the new value for
a cell.
**********************************************************************:EDOC*/
bool ComicDataModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(setDataInternal(index, value, role))
{
// Re-run the main query & tell any views that our
// data has changed.
int pos = query().at();
query().exec();
query().seek(pos);
switch(index.column())
{
case colOwned:
case colPrice:
case colSalePrice:
// Updating these columns may affect the highlighting,
// so we must invalidate the whole row.
dataChanged(index.sibling(index.row(),0),index.sibling(index.row(),columnCount()-1));
break;
default:
dataChanged(index,index);
break;
}
return true;
}
return false;
}
bool ComicDataModel::setDataInternal(const QModelIndex &index, const QVariant &value, int role)
{
// Get the database identifier for the row
int rowId = -1;
if(rowStatus(index) == statusUntracked)
{
// Must first add the item to our collection
QSqlQuery query;
query.prepare("INSERT INTO document.comics(issue_id) VALUES (?);");
query.addBindValue(QSqlQueryModel::data(QSqlQueryModel::index(index.row(), colIssueId)).toInt());
if(!query.exec())
{
QMessageBox::critical(NULL, tr("Database Error"), query.lastError().text());
}
rowId = query.lastInsertId().toInt();
}
else
{
rowId = QSqlQueryModel::data(QSqlQueryModel::index(index.row(), colId)).toInt();
}
// Prepare the UPDATE query
QSqlQuery updateQuery;
QString tableName = columnNameDb[index.column()].section('.',0,-2);
QString columnName = columnNameDb[index.column()].section('.',-1,-1);
updateQuery.prepare(QString("UPDATE %1 SET %2=? WHERE id=?").arg(tableName, columnName));
// Add the user-edited value
switch(index.column())
{
case colOwned:
if(role != Qt::CheckStateRole && role != Qt::EditRole)
return false;
updateQuery.addBindValue(value == Qt::Checked || value == "true");
break;
case colPrice:
case colCondition:
case colStore:
case colUserId:
case colNotes:
updateQuery.addBindValue((value.toString().length()==0) ? QVariant(QVariant::String) : value.toString());
break;
default:
return false;
}
// Finalize & execute
updateQuery.addBindValue(rowId);
if(!updateQuery.exec())
{
QMessageBox::critical(0, QObject::tr("Database Error"), updateQuery.lastError().text());
return false;
}
return true;
}
/*SDOC:**********************************************************************
Name: ComicDataModel::refreshView
Action: Helper that invalidates a given range
**********************************************************************:EDOC*/
void ComicDataModel::refreshView(const QItemSelectionRange range)
{
// Re-run the main query & tell any views that our
// data has changed.
int pos = query().at();
query().finish();
query().exec();
query().seek(pos);
// Refresh entire rows in case highlighting has changed
dataChanged(range.topLeft().sibling(range.top(), 0), range.bottomRight().sibling(range.bottom(),this->columnCount()));
}
/*SDOC:**********************************************************************
Name: ComicDataModel::headerData
Action: Returns the text to display in the header
**********************************************************************:EDOC*/
QVariant ComicDataModel::headerData(int section, Qt::Orientation orientation, int role) const
{
// Use the comic issue number as the vertical header text
if(orientation == Qt::Vertical)
{
switch(role)
{
case Qt::DisplayRole:
return data(index(section,colNumber), role);
case Qt::ForegroundRole:
if(QSqlQueryModel::data(index(section,colIssueId)).toInt() < 0)
return QColor(0,0,255);
switch(rowStatus(index(section,colId)))
{
case statusUntracked:
return QColor(255,0,0);
}
break;
}
}
return QSqlQueryModel::headerData(section, orientation, role);
}
/*SDOC:**********************************************************************
Name: QVariant eval(const QString& str) const;
ComicDataModel::evalExpression
ComicDataModel::evalTerm
ComicDataModel::evalFactor
Action: Simple recursive-descent parser to evaluate a mathematical
expression.
EXPRESSION := TERM
EXPRESSION := TERM ('+'|'-') EXPRESSION
TERM := FACTOR
TERM := FACTOR '*'|'/' TERM
FACTOR := NUMBER
FACTOR := '(' EXPRESSION ')'
**********************************************************************:EDOC*/
QVariant ComicDataModel::eval(const QString& str) const
{
int pos = 0;
const QChar* data = str.constData();
QVariant result = evalExpression(data, pos);
while(data[pos].isSpace()) ++pos;
if(data[pos] != QChar::Null)
return QVariant();
return result;
}
QVariant ComicDataModel::evalExpression(const QChar* str, int &pos) const
{
// Parse the left-hand term in the expression
QVariant result = evalTerm(str, pos);
while(str[pos].isSpace()) ++pos;
// Next character should be an operator; otherwise, exit
QChar op = str[pos];
if( op != '+' && op != '-' )
return result;
++pos;
// Parse the right-hand side of the expression
QVariant rhs = evalExpression(str, pos);
if( result.type() != QVariant::Double || rhs.type() != QVariant::Double )
return QVariant(); // error
// Compute result & return
result = (op == '+') ? result.toDouble() + rhs.toDouble()
/*(op == '-')*/ : result.toDouble() - rhs.toDouble();
return result;
}
QVariant ComicDataModel::evalTerm(const QChar* str, int &pos) const
{
// Parse the left-hand factor in the term
QVariant result = evalFactor(str, pos);
while(str[pos].isSpace()) ++pos;
// Next character should be an operator; otherwise, exit
QChar op = str[pos];
if( op != '*' && op != '/' )
return result;
++pos;
// Parse the right-hand side of the term
QVariant rhs = evalTerm(str, pos);
if( result.type() != QVariant::Double || rhs.type() != QVariant::Double )
return QVariant(); // error
// Compute result & return
if(op == '*')
result = result.toDouble() * rhs.toDouble();
else if(rhs.toDouble() == 0.0) // check for divide-by-zero
result = QVariant();
else //(op == '/')
result = result.toDouble() / rhs.toDouble();
return result;
}
QVariant ComicDataModel::evalFactor(const QChar* str, int &pos) const
{
// Expecting a number or parentheses
while(str[pos].isSpace()) ++pos;
if(str[pos] == '(')
{
++pos;
QVariant result = evalExpression(str, pos);
while(str[pos].isSpace()) ++pos;
if(str[pos++] != ')')
return QVariant(); // error
return result;
}
// Check for unary minus operator
bool negative = false;
if(str[pos] == '-')
{
++pos;
negative = true;
while(str[pos].isSpace()) ++pos;
}
// Parse a number
QString token;
while(str[pos].isDigit() || str[pos] == '.')
token += str[pos++];
while(str[pos].isDigit())
token += str[pos++];
bool ok;
double value = token.toDouble(&ok);
if(ok)
return negative ? -value : value;
return QVariant();
}
/////////////////////////////////////////////////////////////////////////////
// ComicList class
/////////////////////////////////////////////////////////////////////////////
/*SDOC:**********************************************************************
Name: ComicList::ComicList
ComicList::~ComicList
Action: Constructor / Destructor
**********************************************************************:EDOC*/
ComicList::ComicList(QWidget* parent)
: QTableView(parent),
model_(0),
seriesId(-1),
showOwned(true),
showWanted(true),
showSold(true),
showUntracked(false)
{
verticalHeader()->setResizeMode(QHeaderView::Fixed);
}
ComicList::~ComicList()
{
delete model_;
}
/*SDOC:**********************************************************************
Name: ComicList::setModel (SLOT)
Action: Override the base-class' setModel to perform some additional
work.
**********************************************************************:EDOC*/
void ComicList::setModel(QAbstractItemModel* newModel)
{
if(model_) { delete model_; }
model_ = newModel;
// Force read the entire query. It is considered unlikely that
// there would ever be so many issues in a given series that this
// would become a performance problem.
while (model_->canFetchMore(QModelIndex()))
model_->fetchMore(QModelIndex());
QTableView::setModel(model_);
connect(selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(selectionChange(QModelIndex)));
setColumnHidden(ComicDataModel::colId, true); // Hide the "id" column
setColumnHidden(ComicDataModel::colIssueId, true); // Hide the "issue id" column
setColumnHidden(ComicDataModel::colNumber, true); // Hide the "number" column
setColumnHidden(ComicDataModel::colSalePrice, true); // Hide the "sale price" column
setColumnHidden(ComicDataModel::colOrderBy, true); // Hide the ORDER BY column
resizeColumnsToContents();
}
/*SDOC:**********************************************************************
Name: ComicList::setSeries (SLOT)
Action: Filters the list of comics by the selected series
Params: seriesId - the id of the series to filter by
**********************************************************************:EDOC*/
void ComicList::setSeries(int _seriesId)
{
setModel(new ComicDataModel(seriesId = _seriesId, showOwned, showWanted, showSold, showUntracked, this));
}
/*SDOC:**********************************************************************
Name: ComicList::setShowOwned (SLOT)
ComicList::setShowWanted (SLOT)
ComicList::setShowSold (SLOT)
ComicList::setShowUntracked (SLOT)
ComicList::refresh (SLOT)
Action: Toggles filtering is the comic list by various criteria
**********************************************************************:EDOC*/
void ComicList::setShowOwned(bool show)
{
setModel(new ComicDataModel(seriesId, showOwned = show, showWanted, showSold, showUntracked, this));
}
void ComicList::setShowWanted(bool show)
{
setModel(new ComicDataModel(seriesId, showOwned, showWanted = show, showSold, showUntracked, this));
}
void ComicList::setShowSold(bool show)
{
setModel(new ComicDataModel(seriesId, showOwned, showWanted, showSold = show, showUntracked, this));
}
void ComicList::setShowUntracked(bool show)
{
setModel(new ComicDataModel(seriesId, showOwned, showWanted, showSold, showUntracked = show, this));
}
void ComicList::refresh()
{
setModel(new ComicDataModel(seriesId, showOwned, showWanted, showSold, showUntracked, this));
}
/*SDOC:**********************************************************************
Name: ComicList::cut (SLOT)
ComicList::copy (SLOT)
ComicList::paste (SLOT)
ComicList::delete (SLOT)
Action: Clipboard handling & basic editing
**********************************************************************:EDOC*/
void ComicList::cut()
{
copy();
del();
}
void ComicList::copy()
{
if(!selectionModel()->hasSelection())
return;
const QItemSelectionRange selection = selectionModel()->selection().first();
// Copy tab-separated data to the clipboard
QString str;
for(int row = selection.top(); row <= selection.bottom(); ++row)
{
if(row > selection.top()) str += "\n";
for(int column = selection.left(); column <= selection.right(); ++column)
{
if(column > selection.left()) str += "\t";
str += model()->index(row, column).data(Qt::EditRole).toString();
}
}
QApplication::clipboard()->setText(str);
}
void ComicList::paste()
{
if(!selectionModel()->hasSelection())
return;
QItemSelectionRange selection = selectionModel()->selection().first();
// Expect clipboard data as tab-separated values
QString str = QApplication::clipboard()->text();
if(str.isEmpty())
return;
QStringList rows = str.split('\n');
if(rows.count() > 1 && rows.back().length() == 0) rows.pop_back();
int numRows = rows.count();
int numColumns = rows.first().count('\t') + 1;
// We don't support the paste operation unless:
if( selection.height() * selection.width() != 1 && // selection is 1x1 (might still be pasting n x m)
numRows * numColumns != 1 && // paste is 1x1 (selection might still be n x m; data is duplicated)
(selection.height() != numRows || // selection size == paste size
selection.width() != numColumns))
{
QMessageBox::critical(this, tr("Comic Collector"),
tr("The information cannot be pasted because the copy and paste areas aren't the same size."));
return;
}
if(numRows == 1 && numColumns == 1)
{
// Only one piece of data that we're pasting multiple cells
for(int row = selection.top(); row <= selection.bottom(); ++row)
{
for(int column = selection.left(); column <= selection.right(); ++column)
((ComicDataModel*)model_)->setDataInternal(model()->index(row,column), str, Qt::EditRole);
}
}
else
{
selection = QItemSelectionRange(selection.topLeft(), selection.topLeft().sibling(selection.top()+numRows-1, selection.left()+numColumns-1));
for(int row = selection.top(); row <= selection.bottom(); ++row)
{
// Split the line of text
QStringList rowData = rows[row - selection.top()].split('\t');
while(rowData.size() < selection.width())
rowData.push_back(QString());
// Paste into the appropriate cell
for(int column = selection.left(); column <= selection.right(); ++column)
((ComicDataModel*)model_)->setDataInternal(model()->index(row,column), rowData[column-selection.left()], Qt::EditRole);
}
}
((ComicDataModel*)model_)->refreshView(selection);
}
void ComicList::del()
{
if(!selectionModel()->hasSelection())
return;
QItemSelectionRange selection = selectionModel()->selection().first();
if(selection.left() == 0)
{
// The user has requested that we delete entire records (by selecting
// entire rows using the vertical header). Make sure this is what they
// wanted:
if( QMessageBox::question(this, tr("Confirm record delete"),
tr("Are you sure you want to delete the selected records?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes )
{
QStringList ids;
for(int row = selection.top(); row <= selection.bottom(); ++row)
ids.push_back(model()->data(model()->index(row,ComicDataModel::colId), Qt::EditRole).toString());
QString sql = QString("DELETE FROM document.comics WHERE document.comics.id IN (%1);").arg(ids.join(","));
QSqlQuery query;
query.prepare(sql);
query.exec();
// refresh by passing a brand-new model
refresh();
}
}
else
{
// Just delete the contents of all the cells in the selection
for(int row = selection.top(); row <= selection.bottom(); ++row)
{
for(int column = selection.left(); column <= selection.right(); ++column)
((ComicDataModel*)model_)->setDataInternal(model()->index(row,column), QVariant(), Qt::EditRole);
}
((ComicDataModel*)model_)->refreshView(selection);
}
}
/*SDOC:**********************************************************************
Name: ComicList::selectionChange
Action:
**********************************************************************:EDOC*/
void ComicList::selectionChange(const QModelIndex& index)
{
int rowId = model()->data(index.sibling(index.row(),ComicDataModel::colIssueId)).toInt();
selectionChanged(rowId);
}
/*SDOC:**********************************************************************
Name: ComicList::duplicate (SLOT)
Action: Duplicate the selected item
**********************************************************************:EDOC*/
void ComicList::duplicate()
{
if(!selectionModel()->hasSelection())
return;
QItemSelectionRange selection = selectionModel()->selection().first();
QSqlQuery query;
query.prepare("INSERT INTO document.comics(issue_id) VALUES (?);");
query.addBindValue(model()->data(selection.topLeft().sibling(selection.top(), ComicDataModel::colIssueId)).toInt());
if(!query.exec())
{
QMessageBox::critical(NULL, tr("Database Error"), query.lastError().text());
}
int row = selection.top();
int col = selection.left();
// refresh & re-select the old row
refresh();
selectionModel()->setCurrentIndex(model()->index(row,col), QItemSelectionModel::Select);
}
/* end of file */