diff options
author | Dirk Hohndel <dirk@hohndel.org> | 2014-02-27 20:09:57 -0800 |
---|---|---|
committer | Dirk Hohndel <dirk@hohndel.org> | 2014-02-27 20:09:57 -0800 |
commit | 76e6420f6b3503b76bd3eec00ab0e53d6ea17a20 (patch) | |
tree | 8b50298f41bd29d55bbd6f4301f36ad31dc0b008 /qt-ui | |
parent | 006265d7a088cff4fea665159dbb454956c2cd76 (diff) | |
download | subsurface-76e6420f6b3503b76bd3eec00ab0e53d6ea17a20.tar.gz |
Massive automated whitespace cleanup
I know everyone will hate it.
Go ahead. Complain. Call me names.
At least now things are consistent and reproducible.
If you want changes, have your complaint come with a patch to
scripts/whitespace.pl so that we can automate it.
Signed-off-by: Dirk Hohndel <dirk@hohndel.org>
Diffstat (limited to 'qt-ui')
74 files changed, 3251 insertions, 2718 deletions
diff --git a/qt-ui/about.cpp b/qt-ui/about.cpp index 7490c2dee..c94d17ade 100644 --- a/qt-ui/about.cpp +++ b/qt-ui/about.cpp @@ -9,12 +9,12 @@ SubsurfaceAbout::SubsurfaceAbout(QWidget *parent, Qt::WindowFlags f) : QDialog(p setWindowModality(Qt::ApplicationModal); - ui.aboutLabel->setText(tr("<span style='font-size: 18pt; font-weight: bold;'>" \ - "Subsurface %1 </span><br><br>" \ - "Multi-platform divelog software<br>" \ - "<span style='font-size: 8pt'>" \ - "Linus Torvalds, Dirk Hohndel, Tomaz Canabrava, and others, 2011-2014" \ - "</span>").arg(VERSION_STRING)); + ui.aboutLabel->setText(tr("<span style='font-size: 18pt; font-weight: bold;'>" + "Subsurface %1 </span><br><br>" + "Multi-platform divelog software<br>" + "<span style='font-size: 8pt'>" + "Linus Torvalds, Dirk Hohndel, Tomaz Canabrava, and others, 2011-2014" + "</span>").arg(VERSION_STRING)); } void SubsurfaceAbout::on_licenseButton_clicked() diff --git a/qt-ui/about.h b/qt-ui/about.h index 4ec7dd8ce..0fa7d6785 100644 --- a/qt-ui/about.h +++ b/qt-ui/about.h @@ -9,10 +9,12 @@ class SubsurfaceAbout : public QDialog { Q_OBJECT public: - explicit SubsurfaceAbout(QWidget* parent = 0, Qt::WindowFlags f = 0); -private slots: + explicit SubsurfaceAbout(QWidget *parent = 0, Qt::WindowFlags f = 0); +private +slots: void on_licenseButton_clicked(); void on_websiteButton_clicked(); + private: Ui::SubsurfaceAbout ui; }; diff --git a/qt-ui/completionmodels.cpp b/qt-ui/completionmodels.cpp index b0a5db2d3..30e69d26a 100644 --- a/qt-ui/completionmodels.cpp +++ b/qt-ui/completionmodels.cpp @@ -2,35 +2,38 @@ #include "dive.h" #include "mainwindow.h" -#define CREATE_UPDATE_METHOD(Class, diveStructMember) \ -void Class::updateModel() \ -{ \ - QStringList list; \ - struct dive* dive; \ - int i = 0; \ - for_each_dive(i, dive) { \ - QString buddy(dive->diveStructMember); \ - if (!list.contains(buddy)) { \ - list.append(buddy); \ - } \ - } \ - setStringList(list); \ -} +#define CREATE_UPDATE_METHOD(Class, diveStructMember) \ + void Class::updateModel() \ + { \ + QStringList list; \ + struct dive *dive; \ + int i = 0; \ + for_each_dive(i, dive) \ + { \ + QString buddy(dive->diveStructMember); \ + if (!list.contains(buddy)) { \ + list.append(buddy); \ + } \ + } \ + setStringList(list); \ + } -#define CREATE_CSV_UPDATE_METHOD(Class, diveStructMember) \ -void Class::updateModel() \ -{ \ - QSet<QString> set; \ - struct dive* dive; \ - int i = 0; \ - for_each_dive(i, dive) { \ - QString buddy(dive->diveStructMember); \ - foreach (const QString &value, buddy.split(",", QString::SkipEmptyParts)) { \ - set.insert(value.trimmed()); \ - } \ - } \ - setStringList(set.toList()); \ -} +#define CREATE_CSV_UPDATE_METHOD(Class, diveStructMember) \ + void Class::updateModel() \ + { \ + QSet<QString> set; \ + struct dive *dive; \ + int i = 0; \ + for_each_dive(i, dive) \ + { \ + QString buddy(dive->diveStructMember); \ + foreach(const QString &value, buddy.split(",", QString::SkipEmptyParts)) \ + { \ + set.insert(value.trimmed()); \ + } \ + } \ + setStringList(set.toList()); \ + } CREATE_CSV_UPDATE_METHOD(BuddyCompletionModel, buddy); CREATE_CSV_UPDATE_METHOD(DiveMasterCompletionModel, divemaster); diff --git a/qt-ui/divecomputermanagementdialog.cpp b/qt-ui/divecomputermanagementdialog.cpp index c7d7fc75b..238830bd0 100644 --- a/qt-ui/divecomputermanagementdialog.cpp +++ b/qt-ui/divecomputermanagementdialog.cpp @@ -5,7 +5,7 @@ #include "../qthelper.h" #include "../helpers.h" -DiveComputerManagementDialog::DiveComputerManagementDialog(QWidget* parent, Qt::WindowFlags f): QDialog(parent, f), +DiveComputerManagementDialog::DiveComputerManagementDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), model(0) { ui.setupUi(this); @@ -20,7 +20,7 @@ void DiveComputerManagementDialog::init() ui.tableView->setModel(model); } -DiveComputerManagementDialog* DiveComputerManagementDialog::instance() +DiveComputerManagementDialog *DiveComputerManagementDialog::instance() { static DiveComputerManagementDialog *self = new DiveComputerManagementDialog(MainWindow::instance()); self->setAttribute(Qt::WA_QuitOnClose, false); @@ -35,17 +35,16 @@ void DiveComputerManagementDialog::update() layout()->activate(); } -void DiveComputerManagementDialog::tryRemove(const QModelIndex& index) +void DiveComputerManagementDialog::tryRemove(const QModelIndex &index) { if (index.column() != DiveComputerModel::REMOVE) return; QMessageBox::StandardButton response = QMessageBox::question( - this, TITLE_OR_TEXT( - tr("Remove the selected Dive Computer?"), - tr("Are you sure that you want to \n remove the selected dive computer?")), - QMessageBox::Ok | QMessageBox::Cancel - ); + this, TITLE_OR_TEXT( + tr("Remove the selected Dive Computer?"), + tr("Are you sure that you want to \n remove the selected dive computer?")), + QMessageBox::Ok | QMessageBox::Cancel); if (response == QMessageBox::Ok) model->remove(index); diff --git a/qt-ui/divecomputermanagementdialog.h b/qt-ui/divecomputermanagementdialog.h index aba98040b..d065a0208 100644 --- a/qt-ui/divecomputermanagementdialog.h +++ b/qt-ui/divecomputermanagementdialog.h @@ -6,21 +6,22 @@ class QModelIndex; class DiveComputerModel; -class DiveComputerManagementDialog : public QDialog{ -Q_OBJECT +class DiveComputerManagementDialog : public QDialog { + Q_OBJECT public: static DiveComputerManagementDialog *instance(); void update(); void init(); -public slots: - void tryRemove(const QModelIndex& index); +public +slots: + void tryRemove(const QModelIndex &index); void accept(); void reject(); private: - explicit DiveComputerManagementDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit DiveComputerManagementDialog(QWidget *parent = 0, Qt::WindowFlags f = 0); Ui::DiveComputerManagementDialog ui; DiveComputerModel *model; }; diff --git a/qt-ui/divelistview.cpp b/qt-ui/divelistview.cpp index 7c1eb393f..dd4aacba2 100644 --- a/qt-ui/divelistview.cpp +++ b/qt-ui/divelistview.cpp @@ -27,8 +27,7 @@ #include <iostream> -DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelection(false), - sortColumn(0), currentOrder(Qt::DescendingOrder), searchBox(this) +DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelection(false), sortColumn(0), currentOrder(Qt::DescendingOrder), searchBox(this) { setItemDelegate(new DiveListDelegate(this)); setUniformRowHeights(true); @@ -47,7 +46,7 @@ DiveListView::DiveListView(QWidget *parent) : QTreeView(parent), mouseClickSelec header()->setMinimumHeight(metrics.height() + 10); header()->setStretchLastSection(true); QAction *showSearchBox = new QAction(tr("Show Search Box"), this); - showSearchBox->setShortcut( Qt::CTRL + Qt::Key_F); + showSearchBox->setShortcut(Qt::CTRL + Qt::Key_F); showSearchBox->setShortcutContext(Qt::WindowShortcut); addAction(showSearchBox); @@ -112,23 +111,23 @@ int DiveListView::lastVisibleColumn() void DiveListView::backupExpandedRows() { expandedRows.clear(); - for(int i = 0; i < model()->rowCount(); i++) - if (isExpanded( model()->index(i, 0) )) + for (int i = 0; i < model()->rowCount(); i++) + if (isExpanded(model()->index(i, 0))) expandedRows.push_back(i); } void DiveListView::restoreExpandedRows() { setAnimated(false); - Q_FOREACH(const int &i, expandedRows) - setExpanded( model()->index(i, 0), true ); + Q_FOREACH(const int & i, expandedRows) + setExpanded(model()->index(i, 0), true); setAnimated(true); } void DiveListView::fixMessyQtModelBehaviour() { QAbstractItemModel *m = model(); - for(int i = 0; i < model()->rowCount(); i++) - if (m->rowCount( m->index(i, 0) ) != 0) + for (int i = 0; i < model()->rowCount(); i++) + if (m->rowCount(m->index(i, 0)) != 0) setFirstColumnSpanned(i, QModelIndex(), true); } @@ -137,10 +136,10 @@ void DiveListView::rememberSelection() { selectedDives.clear(); QItemSelection selection = selectionModel()->selection(); - Q_FOREACH(const QModelIndex& index , selection.indexes()) { + Q_FOREACH(const QModelIndex & index, selection.indexes()) { if (index.column() != 0) // We only care about the dives, so, let's stick to rows and discard columns. continue; - struct dive *d = (struct dive *) index.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)index.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (d) selectedDives.insert(d->divetrip, get_divenr(d)); } @@ -149,7 +148,7 @@ void DiveListView::rememberSelection() void DiveListView::restoreSelection() { unselectDives(); - Q_FOREACH(dive_trip_t *trip, selectedDives.keys()) { + Q_FOREACH(dive_trip_t * trip, selectedDives.keys()) { QList<int> divesOnTrip = getDivesInTrip(trip); QList<int> selectedDivesOnTrip = selectedDives.values(trip); @@ -167,18 +166,18 @@ void DiveListView::restoreSelection() } } -void DiveListView::selectTrip ( dive_trip_t* trip ) +void DiveListView::selectTrip(dive_trip_t *trip) { if (!trip) return; - QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel*>(model()); - QModelIndexList match = m->match(m->index(0,0), DiveTripModel::TRIP_ROLE, QVariant::fromValue<void*>(trip), 2, Qt::MatchRecursive); + QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel *>(model()); + QModelIndexList match = m->match(m->index(0, 0), DiveTripModel::TRIP_ROLE, QVariant::fromValue<void *>(trip), 2, Qt::MatchRecursive); QItemSelectionModel::SelectionFlags flags; if (!match.count()) return; QModelIndex idx = match.first(); - flags = QItemSelectionModel::Select; + flags = QItemSelectionModel::Select; flags |= QItemSelectionModel::Rows; selectionModel()->select(idx, flags); expand(idx); @@ -189,12 +188,12 @@ void DiveListView::unselectDives() selectionModel()->clearSelection(); } -QList< dive_trip_t* > DiveListView::selectedTrips() +QList<dive_trip_t *> DiveListView::selectedTrips() { QModelIndexList indexes = selectionModel()->selectedRows(); - QList<dive_trip_t*> ret; - Q_FOREACH(const QModelIndex& index, indexes) { - dive_trip_t *trip = static_cast<dive_trip_t*>(index.data(DiveTripModel::TRIP_ROLE).value<void*>()); + QList<dive_trip_t *> ret; + Q_FOREACH(const QModelIndex & index, indexes) { + dive_trip_t *trip = static_cast<dive_trip_t *>(index.data(DiveTripModel::TRIP_ROLE).value<void *>()); if (!trip) continue; ret.push_back(trip); @@ -204,10 +203,10 @@ QList< dive_trip_t* > DiveListView::selectedTrips() void DiveListView::selectDive(int i, bool scrollto, bool toggle) { - if ( i == -1) + if (i == -1) return; - QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel*>(model()); - QModelIndexList match = m->match(m->index(0,0), DiveTripModel::DIVE_IDX, i, 2, Qt::MatchRecursive); + QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel *>(model()); + QModelIndexList match = m->match(m->index(0, 0), DiveTripModel::DIVE_IDX, i, 2, Qt::MatchRecursive); QItemSelectionModel::SelectionFlags flags; QModelIndex idx = match.first(); flags = toggle ? QItemSelectionModel::Toggle : QItemSelectionModel::Select; @@ -222,19 +221,19 @@ void DiveListView::selectDive(int i, bool scrollto, bool toggle) scrollTo(idx, PositionAtCenter); } -void DiveListView::selectDives(const QList< int >& newDiveSelection) +void DiveListView::selectDives(const QList<int> &newDiveSelection) { if (!newDiveSelection.count()) return; - disconnect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(selectionChanged(QItemSelection,QItemSelection))); - disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), - this, SLOT(currentChanged(QModelIndex,QModelIndex))); + disconnect(selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), + this, SLOT(selectionChanged(QItemSelection, QItemSelection))); + disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), + this, SLOT(currentChanged(QModelIndex, QModelIndex))); setAnimated(false); collapseAll(); - QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel*>(model()); + QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel *>(model()); QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select | QItemSelectionModel::Rows; QItemSelection newDeselected = selectionModel()->selection(); @@ -246,17 +245,17 @@ void DiveListView::selectDives(const QList< int >& newDiveSelection) struct dive *dive; for_each_dive(i, dive) { dive->selected = newDiveSelection.contains(i) == true; - if (firstSelectedDive == -1 && dive->selected ) { + if (firstSelectedDive == -1 && dive->selected) { firstSelectedDive = i; } } } select_dive(firstSelectedDive); Q_FOREACH(int i, newDiveSelection) { - diveList.append(m->match(m->index(0,0), DiveTripModel::DIVE_IDX, - i, 2, Qt::MatchRecursive).first()); + diveList.append(m->match(m->index(0, 0), DiveTripModel::DIVE_IDX, + i, 2, Qt::MatchRecursive).first()); } - Q_FOREACH(const QModelIndex& idx, diveList) { + Q_FOREACH(const QModelIndex & idx, diveList) { selectionModel()->select(idx, flags); if (idx.parent().isValid() && !isExpanded(idx.parent())) { expand(idx.parent()); @@ -264,12 +263,12 @@ void DiveListView::selectDives(const QList< int >& newDiveSelection) } setAnimated(true); QTreeView::selectionChanged(selectionModel()->selection(), newDeselected); - connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), - this, SLOT(selectionChanged(QItemSelection,QItemSelection))); - connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), - this, SLOT(currentChanged(QModelIndex,QModelIndex))); + connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), + this, SLOT(selectionChanged(QItemSelection, QItemSelection))); + connect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), + this, SLOT(currentChanged(QModelIndex, QModelIndex))); Q_EMIT currentDiveChanged(selected_dive); - const QModelIndex& idx = m->match(m->index(0,0), DiveTripModel::DIVE_IDX,selected_dive, 2, Qt::MatchRecursive).first(); + const QModelIndex &idx = m->match(m->index(0, 0), DiveTripModel::DIVE_IDX, selected_dive, 2, Qt::MatchRecursive).first(); scrollTo(idx); } @@ -279,17 +278,17 @@ void DiveListView::showSearchEdit() searchBox.setFocus(); } -bool DiveListView::eventFilter(QObject* , QEvent* event) +bool DiveListView::eventFilter(QObject *, QEvent *event) { if (event->type() != QEvent::KeyPress) return false; - QKeyEvent *keyEv = static_cast<QKeyEvent*>(event); + QKeyEvent *keyEv = static_cast<QKeyEvent *>(event); if (keyEv->key() != Qt::Key_Escape) return false; searchBox.clear(); searchBox.hide(); - QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel*>(model()); + QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel *>(model()); m->setFilterFixedString(QString()); return true; } @@ -300,7 +299,7 @@ bool DiveListView::eventFilter(QObject* , QEvent* event) // index. TRIP_ROLE vs DIVE_ROLE? void DiveListView::headerClicked(int i) { - DiveTripModel::Layout newLayout = i == (int) DiveTripModel::NR ? DiveTripModel::TREE : DiveTripModel::LIST; + DiveTripModel::Layout newLayout = i == (int)DiveTripModel::NR ? DiveTripModel::TREE : DiveTripModel::LIST; rememberSelection(); unselectDives(); /* No layout change? Just re-sort, and scroll to first selection, making sure all selections are expanded */ @@ -328,14 +327,14 @@ void DiveListView::reload(DiveTripModel::Layout layout, bool forceSort) layout = currentLayout; else currentLayout = layout; -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) header()->setClickable(true); #else header()->setSectionsClickable(true); #endif connect(header(), SIGNAL(sectionPressed(int)), this, SLOT(headerClicked(int)), Qt::UniqueConnection); - QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel*>(model()); + QSortFilterProxyModel *m = qobject_cast<QSortFilterProxyModel *>(model()); QAbstractItemModel *oldModel = m->sourceModel(); if (oldModel) { oldModel->deleteLater(); @@ -352,10 +351,10 @@ void DiveListView::reload(DiveTripModel::Layout layout, bool forceSort) if (amount_selected && current_dive != NULL) { selectDive(selected_dive, true); } else { - QModelIndex firstDiveOrTrip = m->index(0,0); + QModelIndex firstDiveOrTrip = m->index(0, 0); if (firstDiveOrTrip.isValid()) { - if (m->index(0,0, firstDiveOrTrip).isValid()) - setCurrentIndex(m->index(0,0, firstDiveOrTrip)); + if (m->index(0, 0, firstDiveOrTrip).isValid()) + setCurrentIndex(m->index(0, 0, firstDiveOrTrip)); else setCurrentIndex(firstDiveOrTrip); } @@ -382,19 +381,12 @@ void DiveListView::reloadHeaderActions() if (!header()->actions().size()) { QSettings s; s.beginGroup("DiveListColumnState"); - for(int i = 0; i < model()->columnCount(); i++) { + for (int i = 0; i < model()->columnCount(); i++) { QString title = QString("%1").arg(model()->headerData(i, Qt::Horizontal).toString()); QString settingName = QString("showColumn%1").arg(i); QAction *a = new QAction(title, header()); bool showHeaderFirstRun = !( - i == DiveTripModel::MAXCNS - || i == DiveTripModel::NITROX - || i == DiveTripModel::OTU - || i == DiveTripModel::TEMPERATURE - || i == DiveTripModel::TOTALWEIGHT - || i == DiveTripModel::SUIT - || i == DiveTripModel::CYLINDER - || i == DiveTripModel::SAC ); + i == DiveTripModel::MAXCNS || i == DiveTripModel::NITROX || i == DiveTripModel::OTU || i == DiveTripModel::TEMPERATURE || i == DiveTripModel::TOTALWEIGHT || i == DiveTripModel::SUIT || i == DiveTripModel::CYLINDER || i == DiveTripModel::SAC); bool shown = s.value(settingName, showHeaderFirstRun).toBool(); a->setCheckable(true); a->setChecked(shown); @@ -406,7 +398,7 @@ void DiveListView::reloadHeaderActions() } s.endGroup(); } else { - for(int i = 0; i < model()->columnCount(); i++) { + for (int i = 0; i < model()->columnCount(); i++) { QString title = QString("%1").arg(model()->headerData(i, Qt::Horizontal).toString()); header()->actions()[i]->setText(title); } @@ -415,7 +407,7 @@ void DiveListView::reloadHeaderActions() void DiveListView::toggleColumnVisibilityByIndex() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); if (!action) return; @@ -428,29 +420,29 @@ void DiveListView::toggleColumnVisibilityByIndex() setColumnWidth(lastVisibleColumn(), 10); } -void DiveListView::currentChanged(const QModelIndex& current, const QModelIndex& previous) +void DiveListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) { if (!current.isValid()) return; scrollTo(current); } -void DiveListView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) +void DiveListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { QItemSelection newSelected = selected.size() ? selected : selectionModel()->selection(); QItemSelection newDeselected = deselected; - disconnect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection))); - disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(QModelIndex,QModelIndex))); + disconnect(selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged(QItemSelection, QItemSelection))); + disconnect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(currentChanged(QModelIndex, QModelIndex))); - Q_FOREACH(const QModelIndex& index, newDeselected.indexes()) { + Q_FOREACH(const QModelIndex & index, newDeselected.indexes()) { if (index.column() != 0) continue; const QAbstractItemModel *model = index.model(); - struct dive *dive = (struct dive*) model->data(index, DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *dive = (struct dive *)model->data(index, DiveTripModel::DIVE_ROLE).value<void *>(); if (!dive) { // it's a trip! if (model->rowCount(index)) { - struct dive *child = (struct dive*) model->data(index.child(0,0), DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *child = (struct dive *)model->data(index.child(0, 0), DiveTripModel::DIVE_ROLE).value<void *>(); while (child) { deselect_dive(get_divenr(child)); child = child->next; @@ -460,21 +452,21 @@ void DiveListView::selectionChanged(const QItemSelection& selected, const QItemS deselect_dive(get_divenr(dive)); } } - Q_FOREACH(const QModelIndex& index, newSelected.indexes()) { + Q_FOREACH(const QModelIndex & index, newSelected.indexes()) { if (index.column() != 0) continue; const QAbstractItemModel *model = index.model(); - struct dive *dive = (struct dive*) model->data(index, DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *dive = (struct dive *)model->data(index, DiveTripModel::DIVE_ROLE).value<void *>(); if (!dive) { // it's a trip! if (model->rowCount(index)) { QItemSelection selection; - struct dive *child = (struct dive*) model->data(index.child(0,0), DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *child = (struct dive *)model->data(index.child(0, 0), DiveTripModel::DIVE_ROLE).value<void *>(); while (child) { select_dive(get_divenr(child)); child = child->next; } - selection.select(index.child(0,0), index.child(model->rowCount(index) -1 , 0)); + selection.select(index.child(0, 0), index.child(model->rowCount(index) - 1, 0)); selectionModel()->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows); selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select | QItemSelectionModel::NoUpdate); if (!isExpanded(index)) @@ -485,8 +477,8 @@ void DiveListView::selectionChanged(const QItemSelection& selected, const QItemS } } QTreeView::selectionChanged(selectionModel()->selection(), newDeselected); - connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection))); - connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(QModelIndex,QModelIndex))); + connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged(QItemSelection, QItemSelection))); + connect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(currentChanged(QModelIndex, QModelIndex))); // now that everything is up to date, update the widgets Q_EMIT currentDiveChanged(selected_dive); } @@ -498,7 +490,7 @@ static bool can_merge(const struct dive *a, const struct dive *b) if (a->when > b->when) return false; /* Don't merge dives if there's more than half an hour between them */ - if (a->when + a->duration.seconds + 30*60 < b->when) + if (a->when + a->duration.seconds + 30 * 60 < b->when) return false; return true; } @@ -524,10 +516,10 @@ void DiveListView::mergeDives() void DiveListView::merge_trip(const QModelIndex &a, int offset) { int i = a.row() + offset; - QModelIndex b = a.sibling(i,0); + QModelIndex b = a.sibling(i, 0); - dive_trip_t *trip_a = (dive_trip_t *) a.data(DiveTripModel::TRIP_ROLE).value<void*>(); - dive_trip_t *trip_b = (dive_trip_t *) b.data(DiveTripModel::TRIP_ROLE).value<void*>(); + dive_trip_t *trip_a = (dive_trip_t *)a.data(DiveTripModel::TRIP_ROLE).value<void *>(); + dive_trip_t *trip_b = (dive_trip_t *)b.data(DiveTripModel::TRIP_ROLE).value<void *>(); if (trip_a == trip_b || !trip_a || !trip_b) return; @@ -574,7 +566,7 @@ void DiveListView::newTripAbove() { dive_trip_t *trip; int idx; - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (!d) // shouldn't happen as we only are setting up this action if this is a dive return; rememberSelection(); @@ -595,7 +587,7 @@ void DiveListView::addToTripAbove() int idx, delta = (currentOrder == Qt::AscendingOrder) ? -1 : +1; dive_trip_t *trip = NULL; struct dive *pd = NULL; - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (!d) // shouldn't happen as we only are setting up this action if this is a dive return; rememberSelection(); @@ -638,10 +630,10 @@ void DiveListView::addToTripAbove() void DiveListView::markDiveInvalid() { int i; - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (!d) return; - for_each_dive (i, d) { + for_each_dive(i, d) { if (!d->selected) continue; // now mark the dive invalid... how do we do THAT? @@ -663,7 +655,7 @@ void DiveListView::markDiveInvalid() void DiveListView::deleteDive() { int i; - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (!d) return; // after a dive is deleted the ones following it move forward in the dive_table @@ -693,12 +685,12 @@ void DiveListView::deleteDive() void DiveListView::testSlot() { - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (d) { qDebug("testSlot called on dive #%d", d->number); } else { QModelIndex child = contextMenuIndex.child(0, 0); - d = (struct dive *) child.data(DiveTripModel::DIVE_ROLE).value<void*>(); + d = (struct dive *)child.data(DiveTripModel::DIVE_ROLE).value<void *>(); if (d) qDebug("testSlot called on trip including dive #%d", d->number); else @@ -711,8 +703,8 @@ void DiveListView::contextMenuEvent(QContextMenuEvent *event) QAction *collapseAction = NULL; // let's remember where we are contextMenuIndex = indexAt(event->pos()); - struct dive *d = (struct dive *) contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void*>(); - dive_trip_t *trip = (dive_trip_t *) contextMenuIndex.data(DiveTripModel::TRIP_ROLE).value<void*>(); + struct dive *d = (struct dive *)contextMenuIndex.data(DiveTripModel::DIVE_ROLE).value<void *>(); + dive_trip_t *trip = (dive_trip_t *)contextMenuIndex.data(DiveTripModel::TRIP_ROLE).value<void *>(); QMenu popup(this); if (currentLayout == DiveTripModel::TREE) { popup.addAction(tr("expand all"), this, SLOT(expandAll())); @@ -746,7 +738,7 @@ void DiveListView::contextMenuEvent(QContextMenuEvent *event) popup.addAction(tr("upload dive(s) to divelogs.de"), this, SLOT(uploadToDivelogsDE())); // "collapse all" really closes all trips, // "collapse" keeps the trip with the selected dive open - QAction * actionTaken = popup.exec(event->globalPos()); + QAction *actionTaken = popup.exec(event->globalPos()); if (actionTaken == collapseAction && collapseAction) { this->setAnimated(false); selectDive(selected_dive, true); @@ -776,7 +768,7 @@ void DiveListView::saveSelectedDivesAs() // Keep last open dir QFileInfo fileInfo(fileName); settings.beginGroup("FileDialog"); - settings.setValue("LastDir",fileInfo.dir().path()); + settings.setValue("LastDir", fileInfo.dir().path()); settings.endGroup(); QByteArray bt = QFile::encodeName(fileName); @@ -821,7 +813,7 @@ void DiveListView::loadImages() for (int i = 0; i < fileNames.size(); ++i) { if (readfile(fileNames.at(i).toUtf8().data(), &mem) <= 0) continue; - retval = exif.parseFrom((const unsigned char *) mem.buffer, (unsigned) mem.size); + retval = exif.parseFrom((const unsigned char *)mem.buffer, (unsigned)mem.size); free(mem.buffer); if (retval != PARSE_EXIF_SUCCESS) continue; @@ -831,21 +823,21 @@ void DiveListView::loadImages() imagetime += shiftDialog.amount(); int j = 0; struct dive *dive; - for_each_dive(j, dive){ + for_each_dive(j, dive) { if (!dive->selected) continue; // FIXME: this adds the events only to the first DC - if (dive->when - 3600 < imagetime && dive->when + dive->duration.seconds + 3600 > imagetime){ + if (dive->when - 3600 < imagetime && dive->when + dive->duration.seconds + 3600 > imagetime) { if (dive->when > imagetime) { // Before dive add_event(&(dive->dc), 0, 123, 0, 0, fileNames.at(i).toUtf8().data()); - } else if (dive->when + dive->duration.seconds < imagetime){ + } else if (dive->when + dive->duration.seconds < imagetime) { // After dive add_event(&(dive->dc), dive->duration.seconds, 123, 0, 0, fileNames.at(i).toUtf8().data()); } else { add_event(&(dive->dc), imagetime - dive->when, 123, 0, 0, fileNames.at(i).toUtf8().data()); } - if (!dive->latitude.udeg && !IS_FP_SAME(exif.GeoLocation.Latitude, 0.0)){ + if (!dive->latitude.udeg && !IS_FP_SAME(exif.GeoLocation.Latitude, 0.0)) { dive->latitude.udeg = lrint(1000000.0 * exif.GeoLocation.Latitude); dive->longitude.udeg = lrint(1000000.0 * exif.GeoLocation.Longitude); } @@ -873,7 +865,7 @@ QString DiveListView::lastUsedImageDir() return lastImageDir; } -void DiveListView::updateLastUsedImageDir(const QString& dir) +void DiveListView::updateLastUsedImageDir(const QString &dir) { QSettings s; s.beginGroup("FileDialog"); diff --git a/qt-ui/divelistview.h b/qt-ui/divelistview.h index f078a33f8..f395720bd 100644 --- a/qt-ui/divelistview.h +++ b/qt-ui/divelistview.h @@ -15,24 +15,24 @@ #include <QLineEdit> #include "models.h" -class DiveListView : public QTreeView -{ +class DiveListView : public QTreeView { Q_OBJECT public: DiveListView(QWidget *parent = 0); ~DiveListView(); - void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected); - void currentChanged(const QModelIndex& current, const QModelIndex& previous); + void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); + void currentChanged(const QModelIndex ¤t, const QModelIndex &previous); void reload(DiveTripModel::Layout layout, bool forceSort = true); - bool eventFilter(QObject* , QEvent* ); + bool eventFilter(QObject *, QEvent *); void unselectDives(); void selectDive(int dive_table_idx, bool scrollto = false, bool toggle = false); - void selectDives(const QList<int>& newDiveSelection); + void selectDives(const QList<int> &newDiveSelection); void rememberSelection(); void restoreSelection(); void contextMenuEvent(QContextMenuEvent *event); - QList<dive_trip_t*> selectedTrips(); -public slots: + QList<dive_trip_t *> selectedTrips(); +public +slots: void toggleColumnVisibilityByIndex(); void reloadHeaderActions(); void headerClicked(int); @@ -73,8 +73,8 @@ private: void backupExpandedRows(); void restoreExpandedRows(); int lastVisibleColumn(); - void selectTrip ( dive_trip_t* trip ); - void updateLastUsedImageDir(const QString& s); + void selectTrip(dive_trip_t *trip); + void updateLastUsedImageDir(const QString &s); void updateLastImageTimeOffset(int offset); int lastImageTimeOffset(); }; diff --git a/qt-ui/divelogimportdialog.cpp b/qt-ui/divelogimportdialog.cpp index 36e69d06f..41c906279 100644 --- a/qt-ui/divelogimportdialog.cpp +++ b/qt-ui/divelogimportdialog.cpp @@ -5,15 +5,14 @@ #include "ui_divelogimportdialog.h" const DiveLogImportDialog::CSVAppConfig DiveLogImportDialog::CSVApps[CSVAPPS] = { - {"", }, - {"APD Log Viewer", 1, 2, 16, 7, 18, 19, "Tab"}, - {"XP5", 1, 2, 10, -1, -1, -1, "Tab"}, - {"SensusCSV", 10, 11, -1, -1, -1, -1, ","}, - {NULL,} + { "", }, + { "APD Log Viewer", 1, 2, 16, 7, 18, 19, "Tab" }, + { "XP5", 1, 2, 10, -1, -1, -1, "Tab" }, + { "SensusCSV", 10, 11, -1, -1, -1, -1, "," }, + { NULL, } }; -DiveLogImportDialog::DiveLogImportDialog(QStringList *fn, QWidget *parent) : - QDialog(parent), +DiveLogImportDialog::DiveLogImportDialog(QStringList *fn, QWidget *parent) : QDialog(parent), selector(true), ui(new Ui::DiveLogImportDialog) { @@ -52,7 +51,7 @@ DiveLogImportDialog::~DiveLogImportDialog() delete ui; } -#define VALUE_IF_CHECKED(x) (ui->x->isEnabled() ? ui->x->value() - 1: -1) +#define VALUE_IF_CHECKED(x) (ui->x->isEnabled() ? ui->x->value() - 1 : -1) void DiveLogImportDialog::on_buttonBox_accepted() { char *error = NULL; @@ -60,14 +59,14 @@ void DiveLogImportDialog::on_buttonBox_accepted() if (ui->tabWidget->currentIndex() == 0) { for (int i = 0; i < fileNames.size(); ++i) { parse_csv_file(fileNames[i].toUtf8().data(), ui->CSVTime->value() - 1, - ui->CSVDepth->value() - 1, VALUE_IF_CHECKED(CSVTemperature), - VALUE_IF_CHECKED(CSVpo2), - VALUE_IF_CHECKED(CSVcns), - VALUE_IF_CHECKED(CSVstopdepth), - ui->CSVSeparator->currentIndex(), - specialCSV.contains(ui->knownImports->currentIndex()) ? CSVApps[ui->knownImports->currentIndex()].name.toUtf8().data() : "csv", - ui->CSVUnits->currentIndex(), - &error); + ui->CSVDepth->value() - 1, VALUE_IF_CHECKED(CSVTemperature), + VALUE_IF_CHECKED(CSVpo2), + VALUE_IF_CHECKED(CSVcns), + VALUE_IF_CHECKED(CSVstopdepth), + ui->CSVSeparator->currentIndex(), + specialCSV.contains(ui->knownImports->currentIndex()) ? CSVApps[ui->knownImports->currentIndex()].name.toUtf8().data() : "csv", + ui->CSVUnits->currentIndex(), + &error); if (error != NULL) { MainWindow::instance()->showError(error); free(error); @@ -77,16 +76,16 @@ void DiveLogImportDialog::on_buttonBox_accepted() } else { for (int i = 0; i < fileNames.size(); ++i) { parse_manual_file(fileNames[i].toUtf8().data(), - ui->ManualSeparator->currentIndex(), - ui->Units->currentIndex(), - VALUE_IF_CHECKED(DiveNumber), - VALUE_IF_CHECKED(Date), VALUE_IF_CHECKED(Time), - VALUE_IF_CHECKED(Duration), VALUE_IF_CHECKED(Location), - VALUE_IF_CHECKED(Gps), VALUE_IF_CHECKED(MaxDepth), - VALUE_IF_CHECKED(MeanDepth), VALUE_IF_CHECKED(Buddy), - VALUE_IF_CHECKED(Notes), VALUE_IF_CHECKED(Weight), - VALUE_IF_CHECKED(Tags), - &error); + ui->ManualSeparator->currentIndex(), + ui->Units->currentIndex(), + VALUE_IF_CHECKED(DiveNumber), + VALUE_IF_CHECKED(Date), VALUE_IF_CHECKED(Time), + VALUE_IF_CHECKED(Duration), VALUE_IF_CHECKED(Location), + VALUE_IF_CHECKED(Gps), VALUE_IF_CHECKED(MaxDepth), + VALUE_IF_CHECKED(MeanDepth), VALUE_IF_CHECKED(Buddy), + VALUE_IF_CHECKED(Notes), VALUE_IF_CHECKED(Weight), + VALUE_IF_CHECKED(Tags), + &error); if (error != NULL) { MainWindow::instance()->showError(error); free(error); @@ -104,8 +103,8 @@ void DiveLogImportDialog::on_buttonBox_accepted() ui->CSV->setValue(VAL);\ ui->CSV->setEnabled(VAL >= 0);\ ui->BOX->setChecked(VAL >= 0);\ - ui->CSV->blockSignals(false);\ - }) + ui->CSV->blockSignals(false); \ +}) void DiveLogImportDialog::on_knownImports_currentIndexChanged(int index) { if (specialCSV.contains(index)) { diff --git a/qt-ui/divelogimportdialog.h b/qt-ui/divelogimportdialog.h index 070a1f515..4c499b03e 100644 --- a/qt-ui/divelogimportdialog.h +++ b/qt-ui/divelogimportdialog.h @@ -6,19 +6,20 @@ #include "../dive.h" #include "../divelist.h" -namespace Ui { -class DiveLogImportDialog; +namespace Ui +{ + class DiveLogImportDialog; } -class DiveLogImportDialog : public QDialog -{ +class DiveLogImportDialog : public QDialog { Q_OBJECT public: explicit DiveLogImportDialog(QStringList *fn, QWidget *parent = 0); ~DiveLogImportDialog(); -private slots: +private +slots: void on_buttonBox_accepted(); void on_knownImports_currentIndexChanged(int index); void unknownImports(); diff --git a/qt-ui/diveplanner.cpp b/qt-ui/diveplanner.cpp index 225c05569..a4a2ba861 100644 --- a/qt-ui/diveplanner.cpp +++ b/qt-ui/diveplanner.cpp @@ -29,29 +29,28 @@ #define MAX_DEPTH M_OR_FT(150, 450) #define MIN_DEPTH M_OR_FT(20, 60) -QString gasToStr(const int o2Permille, const int hePermille) { +QString gasToStr(const int o2Permille, const int hePermille) +{ uint o2 = (o2Permille + 5) / 10, he = (hePermille + 5) / 10; - QString result = is_air(o2Permille, hePermille) ? QObject::tr("AIR") - : he == 0 ? QString("EAN%1").arg(o2, 2, 10, QChar('0')) - : QString("%1/%2").arg(o2).arg(he); + QString result = is_air(o2Permille, hePermille) ? QObject::tr("AIR") : he == 0 ? QString("EAN%1").arg(o2, 2, 10, QChar('0')) : QString("%1/%2").arg(o2).arg(he); return result; } -QString dpGasToStr(const divedatapoint& p) +QString dpGasToStr(const divedatapoint &p) { return gasToStr(p.o2, p.he); } QColor getColor(const color_indice_t i) { - if ( profile_color.count() > i && i >= 0) + if (profile_color.count() > i && i >= 0) return profile_color[i].at(0); return QColor(Qt::black); } static DivePlannerPointsModel *plannerModel = DivePlannerPointsModel::instance(); -DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent), +DivePlannerGraphics::DivePlannerGraphics(QWidget *parent) : QGraphicsView(parent), verticalLine(new QGraphicsLineItem(fromPercent(0, Qt::Horizontal), fromPercent(0, Qt::Vertical), fromPercent(0, Qt::Horizontal), fromPercent(100, Qt::Vertical))), horizontalLine(new QGraphicsLineItem(fromPercent(0, Qt::Horizontal), fromPercent(0, Qt::Vertical), fromPercent(100, Qt::Horizontal), fromPercent(0, Qt::Vertical))), activeDraggedHandler(0), @@ -62,14 +61,14 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent depthHandler(new ExpanderGraphics()), timeHandler(new ExpanderGraphics()), minMinutes(TIME_INITIAL_MAX), - minDepth(M_OR_FT(40,120)), + minDepth(M_OR_FT(40, 120)), dpMaxTime(0) { fill_profile_color(); setBackgroundBrush(profile_color[BACKGROUND].at(0)); setMouseTracking(true); setScene(new QGraphicsScene()); - scene()->setSceneRect(0,0,1920,1080); + scene()->setSceneRect(0, 0, 1920, 1080); verticalLine->setPen(QPen(Qt::DotLine)); scene()->addItem(verticalLine); @@ -82,11 +81,10 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent timeLine->setTickInterval(10); timeLine->setColor(getColor(TIME_GRID)); timeLine->setLine( - fromPercent(10, Qt::Horizontal), - fromPercent(85, Qt::Vertical), - fromPercent(90, Qt::Horizontal), - fromPercent(85, Qt::Vertical) - ); + fromPercent(10, Qt::Horizontal), + fromPercent(85, Qt::Vertical), + fromPercent(90, Qt::Horizontal), + fromPercent(85, Qt::Vertical)); timeLine->setOrientation(Qt::Horizontal); timeLine->setTickSize(fromPercent(1, Qt::Vertical)); timeLine->setTextColor(getColor(TIME_TEXT)); @@ -95,14 +93,13 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent depthLine = new Ruler(); depthLine->setMinimum(0); - depthLine->setMaximum(M_OR_FT(40,120)); - depthLine->setTickInterval(M_OR_FT(10,30)); + depthLine->setMaximum(M_OR_FT(40, 120)); + depthLine->setTickInterval(M_OR_FT(10, 30)); depthLine->setLine( - fromPercent(10, Qt::Horizontal), - fromPercent(10, Qt::Vertical), - fromPercent(10, Qt::Horizontal), - fromPercent(85, Qt::Vertical) - ); + fromPercent(10, Qt::Horizontal), + fromPercent(10, Qt::Vertical), + fromPercent(10, Qt::Horizontal), + fromPercent(85, Qt::Vertical)); depthLine->setOrientation(Qt::Vertical); depthLine->setTickSize(fromPercent(1, Qt::Horizontal)); depthLine->setColor(getColor(DEPTH_GRID)); @@ -119,7 +116,7 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent depthString->setBrush(profile_color[SAMPLE_DEEP].at(0)); scene()->addItem(depthString); - diveBg->setPen(QPen(QBrush(),0)); + diveBg->setPen(QPen(QBrush(), 0)); scene()->addItem(diveBg); QString incrText; @@ -150,12 +147,12 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent QAction *action = NULL; -#define ADD_ACTION( SHORTCUT, Slot ) \ - action = new QAction(this); \ - action->setShortcut( SHORTCUT ); \ +#define ADD_ACTION(SHORTCUT, Slot) \ + action = new QAction(this); \ + action->setShortcut(SHORTCUT); \ action->setShortcutContext(Qt::WindowShortcut); \ - addAction(action); \ - connect(action, SIGNAL(triggered(bool)), this, SLOT( Slot )) + addAction(action); \ + connect(action, SIGNAL(triggered(bool)), this, SLOT(Slot)) ADD_ACTION(Qt::Key_Escape, keyEscAction()); ADD_ACTION(Qt::Key_Delete, keyDeleteAction()); @@ -165,12 +162,12 @@ DivePlannerGraphics::DivePlannerGraphics(QWidget* parent) : QGraphicsView(parent ADD_ACTION(Qt::Key_Right, keyRightAction()); #undef ADD_ACTION - connect(plannerModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(drawProfile())); + connect(plannerModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(drawProfile())); - connect(plannerModel, SIGNAL(rowsInserted(const QModelIndex&,int,int)), - this, SLOT(pointInserted(const QModelIndex&, int, int))); - connect(plannerModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), - this, SLOT(pointsRemoved(const QModelIndex&, int, int))); + connect(plannerModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)), + this, SLOT(pointInserted(const QModelIndex &, int, int))); + connect(plannerModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), + this, SLOT(pointsRemoved(const QModelIndex &, int, int))); setRenderHint(QPainter::Antialiasing); } @@ -179,14 +176,14 @@ void DivePlannerGraphics::settingsChanged() if (depthLine->unitSystem == prefs.units.length) return; - depthLine->setTickInterval(M_OR_FT(10,30)); + depthLine->setTickInterval(M_OR_FT(10, 30)); depthLine->updateTicks(); depthLine->unitSystem = prefs.units.length; } -void DivePlannerGraphics::pointInserted(const QModelIndex& parent, int start , int end) +void DivePlannerGraphics::pointInserted(const QModelIndex &parent, int start, int end) { - DiveHandler *item = new DiveHandler (); + DiveHandler *item = new DiveHandler(); scene()->addItem(item); handles << item; @@ -200,14 +197,14 @@ void DivePlannerGraphics::pointInserted(const QModelIndex& parent, int start , i void DivePlannerGraphics::keyDownAction() { - Q_FOREACH(QGraphicsItem *i, scene()->selectedItems()) { - if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler*>(i)) { + Q_FOREACH(QGraphicsItem * i, scene()->selectedItems()) { + if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler *>(i)) { int row = handles.indexOf(handler); divedatapoint dp = plannerModel->at(row); if (dp.depth >= depthLine->maximum()) continue; - dp.depth += M_OR_FT(1,5); + dp.depth += M_OR_FT(1, 5); plannerModel->editStop(row, dp); } } @@ -215,15 +212,15 @@ void DivePlannerGraphics::keyDownAction() void DivePlannerGraphics::keyUpAction() { - Q_FOREACH(QGraphicsItem *i, scene()->selectedItems()) { - if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler*>(i)) { + Q_FOREACH(QGraphicsItem * i, scene()->selectedItems()) { + if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler *>(i)) { int row = handles.indexOf(handler); divedatapoint dp = plannerModel->at(row); if (dp.depth <= 0) continue; - dp.depth -= M_OR_FT(1,5); + dp.depth -= M_OR_FT(1, 5); plannerModel->editStop(row, dp); } } @@ -232,8 +229,8 @@ void DivePlannerGraphics::keyUpAction() void DivePlannerGraphics::keyLeftAction() { - Q_FOREACH(QGraphicsItem *i, scene()->selectedItems()) { - if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler*>(i)) { + Q_FOREACH(QGraphicsItem * i, scene()->selectedItems()) { + if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler *>(i)) { int row = handles.indexOf(handler); divedatapoint dp = plannerModel->at(row); @@ -244,7 +241,7 @@ void DivePlannerGraphics::keyLeftAction() // maybe this is a good place for a 'goto'? double xpos = timeLine->posAtValue((dp.time - 60) / 60); bool nextStep = false; - Q_FOREACH(DiveHandler *h, handles) { + Q_FOREACH(DiveHandler * h, handles) { if (IS_FP_SAME(h->pos().x(), xpos)) { nextStep = true; break; @@ -261,8 +258,8 @@ void DivePlannerGraphics::keyLeftAction() void DivePlannerGraphics::keyRightAction() { - Q_FOREACH(QGraphicsItem *i, scene()->selectedItems()) { - if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler*>(i)) { + Q_FOREACH(QGraphicsItem * i, scene()->selectedItems()) { + if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler *>(i)) { int row = handles.indexOf(handler); divedatapoint dp = plannerModel->at(row); if (dp.time / 60 >= timeLine->maximum()) @@ -272,7 +269,7 @@ void DivePlannerGraphics::keyRightAction() // maybe this is a good place for a 'goto'? double xpos = timeLine->posAtValue((dp.time + 60) / 60); bool nextStep = false; - Q_FOREACH(DiveHandler *h, handles) { + Q_FOREACH(DiveHandler * h, handles) { if (IS_FP_SAME(h->pos().x(), xpos)) { nextStep = true; break; @@ -292,8 +289,8 @@ void DivePlannerGraphics::keyDeleteAction() int selCount = scene()->selectedItems().count(); if (selCount) { QVector<int> selectedIndexes; - Q_FOREACH(QGraphicsItem *i, scene()->selectedItems()) { - if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler*>(i)) { + Q_FOREACH(QGraphicsItem * i, scene()->selectedItems()) { + if (DiveHandler *handler = qgraphicsitem_cast<DiveHandler *>(i)) { selectedIndexes.push_back(handles.indexOf(handler)); } } @@ -301,10 +298,10 @@ void DivePlannerGraphics::keyDeleteAction() } } -void DivePlannerGraphics::pointsRemoved(const QModelIndex& , int start, int end) -{ // start and end are inclusive. +void DivePlannerGraphics::pointsRemoved(const QModelIndex &, int start, int end) +{ // start and end are inclusive. int num = (end - start) + 1; - for(int i = num; i != 0; i--) { + for (int i = num; i != 0; i--) { delete handles.back(); handles.pop_back(); delete gases.back(); @@ -314,16 +311,17 @@ void DivePlannerGraphics::pointsRemoved(const QModelIndex& , int start, int end) drawProfile(); } -bool intLessThan(int a, int b) { +bool intLessThan(int a, int b) +{ return a <= b; } -void DivePlannerPointsModel::removeSelectedPoints(const QVector< int >& rows) +void DivePlannerPointsModel::removeSelectedPoints(const QVector<int> &rows) { int firstRow = rowCount() - rows.count(); QVector<int> v2 = rows; std::sort(v2.begin(), v2.end(), intLessThan); - beginRemoveRows(QModelIndex(), firstRow, rowCount()-1); - for(int i = v2.count()-1; i >= 0; i--) { + beginRemoveRows(QModelIndex(), firstRow, rowCount() - 1); + for (int i = v2.count() - 1; i >= 0; i--) { divepoints.remove(v2[i]); } endRemoveRows(); @@ -348,10 +346,10 @@ qreal DivePlannerGraphics::fromPercent(qreal percent, Qt::Orientation orientatio void DivePlannerGraphics::increaseDepth() { - if (depthLine->maximum() + M_OR_FT(10,30) > MAX_DEPTH) + if (depthLine->maximum() + M_OR_FT(10, 30) > MAX_DEPTH) return; - minDepth += M_OR_FT(10,30); - depthLine->setMaximum( minDepth ); + minDepth += M_OR_FT(10, 30); + depthLine->setMaximum(minDepth); depthLine->updateTicks(); drawProfile(); } @@ -359,27 +357,27 @@ void DivePlannerGraphics::increaseDepth() void DivePlannerGraphics::increaseTime() { minMinutes += 10; - timeLine->setMaximum( minMinutes ); + timeLine->setMaximum(minMinutes); timeLine->updateTicks(); drawProfile(); } void DivePlannerGraphics::decreaseDepth() { - if (depthLine->maximum() - M_OR_FT(10,30) < MIN_DEPTH) + if (depthLine->maximum() - M_OR_FT(10, 30) < MIN_DEPTH) return; - Q_FOREACH(DiveHandler *d, handles) { - if (depthLine->valueAt(d->pos()) > depthLine->maximum() - M_OR_FT(10,30)) { + Q_FOREACH(DiveHandler * d, handles) { + if (depthLine->valueAt(d->pos()) > depthLine->maximum() - M_OR_FT(10, 30)) { QMessageBox::warning(MainWindow::instance(), - tr("Handler Position Error"), - tr("One or more of your stops will be lost with this operations, \n" - "Please, remove them first.")); + tr("Handler Position Error"), + tr("One or more of your stops will be lost with this operations, \n" + "Please, remove them first.")); return; } } - minDepth -= M_OR_FT(10,30); - depthLine->setMaximum( minDepth ); + minDepth -= M_OR_FT(10, 30); + depthLine->setMaximum(minDepth); depthLine->updateTicks(); drawProfile(); } @@ -395,27 +393,27 @@ void DivePlannerGraphics::decreaseTime() drawProfile(); } -void DivePlannerGraphics::mouseDoubleClickEvent(QMouseEvent* event) +void DivePlannerGraphics::mouseDoubleClickEvent(QMouseEvent *event) { QPointF mappedPos = mapToScene(event->pos()); if (isPointOutOfBoundaries(mappedPos)) return; int minutes = rint(timeLine->valueAt(mappedPos)); - int milimeters = rint(depthLine->valueAt(mappedPos) / M_OR_FT(1,1)) * M_OR_FT(1,1); + int milimeters = rint(depthLine->valueAt(mappedPos) / M_OR_FT(1, 1)) * M_OR_FT(1, 1); plannerModel->addStop(milimeters, minutes * 60, -1, 0, 0); } void DivePlannerPointsModel::createSimpleDive() { -// plannerModel->addStop(0, 0, O2_IN_AIR, 0, 0); - plannerModel->addStop(M_OR_FT(15,45), 1 * 60, O2_IN_AIR, 0, 0); - plannerModel->addStop(M_OR_FT(15,45), 40 * 60, O2_IN_AIR, 0, 0); - plannerModel->addStop(M_OR_FT(5,15), 42 * 60, O2_IN_AIR, 0, 0); - plannerModel->addStop(M_OR_FT(5,15), 45 * 60, O2_IN_AIR, 0, 0); + // plannerModel->addStop(0, 0, O2_IN_AIR, 0, 0); + plannerModel->addStop(M_OR_FT(15, 45), 1 * 60, O2_IN_AIR, 0, 0); + plannerModel->addStop(M_OR_FT(15, 45), 40 * 60, O2_IN_AIR, 0, 0); + plannerModel->addStop(M_OR_FT(5, 15), 42 * 60, O2_IN_AIR, 0, 0); + plannerModel->addStop(M_OR_FT(5, 15), 45 * 60, O2_IN_AIR, 0, 0); } -void DivePlannerPointsModel::loadFromDive(dive* d) +void DivePlannerPointsModel::loadFromDive(dive *d) { // We need to make a copy, because as soon as the model is modified, it will // remove all samples from the dive. @@ -448,7 +446,7 @@ void DivePlannerPointsModel::copyCylinders(dive *d) copy_cylinders(stagingDive, d); } -QStringList& DivePlannerPointsModel::getGasList() +QStringList &DivePlannerPointsModel::getGasList() { struct dive *activeDive = isPlanner() ? stagingDive : current_dive; static QStringList list; @@ -480,7 +478,7 @@ void DivePlannerGraphics::drawProfile() plannerModel->deleteTemporaryPlan(); return; } - while(dp->next) { + while (dp->next) { if (dp->depth > max_depth) max_depth = dp->depth; dp = dp->next; @@ -491,8 +489,8 @@ void DivePlannerGraphics::drawProfile() timeLine->setMaximum(minMinutes); timeLine->updateTicks(); } - if (!activeDraggedHandler && (depthLine->maximum() < max_depth + M_OR_FT(10,30) || max_depth + M_OR_FT(10,30) < depthLine->maximum())) { - minDepth = fmax(max_depth + M_OR_FT(10,30), minDepth); + if (!activeDraggedHandler && (depthLine->maximum() < max_depth + M_OR_FT(10, 30) || max_depth + M_OR_FT(10, 30) < depthLine->maximum())) { + minDepth = fmax(max_depth + M_OR_FT(10, 30), minDepth); depthLine->setMaximum(minDepth); depthLine->updateTicks(); } @@ -505,7 +503,7 @@ void DivePlannerGraphics::drawProfile() continue; DiveHandler *h = handles.at(i); h->setPos(timeLine->posAtValue(datapoint.time / 60), depthLine->posAtValue(datapoint.depth)); - QPointF p1 = (last == i) ? QPointF(timeLine->posAtValue(0), depthLine->posAtValue(0)) : handles[last]->pos(); + QPointF p1 = (last == i) ? QPointF(timeLine->posAtValue(0), depthLine->posAtValue(0)) : handles[last]->pos(); QPointF p2 = handles[i]->pos(); QLineF line(p1, p2); QPointF pos = line.pointAt(0.5); @@ -529,7 +527,7 @@ void DivePlannerGraphics::drawProfile() double ypos = depthLine->posAtValue(dp->depth); if (!dp->entered) { QGraphicsLineItem *item = new QGraphicsLineItem(lastx, lasty, xpos, ypos); - item->setPen(QPen(QBrush(Qt::red),0)); + item->setPen(QPen(QBrush(Qt::red), 0)); scene()->addItem(item); lines << item; } @@ -541,11 +539,10 @@ void DivePlannerGraphics::drawProfile() diveBg->setPolygon(poly); QRectF b = poly.boundingRect(); QLinearGradient pat( - b.x(), - b.y(), - b.x(), - b.height() + b.y() - ); + b.x(), + b.y(), + b.x(), + b.height() + b.y()); pat.setColorAt(1, profile_color[DEPTH_BOTTOM].first()); pat.setColorAt(0, profile_color[DEPTH_TOP].first()); @@ -554,19 +551,19 @@ void DivePlannerGraphics::drawProfile() plannerModel->deleteTemporaryPlan(); } -void DivePlannerGraphics::resizeEvent(QResizeEvent* event) +void DivePlannerGraphics::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); fitInView(sceneRect(), Qt::IgnoreAspectRatio); } -void DivePlannerGraphics::showEvent(QShowEvent* event) +void DivePlannerGraphics::showEvent(QShowEvent *event) { QGraphicsView::showEvent(event); fitInView(sceneRect(), Qt::IgnoreAspectRatio); } -void DivePlannerGraphics::mouseMoveEvent(QMouseEvent* event) +void DivePlannerGraphics::mouseMoveEvent(QMouseEvent *event) { QPointF mappedPos = mapToScene(event->pos()); @@ -574,19 +571,15 @@ void DivePlannerGraphics::mouseMoveEvent(QMouseEvent* event) double xpos = timeLine->valueAt(mappedPos); double ypos = depthLine->valueAt(mappedPos); - xpos = (xpos > timeLine->maximum()) ? timeLine->posAtValue(timeLine->maximum()) - : (xpos < timeLine->minimum()) ? timeLine->posAtValue(timeLine->minimum()) - : timeLine->posAtValue(xpos); + xpos = (xpos > timeLine->maximum()) ? timeLine->posAtValue(timeLine->maximum()) : (xpos < timeLine->minimum()) ? timeLine->posAtValue(timeLine->minimum()) : timeLine->posAtValue(xpos); - ypos = (ypos > depthLine->maximum()) ? depthLine->posAtValue(depthLine->maximum()) - : ( ypos < depthLine->minimum()) ? depthLine->posAtValue(depthLine->minimum()) - : depthLine->posAtValue(ypos); + ypos = (ypos > depthLine->maximum()) ? depthLine->posAtValue(depthLine->maximum()) : (ypos < depthLine->minimum()) ? depthLine->posAtValue(depthLine->minimum()) : depthLine->posAtValue(ypos); verticalLine->setPos(xpos, fromPercent(0, Qt::Vertical)); horizontalLine->setPos(fromPercent(0, Qt::Horizontal), ypos); depthString->setPos(fromPercent(1, Qt::Horizontal), ypos); - timeString->setPos(xpos+1, fromPercent(95, Qt::Vertical)); + timeString->setPos(xpos + 1, fromPercent(95, Qt::Vertical)); if (isPointOutOfBoundaries(mappedPos)) return; @@ -597,12 +590,12 @@ void DivePlannerGraphics::mouseMoveEvent(QMouseEvent* event) // calculate the correct color for the depthString. // QGradient doesn't returns it's interpolation, meh. double percent = depthLine->percentAt(mappedPos); - QColor& startColor = profile_color[SAMPLE_SHALLOW].first(); - QColor& endColor = profile_color[SAMPLE_DEEP].first(); + QColor &startColor = profile_color[SAMPLE_SHALLOW].first(); + QColor &endColor = profile_color[SAMPLE_DEEP].first(); short redDelta = (endColor.red() - startColor.red()) * percent + startColor.red(); short greenDelta = (endColor.green() - startColor.green()) * percent + startColor.green(); short blueDelta = (endColor.blue() - startColor.blue()) * percent + startColor.blue(); - depthString->setBrush( QColor(redDelta, greenDelta, blueDelta)); + depthString->setBrush(QColor(redDelta, greenDelta, blueDelta)); if (activeDraggedHandler) moveActiveHandler(mappedPos, handles.indexOf(activeDraggedHandler)); @@ -618,7 +611,7 @@ void DivePlannerGraphics::mouseMoveEvent(QMouseEvent* event) } } -void DivePlannerGraphics::moveActiveHandler(const QPointF& mappedPos, const int pos) +void DivePlannerGraphics::moveActiveHandler(const QPointF &mappedPos, const int pos) { divedatapoint data = plannerModel->at(pos); int mintime = 0, maxtime = (timeLine->maximum() + 10) * 60; @@ -631,7 +624,7 @@ void DivePlannerGraphics::moveActiveHandler(const QPointF& mappedPos, const int if (minutes * 60 <= mintime || minutes * 60 >= maxtime) return; - int milimeters = rint(depthLine->valueAt(mappedPos) / M_OR_FT(1,1)) * M_OR_FT(1,1); + int milimeters = rint(depthLine->valueAt(mappedPos) / M_OR_FT(1, 1)) * M_OR_FT(1, 1); double xpos = timeLine->posAtValue(minutes); double ypos = depthLine->posAtValue(milimeters); @@ -646,7 +639,7 @@ void DivePlannerGraphics::moveActiveHandler(const QPointF& mappedPos, const int drawProfile(); } -bool DivePlannerGraphics::isPointOutOfBoundaries(const QPointF& point) +bool DivePlannerGraphics::isPointOutOfBoundaries(const QPointF &point) { double xpos = timeLine->valueAt(point); double ypos = depthLine->valueAt(point); @@ -660,7 +653,7 @@ bool DivePlannerGraphics::isPointOutOfBoundaries(const QPointF& point) return false; } -void DivePlannerGraphics::mousePressEvent(QMouseEvent* event) +void DivePlannerGraphics::mousePressEvent(QMouseEvent *event) { if (event->modifiers()) { QGraphicsView::mousePressEvent(event); @@ -669,8 +662,8 @@ void DivePlannerGraphics::mousePressEvent(QMouseEvent* event) QPointF mappedPos = mapToScene(event->pos()); if (event->button() == Qt::LeftButton) { - Q_FOREACH(QGraphicsItem *item, scene()->items(mappedPos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder, transform())) { - if (DiveHandler *h = qgraphicsitem_cast<DiveHandler*>(item)) { + Q_FOREACH(QGraphicsItem * item, scene()->items(mappedPos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder, transform())) { + if (DiveHandler *h = qgraphicsitem_cast<DiveHandler *>(item)) { activeDraggedHandler = h; activeDraggedHandler->setBrush(Qt::red); originalHandlerPos = activeDraggedHandler->pos(); @@ -680,7 +673,7 @@ void DivePlannerGraphics::mousePressEvent(QMouseEvent* event) QGraphicsView::mousePressEvent(event); } -void DivePlannerGraphics::mouseReleaseEvent(QMouseEvent* event) +void DivePlannerGraphics::mouseReleaseEvent(QMouseEvent *event) { if (activeDraggedHandler) { /* we already deal with all the positioning in the life update, @@ -691,9 +684,9 @@ void DivePlannerGraphics::mouseReleaseEvent(QMouseEvent* event) } } -DiveHandler::DiveHandler(): QGraphicsEllipseItem() +DiveHandler::DiveHandler() : QGraphicsEllipseItem() { - setRect(-5,-5,10,10); + setRect(-5, -5, 10, 10); setFlag(QGraphicsItem::ItemIgnoresTransformations); setFlag(QGraphicsItem::ItemIsSelectable); setBrush(Qt::white); @@ -702,19 +695,19 @@ DiveHandler::DiveHandler(): QGraphicsEllipseItem() int DiveHandler::parentIndex() { - DivePlannerGraphics *view = qobject_cast<DivePlannerGraphics*>(scene()->views().first()); + DivePlannerGraphics *view = qobject_cast<DivePlannerGraphics *>(scene()->views().first()); return view->handles.indexOf(this); } -void DiveHandler::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) +void DiveHandler::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { QMenu m; GasSelectionModel *model = GasSelectionModel::instance(); model->repopulate(); int rowCount = model->rowCount(); - for(int i = 0; i < rowCount; i++) { + for (int i = 0; i < rowCount; i++) { QAction *action = new QAction(&m); - action->setText( model->data(model->index(i, 0),Qt::DisplayRole).toString()); + action->setText(model->data(model->index(i, 0), Qt::DisplayRole).toString()); connect(action, SIGNAL(triggered(bool)), this, SLOT(changeGas())); m.addAction(action); } @@ -726,18 +719,18 @@ void DiveHandler::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) void DiveHandler::selfRemove() { setSelected(true); - DivePlannerGraphics *view = qobject_cast<DivePlannerGraphics*>(scene()->views().first()); + DivePlannerGraphics *view = qobject_cast<DivePlannerGraphics *>(scene()->views().first()); view->keyDeleteAction(); } void DiveHandler::changeGas() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); QModelIndex index = plannerModel->index(parentIndex(), DivePlannerPointsModel::GAS); plannerModel->setData(index, action->text()); } -void DiveHandler::mousePressEvent(QGraphicsSceneMouseEvent* event) +void DiveHandler::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() != Qt::LeftButton) return; @@ -764,7 +757,7 @@ void Ruler::setMinimum(double minimum) min = minimum; } -void Ruler::setTextColor(const QColor& color) +void Ruler::setTextColor(const QColor &color) { textColor = color; } @@ -821,7 +814,7 @@ void Ruler::updateTicks() label = new QGraphicsSimpleTextItem(QString::number(currValue), this); label->setBrush(QBrush(textColor)); label->setFlag(ItemIgnoresTransformations); - label->setPos(pos - label->boundingRect().width()/2, m.y1() + tickSize + 5); + label->setPos(pos - label->boundingRect().width() / 2, m.y1() + tickSize + 5); labels.push_back(label); } } else { @@ -850,12 +843,12 @@ void Ruler::setTickInterval(double i) interval = i; } -qreal Ruler::valueAt(const QPointF& p) +qreal Ruler::valueAt(const QPointF &p) { QLineF m = line(); - double retValue = orientation == Qt::Horizontal ? - max * (p.x() - m.x1()) / (m.x2() - m.x1()) : - max * (p.y() - m.y1()) / (m.y2() - m.y1()); + double retValue = orientation == Qt::Horizontal ? + max * (p.x() - m.x1()) / (m.x2() - m.x1()) : + max * (p.y() - m.y1()) / (m.y2() - m.y1()); return retValue; } @@ -865,16 +858,16 @@ qreal Ruler::posAtValue(qreal value) double size = max - min; double percent = value / size; double realSize = orientation == Qt::Horizontal ? - m.x2() - m.x1() : - m.y2() - m.y1(); + m.x2() - m.x1() : + m.y2() - m.y1(); double retValue = realSize * percent; - retValue = (orientation == Qt::Horizontal) ? - retValue + m.x1() : - retValue + m.y1(); + retValue = (orientation == Qt::Horizontal) ? + retValue + m.x1() : + retValue + m.y1(); return retValue; } -qreal Ruler::percentAt(const QPointF& p) +qreal Ruler::percentAt(const QPointF &p) { qreal value = valueAt(p); double size = max - min; @@ -892,7 +885,7 @@ double Ruler::minimum() const return min; } -void Ruler::setColor(const QColor& color) +void Ruler::setColor(const QColor &color) { QPen defaultPen(color); defaultPen.setJoinStyle(Qt::RoundJoin); @@ -902,18 +895,18 @@ void Ruler::setColor(const QColor& color) setPen(defaultPen); } -Button::Button(QObject* parent, QGraphicsItem *itemParent) : QObject(parent), +Button::Button(QObject *parent, QGraphicsItem *itemParent) : QObject(parent), QGraphicsRectItem(itemParent), icon(new QGraphicsPixmapItem(this)), text(new QGraphicsSimpleTextItem(this)) { - icon->setPos(0,0); - text->setPos(0,0); + icon->setPos(0, 0); + text->setPos(0, 0); setFlag(ItemIgnoresTransformations); setPen(QPen(QBrush(), 0)); } -void Button::setPixmap(const QPixmap& pixmap) +void Button::setPixmap(const QPixmap &pixmap) { icon->setPixmap(pixmap); if (pixmap.isNull()) @@ -924,26 +917,26 @@ void Button::setPixmap(const QPixmap& pixmap) setRect(childrenBoundingRect()); } -void Button::setText(const QString& t) +void Button::setText(const QString &t) { text->setText(t); if (icon->pixmap().isNull()) { icon->hide(); - text->setPos(0,0); + text->setPos(0, 0); } else { icon->show(); - text->setPos(22,0); + text->setPos(22, 0); } setRect(childrenBoundingRect()); } -void Button::mousePressEvent(QGraphicsSceneMouseEvent* event) +void Button::mousePressEvent(QGraphicsSceneMouseEvent *event) { event->ignore(); emit clicked(); } -DivePlannerWidget::DivePlannerWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) +DivePlannerWidget::DivePlannerWidget(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f) { ui.setupUi(this); ui.tableWidget->setTitle(tr("Dive Planner Points")); @@ -960,11 +953,11 @@ DivePlannerWidget::DivePlannerWidget(QWidget* parent, Qt::WindowFlags f): QWidge connect(ui.cylinderTableWidget, SIGNAL(addButtonClicked()), DivePlannerPointsModel::instance(), SLOT(addCylinder_clicked())); connect(ui.tableWidget, SIGNAL(addButtonClicked()), DivePlannerPointsModel::instance(), SLOT(addStop())); - connect(CylindersModel::instance(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + connect(CylindersModel::instance(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), GasSelectionModel::instance(), SLOT(repopulate())); - connect(CylindersModel::instance(), SIGNAL(rowsInserted(QModelIndex,int,int)), + connect(CylindersModel::instance(), SIGNAL(rowsInserted(QModelIndex, int, int)), GasSelectionModel::instance(), SLOT(repopulate())); - connect(CylindersModel::instance(), SIGNAL(rowsRemoved(QModelIndex,int,int)), + connect(CylindersModel::instance(), SIGNAL(rowsRemoved(QModelIndex, int, int)), GasSelectionModel::instance(), SLOT(repopulate())); ui.tableWidget->setBtnToolTip(tr("add dive data point")); @@ -984,8 +977,8 @@ DivePlannerWidget::DivePlannerWidget(QWidget* parent, Qt::WindowFlags f): QWidge connect(plannerModel, SIGNAL(planCanceled()), MainWindow::instance(), SLOT(showProfile())); /* set defaults. */ - ui.startTime->setTime( QTime(1, 0) ); - ui.ATMPressure->setText( "1013" ); + ui.startTime->setTime(QTime(1, 0)); + ui.ATMPressure->setText("1013"); ui.bottomSAC->setText("20"); ui.decoStopSAC->setText("17"); ui.gflow->setValue(prefs.gflow); @@ -1006,17 +999,17 @@ void DivePlannerPointsModel::addCylinder_clicked() CylindersModel::instance()->add(); } -void DivePlannerWidget::atmPressureChanged(const QString& pressure) +void DivePlannerWidget::atmPressureChanged(const QString &pressure) { plannerModel->setSurfacePressure(pressure.toInt()); } -void DivePlannerWidget::bottomSacChanged(const QString& bottomSac) +void DivePlannerWidget::bottomSacChanged(const QString &bottomSac) { plannerModel->setBottomSac(bottomSac.toInt()); } -void DivePlannerWidget::decoSacChanged(const QString& decosac) +void DivePlannerWidget::decoSacChanged(const QString &decosac) { plannerModel->setDecoSac(decosac.toInt()); } @@ -1031,47 +1024,55 @@ bool DivePlannerPointsModel::isPlanner() return mode == PLAN; } -int DivePlannerPointsModel::columnCount(const QModelIndex& parent) const +int DivePlannerPointsModel::columnCount(const QModelIndex &parent) const { return COLUMNS; } -QVariant DivePlannerPointsModel::data(const QModelIndex& index, int role) const +QVariant DivePlannerPointsModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { divedatapoint p = divepoints.at(index.row()); switch (index.column()) { - case CCSETPOINT: return (double) p.po2 / 1000; - case DEPTH: return rint(get_depth_units(p.depth, NULL, NULL)); - case DURATION: return p.time / 60; - case GAS: return dpGasToStr(p); + case CCSETPOINT: + return (double)p.po2 / 1000; + case DEPTH: + return rint(get_depth_units(p.depth, NULL, NULL)); + case DURATION: + return p.time / 60; + case GAS: + return dpGasToStr(p); } } else if (role == Qt::DecorationRole) { switch (index.column()) { - case REMOVE : return QIcon(":trash"); + case REMOVE: + return QIcon(":trash"); } } else if (role == Qt::FontRole) { - return defaultModelFont(); + return defaultModelFont(); } return QVariant(); } -bool DivePlannerPointsModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool DivePlannerPointsModel::setData(const QModelIndex &index, const QVariant &value, int role) { int o2 = 0; int he = 0; if (role == Qt::EditRole) { - divedatapoint& p = divepoints[index.row()]; + divedatapoint &p = divepoints[index.row()]; switch (index.column()) { - case DEPTH: p.depth = units_to_depth(value.toInt()); break; - case DURATION: p.time = value.toInt() * 60; break; + case DEPTH: + p.depth = units_to_depth(value.toInt()); + break; + case DURATION: + p.time = value.toInt() * 60; + break; case CCSETPOINT: { int po2 = 0; QByteArray gasv = value.toByteArray(); if (validate_po2(gasv.data(), &po2)) p.po2 = po2; - } - break; + } break; case GAS: QByteArray gasv = value.toByteArray(); if (validate_gas(gasv.data(), &o2, &he)) { @@ -1089,34 +1090,38 @@ QVariant DivePlannerPointsModel::headerData(int section, Qt::Orientation orienta { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { - case DEPTH: return tr("Final Depth"); - case DURATION: return tr("Duration"); - case GAS: return tr("Used Gas"); - case CCSETPOINT: return tr("CC Set Point"); + case DEPTH: + return tr("Final Depth"); + case DURATION: + return tr("Duration"); + case GAS: + return tr("Used Gas"); + case CCSETPOINT: + return tr("CC Set Point"); } } else if (role == Qt::FontRole) { - return defaultModelFont(); + return defaultModelFont(); } return QVariant(); } -Qt::ItemFlags DivePlannerPointsModel::flags(const QModelIndex& index) const +Qt::ItemFlags DivePlannerPointsModel::flags(const QModelIndex &index) const { - return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; + return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } -int DivePlannerPointsModel::rowCount(const QModelIndex& parent) const +int DivePlannerPointsModel::rowCount(const QModelIndex &parent) const { return divepoints.count(); } -DivePlannerPointsModel::DivePlannerPointsModel(QObject* parent): QAbstractTableModel(parent), mode(NOTHING), tempDive(NULL), stagingDive(NULL) +DivePlannerPointsModel::DivePlannerPointsModel(QObject *parent) : QAbstractTableModel(parent), mode(NOTHING), tempDive(NULL), stagingDive(NULL) { memset(&diveplan, 0, sizeof(diveplan)); memset(&backupDive, 0, sizeof(backupDive)); } -DivePlannerPointsModel* DivePlannerPointsModel::instance() +DivePlannerPointsModel *DivePlannerPointsModel::instance() { static QScopedPointer<DivePlannerPointsModel> self(new DivePlannerPointsModel()); return self.data(); @@ -1125,46 +1130,46 @@ DivePlannerPointsModel* DivePlannerPointsModel::instance() void DivePlannerPointsModel::setBottomSac(int sac) { diveplan.bottomsac = sac; - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::setDecoSac(int sac) { diveplan.decosac = sac; - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::setGFHigh(const int gfhigh) { diveplan.gfhigh = gfhigh; - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::setGFLow(const int ghflow) { diveplan.gflow = ghflow; - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::setSurfacePressure(int pressure) { diveplan.surface_pressure = pressure; - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::setLastStop6m(bool value) { set_last_stop(value); - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } -void DivePlannerPointsModel::setStartTime(const QTime& t) +void DivePlannerPointsModel::setStartTime(const QTime &t) { diveplan.when = (t.msec() + QDateTime::currentMSecsSinceEpoch()) / 1000 - gettimezoneoffset(); - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } -bool divePointsLessThan(const divedatapoint& p1, const divedatapoint& p2) +bool divePointsLessThan(const divedatapoint &p1, const divedatapoint &p2) { return p1.time <= p2.time; } @@ -1195,7 +1200,7 @@ int DivePlannerPointsModel::addStop(int milimeters, int seconds, int o2, int he, int row = divepoints.count(); if (seconds == 0 && milimeters == 0 && row != 0) { /* this is only possible if the user clicked on the 'plus' sign on the DivePoints Table */ - struct divedatapoint& t = divepoints.last(); + struct divedatapoint &t = divepoints.last(); milimeters = t.depth; seconds = t.time + 600; // 10 minutes. o2 = t.o2; @@ -1203,7 +1208,7 @@ int DivePlannerPointsModel::addStop(int milimeters, int seconds, int o2, int he, ccpoint = t.po2; } else if (seconds == 0 && milimeters == 0 && row == 0) { milimeters = M_OR_FT(5, 15); // 5m / 15ft - seconds = 600; // 10 min + seconds = 600; // 10 min //Default to the first defined gas, if we got one. cylinder_t *cyl = &stagingDive->cylinder[0]; if (cyl) { @@ -1217,7 +1222,7 @@ int DivePlannerPointsModel::addStop(int milimeters, int seconds, int o2, int he, // check if there's already a new stop before this one: for (int i = 0; i < row; i++) { - const divedatapoint& dp = divepoints.at(i); + const divedatapoint &dp = divepoints.at(i); if (dp.time == seconds) { row = i; beginRemoveRows(QModelIndex(), row, row); @@ -1225,7 +1230,7 @@ int DivePlannerPointsModel::addStop(int milimeters, int seconds, int o2, int he, endRemoveRows(); break; } - if (dp.time > seconds ) { + if (dp.time > seconds) { row = i; break; } @@ -1257,7 +1262,7 @@ int DivePlannerPointsModel::addStop(int milimeters, int seconds, int o2, int he, point.o2 = o2; point.he = he; point.po2 = ccpoint; - divepoints.append( point ); + divepoints.append(point); std::sort(divepoints.begin(), divepoints.end(), divePointsLessThan); endInsertRows(); return row; @@ -1267,7 +1272,7 @@ void DivePlannerPointsModel::editStop(int row, divedatapoint newData) { divepoints[row] = newData; std::sort(divepoints.begin(), divepoints.end(), divePointsLessThan); - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } int DivePlannerPointsModel::size() @@ -1280,7 +1285,7 @@ divedatapoint DivePlannerPointsModel::at(int row) return divepoints.at(row); } -void DivePlannerPointsModel::remove(const QModelIndex& index) +void DivePlannerPointsModel::remove(const QModelIndex &index) { if (index.column() != REMOVE) return; @@ -1299,8 +1304,8 @@ void DivePlannerPointsModel::cancelPlan() { if (mode == PLAN && rowCount()) { if (QMessageBox::warning(MainWindow::instance(), TITLE_OR_TEXT(tr("Discard the Plan?"), - tr("You are about to discard your plan.")), - QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Discard) != QMessageBox::Discard) { + tr("You are about to discard your plan.")), + QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Discard) != QMessageBox::Discard) { return; } } @@ -1337,7 +1342,7 @@ void DivePlannerPointsModel::rememberTanks() bool DivePlannerPointsModel::tankInUse(int o2, int he) { for (int j = 0; j < rowCount(); j++) { - divedatapoint& p = divepoints[j]; + divedatapoint &p = divepoints[j]; if (p.time == 0) // special entries that hold the available gases continue; if ((p.o2 == o2 && p.he == he) || @@ -1353,7 +1358,7 @@ void DivePlannerPointsModel::tanksUpdated() // "did a gas change on us". So we look through the diveplan to // see if there is a gas that is now missing and if there is, we // replace it with the matching new gas. - QVector<QPair<int,int> > gases = collectGases(stagingDive); + QVector<QPair<int, int> > gases = collectGases(stagingDive); if (gases.count() == oldGases.count()) { // either nothing relevant changed, or exactly ONE gasmix changed for (int i = 0; i < gases.count(); i++) { @@ -1364,7 +1369,7 @@ void DivePlannerPointsModel::tanksUpdated() break; } for (int j = 0; j < rowCount(); j++) { - divedatapoint& p = divepoints[j]; + divedatapoint &p = divepoints[j]; int o2 = oldGases.at(i).first; int he = oldGases.at(i).second; if ((p.o2 == o2 && p.he == he) || @@ -1377,7 +1382,7 @@ void DivePlannerPointsModel::tanksUpdated() } } } - emit dataChanged(createIndex(0, 0), createIndex(rowCount()-1, COLUMNS-1)); + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, COLUMNS - 1)); } void DivePlannerPointsModel::clear() @@ -1478,13 +1483,13 @@ void DivePlannerPointsModel::createPlan() int mean[MAX_CYLINDERS], duration[MAX_CYLINDERS]; per_cylinder_mean_depth(tempDive, select_dc(&tempDive->dc), mean, duration); for (int i = 0; i < MAX_CYLINDERS; i++) { - cylinder_t *cyl = tempDive->cylinder+i; + cylinder_t *cyl = tempDive->cylinder + i; if (cylinder_none(cyl)) continue; // FIXME: The epic assumption that all the cylinders after the first is deco int sac = i ? diveplan.decosac : diveplan.bottomsac; cyl->start.mbar = cyl->type.workingpressure.mbar; - int consumption = ((depth_to_mbar(mean[i], tempDive) * duration[i] / 60) * sac) / ( cyl->type.size.mliter / 1000); + int consumption = ((depth_to_mbar(mean[i], tempDive) * duration[i] / 60) * sac) / (cyl->type.size.mliter / 1000); cyl->end.mbar = cyl->start.mbar - consumption; } @@ -1502,7 +1507,7 @@ void DivePlannerPointsModel::createPlan() CylindersModel::instance()->update(); } -ExpanderGraphics::ExpanderGraphics(QGraphicsItem* parent) : QGraphicsRectItem(parent), +ExpanderGraphics::ExpanderGraphics(QGraphicsItem *parent) : QGraphicsRectItem(parent), icon(new QGraphicsPixmapItem(this)), increaseBtn(new Button(0, this)), decreaseBtn(new Button(0, this)), @@ -1511,15 +1516,15 @@ ExpanderGraphics::ExpanderGraphics(QGraphicsItem* parent) : QGraphicsRectItem(pa rightWing(new QGraphicsPixmapItem(this)) { QPixmap p; - #define CREATE(item, pixmap) \ - p = QPixmap(QString( pixmap ));\ - item->setPixmap(p); \ +#define CREATE(item, pixmap) \ + p = QPixmap(QString(pixmap)); \ + item->setPixmap(p); CREATE(icon, ":icon_time"); CREATE(bg, ":round_base"); CREATE(leftWing, ":left_wing"); CREATE(rightWing, ":right_wing"); - #undef CREATE +#undef CREATE decreaseBtn->setPixmap(QPixmap(":arrow_down")); increaseBtn->setPixmap(QPixmap(":arrow_up")); @@ -1529,17 +1534,17 @@ ExpanderGraphics::ExpanderGraphics(QGraphicsItem* parent) : QGraphicsRectItem(pa rightWing->setZValue(-2); bg->setZValue(-1); - leftWing->setPos(0,0); - bg->setPos(leftWing->pos().x() + leftWing->boundingRect().width() -60, 5); + leftWing->setPos(0, 0); + bg->setPos(leftWing->pos().x() + leftWing->boundingRect().width() - 60, 5); rightWing->setPos(leftWing->pos().x() + leftWing->boundingRect().width() - 20, 0); - decreaseBtn->setPos(leftWing->pos().x(), leftWing->pos().y() ); - increaseBtn->setPos(rightWing->pos().x(), rightWing->pos().y() ); + decreaseBtn->setPos(leftWing->pos().x(), leftWing->pos().y()); + increaseBtn->setPos(rightWing->pos().x(), rightWing->pos().y()); icon->setPos(bg->pos().x(), bg->pos().y() - 5); //I need to bottom align the items, I need to make the 0,0 ( orgin ) to be // the bottom of this item, so shift everything up. QRectF r = childrenBoundingRect(); - Q_FOREACH(QGraphicsItem *i, childItems()) { + Q_FOREACH(QGraphicsItem * i, childItems()) { i->setPos(i->pos().x(), i->pos().y() - r.height()); } setScale(0.7); diff --git a/qt-ui/diveplanner.h b/qt-ui/diveplanner.h index 364d0396d..4679d0660 100644 --- a/qt-ui/diveplanner.h +++ b/qt-ui/diveplanner.h @@ -12,19 +12,30 @@ class QListView; class QModelIndex; -class DivePlannerPointsModel : public QAbstractTableModel{ +class DivePlannerPointsModel : public QAbstractTableModel { Q_OBJECT public: - static DivePlannerPointsModel* instance(); - enum Sections{REMOVE, DEPTH, DURATION, GAS, CCSETPOINT, COLUMNS}; - enum Mode { NOTHING, PLAN, ADD }; - virtual int columnCount(const QModelIndex& parent = QModelIndex()) const; - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; + static DivePlannerPointsModel *instance(); + enum Sections { + REMOVE, + DEPTH, + DURATION, + GAS, + CCSETPOINT, + COLUMNS + }; + enum Mode { + NOTHING, + PLAN, + ADD + }; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); - virtual Qt::ItemFlags flags(const QModelIndex& index) const; - void removeSelectedPoints(const QVector<int>& rows); + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + virtual Qt::ItemFlags flags(const QModelIndex &index) const; + void removeSelectedPoints(const QVector<int> &rows); void setPlanMode(Mode mode); bool isPlanner(); void createSimpleDive(); @@ -37,35 +48,37 @@ public: /** * @return the row number. */ - void editStop(int row, divedatapoint newData ); + void editStop(int row, divedatapoint newData); divedatapoint at(int row); int size(); struct diveplan getDiveplan(); QStringList &getGasList(); QVector<QPair<int, int> > collectGases(dive *d); -public slots: - int addStop(int millimeters = 0, int seconds = 0, int o2 = 0, int he = 0, int ccpoint = 0 ); +public +slots: + int addStop(int millimeters = 0, int seconds = 0, int o2 = 0, int he = 0, int ccpoint = 0); void addCylinder_clicked(); void setGFHigh(const int gfhigh); void setGFLow(const int ghflow); void setSurfacePressure(int pressure); void setBottomSac(int sac); void setDecoSac(int sac); - void setStartTime(const QTime& t); + void setStartTime(const QTime &t); void setLastStop6m(bool value); void createPlan(); - void remove(const QModelIndex& index); + void remove(const QModelIndex &index); void cancelPlan(); void createTemporaryPlan(); void deleteTemporaryPlan(); - void loadFromDive(dive* d); + void loadFromDive(dive *d); void restoreBackupDive(); signals: void planCreated(); void planCanceled(); + private: - explicit DivePlannerPointsModel(QObject* parent = 0); + explicit DivePlannerPointsModel(QObject *parent = 0); bool addGas(int o2, int he); struct diveplan diveplan; Mode mode; @@ -81,13 +94,15 @@ private: class Button : public QObject, public QGraphicsRectItem { Q_OBJECT public: - Button(QObject* parent = 0, QGraphicsItem *itemParent = 0); - void setText(const QString& text); - void setPixmap(const QPixmap& pixmap); + Button(QObject *parent = 0, QGraphicsItem *itemParent = 0); + void setText(const QString &text); + void setPixmap(const QPixmap &pixmap); + protected: - virtual void mousePressEvent(QGraphicsSceneMouseEvent* event); + virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); signals: void clicked(); + private: QGraphicsPixmapItem *icon; QGraphicsSimpleTextItem *text; @@ -101,27 +116,31 @@ public: QGraphicsPixmapItem *icon; Button *increaseBtn; Button *decreaseBtn; + private: QGraphicsPixmapItem *bg; QGraphicsPixmapItem *leftWing; QGraphicsPixmapItem *rightWing; }; -class DiveHandler : public QObject, public QGraphicsEllipseItem{ -Q_OBJECT +class DiveHandler : public QObject, public QGraphicsEllipseItem { + Q_OBJECT public: DiveHandler(); + protected: - void mousePressEvent(QGraphicsSceneMouseEvent* event); - void contextMenuEvent(QGraphicsSceneContextMenuEvent* event); + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + private: int parentIndex(); -public slots: +public +slots: void selfRemove(); void changeGas(); }; -class Ruler : public QGraphicsLineItem{ +class Ruler : public QGraphicsLineItem { public: Ruler(); ~Ruler(); @@ -133,19 +152,19 @@ public: void updateTicks(); double minimum() const; double maximum() const; - qreal valueAt(const QPointF& p); - qreal percentAt(const QPointF& p); + qreal valueAt(const QPointF &p); + qreal percentAt(const QPointF &p); qreal posAtValue(qreal value); - void setColor(const QColor& color); - void setTextColor(const QColor& color); + void setColor(const QColor &color); + void setTextColor(const QColor &color); int unitSystem; private: void eraseAll(); Qt::Orientation orientation; - QList<QGraphicsLineItem*> ticks; - QList<QGraphicsSimpleTextItem*> labels; + QList<QGraphicsLineItem *> ticks; + QList<QGraphicsSimpleTextItem *> labels; double min; double max; double interval; @@ -156,19 +175,22 @@ private: class DivePlannerGraphics : public QGraphicsView { Q_OBJECT public: - DivePlannerGraphics(QWidget* parent = 0); + DivePlannerGraphics(QWidget *parent = 0); + protected: - virtual void mouseDoubleClickEvent(QMouseEvent* event); - virtual void showEvent(QShowEvent* event); - virtual void resizeEvent(QResizeEvent* event); - virtual void mouseMoveEvent(QMouseEvent* event); - virtual void mousePressEvent(QMouseEvent* event); - virtual void mouseReleaseEvent(QMouseEvent* event); - bool isPointOutOfBoundaries(const QPointF& point); + virtual void mouseDoubleClickEvent(QMouseEvent *event); + virtual void showEvent(QShowEvent *event); + virtual void resizeEvent(QResizeEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + bool isPointOutOfBoundaries(const QPointF &point); qreal fromPercent(qreal percent, Qt::Orientation orientation); -public slots: +public +slots: void settingsChanged(); -private slots: +private +slots: void keyEscAction(); void keyDeleteAction(); void keyUpAction(); @@ -180,17 +202,18 @@ private slots: void decreaseTime(); void decreaseDepth(); void drawProfile(); - void pointInserted(const QModelIndex&, int start, int end); - void pointsRemoved(const QModelIndex&, int start, int end); + void pointInserted(const QModelIndex &, int start, int end); + void pointsRemoved(const QModelIndex &, int start, int end); + private: - void moveActiveHandler(const QPointF& MappedPos, const int pos); + void moveActiveHandler(const QPointF &MappedPos, const int pos); /* This are the lines of the plotted dive. */ - QList<QGraphicsLineItem*> lines; + QList<QGraphicsLineItem *> lines; /* This is the user-entered handles. */ QList<DiveHandler *> handles; - QList<QGraphicsSimpleTextItem*> gases; + QList<QGraphicsSimpleTextItem *> gases; /* those are the lines that follows the mouse. */ QGraphicsLineItem *verticalLine; @@ -219,8 +242,8 @@ private: ExpanderGraphics *timeHandler; int minMinutes; // this holds the minimum requested window time - int minDepth; // this holds the minimum requested window depth - int dpMaxTime; // this is the time of the dive calculated by the deco. + int minDepth; // this holds the minimum requested window depth + int dpMaxTime; // this is the time of the dive calculated by the deco. friend class DiveHandler; }; @@ -230,13 +253,15 @@ private: class DivePlannerWidget : public QWidget { Q_OBJECT public: - explicit DivePlannerWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit DivePlannerWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); -public slots: +public +slots: void settingsChanged(); - void atmPressureChanged(const QString& pressure); - void bottomSacChanged(const QString& bottomSac); - void decoSacChanged(const QString& decosac); + void atmPressureChanged(const QString &pressure); + void bottomSacChanged(const QString &bottomSac); + void decoSacChanged(const QString &decosac); + private: Ui::DivePlanner ui; }; diff --git a/qt-ui/downloadfromdivecomputer.cpp b/qt-ui/downloadfromdivecomputer.cpp index 69d42d930..26635c6e8 100644 --- a/qt-ui/downloadfromdivecomputer.cpp +++ b/qt-ui/downloadfromdivecomputer.cpp @@ -32,11 +32,12 @@ struct mydescriptor { unsigned int model; }; -namespace DownloadFromDcGlobal { +namespace DownloadFromDcGlobal +{ const char *err_string; }; -DownloadFromDCWidget::DownloadFromDCWidget(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f), +DownloadFromDCWidget::DownloadFromDCWidget(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), thread(0), downloading(false), previousLast(0), @@ -87,7 +88,7 @@ void DownloadFromDCWidget::updateProgressBar() ui.progressBar->setFormat(progress_bar_text); } else { ui.progressBar->setFormat("%p%"); - ui.progressBar->setValue(progress_bar_fraction *100); + ui.progressBar->setValue(progress_bar_fraction * 100); } } @@ -111,8 +112,7 @@ void DownloadFromDCWidget::updateState(states state) // user pressed cancel but the application isn't doing anything. // means close the window - else if ((currentState == INITIAL || currentState == CANCELLED || currentState == DONE || currentState == ERROR) - && state == CANCELLING) { + else if ((currentState == INITIAL || currentState == CANCELLED || currentState == DONE || currentState == ERROR) && state == CANCELLING) { timer->stop(); reject(); ui.ok->setText(tr("OK")); @@ -168,7 +168,7 @@ void DownloadFromDCWidget::updateState(states state) currentState = state; } -void DownloadFromDCWidget::on_vendor_currentIndexChanged(const QString& vendor) +void DownloadFromDCWidget::on_vendor_currentIndexChanged(const QString &vendor) { QAbstractItemModel *currentModel = ui.product->model(); if (!currentModel) @@ -205,7 +205,7 @@ void DownloadFromDCWidget::fill_computer_list() QStringList computer; dc_descriptor_iterator(&iterator); - while (dc_iterator_next (iterator, &descriptor) == DC_STATUS_SUCCESS) { + while (dc_iterator_next(iterator, &descriptor) == DC_STATUS_SUCCESS) { const char *vendor = dc_descriptor_get_vendor(descriptor); const char *product = dc_descriptor_get_product(descriptor); @@ -225,7 +225,7 @@ void DownloadFromDCWidget::fill_computer_list() this WILL BREAK if libdivecomputer changes the dc_descriptor struct... eventually the UEMIS code needs to move into libdivecomputer, I guess */ - mydescriptor = (struct mydescriptor*) malloc(sizeof(struct mydescriptor)); + mydescriptor = (struct mydescriptor *)malloc(sizeof(struct mydescriptor)); mydescriptor->vendor = "Uemis"; mydescriptor->product = "Zurich"; mydescriptor->type = DC_FAMILY_NULL; @@ -246,9 +246,9 @@ void DownloadFromDCWidget::on_search_clicked() { if (ui.vendor->currentText() == "Uemis") { QString dirName = QFileDialog::getExistingDirectory(this, - tr("Find Uemis dive computer"), - QDir::homePath(), - QFileDialog::ShowDirsOnly); + tr("Find Uemis dive computer"), + QDir::homePath(), + QFileDialog::ShowDirsOnly); qDebug() << dirName; if (ui.device->findText(dirName) == -1) ui.device->addItem(dirName); @@ -284,7 +284,7 @@ void DownloadFromDCWidget::on_ok_clicked() thread = new DownloadThread(this, &data); connect(thread, SIGNAL(finished()), - this, SLOT(onDownloadThreadFinished()), Qt::QueuedConnection); + this, SLOT(onDownloadThreadFinished()), Qt::QueuedConnection); MainWindow *w = MainWindow::instance(); connect(thread, SIGNAL(finished()), w, SLOT(refreshDisplay())); @@ -311,7 +311,7 @@ void DownloadFromDCWidget::checkLogFile(int state) void DownloadFromDCWidget::pickLogFile() { - QString filename = existing_filename ? : prefs.default_filename; + QString filename = existing_filename ?: prefs.default_filename; QFileInfo fi(filename); filename = fi.absolutePath().append(QDir::separator()).append("subsurface.log"); logFile = QFileDialog::getSaveFileName(this, tr("Choose file for divecomputer download logfile"), @@ -340,7 +340,7 @@ void DownloadFromDCWidget::checkDumpFile(int state) void DownloadFromDCWidget::pickDumpFile() { - QString filename = existing_filename ? : prefs.default_filename; + QString filename = existing_filename ?: prefs.default_filename; QFileInfo fi(filename); filename = fi.absolutePath().append(QDir::separator()).append("subsurface.bin"); dumpFile = QFileDialog::getSaveFileName(this, tr("Choose file for divecomputer binary dump file"), @@ -429,7 +429,7 @@ void DownloadFromDCWidget::fill_device_list() ui.device->setCurrentIndex(deviceIndex); } -DownloadThread::DownloadThread(QObject* parent, device_data_t* data): QThread(parent), +DownloadThread::DownloadThread(QObject *parent, device_data_t *data) : QThread(parent), data(data) { } @@ -438,7 +438,7 @@ static QString str_error(const char *fmt, ...) { va_list args; va_start(args, fmt); - const QString str = QString().vsprintf( fmt, args ); + const QString str = QString().vsprintf(fmt, args); va_end(args); return str; @@ -453,5 +453,5 @@ void DownloadThread::run() else errorText = do_libdivecomputer_import(data); if (errorText) - error = str_error(errorText, data->devname, data->vendor, data->product); + error = str_error(errorText, data->devname, data->vendor, data->product); } diff --git a/qt-ui/downloadfromdivecomputer.h b/qt-ui/downloadfromdivecomputer.h index 4e4c04266..e20ba3051 100644 --- a/qt-ui/downloadfromdivecomputer.h +++ b/qt-ui/downloadfromdivecomputer.h @@ -9,21 +9,22 @@ #include "../libdivecomputer.h" #include "ui_downloadfromdivecomputer.h" -class DownloadThread : public QThread{ +class DownloadThread : public QThread { Q_OBJECT public: - DownloadThread(QObject* parent, device_data_t* data); + DownloadThread(QObject *parent, device_data_t *data); virtual void run(); QString error; + private: device_data_t *data; }; -class DownloadFromDCWidget : public QDialog{ +class DownloadFromDCWidget : public QDialog { Q_OBJECT public: - explicit DownloadFromDCWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit DownloadFromDCWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); void reject(); enum states { @@ -35,11 +36,12 @@ public: DONE, }; -public slots: +public +slots: void on_ok_clicked(); void on_cancel_clicked(); void on_search_clicked(); - void on_vendor_currentIndexChanged(const QString& vendor); + void on_vendor_currentIndexChanged(const QString &vendor); void on_product_currentIndexChanged(); void onDownloadThreadFinished(); @@ -76,7 +78,6 @@ public: bool preferDownloaded(); void updateState(states state); states currentState; - }; #endif // DOWNLOADFROMDIVECOMPUTER_H diff --git a/qt-ui/exif.cpp b/qt-ui/exif.cpp index c122567cb..2614d52e6 100644 --- a/qt-ui/exif.cpp +++ b/qt-ui/exif.cpp @@ -34,158 +34,166 @@ using std::string; -namespace { - // IF Entry - struct IFEntry { - // Raw fields - unsigned short tag; - unsigned short format; - unsigned data; - unsigned length; - - // Parsed fields - string val_string; - unsigned short val_16; - unsigned val_32; - double val_rational; - unsigned char val_byte; - }; - - // Helper functions - unsigned int parse32(const unsigned char *buf, bool intel) { - if (intel) - return ((unsigned)buf[3]<<24) | - ((unsigned)buf[2]<<16) | - ((unsigned)buf[1]<<8) | - buf[0]; - - return ((unsigned)buf[0]<<24) | - ((unsigned)buf[1]<<16) | - ((unsigned)buf[2]<<8) | - buf[3]; - } - - unsigned short parse16(const unsigned char *buf, bool intel) { - if (intel) - return ((unsigned) buf[1]<<8) | buf[0]; - return ((unsigned) buf[0]<<8) | buf[1]; - } - - string parseEXIFString(const unsigned char *buf, - const unsigned num_components, - const unsigned data, - const unsigned base, - const unsigned len) { - string value; - if (num_components <= 4) - value.assign( (const char*)&data, num_components ); - else { - if (base+data+num_components <= len) - value.assign( (const char*)(buf+base+data), num_components ); - } - return value; - } - - double parseEXIFRational(const unsigned char *buf, bool intel) { - double numerator = 0; - double denominator = 1; - - numerator = (double) parse32(buf, intel); - denominator= (double) parse32(buf+4, intel); - if(denominator < 1e-20) - return 0; - return numerator/denominator; - } - - IFEntry parseIFEntry(const unsigned char *buf, - const unsigned offs, - const bool alignIntel, - const unsigned base, - const unsigned len) { - IFEntry result; - - // Each directory entry is composed of: - // 2 bytes: tag number (data field) - // 2 bytes: data format - // 4 bytes: number of components - // 4 bytes: data value or offset to data value - result.tag = parse16(buf + offs, alignIntel); - result.format = parse16(buf + offs + 2, alignIntel); - result.length = parse32(buf + offs + 4, alignIntel); - result.data = parse32(buf + offs + 8, alignIntel); - - // Parse value in specified format - switch (result.format) { - case 1: - result.val_byte = (unsigned char) *(buf + offs + 8); - break; - case 2: - result.val_string = parseEXIFString(buf, result.length, result.data, base, len); - break; - case 3: - result.val_16 = parse16((const unsigned char *) buf + offs + 8, alignIntel); - break; - case 4: - result.val_32 = result.data; - break; - case 5: - if (base + result.data + 8 <= len) - result.val_rational = parseEXIFRational(buf + base + result.data, alignIntel); - break; - case 7: - case 9: - case 10: - break; - default: - result.tag = 0xFF; - } - return result; - } +namespace +{ + // IF Entry + struct IFEntry { + // Raw fields + unsigned short tag; + unsigned short format; + unsigned data; + unsigned length; + + // Parsed fields + string val_string; + unsigned short val_16; + unsigned val_32; + double val_rational; + unsigned char val_byte; + }; + + // Helper functions + unsigned int parse32(const unsigned char *buf, bool intel) + { + if (intel) + return ((unsigned)buf[3] << 24) | + ((unsigned)buf[2] << 16) | + ((unsigned)buf[1] << 8) | + buf[0]; + + return ((unsigned)buf[0] << 24) | + ((unsigned)buf[1] << 16) | + ((unsigned)buf[2] << 8) | + buf[3]; + } + + unsigned short parse16(const unsigned char *buf, bool intel) + { + if (intel) + return ((unsigned)buf[1] << 8) | buf[0]; + return ((unsigned)buf[0] << 8) | buf[1]; + } + + string parseEXIFString(const unsigned char *buf, + const unsigned num_components, + const unsigned data, + const unsigned base, + const unsigned len) + { + string value; + if (num_components <= 4) + value.assign((const char *)&data, num_components); + else { + if (base + data + num_components <= len) + value.assign((const char *)(buf + base + data), num_components); + } + return value; + } + + double parseEXIFRational(const unsigned char *buf, bool intel) + { + double numerator = 0; + double denominator = 1; + + numerator = (double)parse32(buf, intel); + denominator = (double)parse32(buf + 4, intel); + if (denominator < 1e-20) + return 0; + return numerator / denominator; + } + + IFEntry parseIFEntry(const unsigned char *buf, + const unsigned offs, + const bool alignIntel, + const unsigned base, + const unsigned len) + { + IFEntry result; + + // Each directory entry is composed of: + // 2 bytes: tag number (data field) + // 2 bytes: data format + // 4 bytes: number of components + // 4 bytes: data value or offset to data value + result.tag = parse16(buf + offs, alignIntel); + result.format = parse16(buf + offs + 2, alignIntel); + result.length = parse32(buf + offs + 4, alignIntel); + result.data = parse32(buf + offs + 8, alignIntel); + + // Parse value in specified format + switch (result.format) { + case 1: + result.val_byte = (unsigned char)*(buf + offs + 8); + break; + case 2: + result.val_string = parseEXIFString(buf, result.length, result.data, base, len); + break; + case 3: + result.val_16 = parse16((const unsigned char *)buf + offs + 8, alignIntel); + break; + case 4: + result.val_32 = result.data; + break; + case 5: + if (base + result.data + 8 <= len) + result.val_rational = parseEXIFRational(buf + base + result.data, alignIntel); + break; + case 7: + case 9: + case 10: + break; + default: + result.tag = 0xFF; + } + return result; + } } // // Locates the EXIF segment and parses it using parseFromEXIFSegment // -int EXIFInfo::parseFrom(const unsigned char *buf, unsigned len) { - // Sanity check: all JPEG files start with 0xFFD8 and end with 0xFFD9 - // This check also ensures that the user has supplied a correct value for len. - if (!buf || len < 4) - return PARSE_EXIF_ERROR_NO_EXIF; - if (buf[0] != 0xFF || buf[1] != 0xD8) - return PARSE_EXIF_ERROR_NO_JPEG; - if (buf[len-2] != 0xFF || buf[len-1] != 0xD9) - return PARSE_EXIF_ERROR_NO_JPEG; - clear(); - - // Scan for EXIF header (bytes 0xFF 0xE1) and do a sanity check by - // looking for bytes "Exif\0\0". The marker length data is in Motorola - // byte order, which results in the 'false' parameter to parse16(). - // The marker has to contain at least the TIFF header, otherwise the - // EXIF data is corrupt. So the minimum length specified here has to be: - // 2 bytes: section size - // 6 bytes: "Exif\0\0" string - // 2 bytes: TIFF header (either "II" or "MM" string) - // 2 bytes: TIFF magic (short 0x2a00 in Motorola byte order) - // 4 bytes: Offset to first IFD - // ========= - // 16 bytes - unsigned offs = 0; // current offset into buffer - for (offs = 0; offs < len-1; offs++) - if (buf[offs] == 0xFF && buf[offs+1] == 0xE1) - break; - if (offs + 4 > len) - return PARSE_EXIF_ERROR_NO_EXIF; - offs += 2; - unsigned short section_length = parse16(buf + offs, false); - if (offs + section_length > len || section_length < 16) - return PARSE_EXIF_ERROR_CORRUPT; - offs += 2; - - return parseFromEXIFSegment(buf + offs, len - offs); +int EXIFInfo::parseFrom(const unsigned char *buf, unsigned len) +{ + // Sanity check: all JPEG files start with 0xFFD8 and end with 0xFFD9 + // This check also ensures that the user has supplied a correct value for len. + if (!buf || len < 4) + return PARSE_EXIF_ERROR_NO_EXIF; + if (buf[0] != 0xFF || buf[1] != 0xD8) + return PARSE_EXIF_ERROR_NO_JPEG; + if (buf[len - 2] != 0xFF || buf[len - 1] != 0xD9) + return PARSE_EXIF_ERROR_NO_JPEG; + clear(); + + // Scan for EXIF header (bytes 0xFF 0xE1) and do a sanity check by + // looking for bytes "Exif\0\0". The marker length data is in Motorola + // byte order, which results in the 'false' parameter to parse16(). + // The marker has to contain at least the TIFF header, otherwise the + // EXIF data is corrupt. So the minimum length specified here has to be: + // 2 bytes: section size + // 6 bytes: "Exif\0\0" string + // 2 bytes: TIFF header (either "II" or "MM" string) + // 2 bytes: TIFF magic (short 0x2a00 in Motorola byte order) + // 4 bytes: Offset to first IFD + // ========= + // 16 bytes + unsigned offs = 0; // current offset into buffer + for (offs = 0; offs < len - 1; offs++) + if (buf[offs] == 0xFF && buf[offs + 1] == 0xE1) + break; + if (offs + 4 > len) + return PARSE_EXIF_ERROR_NO_EXIF; + offs += 2; + unsigned short section_length = parse16(buf + offs, false); + if (offs + section_length > len || section_length < 16) + return PARSE_EXIF_ERROR_CORRUPT; + offs += 2; + + return parseFromEXIFSegment(buf + offs, len - offs); } -int EXIFInfo::parseFrom(const string &data) { - return parseFrom((const unsigned char *)data.data(), data.length()); +int EXIFInfo::parseFrom(const string &data) +{ + return parseFrom((const unsigned char *)data.data(), data.length()); } // @@ -194,366 +202,368 @@ int EXIFInfo::parseFrom(const string &data) { // PARAM: 'buf' start of the EXIF TIFF, which must be the bytes "Exif\0\0". // PARAM: 'len' length of buffer // -int EXIFInfo::parseFromEXIFSegment(const unsigned char *buf, unsigned len) { - bool alignIntel = true; // byte alignment (defined in EXIF header) - unsigned offs = 0; // current offset into buffer - if (!buf || len < 6) - return PARSE_EXIF_ERROR_NO_EXIF; - - if (!std::equal(buf, buf+6, "Exif\0\0")) - return PARSE_EXIF_ERROR_NO_EXIF; - offs += 6; - - // Now parsing the TIFF header. The first two bytes are either "II" or - // "MM" for Intel or Motorola byte alignment. Sanity check by parsing - // the unsigned short that follows, making sure it equals 0x2a. The - // last 4 bytes are an offset into the first IFD, which are added to - // the global offset counter. For this block, we expect the following - // minimum size: - // 2 bytes: 'II' or 'MM' - // 2 bytes: 0x002a - // 4 bytes: offset to first IDF - // ----------------------------- - // 8 bytes - if (offs + 8 > len) - return PARSE_EXIF_ERROR_CORRUPT; - unsigned tiff_header_start = offs; - if (buf[offs] == 'I' && buf[offs+1] == 'I') - alignIntel = true; - else { - if(buf[offs] == 'M' && buf[offs+1] == 'M') - alignIntel = false; - else - return PARSE_EXIF_ERROR_UNKNOWN_BYTEALIGN; - } - this->ByteAlign = alignIntel; - offs += 2; - if (0x2a != parse16(buf+offs, alignIntel)) - return PARSE_EXIF_ERROR_CORRUPT; - offs += 2; - unsigned first_ifd_offset = parse32(buf + offs, alignIntel); - offs += first_ifd_offset - 4; - if (offs >= len) - return PARSE_EXIF_ERROR_CORRUPT; - - // Now parsing the first Image File Directory (IFD0, for the main image). - // An IFD consists of a variable number of 12-byte directory entries. The - // first two bytes of the IFD section contain the number of directory - // entries in the section. The last 4 bytes of the IFD contain an offset - // to the next IFD, which means this IFD must contain exactly 6 + 12 * num - // bytes of data. - if (offs + 2 > len) - return PARSE_EXIF_ERROR_CORRUPT; - int num_entries = parse16(buf + offs, alignIntel); - if (offs + 6 + 12 * num_entries > len) - return PARSE_EXIF_ERROR_CORRUPT; - offs += 2; - unsigned exif_sub_ifd_offset = len; - unsigned gps_sub_ifd_offset = len; - while (--num_entries >= 0) { - IFEntry result = parseIFEntry(buf, offs, alignIntel, tiff_header_start, len); - offs += 12; - switch(result.tag) { - case 0x102: - // Bits per sample - if (result.format == 3) - this->BitsPerSample = result.val_16; - break; - - case 0x10E: - // Image description - if (result.format == 2) - this->ImageDescription = result.val_string; - break; - - case 0x10F: - // Digicam make - if (result.format == 2) - this->Make = result.val_string; - break; - - case 0x110: - // Digicam model - if (result.format == 2) - this->Model = result.val_string; - break; - - case 0x112: - // Orientation of image - if (result.format == 3) - this->Orientation = result.val_16; - break; - - case 0x131: - // Software used for image - if (result.format == 2) - this->Software = result.val_string; - break; - - case 0x132: - // EXIF/TIFF date/time of image modification - if (result.format == 2) - this->DateTime = result.val_string; - break; - - case 0x8298: - // Copyright information - if (result.format == 2) - this->Copyright = result.val_string; - break; - - case 0x8825: - // GPS IFS offset - gps_sub_ifd_offset = tiff_header_start + result.data; - break; - - case 0x8769: - // EXIF SubIFD offset - exif_sub_ifd_offset = tiff_header_start + result.data; - break; - } - } - - // Jump to the EXIF SubIFD if it exists and parse all the information - // there. Note that it's possible that the EXIF SubIFD doesn't exist. - // The EXIF SubIFD contains most of the interesting information that a - // typical user might want. - if (exif_sub_ifd_offset + 4 <= len) { - offs = exif_sub_ifd_offset; - int num_entries = parse16(buf + offs, alignIntel); - if (offs + 6 + 12 * num_entries > len) - return PARSE_EXIF_ERROR_CORRUPT; - offs += 2; - while (--num_entries >= 0) { - IFEntry result = parseIFEntry(buf, offs, alignIntel, tiff_header_start, len); - switch(result.tag) { - case 0x829a: - // Exposure time in seconds - if (result.format == 5) - this->ExposureTime = result.val_rational; - break; - - case 0x829d: - // FNumber - if (result.format == 5) - this->FNumber = result.val_rational; - break; - - case 0x8827: - // ISO Speed Rating - if (result.format == 3) - this->ISOSpeedRatings = result.val_16; - break; - - case 0x9003: - // Original date and time - if (result.format == 2) - this->DateTimeOriginal = result.val_string; - break; - - case 0x9004: - // Digitization date and time - if (result.format == 2) - this->DateTimeDigitized = result.val_string; - break; - - case 0x9201: - // Shutter speed value - if (result.format == 5) - this->ShutterSpeedValue = result.val_rational; - break; - - case 0x9204: - // Exposure bias value - if (result.format == 5) - this->ExposureBiasValue = result.val_rational; - break; - - case 0x9206: - // Subject distance - if (result.format == 5) - this->SubjectDistance = result.val_rational; - break; - - case 0x9209: - // Flash used - if (result.format == 3) - this->Flash = result.data ? 1 : 0; - break; - - case 0x920a: - // Focal length - if (result.format == 5) - this->FocalLength = result.val_rational; - break; - - case 0x9207: - // Metering mode - if (result.format == 3) - this->MeteringMode = result.val_16; - break; - - case 0x9291: - // Subsecond original time - if (result.format == 2) - this->SubSecTimeOriginal = result.val_string; - break; - - case 0xa002: - // EXIF Image width - if (result.format == 4) - this->ImageWidth = result.val_32; - if (result.format == 3) - this->ImageWidth = result.val_16; - break; - - case 0xa003: - // EXIF Image height - if (result.format == 4) - this->ImageHeight = result.val_32; - if (result.format == 3) - this->ImageHeight = result.val_16; - break; - - case 0xa405: - // Focal length in 35mm film - if (result.format == 3) - this->FocalLengthIn35mm = result.val_16; - break; - } - offs += 12; - } - } - - // Jump to the GPS SubIFD if it exists and parse all the information - // there. Note that it's possible that the GPS SubIFD doesn't exist. - if (gps_sub_ifd_offset + 4 <= len) { - offs = gps_sub_ifd_offset; - int num_entries = parse16(buf + offs, alignIntel); - if (offs + 6 + 12 * num_entries > len) - return PARSE_EXIF_ERROR_CORRUPT; - offs += 2; - while (--num_entries >= 0) { - unsigned short tag = parse16(buf + offs, alignIntel); - unsigned short format = parse16(buf + offs + 2, alignIntel); - unsigned length = parse32(buf + offs + 4, alignIntel); - unsigned data = parse32(buf + offs + 8, alignIntel); - switch(tag) { - case 1: - // GPS north or south - this->GeoLocation.LatComponents.direction = *(buf + offs + 8); - if ('S' == this->GeoLocation.LatComponents.direction) - this->GeoLocation.Latitude = -this->GeoLocation.Latitude; - break; - - case 2: - // GPS latitude - if (format == 5 && length == 3) { - this->GeoLocation.LatComponents.degrees = - parseEXIFRational(buf + data + tiff_header_start, alignIntel); - this->GeoLocation.LatComponents.minutes = - parseEXIFRational(buf + data + tiff_header_start + 8, alignIntel); - this->GeoLocation.LatComponents.seconds = - parseEXIFRational(buf + data + tiff_header_start + 16, alignIntel); - this->GeoLocation.Latitude = - this->GeoLocation.LatComponents.degrees + - this->GeoLocation.LatComponents.minutes / 60 + - this->GeoLocation.LatComponents.seconds / 3600; - if ('S' == this->GeoLocation.LatComponents.direction) - this->GeoLocation.Latitude = -this->GeoLocation.Latitude; - } - break; - - case 3: - // GPS east or west - this->GeoLocation.LonComponents.direction = *(buf + offs + 8); - if ('W' == this->GeoLocation.LonComponents.direction) - this->GeoLocation.Longitude = -this->GeoLocation.Longitude; - break; - - case 4: - // GPS longitude - if (format == 5 && length == 3) { - this->GeoLocation.LonComponents.degrees = - parseEXIFRational(buf + data + tiff_header_start, alignIntel); - this->GeoLocation.LonComponents.minutes = - parseEXIFRational(buf + data + tiff_header_start + 8, alignIntel); - this->GeoLocation.LonComponents.seconds = - parseEXIFRational(buf + data + tiff_header_start + 16, alignIntel); - this->GeoLocation.Longitude = - this->GeoLocation.LonComponents.degrees + - this->GeoLocation.LonComponents.minutes / 60 + - this->GeoLocation.LonComponents.seconds / 3600; - if ('W' == this->GeoLocation.LonComponents.direction) - this->GeoLocation.Longitude = -this->GeoLocation.Longitude; - } - break; - - case 5: - // GPS altitude reference (below or above sea level) - this->GeoLocation.AltitudeRef = *(buf + offs + 8); - if (1 == this->GeoLocation.AltitudeRef) - this->GeoLocation.Altitude = -this->GeoLocation.Altitude; - break; - - case 6: - // GPS altitude reference - if (format == 5) { - this->GeoLocation.Altitude = - parseEXIFRational(buf + data + tiff_header_start, alignIntel); - if (1 == this->GeoLocation.AltitudeRef) - this->GeoLocation.Altitude = -this->GeoLocation.Altitude; - } - break; - } - offs += 12; - } - } - - return PARSE_EXIF_SUCCESS; +int EXIFInfo::parseFromEXIFSegment(const unsigned char *buf, unsigned len) +{ + bool alignIntel = true; // byte alignment (defined in EXIF header) + unsigned offs = 0; // current offset into buffer + if (!buf || len < 6) + return PARSE_EXIF_ERROR_NO_EXIF; + + if (!std::equal(buf, buf + 6, "Exif\0\0")) + return PARSE_EXIF_ERROR_NO_EXIF; + offs += 6; + + // Now parsing the TIFF header. The first two bytes are either "II" or + // "MM" for Intel or Motorola byte alignment. Sanity check by parsing + // the unsigned short that follows, making sure it equals 0x2a. The + // last 4 bytes are an offset into the first IFD, which are added to + // the global offset counter. For this block, we expect the following + // minimum size: + // 2 bytes: 'II' or 'MM' + // 2 bytes: 0x002a + // 4 bytes: offset to first IDF + // ----------------------------- + // 8 bytes + if (offs + 8 > len) + return PARSE_EXIF_ERROR_CORRUPT; + unsigned tiff_header_start = offs; + if (buf[offs] == 'I' && buf[offs + 1] == 'I') + alignIntel = true; + else { + if (buf[offs] == 'M' && buf[offs + 1] == 'M') + alignIntel = false; + else + return PARSE_EXIF_ERROR_UNKNOWN_BYTEALIGN; + } + this->ByteAlign = alignIntel; + offs += 2; + if (0x2a != parse16(buf + offs, alignIntel)) + return PARSE_EXIF_ERROR_CORRUPT; + offs += 2; + unsigned first_ifd_offset = parse32(buf + offs, alignIntel); + offs += first_ifd_offset - 4; + if (offs >= len) + return PARSE_EXIF_ERROR_CORRUPT; + + // Now parsing the first Image File Directory (IFD0, for the main image). + // An IFD consists of a variable number of 12-byte directory entries. The + // first two bytes of the IFD section contain the number of directory + // entries in the section. The last 4 bytes of the IFD contain an offset + // to the next IFD, which means this IFD must contain exactly 6 + 12 * num + // bytes of data. + if (offs + 2 > len) + return PARSE_EXIF_ERROR_CORRUPT; + int num_entries = parse16(buf + offs, alignIntel); + if (offs + 6 + 12 * num_entries > len) + return PARSE_EXIF_ERROR_CORRUPT; + offs += 2; + unsigned exif_sub_ifd_offset = len; + unsigned gps_sub_ifd_offset = len; + while (--num_entries >= 0) { + IFEntry result = parseIFEntry(buf, offs, alignIntel, tiff_header_start, len); + offs += 12; + switch (result.tag) { + case 0x102: + // Bits per sample + if (result.format == 3) + this->BitsPerSample = result.val_16; + break; + + case 0x10E: + // Image description + if (result.format == 2) + this->ImageDescription = result.val_string; + break; + + case 0x10F: + // Digicam make + if (result.format == 2) + this->Make = result.val_string; + break; + + case 0x110: + // Digicam model + if (result.format == 2) + this->Model = result.val_string; + break; + + case 0x112: + // Orientation of image + if (result.format == 3) + this->Orientation = result.val_16; + break; + + case 0x131: + // Software used for image + if (result.format == 2) + this->Software = result.val_string; + break; + + case 0x132: + // EXIF/TIFF date/time of image modification + if (result.format == 2) + this->DateTime = result.val_string; + break; + + case 0x8298: + // Copyright information + if (result.format == 2) + this->Copyright = result.val_string; + break; + + case 0x8825: + // GPS IFS offset + gps_sub_ifd_offset = tiff_header_start + result.data; + break; + + case 0x8769: + // EXIF SubIFD offset + exif_sub_ifd_offset = tiff_header_start + result.data; + break; + } + } + + // Jump to the EXIF SubIFD if it exists and parse all the information + // there. Note that it's possible that the EXIF SubIFD doesn't exist. + // The EXIF SubIFD contains most of the interesting information that a + // typical user might want. + if (exif_sub_ifd_offset + 4 <= len) { + offs = exif_sub_ifd_offset; + int num_entries = parse16(buf + offs, alignIntel); + if (offs + 6 + 12 * num_entries > len) + return PARSE_EXIF_ERROR_CORRUPT; + offs += 2; + while (--num_entries >= 0) { + IFEntry result = parseIFEntry(buf, offs, alignIntel, tiff_header_start, len); + switch (result.tag) { + case 0x829a: + // Exposure time in seconds + if (result.format == 5) + this->ExposureTime = result.val_rational; + break; + + case 0x829d: + // FNumber + if (result.format == 5) + this->FNumber = result.val_rational; + break; + + case 0x8827: + // ISO Speed Rating + if (result.format == 3) + this->ISOSpeedRatings = result.val_16; + break; + + case 0x9003: + // Original date and time + if (result.format == 2) + this->DateTimeOriginal = result.val_string; + break; + + case 0x9004: + // Digitization date and time + if (result.format == 2) + this->DateTimeDigitized = result.val_string; + break; + + case 0x9201: + // Shutter speed value + if (result.format == 5) + this->ShutterSpeedValue = result.val_rational; + break; + + case 0x9204: + // Exposure bias value + if (result.format == 5) + this->ExposureBiasValue = result.val_rational; + break; + + case 0x9206: + // Subject distance + if (result.format == 5) + this->SubjectDistance = result.val_rational; + break; + + case 0x9209: + // Flash used + if (result.format == 3) + this->Flash = result.data ? 1 : 0; + break; + + case 0x920a: + // Focal length + if (result.format == 5) + this->FocalLength = result.val_rational; + break; + + case 0x9207: + // Metering mode + if (result.format == 3) + this->MeteringMode = result.val_16; + break; + + case 0x9291: + // Subsecond original time + if (result.format == 2) + this->SubSecTimeOriginal = result.val_string; + break; + + case 0xa002: + // EXIF Image width + if (result.format == 4) + this->ImageWidth = result.val_32; + if (result.format == 3) + this->ImageWidth = result.val_16; + break; + + case 0xa003: + // EXIF Image height + if (result.format == 4) + this->ImageHeight = result.val_32; + if (result.format == 3) + this->ImageHeight = result.val_16; + break; + + case 0xa405: + // Focal length in 35mm film + if (result.format == 3) + this->FocalLengthIn35mm = result.val_16; + break; + } + offs += 12; + } + } + + // Jump to the GPS SubIFD if it exists and parse all the information + // there. Note that it's possible that the GPS SubIFD doesn't exist. + if (gps_sub_ifd_offset + 4 <= len) { + offs = gps_sub_ifd_offset; + int num_entries = parse16(buf + offs, alignIntel); + if (offs + 6 + 12 * num_entries > len) + return PARSE_EXIF_ERROR_CORRUPT; + offs += 2; + while (--num_entries >= 0) { + unsigned short tag = parse16(buf + offs, alignIntel); + unsigned short format = parse16(buf + offs + 2, alignIntel); + unsigned length = parse32(buf + offs + 4, alignIntel); + unsigned data = parse32(buf + offs + 8, alignIntel); + switch (tag) { + case 1: + // GPS north or south + this->GeoLocation.LatComponents.direction = *(buf + offs + 8); + if ('S' == this->GeoLocation.LatComponents.direction) + this->GeoLocation.Latitude = -this->GeoLocation.Latitude; + break; + + case 2: + // GPS latitude + if (format == 5 && length == 3) { + this->GeoLocation.LatComponents.degrees = + parseEXIFRational(buf + data + tiff_header_start, alignIntel); + this->GeoLocation.LatComponents.minutes = + parseEXIFRational(buf + data + tiff_header_start + 8, alignIntel); + this->GeoLocation.LatComponents.seconds = + parseEXIFRational(buf + data + tiff_header_start + 16, alignIntel); + this->GeoLocation.Latitude = + this->GeoLocation.LatComponents.degrees + + this->GeoLocation.LatComponents.minutes / 60 + + this->GeoLocation.LatComponents.seconds / 3600; + if ('S' == this->GeoLocation.LatComponents.direction) + this->GeoLocation.Latitude = -this->GeoLocation.Latitude; + } + break; + + case 3: + // GPS east or west + this->GeoLocation.LonComponents.direction = *(buf + offs + 8); + if ('W' == this->GeoLocation.LonComponents.direction) + this->GeoLocation.Longitude = -this->GeoLocation.Longitude; + break; + + case 4: + // GPS longitude + if (format == 5 && length == 3) { + this->GeoLocation.LonComponents.degrees = + parseEXIFRational(buf + data + tiff_header_start, alignIntel); + this->GeoLocation.LonComponents.minutes = + parseEXIFRational(buf + data + tiff_header_start + 8, alignIntel); + this->GeoLocation.LonComponents.seconds = + parseEXIFRational(buf + data + tiff_header_start + 16, alignIntel); + this->GeoLocation.Longitude = + this->GeoLocation.LonComponents.degrees + + this->GeoLocation.LonComponents.minutes / 60 + + this->GeoLocation.LonComponents.seconds / 3600; + if ('W' == this->GeoLocation.LonComponents.direction) + this->GeoLocation.Longitude = -this->GeoLocation.Longitude; + } + break; + + case 5: + // GPS altitude reference (below or above sea level) + this->GeoLocation.AltitudeRef = *(buf + offs + 8); + if (1 == this->GeoLocation.AltitudeRef) + this->GeoLocation.Altitude = -this->GeoLocation.Altitude; + break; + + case 6: + // GPS altitude reference + if (format == 5) { + this->GeoLocation.Altitude = + parseEXIFRational(buf + data + tiff_header_start, alignIntel); + if (1 == this->GeoLocation.AltitudeRef) + this->GeoLocation.Altitude = -this->GeoLocation.Altitude; + } + break; + } + offs += 12; + } + } + + return PARSE_EXIF_SUCCESS; } -void EXIFInfo::clear() { - // Strings - ImageDescription = ""; - Make = ""; - Model = ""; - Software = ""; - DateTime = ""; - DateTimeOriginal = ""; - DateTimeDigitized = ""; - SubSecTimeOriginal= ""; - Copyright = ""; - - // Shorts / unsigned / double - ByteAlign = 0; - Orientation = 0; - - BitsPerSample = 0; - ExposureTime = 0; - FNumber = 0; - ISOSpeedRatings = 0; - ShutterSpeedValue = 0; - ExposureBiasValue = 0; - SubjectDistance = 0; - FocalLength = 0; - FocalLengthIn35mm = 0; - Flash = 0; - MeteringMode = 0; - ImageWidth = 0; - ImageHeight = 0; - - // Geolocation - GeoLocation.Latitude = 0; - GeoLocation.Longitude = 0; - GeoLocation.Altitude = 0; - GeoLocation.AltitudeRef = 0; - GeoLocation.LatComponents.degrees = 0; - GeoLocation.LatComponents.minutes = 0; - GeoLocation.LatComponents.seconds = 0; - GeoLocation.LatComponents.direction = 0; - GeoLocation.LonComponents.degrees = 0; - GeoLocation.LonComponents.minutes = 0; - GeoLocation.LonComponents.seconds = 0; - GeoLocation.LonComponents.direction = 0; +void EXIFInfo::clear() +{ + // Strings + ImageDescription = ""; + Make = ""; + Model = ""; + Software = ""; + DateTime = ""; + DateTimeOriginal = ""; + DateTimeDigitized = ""; + SubSecTimeOriginal = ""; + Copyright = ""; + + // Shorts / unsigned / double + ByteAlign = 0; + Orientation = 0; + + BitsPerSample = 0; + ExposureTime = 0; + FNumber = 0; + ISOSpeedRatings = 0; + ShutterSpeedValue = 0; + ExposureBiasValue = 0; + SubjectDistance = 0; + FocalLength = 0; + FocalLengthIn35mm = 0; + Flash = 0; + MeteringMode = 0; + ImageWidth = 0; + ImageHeight = 0; + + // Geolocation + GeoLocation.Latitude = 0; + GeoLocation.Longitude = 0; + GeoLocation.Altitude = 0; + GeoLocation.AltitudeRef = 0; + GeoLocation.LatComponents.degrees = 0; + GeoLocation.LatComponents.minutes = 0; + GeoLocation.LatComponents.seconds = 0; + GeoLocation.LatComponents.direction = 0; + GeoLocation.LonComponents.degrees = 0; + GeoLocation.LonComponents.minutes = 0; + GeoLocation.LonComponents.seconds = 0; + GeoLocation.LonComponents.direction = 0; } diff --git a/qt-ui/exif.h b/qt-ui/exif.h index a3e6706b9..d35d49fa0 100644 --- a/qt-ui/exif.h +++ b/qt-ui/exif.h @@ -15,17 +15,17 @@ ================ 2.1: Released July 2013 - -- fixed a bug where JPEGs without an EXIF SubIFD would not be parsed - -- fixed a bug in parsing GPS coordinate seconds - -- fixed makefile bug - -- added two pathological test images from Matt Galloway + -- fixed a bug where JPEGs without an EXIF SubIFD would not be parsed + -- fixed a bug in parsing GPS coordinate seconds + -- fixed makefile bug + -- added two pathological test images from Matt Galloway http://www.galloway.me.uk/2012/01/uiimageorientation-exif-orientation-sample-images/ - -- split main parsing routine for easier integration into Firefox + -- split main parsing routine for easier integration into Firefox 2.0: Released February 2013 - -- complete rewrite - -- no new/delete - -- added GPS support + -- complete rewrite + -- no new/delete + -- added GPS support 1.0: Released 2010 @@ -58,86 +58,88 @@ // Class responsible for storing and parsing EXIF information from a JPEG blob // class EXIFInfo { - public: - // Parsing function for an entire JPEG image buffer. - // - // PARAM 'data': A pointer to a JPEG image. - // PARAM 'length': The length of the JPEG image. - // RETURN: PARSE_EXIF_SUCCESS (0) on succes with 'result' filled out - // error code otherwise, as defined by the PARSE_EXIF_ERROR_* macros - int parseFrom(const unsigned char *data, unsigned length); - int parseFrom(const std::string &data); - - // Parsing function for an EXIF segment. This is used internally by parseFrom() - // but can be called for special cases where only the EXIF section is - // available (i.e., a blob starting with the bytes "Exif\0\0"). - int parseFromEXIFSegment(const unsigned char *buf, unsigned len); - - // Set all data members to default values. - void clear(); - - // Data fields filled out by parseFrom() - char ByteAlign; // 0 = Motorola byte alignment, 1 = Intel - std::string ImageDescription; // Image description - std::string Make; // Camera manufacturer's name - std::string Model; // Camera model - unsigned short Orientation; // Image orientation, start of data corresponds to - // 0: unspecified in EXIF data - // 1: upper left of image - // 3: lower right of image - // 6: upper right of image - // 8: lower left of image - // 9: undefined - unsigned short BitsPerSample; // Number of bits per component - std::string Software; // Software used - std::string DateTime; // File change date and time - std::string DateTimeOriginal; // Original file date and time (may not exist) - std::string DateTimeDigitized; // Digitization date and time (may not exist) - std::string SubSecTimeOriginal; // Sub-second time that original picture was taken - std::string Copyright; // File copyright information - double ExposureTime; // Exposure time in seconds - double FNumber; // F/stop - unsigned short ISOSpeedRatings; // ISO speed - double ShutterSpeedValue; // Shutter speed (reciprocal of exposure time) - double ExposureBiasValue; // Exposure bias value in EV - double SubjectDistance; // Distance to focus point in meters - double FocalLength; // Focal length of lens in millimeters - unsigned short FocalLengthIn35mm; // Focal length in 35mm film - char Flash; // 0 = no flash, 1 = flash used - unsigned short MeteringMode; // Metering mode - // 1: average - // 2: center weighted average - // 3: spot - // 4: multi-spot - // 5: multi-segment - unsigned ImageWidth; // Image width reported in EXIF data - unsigned ImageHeight; // Image height reported in EXIF data - struct Geolocation_t { // GPS information embedded in file - double Latitude; // Image latitude expressed as decimal - double Longitude; // Image longitude expressed as decimal - double Altitude; // Altitude in meters, relative to sea level - char AltitudeRef; // 0 = above sea level, -1 = below sea level - struct Coord_t { - double degrees; - double minutes; - double seconds; - char direction; - } LatComponents, LonComponents; // Latitude, Longitude expressed in deg/min/sec - } GeoLocation; - EXIFInfo() { - clear(); - } +public: + // Parsing function for an entire JPEG image buffer. + // + // PARAM 'data': A pointer to a JPEG image. + // PARAM 'length': The length of the JPEG image. + // RETURN: PARSE_EXIF_SUCCESS (0) on succes with 'result' filled out + // error code otherwise, as defined by the PARSE_EXIF_ERROR_* macros + int parseFrom(const unsigned char *data, unsigned length); + int parseFrom(const std::string &data); + + // Parsing function for an EXIF segment. This is used internally by parseFrom() + // but can be called for special cases where only the EXIF section is + // available (i.e., a blob starting with the bytes "Exif\0\0"). + int parseFromEXIFSegment(const unsigned char *buf, unsigned len); + + // Set all data members to default values. + void clear(); + + // Data fields filled out by parseFrom() + char ByteAlign; // 0 = Motorola byte alignment, 1 = Intel + std::string ImageDescription; // Image description + std::string Make; // Camera manufacturer's name + std::string Model; // Camera model + unsigned short Orientation; // Image orientation, start of data corresponds to + // 0: unspecified in EXIF data + // 1: upper left of image + // 3: lower right of image + // 6: upper right of image + // 8: lower left of image + // 9: undefined + unsigned short BitsPerSample; // Number of bits per component + std::string Software; // Software used + std::string DateTime; // File change date and time + std::string DateTimeOriginal; // Original file date and time (may not exist) + std::string DateTimeDigitized; // Digitization date and time (may not exist) + std::string SubSecTimeOriginal; // Sub-second time that original picture was taken + std::string Copyright; // File copyright information + double ExposureTime; // Exposure time in seconds + double FNumber; // F/stop + unsigned short ISOSpeedRatings; // ISO speed + double ShutterSpeedValue; // Shutter speed (reciprocal of exposure time) + double ExposureBiasValue; // Exposure bias value in EV + double SubjectDistance; // Distance to focus point in meters + double FocalLength; // Focal length of lens in millimeters + unsigned short FocalLengthIn35mm; // Focal length in 35mm film + char Flash; // 0 = no flash, 1 = flash used + unsigned short MeteringMode; // Metering mode + // 1: average + // 2: center weighted average + // 3: spot + // 4: multi-spot + // 5: multi-segment + unsigned ImageWidth; // Image width reported in EXIF data + unsigned ImageHeight; // Image height reported in EXIF data + struct Geolocation_t + { // GPS information embedded in file + double Latitude; // Image latitude expressed as decimal + double Longitude; // Image longitude expressed as decimal + double Altitude; // Altitude in meters, relative to sea level + char AltitudeRef; // 0 = above sea level, -1 = below sea level + struct Coord_t { + double degrees; + double minutes; + double seconds; + char direction; + } LatComponents, LonComponents; // Latitude, Longitude expressed in deg/min/sec + } GeoLocation; + EXIFInfo() + { + clear(); + } }; // Parse was successful -#define PARSE_EXIF_SUCCESS 0 +#define PARSE_EXIF_SUCCESS 0 // No JPEG markers found in buffer, possibly invalid JPEG file -#define PARSE_EXIF_ERROR_NO_JPEG 1982 +#define PARSE_EXIF_ERROR_NO_JPEG 1982 // No EXIF header found in JPEG file. -#define PARSE_EXIF_ERROR_NO_EXIF 1983 +#define PARSE_EXIF_ERROR_NO_EXIF 1983 // Byte alignment specified in EXIF file was unknown (not Motorola or Intel). -#define PARSE_EXIF_ERROR_UNKNOWN_BYTEALIGN 1984 +#define PARSE_EXIF_ERROR_UNKNOWN_BYTEALIGN 1984 // EXIF header was found, but data was corrupted. -#define PARSE_EXIF_ERROR_CORRUPT 1985 +#define PARSE_EXIF_ERROR_CORRUPT 1985 #endif // EXIF_H diff --git a/qt-ui/globe.cpp b/qt-ui/globe.cpp index 240f8d904..496afb4ac 100644 --- a/qt-ui/globe.cpp +++ b/qt-ui/globe.cpp @@ -24,7 +24,7 @@ #include <QMouseEvent> #include <QMessageBox> -GlobeGPS::GlobeGPS(QWidget* parent) : MarbleWidget(parent), +GlobeGPS::GlobeGPS(QWidget *parent) : MarbleWidget(parent), loadedDives(0), messageWidget(new KMessageWidget(this)), fixZoomTimer(new QTimer(this)), @@ -35,7 +35,7 @@ GlobeGPS::GlobeGPS(QWidget* parent) : MarbleWidget(parent), // if not, check if they are in a known location MapThemeManager mtm; QStringList list = mtm.mapThemeIds(); - QString subsurfaceDataPath; + QString subsurfaceDataPath; QDir marble; if (!list.contains("earth/googlesat/googlesat.dgml")) { subsurfaceDataPath = getSubsurfaceDataPath("marbledata"); @@ -55,7 +55,7 @@ GlobeGPS::GlobeGPS(QWidget* parent) : MarbleWidget(parent), setProjection(Marble::Spherical); setAnimationsEnabled(true); - Q_FOREACH(AbstractFloatItem *i, floatItems()) { + Q_FOREACH(AbstractFloatItem * i, floatItems()) { i->setVisible(false); } @@ -68,7 +68,7 @@ GlobeGPS::GlobeGPS(QWidget* parent) : MarbleWidget(parent), setShowScaleBar(true); setShowCompass(false); connect(this, SIGNAL(mouseClickGeoPosition(qreal, qreal, GeoDataCoordinates::Unit)), - this, SLOT(mouseClicked(qreal, qreal, GeoDataCoordinates::Unit))); + this, SLOT(mouseClicked(qreal, qreal, GeoDataCoordinates::Unit))); setMinimumHeight(0); setMinimumWidth(0); @@ -86,22 +86,22 @@ bool GlobeGPS::eventFilter(QObject *obj, QEvent *ev) // we need to move this to our 'contextMenuEvent' // if we plan to do a different one in the future. if (ev->type() == QEvent::ContextMenu) { - contextMenuEvent(static_cast<QContextMenuEvent*>(ev)); + contextMenuEvent(static_cast<QContextMenuEvent *>(ev)); return true; } if (ev->type() == QEvent::MouseButtonPress) { - QMouseEvent *e = static_cast<QMouseEvent*>(ev); - if (e->button() == Qt::RightButton) + QMouseEvent *e = static_cast<QMouseEvent *>(ev); + if (e->button() == Qt::RightButton) return true; } - return QObject::eventFilter(obj,ev ); + return QObject::eventFilter(obj, ev); } -void GlobeGPS::contextMenuEvent(QContextMenuEvent* ev) +void GlobeGPS::contextMenuEvent(QContextMenuEvent *ev) { QMenu m; QAction *a = m.addAction(tr("Edit Selected Dive Locations"), this, SLOT(prepareForGetDiveCoordinates())); - a->setData(QVariant::fromValue<void*>(&m)); + a->setData(QVariant::fromValue<void *>(&m)); m.exec(ev->globalPos()); } @@ -171,7 +171,7 @@ void GlobeGPS::repopulateLabels() for_each_dive(idx, dive) { if (dive_has_gps_location(dive)) { GeoDataPlacemark *place = new GeoDataPlacemark(dive->location); - place->setCoordinate(dive->longitude.udeg / 1000000.0,dive->latitude.udeg / 1000000.0 , 0, GeoDataCoordinates::Degree); + place->setCoordinate(dive->longitude.udeg / 1000000.0, dive->latitude.udeg / 1000000.0, 0, GeoDataCoordinates::Degree); // don't add dive locations twice, unless they are at least 50m apart if (locationMap[QString(dive->location)]) { GeoDataCoordinates existingLocation = locationMap[QString(dive->location)]->coordinate(); @@ -200,7 +200,7 @@ void GlobeGPS::reload() repopulateLabels(); } -void GlobeGPS::centerOn(dive* dive) +void GlobeGPS::centerOn(dive *dive) { // dive has changed, if we had the 'editingDive', hide it. if (messageWidget->isVisible() && (!dive || dive_has_gps_location(dive))) @@ -221,12 +221,12 @@ void GlobeGPS::centerOn(dive* dive) zoomView(zoomFromDistance(3)); if (!fixZoomTimer->isActive()) - currentZoomLevel = zoom(); + currentZoomLevel = zoom(); // From the marble source code, the maximum time of // 'spin and fit' is 2 seconds, so wait a bit them zoom again. fixZoomTimer->start(2100); - centerOn(longitude,latitude, true); + centerOn(longitude, latitude, true); } void GlobeGPS::fixZoom() @@ -260,7 +260,7 @@ void GlobeGPS::changeDiveGeoPosition(qreal lon, qreal lat, GeoDataCoordinates::U /* change everything on the selection. */ int i; - struct dive* dive; + struct dive *dive; for_each_dive(i, dive) { if (!dive->selected) continue; @@ -273,7 +273,7 @@ void GlobeGPS::changeDiveGeoPosition(qreal lon, qreal lat, GeoDataCoordinates::U MainWindow::instance()->refreshDisplay(); } -void GlobeGPS::mousePressEvent(QMouseEvent* event) +void GlobeGPS::mousePressEvent(QMouseEvent *event) { qreal lat, lon; bool clickOnGlobe = geoCoordinates(event->pos().x(), event->pos().y(), lon, lat, GeoDataCoordinates::Degree); @@ -287,9 +287,9 @@ void GlobeGPS::mousePressEvent(QMouseEvent* event) } } -void GlobeGPS::resizeEvent(QResizeEvent* event) +void GlobeGPS::resizeEvent(QResizeEvent *event) { - int size = event->size().width(); + int size = event->size().width(); MarbleWidget::resizeEvent(event); if (size > 600) messageWidget->setGeometry((size - 600) / 2, 5, 600, 0); diff --git a/qt-ui/globe.h b/qt-ui/globe.h index dad3cf99f..80d9613dd 100644 --- a/qt-ui/globe.h +++ b/qt-ui/globe.h @@ -11,32 +11,34 @@ class KMessageWidget; using namespace Marble; struct dive; -class GlobeGPS : public MarbleWidget{ +class GlobeGPS : public MarbleWidget { Q_OBJECT public: using MarbleWidget::centerOn; GlobeGPS(QWidget *parent); void reload(); void repopulateLabels(); - void centerOn(struct dive* dive); - bool eventFilter(QObject*, QEvent*); + void centerOn(struct dive *dive); + bool eventFilter(QObject *, QEvent *); + protected: /* reimp */ void resizeEvent(QResizeEvent *event); - /* reimp */ void mousePressEvent(QMouseEvent* event); - /* reimp */ void contextMenuEvent(QContextMenuEvent*); + /* reimp */ void mousePressEvent(QMouseEvent *event); + /* reimp */ void contextMenuEvent(QContextMenuEvent *); + private: GeoDataDocument *loadedDives; - KMessageWidget* messageWidget; + KMessageWidget *messageWidget; QTimer *fixZoomTimer; int currentZoomLevel; bool editingDiveLocation; -public slots: - void changeDiveGeoPosition(qreal lon,qreal lat,GeoDataCoordinates::Unit); +public +slots: + void changeDiveGeoPosition(qreal lon, qreal lat, GeoDataCoordinates::Unit); void mouseClicked(qreal lon, qreal lat, GeoDataCoordinates::Unit); void fixZoom(); void prepareForGetDiveCoordinates(); - }; #endif // GLOBE_H diff --git a/qt-ui/graphicsview-common.cpp b/qt-ui/graphicsview-common.cpp index 946f5b021..249016033 100644 --- a/qt-ui/graphicsview-common.cpp +++ b/qt-ui/graphicsview-common.cpp @@ -4,58 +4,58 @@ QMap<color_indice_t, QVector<QColor> > profile_color; void fill_profile_color() { - #define COLOR(x, y, z) QVector<QColor>() << x << y << z; - profile_color[SAC_1] = COLOR(FUNGREEN1, BLACK1_LOW_TRANS, FUNGREEN1); - profile_color[SAC_2] = COLOR(APPLE1, BLACK1_LOW_TRANS, APPLE1); - profile_color[SAC_3] = COLOR(ATLANTIS1, BLACK1_LOW_TRANS, ATLANTIS1); - profile_color[SAC_4] = COLOR(ATLANTIS2, BLACK1_LOW_TRANS, ATLANTIS2); - profile_color[SAC_5] = COLOR(EARLSGREEN1, BLACK1_LOW_TRANS, EARLSGREEN1); - profile_color[SAC_6] = COLOR(HOKEYPOKEY1, BLACK1_LOW_TRANS, HOKEYPOKEY1); - profile_color[SAC_7] = COLOR(TUSCANY1, BLACK1_LOW_TRANS, TUSCANY1); - profile_color[SAC_8] = COLOR(CINNABAR1, BLACK1_LOW_TRANS, CINNABAR1); - profile_color[SAC_9] = COLOR(REDORANGE1, BLACK1_LOW_TRANS, REDORANGE1); +#define COLOR(x, y, z) QVector<QColor>() << x << y << z; + profile_color[SAC_1] = COLOR(FUNGREEN1, BLACK1_LOW_TRANS, FUNGREEN1); + profile_color[SAC_2] = COLOR(APPLE1, BLACK1_LOW_TRANS, APPLE1); + profile_color[SAC_3] = COLOR(ATLANTIS1, BLACK1_LOW_TRANS, ATLANTIS1); + profile_color[SAC_4] = COLOR(ATLANTIS2, BLACK1_LOW_TRANS, ATLANTIS2); + profile_color[SAC_5] = COLOR(EARLSGREEN1, BLACK1_LOW_TRANS, EARLSGREEN1); + profile_color[SAC_6] = COLOR(HOKEYPOKEY1, BLACK1_LOW_TRANS, HOKEYPOKEY1); + profile_color[SAC_7] = COLOR(TUSCANY1, BLACK1_LOW_TRANS, TUSCANY1); + profile_color[SAC_8] = COLOR(CINNABAR1, BLACK1_LOW_TRANS, CINNABAR1); + profile_color[SAC_9] = COLOR(REDORANGE1, BLACK1_LOW_TRANS, REDORANGE1); - profile_color[VELO_STABLE] = COLOR(CAMARONE1, BLACK1_LOW_TRANS, CAMARONE1); - profile_color[VELO_SLOW] = COLOR(LIMENADE1, BLACK1_LOW_TRANS, LIMENADE1); - profile_color[VELO_MODERATE] = COLOR(RIOGRANDE1, BLACK1_LOW_TRANS, RIOGRANDE1); - profile_color[VELO_FAST] = COLOR(PIRATEGOLD1, BLACK1_LOW_TRANS, PIRATEGOLD1); - profile_color[VELO_CRAZY] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); + profile_color[VELO_STABLE] = COLOR(CAMARONE1, BLACK1_LOW_TRANS, CAMARONE1); + profile_color[VELO_SLOW] = COLOR(LIMENADE1, BLACK1_LOW_TRANS, LIMENADE1); + profile_color[VELO_MODERATE] = COLOR(RIOGRANDE1, BLACK1_LOW_TRANS, RIOGRANDE1); + profile_color[VELO_FAST] = COLOR(PIRATEGOLD1, BLACK1_LOW_TRANS, PIRATEGOLD1); + profile_color[VELO_CRAZY] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); - profile_color[PO2] = COLOR(APPLE1, BLACK1_LOW_TRANS, APPLE1); - profile_color[PO2_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); - profile_color[PN2] = COLOR(BLACK1_LOW_TRANS, BLACK1_LOW_TRANS, BLACK1_LOW_TRANS); - profile_color[PN2_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); - profile_color[PHE] = COLOR(PEANUT, BLACK1_LOW_TRANS, PEANUT); - profile_color[PHE_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); - profile_color[PP_LINES] = COLOR(BLACK1_HIGH_TRANS, BLACK1_LOW_TRANS, BLACK1_HIGH_TRANS); + profile_color[PO2] = COLOR(APPLE1, BLACK1_LOW_TRANS, APPLE1); + profile_color[PO2_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); + profile_color[PN2] = COLOR(BLACK1_LOW_TRANS, BLACK1_LOW_TRANS, BLACK1_LOW_TRANS); + profile_color[PN2_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); + profile_color[PHE] = COLOR(PEANUT, BLACK1_LOW_TRANS, PEANUT); + profile_color[PHE_ALERT] = COLOR(RED1, BLACK1_LOW_TRANS, RED1); + profile_color[PP_LINES] = COLOR(BLACK1_HIGH_TRANS, BLACK1_LOW_TRANS, BLACK1_HIGH_TRANS); profile_color[TEXT_BACKGROUND] = COLOR(CONCRETE1_LOWER_TRANS, WHITE1, CONCRETE1_LOWER_TRANS); - profile_color[ALERT_BG] = COLOR(BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS, BROOM1_LOWER_TRANS); - profile_color[ALERT_FG] = COLOR(BLACK1_LOW_TRANS, WHITE1, BLACK1_LOW_TRANS); - profile_color[EVENTS] = COLOR(REDORANGE1, BLACK1_LOW_TRANS, REDORANGE1); - profile_color[SAMPLE_DEEP] = COLOR(QColor(Qt::red).darker(), BLACK1, PERSIANRED1); - profile_color[SAMPLE_SHALLOW] = COLOR(QColor(Qt::red).lighter(), BLACK1_LOW_TRANS, PERSIANRED1); - profile_color[SMOOTHED] = COLOR(REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS, REDORANGE1_HIGH_TRANS); - profile_color[MINUTE] = COLOR(MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS, MEDIUMREDVIOLET1_HIGHER_TRANS); - profile_color[TIME_GRID] = COLOR(WHITE1, BLACK1_HIGH_TRANS, TUNDORA1_MED_TRANS); - profile_color[TIME_TEXT] = COLOR(FORESTGREEN1, BLACK1, FORESTGREEN1); - profile_color[DEPTH_GRID] = COLOR(WHITE1, BLACK1_HIGH_TRANS, TUNDORA1_MED_TRANS); - profile_color[MEAN_DEPTH] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); - profile_color[HR_PLOT] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); - profile_color[HR_TEXT] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); - profile_color[DEPTH_BOTTOM] = COLOR(GOVERNORBAY1_MED_TRANS, BLACK1_HIGH_TRANS, GOVERNORBAY1_MED_TRANS); - profile_color[DEPTH_TOP] = COLOR(MERCURY1_MED_TRANS, WHITE1_MED_TRANS, MERCURY1_MED_TRANS); - profile_color[TEMP_TEXT] = COLOR(GOVERNORBAY2, BLACK1_LOW_TRANS, GOVERNORBAY2); - profile_color[TEMP_PLOT] = COLOR(ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS, ROYALBLUE2_LOW_TRANS); - profile_color[SAC_DEFAULT] = COLOR(WHITE1, BLACK1_LOW_TRANS, FORESTGREEN1); - profile_color[BOUNDING_BOX] = COLOR(WHITE1, BLACK1_LOW_TRANS, TUNDORA1_MED_TRANS); - profile_color[PRESSURE_TEXT] = COLOR(KILLARNEY1, BLACK1_LOW_TRANS, KILLARNEY1); - profile_color[BACKGROUND] = COLOR(SPRINGWOOD1, WHITE1, SPRINGWOOD1); + profile_color[ALERT_BG] = COLOR(BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS, BROOM1_LOWER_TRANS); + profile_color[ALERT_FG] = COLOR(BLACK1_LOW_TRANS, WHITE1, BLACK1_LOW_TRANS); + profile_color[EVENTS] = COLOR(REDORANGE1, BLACK1_LOW_TRANS, REDORANGE1); + profile_color[SAMPLE_DEEP] = COLOR(QColor(Qt::red).darker(), BLACK1, PERSIANRED1); + profile_color[SAMPLE_SHALLOW] = COLOR(QColor(Qt::red).lighter(), BLACK1_LOW_TRANS, PERSIANRED1); + profile_color[SMOOTHED] = COLOR(REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS, REDORANGE1_HIGH_TRANS); + profile_color[MINUTE] = COLOR(MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS, MEDIUMREDVIOLET1_HIGHER_TRANS); + profile_color[TIME_GRID] = COLOR(WHITE1, BLACK1_HIGH_TRANS, TUNDORA1_MED_TRANS); + profile_color[TIME_TEXT] = COLOR(FORESTGREEN1, BLACK1, FORESTGREEN1); + profile_color[DEPTH_GRID] = COLOR(WHITE1, BLACK1_HIGH_TRANS, TUNDORA1_MED_TRANS); + profile_color[MEAN_DEPTH] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); + profile_color[HR_PLOT] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); + profile_color[HR_TEXT] = COLOR(REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS, REDORANGE1_MED_TRANS); + profile_color[DEPTH_BOTTOM] = COLOR(GOVERNORBAY1_MED_TRANS, BLACK1_HIGH_TRANS, GOVERNORBAY1_MED_TRANS); + profile_color[DEPTH_TOP] = COLOR(MERCURY1_MED_TRANS, WHITE1_MED_TRANS, MERCURY1_MED_TRANS); + profile_color[TEMP_TEXT] = COLOR(GOVERNORBAY2, BLACK1_LOW_TRANS, GOVERNORBAY2); + profile_color[TEMP_PLOT] = COLOR(ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS, ROYALBLUE2_LOW_TRANS); + profile_color[SAC_DEFAULT] = COLOR(WHITE1, BLACK1_LOW_TRANS, FORESTGREEN1); + profile_color[BOUNDING_BOX] = COLOR(WHITE1, BLACK1_LOW_TRANS, TUNDORA1_MED_TRANS); + profile_color[PRESSURE_TEXT] = COLOR(KILLARNEY1, BLACK1_LOW_TRANS, KILLARNEY1); + profile_color[BACKGROUND] = COLOR(SPRINGWOOD1, WHITE1, SPRINGWOOD1); profile_color[CEILING_SHALLOW] = COLOR(REDORANGE1_HIGH_TRANS, BLACK1_HIGH_TRANS, REDORANGE1_HIGH_TRANS); - profile_color[CEILING_DEEP] = COLOR(RED1_MED_TRANS, BLACK1_HIGH_TRANS, RED1_MED_TRANS); + profile_color[CEILING_DEEP] = COLOR(RED1_MED_TRANS, BLACK1_HIGH_TRANS, RED1_MED_TRANS); profile_color[CALC_CEILING_SHALLOW] = COLOR(FUNGREEN1_HIGH_TRANS, BLACK1_HIGH_TRANS, FUNGREEN1_HIGH_TRANS); - profile_color[CALC_CEILING_DEEP] = COLOR(APPLE1_HIGH_TRANS, BLACK1_HIGH_TRANS, APPLE1_HIGH_TRANS); - #undef COLOR + profile_color[CALC_CEILING_DEEP] = COLOR(APPLE1_HIGH_TRANS, BLACK1_HIGH_TRANS, APPLE1_HIGH_TRANS); +#undef COLOR } QColor getColor(const color_indice_t i, bool isGrayscale = false) diff --git a/qt-ui/graphicsview-common.h b/qt-ui/graphicsview-common.h index 387e765db..046527d3f 100644 --- a/qt-ui/graphicsview-common.h +++ b/qt-ui/graphicsview-common.h @@ -13,23 +13,62 @@ typedef enum { /* SAC colors. Order is important, the SAC_COLORS_START_IDX define above. */ - SAC_1, SAC_2, SAC_3, SAC_4, SAC_5, SAC_6, SAC_7, SAC_8, SAC_9, + SAC_1, + SAC_2, + SAC_3, + SAC_4, + SAC_5, + SAC_6, + SAC_7, + SAC_8, + SAC_9, /* Velocity colors. Order is still important, ref VELOCITY_COLORS_START_IDX. */ - VELO_STABLE, VELO_SLOW, VELO_MODERATE, VELO_FAST, VELO_CRAZY, + VELO_STABLE, + VELO_SLOW, + VELO_MODERATE, + VELO_FAST, + VELO_CRAZY, /* gas colors */ - PO2, PO2_ALERT, PN2, PN2_ALERT, PHE, PHE_ALERT, PP_LINES, + PO2, + PO2_ALERT, + PN2, + PN2_ALERT, + PHE, + PHE_ALERT, + PP_LINES, /* Other colors */ - TEXT_BACKGROUND, ALERT_BG, ALERT_FG, EVENTS, SAMPLE_DEEP, SAMPLE_SHALLOW, - SMOOTHED, MINUTE, TIME_GRID, TIME_TEXT, DEPTH_GRID, MEAN_DEPTH, HR_TEXT, HR_PLOT, DEPTH_TOP, - DEPTH_BOTTOM, TEMP_TEXT, TEMP_PLOT, SAC_DEFAULT, BOUNDING_BOX, PRESSURE_TEXT, BACKGROUND, - CEILING_SHALLOW, CEILING_DEEP, CALC_CEILING_SHALLOW, CALC_CEILING_DEEP + TEXT_BACKGROUND, + ALERT_BG, + ALERT_FG, + EVENTS, + SAMPLE_DEEP, + SAMPLE_SHALLOW, + SMOOTHED, + MINUTE, + TIME_GRID, + TIME_TEXT, + DEPTH_GRID, + MEAN_DEPTH, + HR_TEXT, + HR_PLOT, + DEPTH_TOP, + DEPTH_BOTTOM, + TEMP_TEXT, + TEMP_PLOT, + SAC_DEFAULT, + BOUNDING_BOX, + PRESSURE_TEXT, + BACKGROUND, + CEILING_SHALLOW, + CEILING_DEEP, + CALC_CEILING_SHALLOW, + CALC_CEILING_DEEP } color_indice_t; - /* profile_color[color indice] = COLOR(screen color, b/w printer color, color printer}} printer & screen colours could be different */ extern QMap<color_indice_t, QVector<QColor> > profile_color; diff --git a/qt-ui/groupedlineedit.cpp b/qt-ui/groupedlineedit.cpp index fe1777cc6..3ed6d239a 100644 --- a/qt-ui/groupedlineedit.cpp +++ b/qt-ui/groupedlineedit.cpp @@ -54,9 +54,8 @@ struct GroupedLineEdit::Private { QVector<QColor> colors; }; -GroupedLineEdit::GroupedLineEdit(QWidget* parent) - : QPlainTextEdit(parent), - d(new Private) +GroupedLineEdit::GroupedLineEdit(QWidget *parent) : QPlainTextEdit(parent), + d(new Private) { setWordWrapMode(QTextOption::NoWrap); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); @@ -90,7 +89,7 @@ void GroupedLineEdit::addBlock(int start, int end) block.start = start; block.end = end; - block.text = text().mid(start, end-start+1).trimmed(); + block.text = text().mid(start, end - start + 1).trimmed(); d->blocks.append(block); viewport()->update(); } @@ -110,7 +109,7 @@ QStringList GroupedLineEdit::getBlockStringList() QStringList retList; Private::Block block; foreach(block, d->blocks) - retList.append(block.text); + retList.append(block.text); return retList; } @@ -150,11 +149,10 @@ void GroupedLineEdit::removeAllBlocks() QSize GroupedLineEdit::sizeHint() const { QSize rs( - 40, - document()->findBlock(0).layout()->lineAt(0).height() + - document()->documentMargin() * 2 + - frameWidth() * 2 - ); + 40, + document()->findBlock(0).layout()->lineAt(0).height() + + document()->documentMargin() * 2 + + frameWidth() * 2); return rs; } @@ -191,23 +189,22 @@ void GroupedLineEdit::paintEvent(QPaintEvent *e) QVectorIterator<QColor> i(d->colors); i.toFront(); - foreach (const Private::Block &block, d->blocks) { + foreach(const Private::Block & block, d->blocks) { qreal start_x = line.cursorToX(block.start, QTextLine::Trailing); qreal end_x = line.cursorToX(block.end + 1, QTextLine::Leading); QPainterPath path; QRectF rectangle( - start_x - 1.0 - double(horizontalScrollBar()->value()), - 1.0, - end_x - start_x + 2.0, - double(viewport()->height() - 2) - ); - if (! i.hasNext()) + start_x - 1.0 - double(horizontalScrollBar()->value()), + 1.0, + end_x - start_x + 2.0, + double(viewport()->height() - 2)); + if (!i.hasNext()) i.toFront(); path.addRoundedRect(rectangle, 5.0, 5.0); painter.setPen(i.peekNext()); - if (palette().color(QPalette::Text).lightnessF() <= 0.3 ) + if (palette().color(QPalette::Text).lightnessF() <= 0.3) painter.setBrush(i.next().lighter()); - else if (palette().color(QPalette::Text).lightnessF() <= 0.6 ) + else if (palette().color(QPalette::Text).lightnessF() <= 0.6) painter.setBrush(i.next()); else painter.setBrush(i.next().darker()); diff --git a/qt-ui/groupedlineedit.h b/qt-ui/groupedlineedit.h index d0b675e98..c9cd1a0e0 100644 --- a/qt-ui/groupedlineedit.h +++ b/qt-ui/groupedlineedit.h @@ -33,8 +33,7 @@ #include <QPlainTextEdit> #include <QStringList> -class GroupedLineEdit : public QPlainTextEdit -{ +class GroupedLineEdit : public QPlainTextEdit { Q_OBJECT public: @@ -65,6 +64,7 @@ signals: protected: virtual void paintEvent(QPaintEvent *e); virtual void keyPressEvent(QKeyEvent *e); + private: struct Private; Private *d; diff --git a/qt-ui/kmessagewidget.cpp b/qt-ui/kmessagewidget.cpp index 8094eca6f..c21dea867 100644 --- a/qt-ui/kmessagewidget.cpp +++ b/qt-ui/kmessagewidget.cpp @@ -30,7 +30,7 @@ #include <QStyle> #include <QAction> -void KMessageWidgetPrivate::init(KMessageWidget* q_ptr) +void KMessageWidgetPrivate::init(KMessageWidget *q_ptr) { q = q_ptr; @@ -52,10 +52,10 @@ void KMessageWidgetPrivate::init(KMessageWidget* q_ptr) textLabel = new QLabel(content); textLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); textLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); - QObject::connect(textLabel, SIGNAL(linkActivated(const QString&)), q, SIGNAL(linkActivated(const QString&))); - QObject::connect(textLabel, SIGNAL(linkHovered(const QString&)), q, SIGNAL(linkHovered(const QString&))); + QObject::connect(textLabel, SIGNAL(linkActivated(const QString &)), q, SIGNAL(linkActivated(const QString &))); + QObject::connect(textLabel, SIGNAL(linkHovered(const QString &)), q, SIGNAL(linkHovered(const QString &))); - QAction* closeAction = new QAction(QObject::tr("Close"), q); + QAction *closeAction = new QAction(QObject::tr("Close"), q); q->connect(closeAction, SIGNAL(triggered(bool)), q, SLOT(animatedHide())); closeButton = new QToolButton(content); @@ -74,8 +74,8 @@ void KMessageWidgetPrivate::createLayout() qDeleteAll(buttons); buttons.clear(); - Q_FOREACH(QAction* action, q->actions()) { - QToolButton* button = new QToolButton(content); + Q_FOREACH(QAction * action, q->actions()) { + QToolButton *button = new QToolButton(content); button->setDefaultAction(action); button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); buttons.append(button); @@ -87,14 +87,14 @@ void KMessageWidgetPrivate::createLayout() closeButton->setAutoRaise(buttons.isEmpty()); if (wordWrap) { - QGridLayout* layout = new QGridLayout(content); + QGridLayout *layout = new QGridLayout(content); // Set alignment to make sure icon does not move down if text wraps layout->addWidget(iconLabel, 0, 0, 1, 1, Qt::AlignHCenter | Qt::AlignTop); layout->addWidget(textLabel, 0, 1); - QHBoxLayout* buttonLayout = new QHBoxLayout; + QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(); - Q_FOREACH(QToolButton* button, buttons) { + Q_FOREACH(QToolButton * button, buttons) { // For some reason, calling show() is necessary if wordwrap is true, // otherwise the buttons do not show up. It is not needed if // wordwrap is false. @@ -104,11 +104,11 @@ void KMessageWidgetPrivate::createLayout() buttonLayout->addWidget(closeButton); layout->addItem(buttonLayout, 1, 0, 1, 2); } else { - QHBoxLayout* layout = new QHBoxLayout(content); + QHBoxLayout *layout = new QHBoxLayout(content); layout->addWidget(iconLabel); layout->addWidget(textLabel); - Q_FOREACH(QToolButton* button, buttons) { + Q_FOREACH(QToolButton * button, buttons) { layout->addWidget(button); } @@ -174,16 +174,12 @@ int KMessageWidgetPrivate::bestContentHeight() const //--------------------------------------------------------------------- // KMessageWidget //--------------------------------------------------------------------- -KMessageWidget::KMessageWidget(QWidget* parent) - : QFrame(parent) - , d(new KMessageWidgetPrivate) +KMessageWidget::KMessageWidget(QWidget *parent) : QFrame(parent), d(new KMessageWidgetPrivate) { d->init(this); } -KMessageWidget::KMessageWidget(const QString& text, QWidget* parent) - : QFrame(parent) - , d(new KMessageWidgetPrivate) +KMessageWidget::KMessageWidget(const QString &text, QWidget *parent) : QFrame(parent), d(new KMessageWidgetPrivate) { d->init(this); setText(text); @@ -199,7 +195,7 @@ QString KMessageWidget::text() const return d->textLabel->text(); } -void KMessageWidget::setText(const QString& text) +void KMessageWidget::setText(const QString &text) { d->textLabel->setText(text); updateGeometry(); @@ -242,7 +238,7 @@ void KMessageWidget::setMessageType(KMessageWidget::MessageType type) bg2 = bg1.darker(110); border = bg2.darker(110); d->content->setStyleSheet( - QString(".QFrame {" + QString(".QFrame {" "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," " stop: 0 %1," " stop: 0.1 %2," @@ -251,20 +247,17 @@ void KMessageWidget::setMessageType(KMessageWidget::MessageType type) "border: 1px solid %4;" "margin: %5px;" "}" - ".QLabel { color: %6; }" - ).arg(bg0.name()) + ".QLabel { color: %6; }").arg(bg0.name()) .arg(bg1.name()) .arg(bg2.name()) .arg(border.name()) - /* + /* DefaultFrameWidth returns the size of the external margin + border width. We know our border is 1px, so we subtract this from the frame normal QStyle FrameWidth to get our margin */ - - .arg(style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this) -1) - .arg(fg.name()) - ); + .arg(style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, this) - 1) + .arg(fg.name())); } QSize KMessageWidget::sizeHint() const @@ -279,7 +272,7 @@ QSize KMessageWidget::minimumSizeHint() const return d->content->minimumSizeHint(); } -bool KMessageWidget::event(QEvent* event) +bool KMessageWidget::event(QEvent *event) { if (event->type() == QEvent::Polish && !d->content->layout()) { d->createLayout(); @@ -288,7 +281,7 @@ bool KMessageWidget::event(QEvent* event) return QFrame::event(event); } -void KMessageWidget::resizeEvent(QResizeEvent* event) +void KMessageWidget::resizeEvent(QResizeEvent *event) { QFrame::resizeEvent(event); @@ -303,7 +296,7 @@ int KMessageWidget::heightForWidth(int width) const return d->content->heightForWidth(width); } -void KMessageWidget::paintEvent(QPaintEvent* event) +void KMessageWidget::paintEvent(QPaintEvent *event) { QFrame::paintEvent(event); @@ -314,7 +307,7 @@ void KMessageWidget::paintEvent(QPaintEvent* event) } } -void KMessageWidget::showEvent(QShowEvent* event) +void KMessageWidget::showEvent(QShowEvent *event) { // Keep this method here to avoid breaking binary compatibility: // QFrame::showEvent() used to be reimplemented. @@ -354,13 +347,13 @@ void KMessageWidget::setCloseButtonVisible(bool show) updateGeometry(); } -void KMessageWidget::addAction(QAction* action) +void KMessageWidget::addAction(QAction *action) { QFrame::addAction(action); d->updateLayout(); } -void KMessageWidget::removeAction(QAction* action) +void KMessageWidget::removeAction(QAction *action) { QFrame::removeAction(action); d->updateLayout(); @@ -408,15 +401,14 @@ QIcon KMessageWidget::icon() const return d->icon; } -void KMessageWidget::setIcon(const QIcon& icon) +void KMessageWidget::setIcon(const QIcon &icon) { d->icon = icon; if (d->icon.isNull()) { d->iconLabel->hide(); } else { - d->iconLabel->setPixmap(d->icon.pixmap(QSize(16,16))); + d->iconLabel->setPixmap(d->icon.pixmap(QSize(16, 16))); d->iconLabel->show(); } } - diff --git a/qt-ui/kmessagewidget.h b/qt-ui/kmessagewidget.h index 548421103..7a0a253ae 100644 --- a/qt-ui/kmessagewidget.h +++ b/qt-ui/kmessagewidget.h @@ -87,118 +87,118 @@ class KMessageWidgetPrivate; * @author Aurélien Gâteau <agateau@kde.org> * @since 4.7 */ -class KMessageWidget : public QFrame -{ - Q_OBJECT - Q_ENUMS(MessageType) - - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap) - Q_PROPERTY(bool closeButtonVisible READ isCloseButtonVisible WRITE setCloseButtonVisible) - Q_PROPERTY(MessageType messageType READ messageType WRITE setMessageType) - Q_PROPERTY(QIcon icon READ icon WRITE setIcon) +class KMessageWidget : public QFrame { + Q_OBJECT + Q_ENUMS(MessageType) + + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap) + Q_PROPERTY(bool closeButtonVisible READ isCloseButtonVisible WRITE setCloseButtonVisible) + Q_PROPERTY(MessageType messageType READ messageType WRITE setMessageType) + Q_PROPERTY(QIcon icon READ icon WRITE setIcon) public: - enum MessageType { - Positive, - Information, - Warning, - Error - }; - - /** + enum MessageType { + Positive, + Information, + Warning, + Error + }; + + /** * Constructs a KMessageWidget with the specified parent. */ - explicit KMessageWidget(QWidget *parent = 0); + explicit KMessageWidget(QWidget *parent = 0); - explicit KMessageWidget(const QString &text, QWidget *parent = 0); + explicit KMessageWidget(const QString &text, QWidget *parent = 0); - ~KMessageWidget(); + ~KMessageWidget(); - QString text() const; + QString text() const; - bool wordWrap() const; + bool wordWrap() const; - bool isCloseButtonVisible() const; + bool isCloseButtonVisible() const; - MessageType messageType() const; + MessageType messageType() const; - void addAction(QAction *action); + void addAction(QAction *action); - void removeAction(QAction *action); + void removeAction(QAction *action); - QSize sizeHint() const; + QSize sizeHint() const; - QSize minimumSizeHint() const; + QSize minimumSizeHint() const; - int heightForWidth(int width) const; + int heightForWidth(int width) const; - /** + /** * The icon shown on the left of the text. By default, no icon is shown. * @since 4.11 */ - QIcon icon() const; + QIcon icon() const; -public Q_SLOTS: - void setText(const QString &text); +public +Q_SLOTS: + void setText(const QString &text); - void setWordWrap(bool wordWrap); + void setWordWrap(bool wordWrap); - void setCloseButtonVisible(bool visible); + void setCloseButtonVisible(bool visible); - void setMessageType(KMessageWidget::MessageType type); + void setMessageType(KMessageWidget::MessageType type); - /** + /** * Show the widget using an animation, unless * KGlobalSettings::graphicsEffectLevel() does not allow simple effects. */ - void animatedShow(); + void animatedShow(); - /** + /** * Hide the widget using an animation, unless * KGlobalSettings::graphicsEffectLevel() does not allow simple effects. */ - void animatedHide(); + void animatedHide(); - /** + /** * Define an icon to be shown on the left of the text * @since 4.11 */ - void setIcon(const QIcon &icon); + void setIcon(const QIcon &icon); Q_SIGNALS: - /** + /** * This signal is emitted when the user clicks a link in the text label. * The URL referred to by the href anchor is passed in contents. * @param contents text of the href anchor * @see QLabel::linkActivated() * @since 4.10 */ - void linkActivated(const QString& contents); + void linkActivated(const QString &contents); - /** + /** * This signal is emitted when the user hovers over a link in the text label. * The URL referred to by the href anchor is passed in contents. * @param contents text of the href anchor * @see QLabel::linkHovered() * @since 4.11 */ - void linkHovered(const QString& contents); + void linkHovered(const QString &contents); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event); - bool event(QEvent *event); + bool event(QEvent *event); - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); - void showEvent(QShowEvent *event); + void showEvent(QShowEvent *event); private: - KMessageWidgetPrivate *const d; - friend class KMessageWidgetPrivate; + KMessageWidgetPrivate *const d; + friend class KMessageWidgetPrivate; - Q_PRIVATE_SLOT(d, void slotTimeLineChanged(qreal)) - Q_PRIVATE_SLOT(d, void slotTimeLineFinished()) + Q_PRIVATE_SLOT(d, void slotTimeLineChanged(qreal)) + Q_PRIVATE_SLOT(d, void slotTimeLineFinished()) }; //--------------------------------------------------------------------- @@ -209,22 +209,21 @@ class QToolButton; class QTimeLine; #include <QIcon> -class KMessageWidgetPrivate -{ +class KMessageWidgetPrivate { public: - void init(KMessageWidget*); - - KMessageWidget* q; - QFrame* content; - QLabel* iconLabel; - QLabel* textLabel; - QToolButton* closeButton; - QTimeLine* timeLine; + void init(KMessageWidget *); + + KMessageWidget *q; + QFrame *content; + QLabel *iconLabel; + QLabel *textLabel; + QToolButton *closeButton; + QTimeLine *timeLine; QIcon icon; KMessageWidget::MessageType messageType; bool wordWrap; - QList<QToolButton*> buttons; + QList<QToolButton *> buttons; QPixmap contentSnapShot; void createLayout(); diff --git a/qt-ui/maintab.cpp b/qt-ui/maintab.cpp index 554b3ccc6..2af6b7b27 100644 --- a/qt-ui/maintab.cpp +++ b/qt-ui/maintab.cpp @@ -26,9 +26,9 @@ #include <QScrollBar> MainTab::MainTab(QWidget *parent) : QTabWidget(parent), - weightModel(new WeightModel(this)), - cylindersModel(CylindersModel::instance()), - editMode(NONE) + weightModel(new WeightModel(this)), + cylindersModel(CylindersModel::instance()), + editMode(NONE) { ui.setupUi(this); @@ -69,8 +69,8 @@ MainTab::MainTab(QWidget *parent) : QTabWidget(parent), ui.tagWidget->installEventFilter(this); QList<QObject *> statisticsTabWidgets = ui.statisticsTab->children(); - Q_FOREACH(QObject* obj, statisticsTabWidgets) { - QLabel* label = qobject_cast<QLabel *>(obj); + Q_FOREACH(QObject * obj, statisticsTabWidgets) { + QLabel *label = qobject_cast<QLabel *>(obj); if (label) label->setAlignment(Qt::AlignHCenter); } @@ -134,18 +134,17 @@ MainTab::MainTab(QWidget *parent) : QTabWidget(parent), " background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," " stop: 0 #E0E0E0, stop: 1 #FFFFFF);" "}"); - Q_FOREACH(QGroupBox *box, findChildren<QGroupBox*>()) { + Q_FOREACH(QGroupBox * box, findChildren<QGroupBox *>()) { box->setStyleSheet(gnomeCss); } - } ui.cylinders->view()->horizontalHeader()->setContextMenuPolicy(Qt::ActionsContextMenu); QSettings s; s.beginGroup("cylinders_dialog"); - for(int i = 0; i < CylindersModel::COLUMNS; i++) { + for (int i = 0; i < CylindersModel::COLUMNS; i++) { if ((i == CylindersModel::REMOVE) || (i == CylindersModel::TYPE)) - continue; + continue; bool checked = s.value(QString("column%1_hidden").arg(i)).toBool(); action = new QAction(cylindersModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString(), ui.cylinders->view()); action->setCheckable(true); @@ -161,16 +160,16 @@ MainTab::~MainTab() { QSettings s; s.beginGroup("cylinders_dialog"); - for(int i = 0; i < CylindersModel::COLUMNS; i++) { + for (int i = 0; i < CylindersModel::COLUMNS; i++) { if ((i == CylindersModel::REMOVE) || (i == CylindersModel::TYPE)) - continue; + continue; s.setValue(QString("column%1_hidden").arg(i), ui.cylinders->view()->isColumnHidden(i)); } } void MainTab::toggleTriggeredColumn() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); int col = action->data().toInt(); QTableView *view = ui.cylinders->view(); @@ -178,8 +177,7 @@ void MainTab::toggleTriggeredColumn() view->showColumn(col); if (view->columnWidth(col) <= 15) view->setColumnWidth(col, 80); - } - else + } else view->hideColumn(col); } @@ -188,7 +186,7 @@ void MainTab::addDiveStarted() enableEdition(ADD); } -void MainTab::addMessageAction(QAction* action) +void MainTab::addMessageAction(QAction *action) { ui.diveEquipmentMessage->addAction(action); ui.diveNotesMessage->addAction(action); @@ -272,7 +270,7 @@ void MainTab::enableEdition(EditMode newEditMode) notesBackup[mydive].visibility = mydive->visibility; notesBackup[mydive].latitude = mydive->latitude; notesBackup[mydive].longitude = mydive->longitude; - notesBackup[mydive].coordinates = ui.coordinates->text(); + notesBackup[mydive].coordinates = ui.coordinates->text(); notesBackup[mydive].airtemp = get_temperature_string(mydive->airtemp, true); notesBackup[mydive].watertemp = get_temperature_string(mydive->watertemp, true); notesBackup[mydive].datetime = QDateTime::fromTime_t(mydive->when).toUTC().toString(); @@ -293,7 +291,7 @@ void MainTab::enableEdition(EditMode newEditMode) } } -bool MainTab::eventFilter(QObject* object, QEvent* event) +bool MainTab::eventFilter(QObject *object, QEvent *event) { if (!isEnabled()) return false; @@ -349,17 +347,17 @@ void MainTab::clearStats() ui.timeLimits->clear(); } -#define UPDATE_TEXT(d, field) \ - if (!d || !d->field) \ - ui.field->setText(""); \ - else \ - ui.field->setText(d->field) +#define UPDATE_TEXT(d, field) \ + if (!d || !d->field) \ + ui.field->setText(""); \ + else \ + ui.field->setText(d->field) -#define UPDATE_TEMP(d, field) \ - if (!d || d->field.mkelvin == 0) \ - ui.field->setText(""); \ - else \ - ui.field->setText(get_temperature_string(d->field, true)) +#define UPDATE_TEMP(d, field) \ + if (!d || d->field.mkelvin == 0) \ + ui.field->setText(""); \ + else \ + ui.field->setText(get_temperature_string(d->field, true)) bool MainTab::isEditing() { @@ -480,7 +478,7 @@ void MainTab::updateDiveInfo(int dive) } else { SACs = QString(tr("unknown")); } - for(int i=1; i < MAX_CYLINDERS && gases[i].mliter != 0; i++) { + for (int i = 1; i < MAX_CYLINDERS && gases[i].mliter != 0; i++) { volumes.append("\n" + get_volume_string(gases[i], true)); if (duration[i]) { sac.mliter = gases[i].mliter / (depth_to_atm(mean[i], d) * duration[i] / 60); @@ -507,7 +505,7 @@ void MainTab::updateDiveInfo(int dive) else ui.airPressureText->clear(); if (d->salinity) - ui.salinityText->setText(QString("%1g/l").arg(d->salinity/10.0)); + ui.salinityText->setText(QString("%1g/l").arg(d->salinity / 10.0)); else ui.salinityText->clear(); ui.depthLimits->setMaximum(get_depth_string(stats_selection.max_depth, true)); @@ -542,7 +540,7 @@ void MainTab::updateDiveInfo(int dive) ui.coordinates->clear(); ui.visibility->setCurrentStars(0); /* turns out this is non-trivial for a dateTimeEdit... this is a partial hack */ - QLineEdit *le = ui.dateTimeEdit->findChild<QLineEdit*>(); + QLineEdit *le = ui.dateTimeEdit->findChild<QLineEdit *>(); le->setText(""); } } @@ -580,28 +578,28 @@ void MainTab::acceptChanges() /* now figure out if things have changed */ if (MainWindow::instance() && MainWindow::instance()->dive_list()->selectedTrips().count() == 1) { if (notesBackup[NULL].notes != ui.notes->toPlainText() || - notesBackup[NULL].location != ui.location->text()) + notesBackup[NULL].location != ui.location->text()) mark_divelist_changed(true); } else { struct dive *curr = current_dive; //Reset coordinates field, in case it contains garbage. updateGpsCoordinates(curr); if (notesBackup[curr].buddy != ui.buddy->text() || - notesBackup[curr].suit != ui.suit->text() || - notesBackup[curr].notes != ui.notes->toPlainText() || - notesBackup[curr].divemaster != ui.divemaster->text() || - notesBackup[curr].location != ui.location->text() || - notesBackup[curr].coordinates != ui.coordinates->text() || - notesBackup[curr].rating != ui.visibility->currentStars() || - notesBackup[curr].airtemp != ui.airtemp->text() || - notesBackup[curr].watertemp != ui.watertemp->text() || - notesBackup[curr].datetime != ui.dateTimeEdit->dateTime().toString() || - notesBackup[curr].visibility != ui.rating->currentStars() || - notesBackup[curr].tags != ui.tagWidget->text()) { + notesBackup[curr].suit != ui.suit->text() || + notesBackup[curr].notes != ui.notes->toPlainText() || + notesBackup[curr].divemaster != ui.divemaster->text() || + notesBackup[curr].location != ui.location->text() || + notesBackup[curr].coordinates != ui.coordinates->text() || + notesBackup[curr].rating != ui.visibility->currentStars() || + notesBackup[curr].airtemp != ui.airtemp->text() || + notesBackup[curr].watertemp != ui.watertemp->text() || + notesBackup[curr].datetime != ui.dateTimeEdit->dateTime().toString() || + notesBackup[curr].visibility != ui.rating->currentStars() || + notesBackup[curr].tags != ui.tagWidget->text()) { mark_divelist_changed(true); } if (notesBackup[curr].location != ui.location->text() || - notesBackup[curr].coordinates != ui.coordinates->text()) { + notesBackup[curr].coordinates != ui.coordinates->text()) { MainWindow::instance()->globe()->reload(); } @@ -611,7 +609,7 @@ void MainTab::acceptChanges() DivePlannerPointsModel::instance()->copyCylinders(curr); } else if (editMode != ADD && cylindersModel->changed) { mark_divelist_changed(true); - Q_FOREACH (dive *d, notesBackup.keys()) { + Q_FOREACH(dive * d, notesBackup.keys()) { for (int i = 0; i < MAX_CYLINDERS; i++) { if (notesBackup.keys().count() > 1) // only copy the cylinder type, none of the other values @@ -624,13 +622,12 @@ void MainTab::acceptChanges() if (weightModel->changed) { mark_divelist_changed(true); - Q_FOREACH (dive *d, notesBackup.keys()) { + Q_FOREACH(dive * d, notesBackup.keys()) { for (int i = 0; i < MAX_WEIGHTSYSTEMS; i++) { d->weightsystem[i] = multiEditEquipmentPlaceholder.weightsystem[i]; } } } - } if (current_dive->divetrip) { current_dive->divetrip->when = current_dive->when; @@ -650,7 +647,7 @@ void MainTab::acceptChanges() } // each dive that was selected might have had the temperatures in its active divecomputer changed // so re-populate the temperatures - easiest way to do this is by calling fixup_dive - Q_FOREACH(dive *d, notesBackup.keys()) { + Q_FOREACH(dive * d, notesBackup.keys()) { if (d) fixup_dive(d); } @@ -658,13 +655,13 @@ void MainTab::acceptChanges() resetPallete(); if (editMode == ADD || editMode == MANUALLY_ADDED_DIVE) { MainWindow::instance()->dive_list()->unselectDives(); - struct dive *d = get_dive(dive_table.nr -1 ); + struct dive *d = get_dive(dive_table.nr - 1); // mark the dive as remembered (abusing the selected flag) // and then clear that flag out on the other side of the sort_table() d->selected = true; sort_table(&dive_table); int i = 0; - for_each_dive(i,d) { + for_each_dive(i, d) { if (d->selected) { d->selected = false; break; @@ -672,7 +669,7 @@ void MainTab::acceptChanges() } editMode = NONE; MainWindow::instance()->refreshDisplay(); - MainWindow::instance()->dive_list()->selectDive( i, true ); + MainWindow::instance()->dive_list()->selectDive(i, true); } else { editMode = NONE; MainWindow::instance()->dive_list()->rememberSelection(); @@ -700,14 +697,14 @@ void MainTab::resetPallete() ui.tagWidget->setPalette(p); } -#define EDIT_TEXT2(what, text) \ +#define EDIT_TEXT2(what, text) \ textByteArray = text.toUtf8(); \ - free(what);\ + free(what); \ what = strdup(textByteArray.data()); -#define EDIT_TEXT(what, text) \ +#define EDIT_TEXT(what, text) \ QByteArray textByteArray = text.toUtf8(); \ - free(what);\ + free(what); \ what = strdup(textByteArray.data()); void MainTab::rejectChanges() @@ -718,19 +715,19 @@ void MainTab::rejectChanges() MainWindow::instance()->dive_list()->setEnabled(true); if (MainWindow::instance() && MainWindow::instance()->dive_list()->selectedTrips().count() == 1) { - ui.notes->setText(notesBackup[NULL].notes ); + ui.notes->setText(notesBackup[NULL].notes); ui.location->setText(notesBackup[NULL].location); } else { if (lastMode == ADD) { // clean up DivePlannerPointsModel::instance()->cancelPlan(); - } else if (lastMode == MANUALLY_ADDED_DIVE ) { + } else if (lastMode == MANUALLY_ADDED_DIVE) { // when we tried to edit a manually added dive, we destroyed // the dive we edited, so let's just restore it from backup DivePlannerPointsModel::instance()->restoreBackupDive(); } struct dive *curr = current_dive; - ui.notes->setText(notesBackup[curr].notes ); + ui.notes->setText(notesBackup[curr].notes); ui.location->setText(notesBackup[curr].location); ui.buddy->setText(notesBackup[curr].buddy); ui.suit->setText(notesBackup[curr].suit); @@ -744,7 +741,7 @@ void MainTab::rejectChanges() if (curr) { ui.dateTimeEdit->setDateTime(QDateTime::fromString(notesBackup[curr].datetime)); } else { - QLineEdit *le = ui.dateTimeEdit->findChild<QLineEdit*>(); + QLineEdit *le = ui.dateTimeEdit->findChild<QLineEdit *>(); le->setText(""); } @@ -810,74 +807,72 @@ void MainTab::rejectChanges() } #undef EDIT_TEXT2 -#define EDIT_SELECTED_DIVES( WHAT ) do { \ - if (editMode == NONE) \ - return; \ -\ - for (int _i = 0; _i < dive_table.nr; _i++) { \ - struct dive *mydive = get_dive(_i); \ - if (!mydive) \ - continue; \ - if (!mydive->selected) \ - continue; \ -\ - WHAT; \ - } \ -} while(0) - -void markChangedWidget(QWidget *w) { +#define EDIT_SELECTED_DIVES(WHAT) \ + do { \ + if (editMode == NONE) \ + return; \ + \ + for (int _i = 0; _i < dive_table.nr; _i++) { \ + struct dive *mydive = get_dive(_i); \ + if (!mydive) \ + continue; \ + if (!mydive->selected) \ + continue; \ + \ + WHAT; \ + } \ + } while (0) + +void markChangedWidget(QWidget *w) +{ QPalette p; qreal h, s, l, a; qApp->palette().color(QPalette::Text).getHslF(&h, &s, &l, &a); - p.setBrush(QPalette::Base, ( l <= 0.3 ) ? QColor(Qt::yellow).lighter() - :( l <= 0.6 ) ? QColor(Qt::yellow).light() - :/* else */ QColor(Qt::yellow).darker(300) - ); + p.setBrush(QPalette::Base, (l <= 0.3) ? QColor(Qt::yellow).lighter() : (l <= 0.6) ? QColor(Qt::yellow).light() : /* else */ QColor(Qt::yellow).darker(300)); w->setPalette(p); } void MainTab::on_buddy_textChanged() { QString text = ui.buddy->toPlainText().split(",", QString::SkipEmptyParts).join(", "); - EDIT_SELECTED_DIVES( EDIT_TEXT(mydive->buddy, text) ); + EDIT_SELECTED_DIVES(EDIT_TEXT(mydive->buddy, text)); markChangedWidget(ui.buddy); } void MainTab::on_divemaster_textChanged() { QString text = ui.divemaster->toPlainText().split(",", QString::SkipEmptyParts).join(", "); - EDIT_SELECTED_DIVES( EDIT_TEXT(mydive->divemaster, text) ); + EDIT_SELECTED_DIVES(EDIT_TEXT(mydive->divemaster, text)); markChangedWidget(ui.divemaster); } -void MainTab::on_airtemp_textChanged(const QString& text) +void MainTab::on_airtemp_textChanged(const QString &text) { - EDIT_SELECTED_DIVES( select_dc(&mydive->dc)->airtemp.mkelvin = parseTemperatureToMkelvin(text) ); + EDIT_SELECTED_DIVES(select_dc(&mydive->dc)->airtemp.mkelvin = parseTemperatureToMkelvin(text)); markChangedWidget(ui.airtemp); } -void MainTab::on_watertemp_textChanged(const QString& text) +void MainTab::on_watertemp_textChanged(const QString &text) { - EDIT_SELECTED_DIVES( select_dc(&mydive->dc)->watertemp.mkelvin = parseTemperatureToMkelvin(text) ); + EDIT_SELECTED_DIVES(select_dc(&mydive->dc)->watertemp.mkelvin = parseTemperatureToMkelvin(text)); markChangedWidget(ui.watertemp); } -void MainTab::on_dateTimeEdit_dateTimeChanged(const QDateTime& datetime) +void MainTab::on_dateTimeEdit_dateTimeChanged(const QDateTime &datetime) { QDateTime dateTimeUtc(datetime); dateTimeUtc.setTimeSpec(Qt::UTC); - EDIT_SELECTED_DIVES( mydive->when = dateTimeUtc.toTime_t() ); + EDIT_SELECTED_DIVES(mydive->when = dateTimeUtc.toTime_t()); markChangedWidget(ui.dateTimeEdit); } void MainTab::saveTags() { EDIT_SELECTED_DIVES( - QString tag; - taglist_clear(mydive->tag_list); - foreach (tag, ui.tagWidget->getBlockStringList()) - taglist_add_tag(mydive->tag_list, tag.toUtf8().data()); - ); + QString tag; + taglist_clear(mydive->tag_list); + foreach(tag, ui.tagWidget->getBlockStringList()) + taglist_add_tag(mydive->tag_list, tag.toUtf8().data());); } void MainTab::on_tagWidget_textChanged() @@ -885,7 +880,7 @@ void MainTab::on_tagWidget_textChanged() markChangedWidget(ui.tagWidget); } -void MainTab::on_location_textChanged(const QString& text) +void MainTab::on_location_textChanged(const QString &text) { if (editMode == NONE) return; @@ -896,14 +891,14 @@ void MainTab::on_location_textChanged(const QString& text) } else if (editMode == DIVE || editMode == ADD || editMode == MANUALLY_ADDED_DIVE) { if (!ui.coordinates->isModified() || ui.coordinates->text().trimmed().isEmpty()) { - struct dive* dive; + struct dive *dive; int i = 0; for_each_dive(i, dive) { QString location(dive->location); if (location == text && (dive->latitude.udeg || dive->longitude.udeg)) { - EDIT_SELECTED_DIVES( mydive->latitude = dive->latitude ); - EDIT_SELECTED_DIVES( mydive->longitude = dive->longitude ); + EDIT_SELECTED_DIVES(mydive->latitude = dive->latitude); + EDIT_SELECTED_DIVES(mydive->longitude = dive->longitude); //Don't use updateGpsCoordinates() since we don't want to set modified state yet ui.coordinates->setText(printGPSCoords(dive->latitude.udeg, dive->longitude.udeg)); markChangedWidget(ui.coordinates); @@ -911,15 +906,15 @@ void MainTab::on_location_textChanged(const QString& text) } } } - EDIT_SELECTED_DIVES( EDIT_TEXT(mydive->location, text) ); + EDIT_SELECTED_DIVES(EDIT_TEXT(mydive->location, text)); MainWindow::instance()->globe()->repopulateLabels(); } markChangedWidget(ui.location); } -void MainTab::on_suit_textChanged(const QString& text) +void MainTab::on_suit_textChanged(const QString &text) { - EDIT_SELECTED_DIVES( EDIT_TEXT(mydive->suit, text) ); + EDIT_SELECTED_DIVES(EDIT_TEXT(mydive->suit, text)); markChangedWidget(ui.suit); } @@ -932,14 +927,14 @@ void MainTab::on_notes_textChanged() dive_trip_t *currentTrip = *MainWindow::instance()->dive_list()->selectedTrips().begin(); EDIT_TEXT(currentTrip->notes, ui.notes->toPlainText()); } else if (editMode == DIVE || editMode == ADD || editMode == MANUALLY_ADDED_DIVE) { - EDIT_SELECTED_DIVES( EDIT_TEXT(mydive->notes, ui.notes->toPlainText()) ); + EDIT_SELECTED_DIVES(EDIT_TEXT(mydive->notes, ui.notes->toPlainText())); } markChangedWidget(ui.notes); } #undef EDIT_TEXT -void MainTab::on_coordinates_textChanged(const QString& text) +void MainTab::on_coordinates_textChanged(const QString &text) { bool gpsChanged = false; bool parsed = false; @@ -955,15 +950,15 @@ void MainTab::on_coordinates_textChanged(const QString& text) void MainTab::on_rating_valueChanged(int value) { - EDIT_SELECTED_DIVES(mydive->rating = value ); + EDIT_SELECTED_DIVES(mydive->rating = value); } void MainTab::on_visibility_valueChanged(int value) { - EDIT_SELECTED_DIVES( mydive->visibility = value ); + EDIT_SELECTED_DIVES(mydive->visibility = value); } -void MainTab::editCylinderWidget(const QModelIndex& index) +void MainTab::editCylinderWidget(const QModelIndex &index) { if (editMode == NONE) enableEdition(); @@ -972,7 +967,7 @@ void MainTab::editCylinderWidget(const QModelIndex& index) ui.cylinders->edit(index); } -void MainTab::editWeightWidget(const QModelIndex& index) +void MainTab::editWeightWidget(const QModelIndex &index) { if (editMode == NONE) enableEdition(); @@ -985,7 +980,7 @@ QString MainTab::printGPSCoords(int lat, int lon) { unsigned int latdeg, londeg; unsigned int latmin, lonmin; - double latsec, lonsec; + double latsec, lonsec; QString lath, lonh, result; if (!lat && !lon) diff --git a/qt-ui/maintab.h b/qt-ui/maintab.h index a1e588f77..946b673b6 100644 --- a/qt-ui/maintab.h +++ b/qt-ui/maintab.h @@ -18,7 +18,7 @@ class QCompleter; struct dive; -struct NotesBackup{ +struct NotesBackup { QString airtemp; QString watertemp; QString datetime; @@ -34,10 +34,10 @@ struct NotesBackup{ QString divemaster; QString tags; cylinder_t cylinders[MAX_CYLINDERS]; - weightsystem_t weightsystem[MAX_WEIGHTSYSTEMS ]; + weightsystem_t weightsystem[MAX_WEIGHTSYSTEMS]; }; -struct Completers{ +struct Completers { QCompleter *location; QCompleter *divemaster; QCompleter *buddy; @@ -45,11 +45,16 @@ struct Completers{ QCompleter *tags; }; -class MainTab : public QTabWidget -{ +class MainTab : public QTabWidget { Q_OBJECT public: - enum EditMode { NONE, DIVE, TRIP, ADD, MANUALLY_ADDED_DIVE }; + enum EditMode { + NONE, + DIVE, + TRIP, + ADD, + MANUALLY_ADDED_DIVE + }; MainTab(QWidget *parent); ~MainTab(); @@ -57,42 +62,44 @@ public: void clearInfo(); void clearEquipment(); void reload(); - bool eventFilter(QObject* , QEvent*); + bool eventFilter(QObject *, QEvent *); void initialUiSetup(); bool isEditing(); void updateCoordinatesText(qreal lat, qreal lon); -public slots: +public +slots: void addCylinder_clicked(); void addWeight_clicked(); void updateDiveInfo(int dive = selected_dive); void acceptChanges(); void rejectChanges(); - void on_location_textChanged(const QString& text); - void on_coordinates_textChanged(const QString& text); + void on_location_textChanged(const QString &text); + void on_coordinates_textChanged(const QString &text); void on_divemaster_textChanged(); void on_buddy_textChanged(); - void on_suit_textChanged(const QString& text); + void on_suit_textChanged(const QString &text); void on_notes_textChanged(); - void on_airtemp_textChanged(const QString& text); - void on_watertemp_textChanged(const QString& text); - void on_dateTimeEdit_dateTimeChanged(const QDateTime& datetime); + void on_airtemp_textChanged(const QString &text); + void on_watertemp_textChanged(const QString &text); + void on_dateTimeEdit_dateTimeChanged(const QDateTime &datetime); void on_rating_valueChanged(int value); void on_visibility_valueChanged(int value); void on_tagWidget_textChanged(); - void editCylinderWidget(const QModelIndex& index); - void editWeightWidget(const QModelIndex& index); + void editCylinderWidget(const QModelIndex &index); + void editWeightWidget(const QModelIndex &index); void addDiveStarted(); - void addMessageAction(QAction* action); + void addMessageAction(QAction *action); void hideMessage(); void closeMessage(); void displayMessage(QString str); void enableEdition(EditMode newEditMode = NONE); void toggleTriggeredColumn(); + private: Ui::MainTab ui; WeightModel *weightModel; CylindersModel *cylindersModel; - QMap<dive*, NotesBackup> notesBackup; + QMap<dive *, NotesBackup> notesBackup; EditMode editMode; BuddyCompletionModel buddyModel; diff --git a/qt-ui/mainwindow.h b/qt-ui/mainwindow.h index 9c91a869c..aae4e54b2 100644 --- a/qt-ui/mainwindow.h +++ b/qt-ui/mainwindow.h @@ -29,16 +29,33 @@ class MainTab; class ProfileGraphicsView; class QWebView; -enum MainWindowTitleFormat { MWTF_DEFAULT, MWTF_FILENAME }; +enum MainWindowTitleFormat { + MWTF_DEFAULT, + MWTF_FILENAME +}; -class MainWindow : public QMainWindow -{ -Q_OBJECT +class MainWindow : public QMainWindow { + Q_OBJECT public: - enum {COLLAPSED, EXPANDED}; - enum StackWidgetIndexes{ PROFILE, PLANNERPROFILE}; - enum InfoWidgetIndexes{ MAINTAB, PLANNERWIDGET}; - enum CurrentState{ VIEWALL, GLOBE_MAXIMIZED, INFO_MAXIMIZED, PROFILE_MAXIMIZED, LIST_MAXIMIZED}; + enum { + COLLAPSED, + EXPANDED + }; + enum StackWidgetIndexes { + PROFILE, + PLANNERPROFILE + }; + enum InfoWidgetIndexes { + MAINTAB, + PLANNERWIDGET + }; + enum CurrentState { + VIEWALL, + GLOBE_MAXIMIZED, + INFO_MAXIMIZED, + PROFILE_MAXIMIZED, + LIST_MAXIMIZED + }; MainWindow(); virtual ~MainWindow(); @@ -60,7 +77,8 @@ public: void importFiles(const QStringList importFiles); void cleanUpEmpty(); QTabWidget *tabWidget(); -private slots: +private +slots: /* file menu action */ void recentFileTriggered(bool checked); void on_actionNew_triggered(); @@ -127,7 +145,8 @@ private slots: protected: void closeEvent(QCloseEvent *); -public slots: +public +slots: void readSettings(); void refreshDisplay(bool recreateDiveList = true); void showProfile(); @@ -149,7 +168,7 @@ private: void beginChangeState(CurrentState s); void saveSplitterSizes(); QString lastUsedDir(); - void updateLastUsedDir(const QString& s); + void updateLastUsedDir(const QString &s); }; MainWindow *mainWindow(); diff --git a/qt-ui/modeldelegates.cpp b/qt-ui/modeldelegates.cpp index 5e5bc9353..85542f0f9 100644 --- a/qt-ui/modeldelegates.cpp +++ b/qt-ui/modeldelegates.cpp @@ -18,9 +18,9 @@ #include <QAbstractItemView> #include <QApplication> -QSize DiveListDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const +QSize DiveListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { - return QSize(50,22); + return QSize(50, 22); } // Gets the index of the model in the currentRow and column. @@ -28,14 +28,12 @@ QSize DiveListDelegate::sizeHint(const QStyleOptionViewItem& option, const QMode #define IDX(_XX) mymodel->index(currCombo.currRow, (_XX)) static bool keyboardFinished = false; -StarWidgetsDelegate::StarWidgetsDelegate(QWidget* parent): - QStyledItemDelegate(parent), +StarWidgetsDelegate::StarWidgetsDelegate(QWidget *parent) : QStyledItemDelegate(parent), parentWidget(parent) { - } -void StarWidgetsDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +void StarWidgetsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyledItemDelegate::paint(painter, option, index); if (!index.isValid()) @@ -46,7 +44,7 @@ void StarWidgetsDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o return; int rating = value.toInt(); - int deltaY = option.rect.height() / 2 - StarWidget::starActive().height() / 2 ; + int deltaY = option.rect.height() / 2 - StarWidget::starActive().height() / 2; painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); for (int i = 0; i < rating; i++) @@ -56,20 +54,20 @@ void StarWidgetsDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o painter->restore(); } -QSize StarWidgetsDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const +QSize StarWidgetsDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { - return QSize(IMG_SIZE * TOTALSTARS + SPACING * (TOTALSTARS-1), IMG_SIZE); + return QSize(IMG_SIZE * TOTALSTARS + SPACING * (TOTALSTARS - 1), IMG_SIZE); } -ComboBoxDelegate::ComboBoxDelegate(QAbstractItemModel *model, QObject* parent): QStyledItemDelegate(parent), model(model) +ComboBoxDelegate::ComboBoxDelegate(QAbstractItemModel *model, QObject *parent) : QStyledItemDelegate(parent), model(model) { - connect(this, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), - this, SLOT(revertModelData(QWidget*, QAbstractItemDelegate::EndEditHint))); + connect(this, SIGNAL(closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint)), + this, SLOT(revertModelData(QWidget *, QAbstractItemDelegate::EndEditHint))); } -void ComboBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const +void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { - QComboBox *c = qobject_cast<QComboBox*>(editor); + QComboBox *c = qobject_cast<QComboBox *>(editor); QString data = index.model()->data(index, Qt::DisplayRole).toString(); int i = c->findText(data); if (i != -1) @@ -86,7 +84,7 @@ struct CurrSelected { bool ignoreSelection; } currCombo; -QWidget* ComboBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const +QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QComboBox *comboDelegate = new QComboBox(parent); comboDelegate->setModel(model); @@ -95,14 +93,14 @@ QWidget* ComboBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewI comboDelegate->setAutoCompletionCaseSensitivity(Qt::CaseInsensitive); comboDelegate->completer()->setCompletionMode(QCompleter::PopupCompletion); comboDelegate->view()->setEditTriggers(QAbstractItemView::AllEditTriggers); - comboDelegate->lineEdit()->installEventFilter( const_cast<QObject*>(qobject_cast<const QObject*>(this))); - comboDelegate->view()->installEventFilter( const_cast<QObject*>(qobject_cast<const QObject*>(this))); + comboDelegate->lineEdit()->installEventFilter(const_cast<QObject *>(qobject_cast<const QObject *>(this))); + comboDelegate->view()->installEventFilter(const_cast<QObject *>(qobject_cast<const QObject *>(this))); connect(comboDelegate, SIGNAL(highlighted(QString)), this, SLOT(testActivation(QString))); connect(comboDelegate, SIGNAL(activated(QString)), this, SLOT(fakeActivation())); - connect(this, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)), this, SLOT(fixTabBehavior())); + connect(this, SIGNAL(closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint)), this, SLOT(fixTabBehavior())); currCombo.comboEditor = comboDelegate; currCombo.currRow = index.row(); - currCombo.model = const_cast<QAbstractItemModel*>(index.model()); + currCombo.model = const_cast<QAbstractItemModel *>(index.model()); keyboardFinished = false; // Current display of things on Gnome3 looks like shit, so @@ -122,14 +120,15 @@ QWidget* ComboBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewI * One thing is important, if the user writes a *new* cylinder or weight type, it will * be ADDED to the list, and the user will need to fill the other data. */ -void ComboBoxDelegate::testActivation(const QString& currText) +void ComboBoxDelegate::testActivation(const QString &currText) { currCombo.activeText = currText.isEmpty() ? currCombo.comboEditor->currentText() : currText; setModelData(currCombo.comboEditor, currCombo.model, QModelIndex()); } // HACK, send a fake event so Qt thinks we hit 'enter' on the line edit. -void ComboBoxDelegate::fakeActivation() { +void ComboBoxDelegate::fakeActivation() +{ /* this test is needed because as soon as I show the selector, * the first item gots selected, this sending an activated signal, * calling this fakeActivation code and setting as the current, @@ -151,28 +150,28 @@ void ComboBoxDelegate::fakeActivation() { void ComboBoxDelegate::fixTabBehavior() { if (keyboardFinished) { - setModelData(0,0,QModelIndex()); + setModelData(0, 0, QModelIndex()); } } -bool ComboBoxDelegate::eventFilter(QObject* object, QEvent* event) +bool ComboBoxDelegate::eventFilter(QObject *object, QEvent *event) { // Reacts on Key_UP and Key_DOWN to show the QComboBox - list of choices. if (event->type() == QEvent::KeyPress || event->type() == QEvent::ShortcutOverride) { if (object == currCombo.comboEditor) { // the 'LineEdit' part - QKeyEvent *ev = static_cast<QKeyEvent*>(event); + QKeyEvent *ev = static_cast<QKeyEvent *>(event); if (ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) { currCombo.ignoreSelection = true; currCombo.comboEditor->showPopup(); } if (ev->key() == Qt::Key_Tab || ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) { - currCombo.activeText = currCombo.comboEditor->currentText(); + currCombo.activeText = currCombo.comboEditor->currentText(); keyboardFinished = true; } - } else { // the 'Drop Down Menu' part. - QKeyEvent *ev = static_cast<QKeyEvent*>(event); + } else { // the 'Drop Down Menu' part. + QKeyEvent *ev = static_cast<QKeyEvent *>(event); if (ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return || - ev->key() == Qt::Key_Tab || ev->key() == Qt::Key_Backtab || + ev->key() == Qt::Key_Tab || ev->key() == Qt::Key_Backtab || ev->key() == Qt::Key_Escape) { // treat Qt as a silly little boy - pretending that the key_return nwas pressed on the combo, // instead of the list of choices. this can be extended later for @@ -185,13 +184,13 @@ bool ComboBoxDelegate::eventFilter(QObject* object, QEvent* event) return QStyledItemDelegate::eventFilter(object, event); } -void ComboBoxDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const +void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { QRect defaultRect = option.rect; - defaultRect.setX( defaultRect.x() -1); - defaultRect.setY( defaultRect.y() -1); - defaultRect.setWidth( defaultRect.width() + 2); - defaultRect.setHeight( defaultRect.height() + 2); + defaultRect.setX(defaultRect.x() - 1); + defaultRect.setY(defaultRect.y() - 1); + defaultRect.setWidth(defaultRect.width() + 2); + defaultRect.setHeight(defaultRect.height() + 2); editor->setGeometry(defaultRect); } @@ -201,16 +200,16 @@ struct RevertCylinderData { int size; } currCylinderData; -void TankInfoDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& thisindex) const +void TankInfoDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &thisindex) const { CylindersModel *mymodel = qobject_cast<CylindersModel *>(currCombo.model); TankInfoModel *tanks = TankInfoModel::instance(); - QModelIndexList matches = tanks->match(tanks->index(0,0), Qt::DisplayRole, currCombo.activeText); + QModelIndexList matches = tanks->match(tanks->index(0, 0), Qt::DisplayRole, currCombo.activeText); int row; if (matches.isEmpty()) { // we need to add this tanks->insertRows(tanks->rowCount(), 1); - tanks->setData(tanks->index(tanks->rowCount() -1, 0), currCombo.activeText); + tanks->setData(tanks->index(tanks->rowCount() - 1, 0), currCombo.activeText); row = tanks->rowCount() - 1; } else { row = matches.first().row(); @@ -223,17 +222,17 @@ void TankInfoDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, mymodel->passInData(IDX(CylindersModel::SIZE), tankSize); } -TankInfoDelegate::TankInfoDelegate(QObject* parent): ComboBoxDelegate(TankInfoModel::instance(), parent) +TankInfoDelegate::TankInfoDelegate(QObject *parent) : ComboBoxDelegate(TankInfoModel::instance(), parent) { } -void TankInfoDelegate::revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint) +void TankInfoDelegate::revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint) { if ( #if !defined __APPLE__ - hint == QAbstractItemDelegate::NoHint || + hint == QAbstractItemDelegate::NoHint || #endif - hint == QAbstractItemDelegate::RevertModelCache) { + hint == QAbstractItemDelegate::RevertModelCache) { CylindersModel *mymodel = qobject_cast<CylindersModel *>(currCombo.model); mymodel->setData(IDX(CylindersModel::TYPE), currCylinderData.type, Qt::EditRole); mymodel->passInData(IDX(CylindersModel::WORKINGPRESS), currCylinderData.pressure); @@ -241,7 +240,7 @@ void TankInfoDelegate::revertModelData(QWidget* widget, QAbstractItemDelegate::E } } -QWidget* TankInfoDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const +QWidget *TankInfoDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { // ncreate editor needs to be called before because it will populate a few // things in the currCombo global var. @@ -259,24 +258,24 @@ struct RevertWeightData { int weight; } currWeight; -void WSInfoDelegate::revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint) +void WSInfoDelegate::revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint) { if ( #if !defined __APPLE__ - hint == QAbstractItemDelegate::NoHint || + hint == QAbstractItemDelegate::NoHint || #endif - hint == QAbstractItemDelegate::RevertModelCache) { + hint == QAbstractItemDelegate::RevertModelCache) { WeightModel *mymodel = qobject_cast<WeightModel *>(currCombo.model); mymodel->setData(IDX(WeightModel::TYPE), currWeight.type, Qt::EditRole); mymodel->passInData(IDX(WeightModel::WEIGHT), currWeight.weight); } } -void WSInfoDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& thisindex) const +void WSInfoDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &thisindex) const { WeightModel *mymodel = qobject_cast<WeightModel *>(currCombo.model); WSInfoModel *wsim = WSInfoModel::instance(); - QModelIndexList matches = wsim->match(wsim->index(0,0), Qt::DisplayRole, currCombo.activeText); + QModelIndexList matches = wsim->match(wsim->index(0, 0), Qt::DisplayRole, currCombo.activeText); int row; if (matches.isEmpty()) { // we need to add this puppy @@ -293,11 +292,11 @@ void WSInfoDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, co mymodel->passInData(IDX(WeightModel::WEIGHT), grams); } -WSInfoDelegate::WSInfoDelegate(QObject* parent): ComboBoxDelegate(WSInfoModel::instance(), parent) +WSInfoDelegate::WSInfoDelegate(QObject *parent) : ComboBoxDelegate(WSInfoModel::instance(), parent) { } -QWidget* WSInfoDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const +QWidget *WSInfoDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { /* First, call the combobox-create editor, it will setup our globals. */ QWidget *editor = ComboBoxDelegate::createEditor(parent, option, index); @@ -308,24 +307,23 @@ QWidget* WSInfoDelegate::createEditor(QWidget* parent, const QStyleOptionViewIte return editor; } -void AirTypesDelegate::revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint) +void AirTypesDelegate::revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint) { } -void AirTypesDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const +void AirTypesDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (!index.isValid()) return; - QComboBox *combo = qobject_cast<QComboBox*>(editor); + QComboBox *combo = qobject_cast<QComboBox *>(editor); model->setData(index, QVariant(combo->currentText())); } -AirTypesDelegate::AirTypesDelegate(QObject* parent) : ComboBoxDelegate(GasSelectionModel::instance(), parent) +AirTypesDelegate::AirTypesDelegate(QObject *parent) : ComboBoxDelegate(GasSelectionModel::instance(), parent) { } -ProfilePrintDelegate::ProfilePrintDelegate(QObject *parent) - : QStyledItemDelegate(parent) +ProfilePrintDelegate::ProfilePrintDelegate(QObject *parent) : QStyledItemDelegate(parent) { } diff --git a/qt-ui/modeldelegates.h b/qt-ui/modeldelegates.h index a2ecf2900..d4060f940 100644 --- a/qt-ui/modeldelegates.h +++ b/qt-ui/modeldelegates.h @@ -5,75 +5,83 @@ class QComboBox; class QPainter; -class DiveListDelegate : public QStyledItemDelegate{ +class DiveListDelegate : public QStyledItemDelegate { public: - explicit DiveListDelegate(QObject *parent = 0): QStyledItemDelegate(parent){} - QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; + explicit DiveListDelegate(QObject *parent = 0) + : QStyledItemDelegate(parent) + { + } + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; }; class StarWidgetsDelegate : public QStyledItemDelegate { Q_OBJECT public: - explicit StarWidgetsDelegate(QWidget* parent = 0); - virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - virtual QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; + explicit StarWidgetsDelegate(QWidget *parent = 0); + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + private: QWidget *parentWidget; }; -class ComboBoxDelegate : public QStyledItemDelegate{ +class ComboBoxDelegate : public QStyledItemDelegate { Q_OBJECT public: - explicit ComboBoxDelegate(QAbstractItemModel *model, QObject* parent = 0); - virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; - virtual void setEditorData(QWidget* editor, const QModelIndex& index) const; - virtual void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const; - virtual bool eventFilter(QObject* object, QEvent* event); -public slots: - void testActivation(const QString& currString = QString()); + explicit ComboBoxDelegate(QAbstractItemModel *model, QObject *parent = 0); + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; + virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual bool eventFilter(QObject *object, QEvent *event); +public +slots: + void testActivation(const QString &currString = QString()); //HACK: try to get rid of this in the future. void fakeActivation(); void fixTabBehavior(); - virtual void revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint) = 0; + virtual void revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint) = 0; + protected: QAbstractItemModel *model; }; -class TankInfoDelegate : public ComboBoxDelegate{ +class TankInfoDelegate : public ComboBoxDelegate { Q_OBJECT public: - explicit TankInfoDelegate(QObject* parent = 0); - virtual void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const; - virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; -public slots: - void revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint); + explicit TankInfoDelegate(QObject *parent = 0); + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; +public +slots: + void revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint); }; -class WSInfoDelegate : public ComboBoxDelegate{ +class WSInfoDelegate : public ComboBoxDelegate { Q_OBJECT public: - explicit WSInfoDelegate(QObject* parent = 0); - virtual void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const; - virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; -public slots: - void revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint); + explicit WSInfoDelegate(QObject *parent = 0); + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; +public +slots: + void revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint); }; -class AirTypesDelegate : public ComboBoxDelegate{ +class AirTypesDelegate : public ComboBoxDelegate { Q_OBJECT public: - explicit AirTypesDelegate(QObject* parent = 0); - virtual void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const; -public slots: - void revertModelData(QWidget* widget, QAbstractItemDelegate::EndEditHint hint); + explicit AirTypesDelegate(QObject *parent = 0); + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; +public +slots: + void revertModelData(QWidget *widget, QAbstractItemDelegate::EndEditHint hint); }; /* ProfilePrintDelagate: * this delegate is used to modify the look of the table that is printed * bellow profiles. */ -class ProfilePrintDelegate : public QStyledItemDelegate -{ +class ProfilePrintDelegate : public QStyledItemDelegate { public: explicit ProfilePrintDelegate(QObject *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; diff --git a/qt-ui/models.cpp b/qt-ui/models.cpp index 66a79fc90..3c455206b 100644 --- a/qt-ui/models.cpp +++ b/qt-ui/models.cpp @@ -28,15 +28,15 @@ QFont defaultModelFont() { QFont font; - font.setPointSizeF( font.pointSizeF() * 0.8); + font.setPointSizeF(font.pointSizeF() * 0.8); return font; } -CleanerTableModel::CleanerTableModel(QObject *parent): QAbstractTableModel(parent) +CleanerTableModel::CleanerTableModel(QObject *parent) : QAbstractTableModel(parent) { } -int CleanerTableModel::columnCount(const QModelIndex& parent) const +int CleanerTableModel::columnCount(const QModelIndex &parent) const { return headers.count(); } @@ -58,18 +58,17 @@ QVariant CleanerTableModel::headerData(int section, Qt::Orientation orientation, return ret; } -void CleanerTableModel::setHeaderDataStrings(const QStringList& newHeaders) +void CleanerTableModel::setHeaderDataStrings(const QStringList &newHeaders) { headers = newHeaders; } -CylindersModel::CylindersModel(QObject* parent): current(0), rows(0) +CylindersModel::CylindersModel(QObject *parent) : current(0), rows(0) { // enum {REMOVE, TYPE, SIZE, WORKINGPRESS, START, END, O2, HE, DEPTH}; - setHeaderDataStrings( QStringList() << "" << tr("Type") << tr("Size") << tr("WorkPress") << - tr("StartPress") << tr("EndPress") << trUtf8("O" UTF8_SUBSCRIPT_2 "%") << tr("He%") - // while the planner is disabled, we don't need this column: << tr("Switch at") - ); + setHeaderDataStrings(QStringList() << "" << tr("Type") << tr("Size") << tr("WorkPress") << tr("StartPress") << tr("EndPress") << trUtf8("O" UTF8_SUBSCRIPT_2 "%") << tr("He%") + // while the planner is disabled, we don't need this column: << tr("Switch at") + ); } CylindersModel *CylindersModel::instance() @@ -87,7 +86,7 @@ static QVariant percent_string(fraction_t fraction) return QString("%1%").arg(permille / 10.0, 0, 'f', 1); } -QVariant CylindersModel::data(const QModelIndex& index, int role) const +QVariant CylindersModel::data(const QModelIndex &index, int role) const { QVariant ret; @@ -99,15 +98,19 @@ QVariant CylindersModel::data(const QModelIndex& index, int role) const case Qt::FontRole: { QFont font = defaultModelFont(); switch (index.column()) { - case START: font.setItalic(!cyl->start.mbar); break; - case END: font.setItalic(!cyl->end.mbar); break; + case START: + font.setItalic(!cyl->start.mbar); + break; + case END: + font.setItalic(!cyl->end.mbar); + break; } ret = font; break; } case Qt::TextAlignmentRole: ret = Qt::AlignCenter; - break; + break; case Qt::DisplayRole: case Qt::EditRole: switch (index.column()) { @@ -140,9 +143,9 @@ QVariant CylindersModel::data(const QModelIndex& index, int role) const case HE: ret = percent_string(cyl->gasmix.he); break; - // case DEPTH: - // ret = get_depth_string(cyl->depth, true); - // break; + // case DEPTH: + // ret = get_depth_string(cyl->depth, true); + // break; } break; case Qt::DecorationRole: @@ -159,7 +162,7 @@ QVariant CylindersModel::data(const QModelIndex& index, int role) const return ret; } -cylinder_t* CylindersModel::cylinderAt(const QModelIndex& index) +cylinder_t *CylindersModel::cylinderAt(const QModelIndex &index) { return ¤t->cylinder[index.row()]; } @@ -167,7 +170,7 @@ cylinder_t* CylindersModel::cylinderAt(const QModelIndex& index) // this is our magic 'pass data in' function that allows the delegate to get // the data here without silly unit conversions; // so we only implement the two columns we care about -void CylindersModel::passInData(const QModelIndex& index, const QVariant& value) +void CylindersModel::passInData(const QModelIndex &index, const QVariant &value) { cylinder_t *cyl = cylinderAt(index); switch (index.column()) { @@ -188,9 +191,9 @@ void CylindersModel::passInData(const QModelIndex& index, const QVariant& value) /* Has the string value changed */ #define CHANGED() \ - (vString = value.toString()) != data(index, role).toString() + (vString = value.toString()) != data(index, role).toString() -bool CylindersModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool CylindersModel::setData(const QModelIndex &index, const QVariant &value, int role) { QString vString; bool addDiveMode = DivePlannerPointsModel::instance()->currentMode() != DivePlannerPointsModel::NOTHING; @@ -212,7 +215,7 @@ bool CylindersModel::setData(const QModelIndex& index, const QVariant& value, in case SIZE: if (CHANGED()) { TankInfoModel *tanks = TankInfoModel::instance(); - QModelIndexList matches = tanks->match(tanks->index(0,0), Qt::DisplayRole, cyl->type.description); + QModelIndexList matches = tanks->match(tanks->index(0, 0), Qt::DisplayRole, cyl->type.description); cyl->type.size = string_to_volume(vString.toUtf8().data(), cyl->type.workingpressure); mark_divelist_changed(true); @@ -224,7 +227,7 @@ bool CylindersModel::setData(const QModelIndex& index, const QVariant& value, in case WORKINGPRESS: if (CHANGED()) { TankInfoModel *tanks = TankInfoModel::instance(); - QModelIndexList matches = tanks->match(tanks->index(0,0), Qt::DisplayRole, cyl->type.description); + QModelIndexList matches = tanks->match(tanks->index(0, 0), Qt::DisplayRole, cyl->type.description); cyl->type.workingpressure = string_to_pressure(vString.toUtf8().data()); if (!matches.isEmpty()) tanks->setData(tanks->index(matches.first().row(), TankInfoModel::BAR), cyl->type.workingpressure.mbar / 1000.0); @@ -255,9 +258,9 @@ bool CylindersModel::setData(const QModelIndex& index, const QVariant& value, in changed = true; } break; - // case DEPTH: - // if (CHANGED()) - // cyl->depth = string_to_depth(vString.toUtf8().data()); + // case DEPTH: + // if (CHANGED()) + // cyl->depth = string_to_depth(vString.toUtf8().data()); } dataChanged(index, index); if (addDiveMode) @@ -265,9 +268,9 @@ bool CylindersModel::setData(const QModelIndex& index, const QVariant& value, in return true; } -int CylindersModel::rowCount(const QModelIndex& parent) const +int CylindersModel::rowCount(const QModelIndex &parent) const { - return rows; + return rows; } void CylindersModel::add() @@ -294,40 +297,40 @@ void CylindersModel::update() void CylindersModel::clear() { if (rows > 0) { - beginRemoveRows(QModelIndex(), 0, rows-1); + beginRemoveRows(QModelIndex(), 0, rows - 1); endRemoveRows(); } } -void CylindersModel::setDive(dive* d) +void CylindersModel::setDive(dive *d) { if (current) clear(); if (!d) return; rows = 0; - for(int i = 0; i < MAX_CYLINDERS; i++) { + for (int i = 0; i < MAX_CYLINDERS; i++) { if (!cylinder_none(&d->cylinder[i]) && (prefs.display_unused_tanks || d->cylinder[i].used)) { - rows = i+1; + rows = i + 1; } } current = d; changed = false; if (rows > 0) { - beginInsertRows(QModelIndex(), 0, rows-1); + beginInsertRows(QModelIndex(), 0, rows - 1); endInsertRows(); } } -Qt::ItemFlags CylindersModel::flags(const QModelIndex& index) const +Qt::ItemFlags CylindersModel::flags(const QModelIndex &index) const { if (index.column() == REMOVE) return Qt::ItemIsEnabled; return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } -void CylindersModel::remove(const QModelIndex& index) +void CylindersModel::remove(const QModelIndex &index) { if (index.column() != REMOVE) { return; @@ -335,9 +338,9 @@ void CylindersModel::remove(const QModelIndex& index) cylinder_t *cyl = ¤t->cylinder[index.row()]; if (DivePlannerPointsModel::instance()->tankInUse(cyl->gasmix.o2.permille, cyl->gasmix.he.permille)) { QMessageBox::warning(MainWindow::instance(), TITLE_OR_TEXT( - tr("Cylinder cannot be removed"), - tr("This gas in use. Only cylinders that are not used in the dive can be removed.")), - QMessageBox::Ok); + tr("Cylinder cannot be removed"), + tr("This gas in use. Only cylinders that are not used in the dive can be removed.")), + QMessageBox::Ok); return; } beginRemoveRows(QModelIndex(), index.row(), index.row()); // yah, know, ugly. @@ -347,18 +350,18 @@ void CylindersModel::remove(const QModelIndex& index) endRemoveRows(); } -WeightModel::WeightModel(QObject* parent): CleanerTableModel(parent), current(0), rows(0) +WeightModel::WeightModel(QObject *parent) : CleanerTableModel(parent), current(0), rows(0) { //enum Column {REMOVE, TYPE, WEIGHT}; setHeaderDataStrings(QStringList() << tr("") << tr("Type") << tr("Weight")); } -weightsystem_t* WeightModel::weightSystemAt(const QModelIndex& index) +weightsystem_t *WeightModel::weightSystemAt(const QModelIndex &index) { return ¤t->weightsystem[index.row()]; } -void WeightModel::remove(const QModelIndex& index) +void WeightModel::remove(const QModelIndex &index) { if (index.column() != REMOVE) { return; @@ -373,12 +376,12 @@ void WeightModel::remove(const QModelIndex& index) void WeightModel::clear() { if (rows > 0) { - beginRemoveRows(QModelIndex(), 0, rows-1); + beginRemoveRows(QModelIndex(), 0, rows - 1); endRemoveRows(); } } -QVariant WeightModel::data(const QModelIndex& index, int role) const +QVariant WeightModel::data(const QModelIndex &index, int role) const { QVariant ret; if (!index.isValid() || index.row() >= MAX_WEIGHTSYSTEMS) @@ -392,7 +395,7 @@ QVariant WeightModel::data(const QModelIndex& index, int role) const break; case Qt::TextAlignmentRole: ret = Qt::AlignCenter; - break; + break; case Qt::DisplayRole: case Qt::EditRole: switch (index.column()) { @@ -419,7 +422,7 @@ QVariant WeightModel::data(const QModelIndex& index, int role) const // this is our magic 'pass data in' function that allows the delegate to get // the data here without silly unit conversions; // so we only implement the two columns we care about -void WeightModel::passInData(const QModelIndex& index, const QVariant& value) +void WeightModel::passInData(const QModelIndex &index, const QVariant &value) { weightsystem_t *ws = ¤t->weightsystem[index.row()]; if (index.column() == WEIGHT) { @@ -542,7 +545,7 @@ fraction_t string_to_fraction(const char *str) return fraction; } -bool WeightModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool WeightModel::setData(const QModelIndex &index, const QVariant &value, int role) { QString vString = value.toString(); weightsystem_t *ws = ¤t->weightsystem[index.row()]; @@ -552,7 +555,7 @@ bool WeightModel::setData(const QModelIndex& index, const QVariant& value, int r if (!ws->description || gettextFromC::instance()->tr(ws->description) != vString) { // loop over translations to see if one matches int i = -1; - while(ws_info[++i].name) { + while (ws_info[++i].name) { if (gettextFromC::instance()->tr(ws_info[i].name) == vString) { ws->description = ws_info[i].name; break; @@ -570,7 +573,7 @@ bool WeightModel::setData(const QModelIndex& index, const QVariant& value, int r // now update the ws_info changed = true; WSInfoModel *wsim = WSInfoModel::instance(); - QModelIndexList matches = wsim->match(wsim->index(0,0), Qt::DisplayRole, gettextFromC::instance()->tr(ws->description)); + QModelIndexList matches = wsim->match(wsim->index(0, 0), Qt::DisplayRole, gettextFromC::instance()->tr(ws->description)); if (!matches.isEmpty()) wsim->setData(wsim->index(matches.first().row(), WSInfoModel::GR), ws->weight.grams); } @@ -580,14 +583,14 @@ bool WeightModel::setData(const QModelIndex& index, const QVariant& value, int r return true; } -Qt::ItemFlags WeightModel::flags(const QModelIndex& index) const +Qt::ItemFlags WeightModel::flags(const QModelIndex &index) const { if (index.column() == REMOVE) return Qt::ItemIsEnabled; return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } -int WeightModel::rowCount(const QModelIndex& parent) const +int WeightModel::rowCount(const QModelIndex &parent) const { return rows; } @@ -609,31 +612,31 @@ void WeightModel::update() setDive(current); } -void WeightModel::setDive(dive* d) +void WeightModel::setDive(dive *d) { if (current) clear(); rows = 0; - for(int i = 0; i < MAX_WEIGHTSYSTEMS; i++) { + for (int i = 0; i < MAX_WEIGHTSYSTEMS; i++) { if (!weightsystem_none(&d->weightsystem[i])) { - rows = i+1; + rows = i + 1; } } current = d; changed = false; if (rows > 0) { - beginInsertRows(QModelIndex(), 0, rows-1); + beginInsertRows(QModelIndex(), 0, rows - 1); endInsertRows(); } } -WSInfoModel* WSInfoModel::instance() +WSInfoModel *WSInfoModel::instance() { static QScopedPointer<WSInfoModel> self(new WSInfoModel()); return self.data(); } -bool WSInfoModel::insertRows(int row, int count, const QModelIndex& parent) +bool WSInfoModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, rowCount(), rowCount()); rows += count; @@ -641,7 +644,7 @@ bool WSInfoModel::insertRows(int row, int count, const QModelIndex& parent) return true; } -bool WSInfoModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool WSInfoModel::setData(const QModelIndex &index, const QVariant &value, int role) { struct ws_info_t *info = &ws_info[index.row()]; switch (index.column()) { @@ -660,7 +663,7 @@ void WSInfoModel::clear() { } -QVariant WSInfoModel::data(const QModelIndex& index, int role) const +QVariant WSInfoModel::data(const QModelIndex &index, int role) const { QVariant ret; if (!index.isValid()) { @@ -670,41 +673,41 @@ QVariant WSInfoModel::data(const QModelIndex& index, int role) const int gr = info->grams; switch (role) { - case Qt::FontRole : - ret = defaultModelFont(); + case Qt::FontRole: + ret = defaultModelFont(); + break; + case Qt::DisplayRole: + case Qt::EditRole: + switch (index.column()) { + case GR: + ret = gr; break; - case Qt::DisplayRole : - case Qt::EditRole : - switch (index.column()) { - case GR: - ret = gr; - break; - case DESCRIPTION: - ret = gettextFromC::instance()->tr(info->name); - break; - } + case DESCRIPTION: + ret = gettextFromC::instance()->tr(info->name); break; + } + break; } return ret; } -int WSInfoModel::rowCount(const QModelIndex& parent) const +int WSInfoModel::rowCount(const QModelIndex &parent) const { - return rows+1; + return rows + 1; } -const QString& WSInfoModel::biggerString() const +const QString &WSInfoModel::biggerString() const { return biggerEntry; } WSInfoModel::WSInfoModel() : rows(-1) { - setHeaderDataStrings( QStringList() << tr("Description") << tr("kg")); + setHeaderDataStrings(QStringList() << tr("Description") << tr("kg")); struct ws_info_t *info = ws_info; for (info = ws_info; info->name; info++, rows++) { QString wsInfoName = gettextFromC::instance()->tr(info->name); - if ( wsInfoName.count() > biggerEntry.count()) + if (wsInfoName.count() > biggerEntry.count()) biggerEntry = wsInfoName; } @@ -722,7 +725,7 @@ void WSInfoModel::updateInfo() rows = -1; for (info = ws_info; info->name; info++, rows++) { QString wsInfoName = gettextFromC::instance()->tr(info->name); - if ( wsInfoName.count() > biggerEntry.count()) + if (wsInfoName.count() > biggerEntry.count()) biggerEntry = wsInfoName; } @@ -740,7 +743,8 @@ void WSInfoModel::update() rows = -1; } struct ws_info_t *info = ws_info; - for (info = ws_info; info->name; info++, rows++); + for (info = ws_info; info->name; info++, rows++) + ; if (rows > -1) { beginInsertRows(QModelIndex(), 0, rows); @@ -748,18 +752,18 @@ void WSInfoModel::update() } } -TankInfoModel* TankInfoModel::instance() +TankInfoModel *TankInfoModel::instance() { static QScopedPointer<TankInfoModel> self(new TankInfoModel()); return self.data(); } -const QString& TankInfoModel::biggerString() const +const QString &TankInfoModel::biggerString() const { return biggerEntry; } -bool TankInfoModel::insertRows(int row, int count, const QModelIndex& parent) +bool TankInfoModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, rowCount(), rowCount()); rows += count; @@ -767,7 +771,7 @@ bool TankInfoModel::insertRows(int row, int count, const QModelIndex& parent) return true; } -bool TankInfoModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool TankInfoModel::setData(const QModelIndex &index, const QVariant &value, int role) { struct tank_info_t *info = &tank_info[index.row()]; switch (index.column()) { @@ -789,7 +793,7 @@ void TankInfoModel::clear() { } -QVariant TankInfoModel::data(const QModelIndex& index, int role) const +QVariant TankInfoModel::data(const QModelIndex &index, int role) const { QVariant ret; if (!index.isValid()) { @@ -807,28 +811,28 @@ QVariant TankInfoModel::data(const QModelIndex& index, int role) const ml = cuft_to_l(info->cuft) * 1000 / bar_to_atm(bar); switch (index.column()) { - case BAR: - ret = bar * 1000; - break; - case ML: - ret = ml; - break; - case DESCRIPTION: - ret = QString(info->name); - break; + case BAR: + ret = bar * 1000; + break; + case ML: + ret = ml; + break; + case DESCRIPTION: + ret = QString(info->name); + break; } } return ret; } -int TankInfoModel::rowCount(const QModelIndex& parent) const +int TankInfoModel::rowCount(const QModelIndex &parent) const { - return rows+1; + return rows + 1; } -TankInfoModel::TankInfoModel() : rows(-1) +TankInfoModel::TankInfoModel() : rows(-1) { - setHeaderDataStrings( QStringList() << tr("Description") << tr("ml") << tr("bar")); + setHeaderDataStrings(QStringList() << tr("Description") << tr("ml") << tr("bar")); struct tank_info_t *info = tank_info; for (info = tank_info; info->name; info++, rows++) { QString infoName = gettextFromC::instance()->tr(info->name); @@ -850,7 +854,8 @@ void TankInfoModel::update() rows = -1; } struct tank_info_t *info = tank_info; - for (info = tank_info; info->name; info++, rows++); + for (info = tank_info; info->name; info++, rows++) + ; if (rows > -1) { beginInsertRows(QModelIndex(), 0, rows); @@ -882,7 +887,7 @@ TreeItem::~TreeItem() qDeleteAll(children); } -Qt::ItemFlags TreeItem::flags(const QModelIndex& index) const +Qt::ItemFlags TreeItem::flags(const QModelIndex &index) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } @@ -890,7 +895,7 @@ Qt::ItemFlags TreeItem::flags(const QModelIndex& index) const int TreeItem::row() const { if (parent) - return parent->children.indexOf(const_cast<TreeItem*>(this)); + return parent->children.indexOf(const_cast<TreeItem *>(this)); return 0; } @@ -899,7 +904,7 @@ QVariant TreeItem::data(int column, int role) const return QVariant(); } -TreeModel::TreeModel(QObject* parent): QAbstractItemModel(parent) +TreeModel::TreeModel(QObject *parent) : QAbstractItemModel(parent) { rootItem = new TreeItem(); } @@ -909,12 +914,12 @@ TreeModel::~TreeModel() delete rootItem; } -QVariant TreeModel::data(const QModelIndex& index, int role) const +QVariant TreeModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); - TreeItem* item = static_cast<TreeItem*>(index.internalPointer()); + TreeItem *item = static_cast<TreeItem *>(index.internalPointer()); QVariant val = item->data(index.column(), role); if (role == Qt::FontRole && !val.isValid()) @@ -923,31 +928,31 @@ QVariant TreeModel::data(const QModelIndex& index, int role) const return val; } -bool TreeItem::setData(const QModelIndex& index, const QVariant& value, int role) +bool TreeItem::setData(const QModelIndex &index, const QVariant &value, int role) { return false; } -QModelIndex TreeModel::index(int row, int column, const QModelIndex& parent) -const +QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) + const { if (!hasIndex(row, column, parent)) return QModelIndex(); - TreeItem* parentItem = (!parent.isValid()) ? rootItem : static_cast<TreeItem*>(parent.internalPointer()); + TreeItem *parentItem = (!parent.isValid()) ? rootItem : static_cast<TreeItem *>(parent.internalPointer()); - TreeItem* childItem = parentItem->children[row]; + TreeItem *childItem = parentItem->children[row]; return (childItem) ? createIndex(row, column, childItem) : QModelIndex(); } -QModelIndex TreeModel::parent(const QModelIndex& index) const +QModelIndex TreeModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); - TreeItem* childItem = static_cast<TreeItem*>(index.internalPointer()); - TreeItem* parentItem = childItem->parent; + TreeItem *childItem = static_cast<TreeItem *>(index.internalPointer()); + TreeItem *parentItem = childItem->parent; if (parentItem == rootItem || !parentItem) return QModelIndex(); @@ -955,20 +960,20 @@ QModelIndex TreeModel::parent(const QModelIndex& index) const return createIndex(parentItem->row(), 0, parentItem); } -int TreeModel::rowCount(const QModelIndex& parent) const +int TreeModel::rowCount(const QModelIndex &parent) const { - TreeItem* parentItem; + TreeItem *parentItem; if (!parent.isValid()) parentItem = rootItem; else - parentItem = static_cast<TreeItem*>(parent.internalPointer()); + parentItem = static_cast<TreeItem *>(parent.internalPointer()); int amount = parentItem->children.count(); return amount; } -int TreeModel::columnCount(const QModelIndex& parent) const +int TreeModel::columnCount(const QModelIndex &parent) const { return columns; } @@ -980,7 +985,7 @@ int TreeModel::columnCount(const QModelIndex& parent) const * ############################################################### */ struct TripItem : public TreeItem { virtual QVariant data(int column, int role) const; - dive_trip_t* trip; + dive_trip_t *trip; }; QVariant TripItem::data(int column, int role) const @@ -988,14 +993,14 @@ QVariant TripItem::data(int column, int role) const QVariant ret; if (role == DiveTripModel::TRIP_ROLE) - return QVariant::fromValue<void*>(trip); + return QVariant::fromValue<void *>(trip); if (role == DiveTripModel::SORT_ROLE) return (qulonglong)trip->when; if (role == Qt::DisplayRole) { switch (column) { - case DiveTripModel::NR: + case DiveTripModel::NR: if (trip->location && *trip->location) ret = QString(trip->location) + ", " + get_trip_date_string(trip->when, trip->nrdives); else @@ -1011,7 +1016,7 @@ static int nitrox_sort_value(struct dive *dive) { int o2, he, o2low; get_dive_gas(dive, &o2, &he, &o2low); - return he*1000 + o2; + return he * 1000 + o2; } QVariant DiveItem::data(int column, int role) const @@ -1032,41 +1037,95 @@ QVariant DiveItem::data(int column, int role) const break; } break; - case DiveTripModel::SORT_ROLE: + case DiveTripModel::SORT_ROLE: Q_ASSERT(dive != NULL); switch (column) { - case NR: retVal = (qulonglong) dive->when; break; - case DATE: retVal = (qulonglong) dive->when; break; - case RATING: retVal = dive->rating; break; - case DEPTH: retVal = dive->maxdepth.mm; break; - case DURATION: retVal = dive->duration.seconds; break; - case TEMPERATURE: retVal = dive->watertemp.mkelvin; break; - case TOTALWEIGHT: retVal = total_weight(dive); break; - case SUIT: retVal = QString(dive->suit); break; - case CYLINDER: retVal = QString(dive->cylinder[0].type.description); break; - case NITROX: retVal = nitrox_sort_value(dive); break; - case SAC: retVal = dive->sac; break; - case OTU: retVal = dive->otu; break; - case MAXCNS: retVal = dive->maxcns; break; - case LOCATION: retVal = QString(dive->location); break; + case NR: + retVal = (qulonglong)dive->when; + break; + case DATE: + retVal = (qulonglong)dive->when; + break; + case RATING: + retVal = dive->rating; + break; + case DEPTH: + retVal = dive->maxdepth.mm; + break; + case DURATION: + retVal = dive->duration.seconds; + break; + case TEMPERATURE: + retVal = dive->watertemp.mkelvin; + break; + case TOTALWEIGHT: + retVal = total_weight(dive); + break; + case SUIT: + retVal = QString(dive->suit); + break; + case CYLINDER: + retVal = QString(dive->cylinder[0].type.description); + break; + case NITROX: + retVal = nitrox_sort_value(dive); + break; + case SAC: + retVal = dive->sac; + break; + case OTU: + retVal = dive->otu; + break; + case MAXCNS: + retVal = dive->maxcns; + break; + case LOCATION: + retVal = QString(dive->location); + break; } break; case Qt::DisplayRole: Q_ASSERT(dive != NULL); switch (column) { - case NR: retVal = dive->number; break; - case DATE: retVal = displayDate(); break; - case DEPTH: retVal = displayDepth(); break; - case DURATION: retVal = displayDuration(); break; - case TEMPERATURE: retVal = displayTemperature(); break; - case TOTALWEIGHT: retVal = displayWeight(); break; - case SUIT: retVal = QString(dive->suit); break; - case CYLINDER: retVal = QString(dive->cylinder[0].type.description); break; - case NITROX: retVal = QString(get_nitrox_string(dive)); break; - case SAC: retVal = displaySac(); break; - case OTU: retVal = dive->otu; break; - case MAXCNS: retVal = dive->maxcns; break; - case LOCATION: retVal = QString(dive->location); break; + case NR: + retVal = dive->number; + break; + case DATE: + retVal = displayDate(); + break; + case DEPTH: + retVal = displayDepth(); + break; + case DURATION: + retVal = displayDuration(); + break; + case TEMPERATURE: + retVal = displayTemperature(); + break; + case TOTALWEIGHT: + retVal = displayWeight(); + break; + case SUIT: + retVal = QString(dive->suit); + break; + case CYLINDER: + retVal = QString(dive->cylinder[0].type.description); + break; + case NITROX: + retVal = QString(get_nitrox_string(dive)); + break; + case SAC: + retVal = displaySac(); + break; + case OTU: + retVal = dive->otu; + break; + case MAXCNS: + retVal = dive->maxcns; + break; + case LOCATION: + retVal = QString(dive->location); + break; } break; } @@ -1076,7 +1135,7 @@ QVariant DiveItem::data(int column, int role) const retVal = dive->rating; } if (role == DiveTripModel::DIVE_ROLE) { - retVal = QVariant::fromValue<void*>(dive); + retVal = QVariant::fromValue<void *>(dive); } if (role == DiveTripModel::DIVE_IDX) { Q_ASSERT(dive != NULL); @@ -1085,7 +1144,7 @@ QVariant DiveItem::data(int column, int role) const return retVal; } -Qt::ItemFlags DiveItem::flags(const QModelIndex& index) const +Qt::ItemFlags DiveItem::flags(const QModelIndex &index) const { if (index.column() == NR) { return TreeItem::flags(index) | Qt::ItemIsEditable; @@ -1093,7 +1152,7 @@ Qt::ItemFlags DiveItem::flags(const QModelIndex& index) const return TreeItem::flags(index); } -bool DiveItem::setData(const QModelIndex& index, const QVariant& value, int role) +bool DiveItem::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole) return false; @@ -1135,7 +1194,7 @@ QString DiveItem::displayDepth() const str = QString("%1.%2").arg((unsigned)(dive->maxdepth.mm / scale)).arg(fract, 1, QChar('0')); } if (get_units()->length == units::FEET) { - str = QString::number(mm_to_feet(dive->maxdepth.mm),'f',0); + str = QString::number(mm_to_feet(dive->maxdepth.mm), 'f', 0); } return str; } @@ -1199,17 +1258,17 @@ int DiveItem::weight() const return tw.grams; } -DiveTripModel::DiveTripModel(QObject* parent): TreeModel(parent) +DiveTripModel::DiveTripModel(QObject *parent) : TreeModel(parent) { columns = COLUMNS; } -Qt::ItemFlags DiveTripModel::flags(const QModelIndex& index) const +Qt::ItemFlags DiveTripModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; - TripItem *item = static_cast<TripItem*>(index.internalPointer()); + TripItem *item = static_cast<TripItem *>(index.internalPointer()); return item->flags(index); } @@ -1220,25 +1279,55 @@ QVariant DiveTripModel::headerData(int section, Qt::Orientation orientation, int return ret; switch (role) { - case Qt::FontRole : - ret = defaultModelFont(); break; - case Qt::DisplayRole : - switch (section) { - case NR: ret = tr("#"); break; - case DATE: ret = tr("date"); break; - case RATING: ret = UTF8_BLACKSTAR; break; - case DEPTH: ret = (get_units()->length == units::METERS) ? tr("m") : tr("ft"); break; - case DURATION: ret = tr("min"); break; - case TEMPERATURE:ret = QString("%1%2").arg(UTF8_DEGREE).arg((get_units()->temperature == units::CELSIUS) ? "C" : "F"); break; - case TOTALWEIGHT:ret = (get_units()->weight == units::KG) ? tr("kg") : tr("lbs"); break; - case SUIT: ret = tr("suit"); break; - case CYLINDER: ret = tr("cyl"); break; - case NITROX: ret = QString("O%1%").arg(UTF8_SUBSCRIPT_2); break; - case SAC: ret = tr("SAC"); break; - case OTU: ret = tr("OTU"); break; - case MAXCNS: ret = tr("maxCNS"); break; - case LOCATION: ret = tr("location"); break; - }break; + case Qt::FontRole: + ret = defaultModelFont(); + break; + case Qt::DisplayRole: + switch (section) { + case NR: + ret = tr("#"); + break; + case DATE: + ret = tr("date"); + break; + case RATING: + ret = UTF8_BLACKSTAR; + break; + case DEPTH: + ret = (get_units()->length == units::METERS) ? tr("m") : tr("ft"); + break; + case DURATION: + ret = tr("min"); + break; + case TEMPERATURE: + ret = QString("%1%2").arg(UTF8_DEGREE).arg((get_units()->temperature == units::CELSIUS) ? "C" : "F"); + break; + case TOTALWEIGHT: + ret = (get_units()->weight == units::KG) ? tr("kg") : tr("lbs"); + break; + case SUIT: + ret = tr("suit"); + break; + case CYLINDER: + ret = tr("cyl"); + break; + case NITROX: + ret = QString("O%1%").arg(UTF8_SUBSCRIPT_2); + break; + case SAC: + ret = tr("SAC"); + break; + case OTU: + ret = tr("OTU"); + break; + case MAXCNS: + ret = tr("maxCNS"); + break; + case LOCATION: + ret = tr("location"); + break; + } + break; } return ret; @@ -1249,7 +1338,7 @@ void DiveTripModel::setupModelData() int i = dive_table.nr; if (rowCount()) { - beginRemoveRows(QModelIndex(), 0, rowCount()-1); + beginRemoveRows(QModelIndex(), 0, rowCount() - 1); endRemoveRows(); } @@ -1257,11 +1346,11 @@ void DiveTripModel::setupModelData() autogroup_dives(); dive_table.preexisting = dive_table.nr; while (--i >= 0) { - struct dive* dive = get_dive(i); + struct dive *dive = get_dive(i); update_cylinder_related_info(dive); - dive_trip_t* trip = dive->divetrip; + dive_trip_t *trip = dive->divetrip; - DiveItem* diveItem = new DiveItem(); + DiveItem *diveItem = new DiveItem(); diveItem->diveId = dive->id; if (!trip || currentLayout == LIST) { @@ -1273,7 +1362,7 @@ void DiveTripModel::setupModelData() continue; if (!trips.keys().contains(trip)) { - TripItem* tripItem = new TripItem(); + TripItem *tripItem = new TripItem(); tripItem->trip = trip; tripItem->parent = rootItem; tripItem->children.push_back(diveItem); @@ -1281,7 +1370,7 @@ void DiveTripModel::setupModelData() rootItem->children.push_back(tripItem); continue; } - TripItem* tripItem = trips[trip]; + TripItem *tripItem = trips[trip]; tripItem->children.push_back(diveItem); } @@ -1302,13 +1391,14 @@ void DiveTripModel::setLayout(DiveTripModel::Layout layout) setupModelData(); } -bool DiveTripModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool DiveTripModel::setData(const QModelIndex &index, const QVariant &value, int role) { - TreeItem* item = static_cast<TreeItem*>(index.internalPointer()); - DiveItem *diveItem = dynamic_cast<DiveItem*>(item); + TreeItem *item = static_cast<TreeItem *>(index.internalPointer()); + DiveItem *diveItem = dynamic_cast<DiveItem *>(item); if (!diveItem) return false; - return diveItem->setData(index, value, role);} + return diveItem->setData(index, value, role); +} /*#################################################################### @@ -1318,14 +1408,14 @@ bool DiveTripModel::setData(const QModelIndex& index, const QVariant& value, int *#################################################################### */ -DiveComputerModel::DiveComputerModel(QMultiMap<QString, DiveComputerNode> &dcMap, QObject* parent): CleanerTableModel() +DiveComputerModel::DiveComputerModel(QMultiMap<QString, DiveComputerNode> &dcMap, QObject *parent) : CleanerTableModel() { setHeaderDataStrings(QStringList() << "" << tr("Model") << tr("Device ID") << tr("Nickname")); dcWorkingMap = dcMap; numRows = 0; } -QVariant DiveComputerModel::data(const QModelIndex& index, int role) const +QVariant DiveComputerModel::data(const QModelIndex &index, int role) const { QList<DiveComputerNode> values = dcWorkingMap.values(); DiveComputerNode node = values.at(index.row()); @@ -1333,22 +1423,32 @@ QVariant DiveComputerModel::data(const QModelIndex& index, int role) const QVariant ret; if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { - case ID: ret = QString("0x").append(QString::number(node.deviceId, 16)); break; - case MODEL: ret = node.model; break; - case NICKNAME: ret = node.nickName; break; + case ID: + ret = QString("0x").append(QString::number(node.deviceId, 16)); + break; + case MODEL: + ret = node.model; + break; + case NICKNAME: + ret = node.nickName; + break; } } if (index.column() == REMOVE) { switch (role) { - case Qt::DecorationRole : ret = QIcon(":trash"); break; - case Qt::ToolTipRole : ret = tr("Clicking here will remove this divecomputer."); break; + case Qt::DecorationRole: + ret = QIcon(":trash"); + break; + case Qt::ToolTipRole: + ret = tr("Clicking here will remove this divecomputer."); + break; } } return ret; } -int DiveComputerModel::rowCount(const QModelIndex& parent) const +int DiveComputerModel::rowCount(const QModelIndex &parent) const { return numRows; } @@ -1359,27 +1459,27 @@ void DiveComputerModel::update() int count = values.count(); if (numRows) { - beginRemoveRows(QModelIndex(), 0, numRows-1); + beginRemoveRows(QModelIndex(), 0, numRows - 1); numRows = 0; endRemoveRows(); } if (count) { - beginInsertRows(QModelIndex(), 0, count-1); + beginInsertRows(QModelIndex(), 0, count - 1); numRows = count; endInsertRows(); } } -Qt::ItemFlags DiveComputerModel::flags(const QModelIndex& index) const +Qt::ItemFlags DiveComputerModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (index.column() == NICKNAME) flags |= Qt::ItemIsEditable; - return flags; + return flags; } -bool DiveComputerModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool DiveComputerModel::setData(const QModelIndex &index, const QVariant &value, int role) { QList<DiveComputerNode> values = dcWorkingMap.values(); DiveComputerNode node = values.at(index.row()); @@ -1390,7 +1490,7 @@ bool DiveComputerModel::setData(const QModelIndex& index, const QVariant& value, return true; } -void DiveComputerModel::remove(const QModelIndex& index) +void DiveComputerModel::remove(const QModelIndex &index) { QList<DiveComputerNode> values = dcWorkingMap.values(); DiveComputerNode node = values.at(index.row()); @@ -1419,11 +1519,28 @@ void DiveComputerModel::keepWorkingList() class YearStatisticsItem : public TreeItem { public: - enum {YEAR, DIVES, TOTAL_TIME, AVERAGE_TIME, SHORTEST_TIME, LONGEST_TIME, AVG_DEPTH, MIN_DEPTH, - MAX_DEPTH, AVG_SAC, MIN_SAC, MAX_SAC, AVG_TEMP, MIN_TEMP, MAX_TEMP, COLUMNS}; + enum { + YEAR, + DIVES, + TOTAL_TIME, + AVERAGE_TIME, + SHORTEST_TIME, + LONGEST_TIME, + AVG_DEPTH, + MIN_DEPTH, + MAX_DEPTH, + AVG_SAC, + MIN_SAC, + MAX_SAC, + AVG_TEMP, + MIN_TEMP, + MAX_TEMP, + COLUMNS + }; QVariant data(int column, int role) const; YearStatisticsItem(stats_t interval); + private: stats_t stats_interval; }; @@ -1449,20 +1566,42 @@ QVariant YearStatisticsItem::data(int column, int role) const if (stats_interval.is_trip) { ret = stats_interval.location; } else { - ret = stats_interval.period; + ret = stats_interval.period; } break; - case DIVES: ret = stats_interval.selection_size; break; - case TOTAL_TIME: ret = get_time_string(stats_interval.total_time.seconds, 0); break; - case AVERAGE_TIME: ret = get_minutes(stats_interval.total_time.seconds / stats_interval.selection_size); break; - case SHORTEST_TIME: ret = get_minutes(stats_interval.shortest_time.seconds); break; - case LONGEST_TIME: ret = get_minutes(stats_interval.longest_time.seconds); break; - case AVG_DEPTH: ret = get_depth_string(stats_interval.avg_depth); break; - case MIN_DEPTH: ret = get_depth_string(stats_interval.min_depth); break; - case MAX_DEPTH: ret = get_depth_string(stats_interval.max_depth); break; - case AVG_SAC: ret = get_volume_string(stats_interval.avg_sac); break; - case MIN_SAC: ret = get_volume_string(stats_interval.min_sac); break; - case MAX_SAC: ret = get_volume_string(stats_interval.max_sac); break; + case DIVES: + ret = stats_interval.selection_size; + break; + case TOTAL_TIME: + ret = get_time_string(stats_interval.total_time.seconds, 0); + break; + case AVERAGE_TIME: + ret = get_minutes(stats_interval.total_time.seconds / stats_interval.selection_size); + break; + case SHORTEST_TIME: + ret = get_minutes(stats_interval.shortest_time.seconds); + break; + case LONGEST_TIME: + ret = get_minutes(stats_interval.longest_time.seconds); + break; + case AVG_DEPTH: + ret = get_depth_string(stats_interval.avg_depth); + break; + case MIN_DEPTH: + ret = get_depth_string(stats_interval.min_depth); + break; + case MAX_DEPTH: + ret = get_depth_string(stats_interval.max_depth); + break; + case AVG_SAC: + ret = get_volume_string(stats_interval.avg_sac); + break; + case MIN_SAC: + ret = get_volume_string(stats_interval.min_sac); + break; + case MAX_SAC: + ret = get_volume_string(stats_interval.max_sac); + break; case AVG_TEMP: if (stats_interval.combined_temp && stats_interval.combined_count) { ret = QString::number(stats_interval.combined_temp / stats_interval.combined_count, 'f', 1); @@ -1471,18 +1610,18 @@ QVariant YearStatisticsItem::data(int column, int role) const case MIN_TEMP: value = get_temp_units(stats_interval.min_temp, NULL); if (value > -100.0) - ret = QString::number(value, 'f', 1); + ret = QString::number(value, 'f', 1); break; case MAX_TEMP: value = get_temp_units(stats_interval.max_temp, NULL); if (value > -100.0) - ret = QString::number(value, 'f', 1); + ret = QString::number(value, 'f', 1); break; } return ret; } -YearlyStatisticsModel::YearlyStatisticsModel(QObject* parent) +YearlyStatisticsModel::YearlyStatisticsModel(QObject *parent) { columns = COLUMNS; update_yearly_stats(); @@ -1492,25 +1631,55 @@ QVariant YearlyStatisticsModel::headerData(int section, Qt::Orientation orientat { QVariant val; if (role == Qt::FontRole) - val = defaultModelFont(); + val = defaultModelFont(); if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { - case YEAR: val = tr("Year \n > Month / Trip"); break; - case DIVES: val = tr("#"); break; - case TOTAL_TIME: val = tr("Duration \n Total"); break; - case AVERAGE_TIME: val = tr("\nAverage"); break; - case SHORTEST_TIME: val = tr("\nShortest"); break; - case LONGEST_TIME: val = tr("\nLongest"); break; - case AVG_DEPTH: val = QString(tr("Depth (%1)\n Average")).arg(get_depth_unit()); break; - case MIN_DEPTH: val = tr("\nMinimum"); break; - case MAX_DEPTH: val = tr("\nMaximum"); break; - case AVG_SAC: val = QString(tr("SAC (%1)\n Average")).arg(get_volume_unit()); break; - case MIN_SAC: val = tr("\nMinimum"); break; - case MAX_SAC: val = tr("\nMaximum"); break; - case AVG_TEMP: val = QString(tr("Temp. (%1)\n Average").arg(get_temp_unit())); break; - case MIN_TEMP: val = tr("\nMinimum"); break; - case MAX_TEMP: val = tr("\nMaximum"); break; + case YEAR: + val = tr("Year \n > Month / Trip"); + break; + case DIVES: + val = tr("#"); + break; + case TOTAL_TIME: + val = tr("Duration \n Total"); + break; + case AVERAGE_TIME: + val = tr("\nAverage"); + break; + case SHORTEST_TIME: + val = tr("\nShortest"); + break; + case LONGEST_TIME: + val = tr("\nLongest"); + break; + case AVG_DEPTH: + val = QString(tr("Depth (%1)\n Average")).arg(get_depth_unit()); + break; + case MIN_DEPTH: + val = tr("\nMinimum"); + break; + case MAX_DEPTH: + val = tr("\nMaximum"); + break; + case AVG_SAC: + val = QString(tr("SAC (%1)\n Average")).arg(get_volume_unit()); + break; + case MIN_SAC: + val = tr("\nMinimum"); + break; + case MAX_SAC: + val = tr("\nMaximum"); + break; + case AVG_TEMP: + val = QString(tr("Temp. (%1)\n Average").arg(get_temp_unit())); + break; + case MIN_TEMP: + val = tr("\nMinimum"); + break; + case MAX_TEMP: + val = tr("\nMaximum"); + break; } } return val; @@ -1595,13 +1764,20 @@ QVariant TablePrintModel::data(const QModelIndex &index, int role) const return QColor(list.at(index.row())->colorBackground); if (role == Qt::DisplayRole) switch (index.column()) { - case 0: return list.at(index.row())->number; - case 1: return list.at(index.row())->date; - case 2: return list.at(index.row())->depth; - case 3: return list.at(index.row())->duration; - case 4: return list.at(index.row())->divemaster; - case 5: return list.at(index.row())->buddy; - case 6: return list.at(index.row())->location; + case 0: + return list.at(index.row())->number; + case 1: + return list.at(index.row())->date; + case 2: + return list.at(index.row())->depth; + case 3: + return list.at(index.row())->duration; + case 4: + return list.at(index.row())->divemaster; + case 5: + return list.at(index.row())->buddy; + case 6: + return list.at(index.row())->location; } return QVariant(); } @@ -1611,12 +1787,18 @@ bool TablePrintModel::setData(const QModelIndex &index, const QVariant &value, i if (index.isValid()) { if (role == Qt::DisplayRole) { switch (index.column()) { - case 0: list.at(index.row())->number = value.toString(); - case 1: list.at(index.row())->date = value.toString(); - case 2: list.at(index.row())->depth = value.toString(); - case 3: list.at(index.row())->duration = value.toString(); - case 4: list.at(index.row())->divemaster = value.toString(); - case 5: list.at(index.row())->buddy = value.toString(); + case 0: + list.at(index.row())->number = value.toString(); + case 1: + list.at(index.row())->date = value.toString(); + case 2: + list.at(index.row())->depth = value.toString(); + case 3: + list.at(index.row())->duration = value.toString(); + case 4: + list.at(index.row())->divemaster = value.toString(); + case 5: + list.at(index.row())->buddy = value.toString(); case 6: { /* truncate if there are more than N lines of text, * we don't want a row to be larger that a single page! */ @@ -1810,12 +1992,12 @@ QVariant ProfilePrintModel::data(const QModelIndex &index, int role) const return QVariant(); } -Qt::ItemFlags GasSelectionModel::flags(const QModelIndex& index) const +Qt::ItemFlags GasSelectionModel::flags(const QModelIndex &index) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } -GasSelectionModel* GasSelectionModel::instance() +GasSelectionModel *GasSelectionModel::instance() { static QScopedPointer<GasSelectionModel> self(new GasSelectionModel()); return self.data(); @@ -1826,7 +2008,7 @@ void GasSelectionModel::repopulate() setStringList(DivePlannerPointsModel::instance()->getGasList()); } -QVariant GasSelectionModel::data(const QModelIndex& index, int role) const +QVariant GasSelectionModel::data(const QModelIndex &index, int role) const { if (role == Qt::FontRole) { return defaultModelFont(); @@ -1836,26 +2018,26 @@ QVariant GasSelectionModel::data(const QModelIndex& index, int role) const // Language Model, The Model to populate the list of possible Languages. -LanguageModel* LanguageModel::instance() +LanguageModel *LanguageModel::instance() { static LanguageModel *self = new LanguageModel(); QLocale l; return self; } -LanguageModel::LanguageModel(QObject* parent): QAbstractListModel(parent) +LanguageModel::LanguageModel(QObject *parent) : QAbstractListModel(parent) { QSettings s; QDir d(getSubsurfaceDataPath("translations")); QStringList result = d.entryList(); - Q_FOREACH(const QString& s, result) { - if ( s.startsWith("subsurface_") && s.endsWith(".qm") ) { - languages.push_back( (s == "subsurface_source.qm") ? "English" : s); + Q_FOREACH(const QString & s, result) { + if (s.startsWith("subsurface_") && s.endsWith(".qm")) { + languages.push_back((s == "subsurface_source.qm") ? "English" : s); } } } -QVariant LanguageModel::data(const QModelIndex& index, int role) const +QVariant LanguageModel::data(const QModelIndex &index, int role) const { QLocale loc; QString currentString = languages.at(index.row()); @@ -1863,7 +2045,7 @@ QVariant LanguageModel::data(const QModelIndex& index, int role) const return QVariant(); switch (role) { case Qt::DisplayRole: { - QLocale l( currentString.remove("subsurface_")); + QLocale l(currentString.remove("subsurface_")); return currentString == "English" ? currentString : QString("%1 (%2)").arg(l.languageToString(l.language())).arg(l.countryToString(l.country())); } case Qt::UserRole: @@ -1872,7 +2054,7 @@ QVariant LanguageModel::data(const QModelIndex& index, int role) const return QVariant(); } -int LanguageModel::rowCount(const QModelIndex& parent) const +int LanguageModel::rowCount(const QModelIndex &parent) const { return languages.count(); } diff --git a/qt-ui/models.h b/qt-ui/models.h index df991047d..9a198f657 100644 --- a/qt-ui/models.h +++ b/qt-ui/models.h @@ -19,14 +19,16 @@ QFont defaultModelFont(); // Encapsulates Boilerplate. -class CleanerTableModel : public QAbstractTableModel{ +class CleanerTableModel : public QAbstractTableModel { Q_OBJECT public: explicit CleanerTableModel(QObject *parent = 0); - virtual int columnCount(const QModelIndex& parent = QModelIndex()) const; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + protected: - void setHeaderDataStrings(const QStringList& headers); + void setHeaderDataStrings(const QStringList &headers); + private: QStringList headers; }; @@ -34,21 +36,27 @@ private: /* Encapsulates the tank_info global variable * to show on Qt's Model View System.*/ class TankInfoModel : public CleanerTableModel { -Q_OBJECT + Q_OBJECT public: - static TankInfoModel* instance(); + static TankInfoModel *instance(); - enum Column {DESCRIPTION, ML, BAR}; + enum Column { + DESCRIPTION, + ML, + BAR + }; TankInfoModel(); - /*reimp*/ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - /*reimp*/ int rowCount(const QModelIndex& parent = QModelIndex()) const; - /*reimp*/ bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()); - /*reimp*/ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); - const QString& biggerString() const; + /*reimp*/ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + /*reimp*/ int rowCount(const QModelIndex &parent = QModelIndex()) const; + /*reimp*/ bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); + /*reimp*/ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + const QString &biggerString() const; void clear(); -public slots: +public +slots: void update(); + private: int rows; QString biggerEntry; @@ -56,21 +64,25 @@ private: /* Encapsulate ws_info */ class WSInfoModel : public CleanerTableModel { -Q_OBJECT + Q_OBJECT public: - static WSInfoModel* instance(); + static WSInfoModel *instance(); - enum Column {DESCRIPTION, GR}; + enum Column { + DESCRIPTION, + GR + }; WSInfoModel(); - /*reimp*/ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - /*reimp*/ int rowCount(const QModelIndex& parent = QModelIndex()) const; - /*reimp*/ bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()); - /*reimp*/ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); - const QString& biggerString() const; + /*reimp*/ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + /*reimp*/ int rowCount(const QModelIndex &parent = QModelIndex()) const; + /*reimp*/ bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); + /*reimp*/ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + const QString &biggerString() const; void clear(); void update(); void updateInfo(); + private: int rows; QString biggerEntry; @@ -79,27 +91,38 @@ private: /* Encapsulation of the Cylinder Model, that presents the * Current cylinders that are used on a dive. */ class CylindersModel : public CleanerTableModel { -Q_OBJECT + Q_OBJECT public: - enum Column {REMOVE, TYPE, SIZE, WORKINGPRESS, START, END, O2, HE, /* DEPTH, */ COLUMNS}; - - explicit CylindersModel(QObject* parent = 0); + enum Column { + REMOVE, + TYPE, + SIZE, + WORKINGPRESS, + START, + END, + O2, + HE, + /* DEPTH, */ COLUMNS + }; + + explicit CylindersModel(QObject *parent = 0); static CylindersModel *instance(); - /*reimp*/ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - /*reimp*/ int rowCount(const QModelIndex& parent = QModelIndex()) const; - /*reimp*/ Qt::ItemFlags flags(const QModelIndex& index) const; - /*reimp*/ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); + /*reimp*/ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + /*reimp*/ int rowCount(const QModelIndex &parent = QModelIndex()) const; + /*reimp*/ Qt::ItemFlags flags(const QModelIndex &index) const; + /*reimp*/ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - void passInData(const QModelIndex& index, const QVariant& value); + void passInData(const QModelIndex &index, const QVariant &value); void add(); void clear(); void update(); void setDive(struct dive *d); - cylinder_t *cylinderAt(const QModelIndex& index); + cylinder_t *cylinderAt(const QModelIndex &index); bool changed; -public slots: - void remove(const QModelIndex& index); +public +slots: + void remove(const QModelIndex &index); private: struct dive *current; @@ -109,26 +132,31 @@ private: /* Encapsulation of the Weight Model, that represents * the current weights on a dive. */ class WeightModel : public CleanerTableModel { -Q_OBJECT + Q_OBJECT public: - enum Column {REMOVE, TYPE, WEIGHT}; + enum Column { + REMOVE, + TYPE, + WEIGHT + }; explicit WeightModel(QObject *parent = 0); - /*reimp*/ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - /*reimp*/ int rowCount(const QModelIndex& parent = QModelIndex()) const; - /*reimp*/ Qt::ItemFlags flags(const QModelIndex& index) const; - /*reimp*/ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); + /*reimp*/ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + /*reimp*/ int rowCount(const QModelIndex &parent = QModelIndex()) const; + /*reimp*/ Qt::ItemFlags flags(const QModelIndex &index) const; + /*reimp*/ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - void passInData(const QModelIndex& index, const QVariant& value); + void passInData(const QModelIndex &index, const QVariant &value); void add(); void clear(); void update(); void setDive(struct dive *d); - weightsystem_t *weightSystemAt(const QModelIndex& index); + weightsystem_t *weightSystemAt(const QModelIndex &index); bool changed; -public slots: - void remove(const QModelIndex& index); +public +slots: + void remove(const QModelIndex &index); private: struct dive *current; @@ -140,27 +168,43 @@ private: */ struct TreeItem { - Q_DECLARE_TR_FUNCTIONS (TreeItemDT); + Q_DECLARE_TR_FUNCTIONS(TreeItemDT); + public: virtual ~TreeItem(); TreeItem(); - virtual QVariant data (int column, int role) const; - virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); + virtual QVariant data(int column, int role) const; + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); virtual Qt::ItemFlags flags(const QModelIndex &index) const; int row() const; - QList<TreeItem*> children; + QList<TreeItem *> children; TreeItem *parent; }; struct DiveItem : public TreeItem { - enum Column {NR, DATE, RATING, DEPTH, DURATION, TEMPERATURE, TOTALWEIGHT, - SUIT, CYLINDER, NITROX, SAC, OTU, MAXCNS, LOCATION, COLUMNS }; + enum Column { + NR, + DATE, + RATING, + DEPTH, + DURATION, + TEMPERATURE, + TOTALWEIGHT, + SUIT, + CYLINDER, + NITROX, + SAC, + OTU, + MAXCNS, + LOCATION, + COLUMNS + }; virtual QVariant data(int column, int role) const; int diveId; - virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); - virtual Qt::ItemFlags flags(const QModelIndex& index) const; + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + virtual Qt::ItemFlags flags(const QModelIndex &index) const; QString displayDate() const; QString displayDuration() const; QString displayDepth() const; @@ -172,14 +216,13 @@ struct DiveItem : public TreeItem { struct TripItem; -class TreeModel : public QAbstractItemModel -{ +class TreeModel : public QAbstractItemModel { Q_OBJECT public: TreeModel(QObject *parent = 0); virtual ~TreeModel(); - virtual QVariant data(const QModelIndex &index, int role) const; + virtual QVariant data(const QModelIndex &index, int role) const; /*reimp*/ int rowCount(const QModelIndex &parent = QModelIndex()) const; /*reimp*/ int columnCount(const QModelIndex &parent = QModelIndex()) const; /*reimp*/ QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; @@ -193,40 +236,72 @@ protected: class DiveTripModel : public TreeModel { Q_OBJECT public: - enum Column {NR, DATE, RATING, DEPTH, DURATION, TEMPERATURE, TOTALWEIGHT, - SUIT, CYLINDER, NITROX, SAC, OTU, MAXCNS, LOCATION, COLUMNS }; - - enum ExtraRoles{STAR_ROLE = Qt::UserRole + 1, DIVE_ROLE, TRIP_ROLE, SORT_ROLE, DIVE_IDX}; - enum Layout{TREE, LIST, CURRENT}; + enum Column { + NR, + DATE, + RATING, + DEPTH, + DURATION, + TEMPERATURE, + TOTALWEIGHT, + SUIT, + CYLINDER, + NITROX, + SAC, + OTU, + MAXCNS, + LOCATION, + COLUMNS + }; + + enum ExtraRoles { + STAR_ROLE = Qt::UserRole + 1, + DIVE_ROLE, + TRIP_ROLE, + SORT_ROLE, + DIVE_IDX + }; + enum Layout { + TREE, + LIST, + CURRENT + }; Qt::ItemFlags flags(const QModelIndex &index) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); - DiveTripModel(QObject* parent = 0); + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); + DiveTripModel(QObject *parent = 0); Layout layout() const; void setLayout(Layout layout); + private: void setupModelData(); - QMap<dive_trip_t*, TripItem*> trips; + QMap<dive_trip_t *, TripItem *> trips; Layout currentLayout; }; -class DiveComputerModel : public CleanerTableModel -{ +class DiveComputerModel : public CleanerTableModel { Q_OBJECT public: - enum {REMOVE, MODEL, ID, NICKNAME}; + enum { + REMOVE, + MODEL, + ID, + NICKNAME + }; DiveComputerModel(QMultiMap<QString, DiveComputerNode> &dcMap, QObject *parent = 0); - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; - virtual Qt::ItemFlags flags(const QModelIndex& index) const; - virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; + virtual Qt::ItemFlags flags(const QModelIndex &index) const; + virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); void update(); void keepWorkingList(); void dropWorkingList(); -public slots: - void remove(const QModelIndex& index); +public +slots: + void remove(const QModelIndex &index); + private: int numRows; QMultiMap<QString, DiveComputerNode> dcWorkingMap; @@ -235,11 +310,27 @@ private: class YearlyStatisticsModel : public TreeModel { Q_OBJECT public: - enum { YEAR,DIVES,TOTAL_TIME,AVERAGE_TIME,SHORTEST_TIME,LONGEST_TIME,AVG_DEPTH,MIN_DEPTH, - MAX_DEPTH,AVG_SAC,MIN_SAC,MAX_SAC,AVG_TEMP,MIN_TEMP,MAX_TEMP,COLUMNS}; + enum { + YEAR, + DIVES, + TOTAL_TIME, + AVERAGE_TIME, + SHORTEST_TIME, + LONGEST_TIME, + AVG_DEPTH, + MIN_DEPTH, + MAX_DEPTH, + AVG_SAC, + MIN_SAC, + MAX_SAC, + AVG_TEMP, + MIN_TEMP, + MAX_TEMP, + COLUMNS + }; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - YearlyStatisticsModel(QObject* parent = 0); + YearlyStatisticsModel(QObject *parent = 0); void update_yearly_stats(); }; @@ -262,8 +353,7 @@ struct TablePrintItem { unsigned int colorBackground; }; -class TablePrintModel : public QAbstractTableModel -{ +class TablePrintModel : public QAbstractTableModel { Q_OBJECT private: @@ -277,7 +367,7 @@ public: void insertRow(int index = -1); void callReset(); - QVariant data(const QModelIndex &index, int role) const; + QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &index, const QVariant &value, int role); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; @@ -287,8 +377,7 @@ public: * this model is used when printing a data table under a profile. it requires * some exact usage of setSpan(..) on the target QTableView widget. */ -class ProfilePrintModel : public QAbstractTableModel -{ +class ProfilePrintModel : public QAbstractTableModel { Q_OBJECT private: @@ -303,13 +392,14 @@ public: void setDive(struct dive *divePtr); }; -class GasSelectionModel : public QStringListModel{ +class GasSelectionModel : public QStringListModel { Q_OBJECT public: - static GasSelectionModel* instance(); - Qt::ItemFlags flags(const QModelIndex& index) const; - virtual QVariant data(const QModelIndex& index, int role) const; -public slots: + static GasSelectionModel *instance(); + Qt::ItemFlags flags(const QModelIndex &index) const; + virtual QVariant data(const QModelIndex &index, int role) const; +public +slots: void repopulate(); }; @@ -317,11 +407,12 @@ public slots: class LanguageModel : public QAbstractListModel { Q_OBJECT public: - static LanguageModel* instance(); - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; + static LanguageModel *instance(); + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; + private: - LanguageModel(QObject* parent = 0); + LanguageModel(QObject *parent = 0); QStringList languages; }; diff --git a/qt-ui/preferences.cpp b/qt-ui/preferences.cpp index 4d3816feb..2c72cebf2 100644 --- a/qt-ui/preferences.cpp +++ b/qt-ui/preferences.cpp @@ -6,7 +6,7 @@ #include <QMessageBox> #include <QSortFilterProxyModel> -PreferencesDialog* PreferencesDialog::instance() +PreferencesDialog *PreferencesDialog::instance() { static PreferencesDialog *dialog = new PreferencesDialog(MainWindow::instance()); dialog->setAttribute(Qt::WA_QuitOnClose, false); @@ -14,10 +14,10 @@ PreferencesDialog* PreferencesDialog::instance() return dialog; } -PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) +PreferencesDialog::PreferencesDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { ui.setupUi(this); - connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonClicked(QAbstractButton*))); + connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonClicked(QAbstractButton *))); connect(ui.gflow, SIGNAL(valueChanged(int)), this, SLOT(gflowChanged(int))); connect(ui.gfhigh, SIGNAL(valueChanged(int)), this, SLOT(gfhighChanged(int))); loadSettings(); @@ -25,7 +25,7 @@ PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : QDial rememberPrefs(); } -#define DANGER_GF ( gf > 100 ) ? "* { color: red; }" : "" +#define DANGER_GF (gf > 100) ? "* { color: red; }" : "" void PreferencesDialog::gflowChanged(int gf) { ui.gflow->setStyleSheet(DANGER_GF); @@ -80,7 +80,7 @@ void PreferencesDialog::setUiFromPrefs() ui.fontsize->setValue(prefs.font_size); ui.defaultfilename->setText(prefs.default_filename); ui.default_cylinder->clear(); - for(int i=0; tank_info[i].name != NULL; i++) { + for (int i = 0; tank_info[i].name != NULL; i++) { ui.default_cylinder->addItem(tank_info[i].name); if (prefs.default_cylinder && strcmp(tank_info[i].name, prefs.default_cylinder) == 0) ui.default_cylinder->setCurrentIndex(i); @@ -101,7 +101,7 @@ void PreferencesDialog::setUiFromPrefs() s.beginGroup("Language"); ui.languageSystemDefault->setChecked(s.value("UseSystemLanguage", true).toBool()); QAbstractItemModel *m = ui.languageView->model(); - QModelIndexList languages = m->match( m->index(0,0), Qt::UserRole, s.value("UiLanguage").toString()); + QModelIndexList languages = m->match(m->index(0, 0), Qt::UserRole, s.value("UiLanguage").toString()); if (languages.count()) ui.languageView->setCurrentIndex(languages.first()); } @@ -120,47 +120,47 @@ void PreferencesDialog::rememberPrefs() #define SB(V, B) s.setValue(V, (int)(B->isChecked() ? 1 : 0)) -#define GET_UNIT(name, field, f, t) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ +#define GET_UNIT(name, field, f, t) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ prefs.units.field = (v.toInt() == (t)) ? (t) : (f); \ - else \ - prefs.units.field = default_prefs.units.field - -#define GET_BOOL(name, field) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ - prefs.field = v.toInt() ? true : false; \ - else \ - prefs.field = default_prefs.field - -#define GET_DOUBLE(name, field) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ - prefs.field = v.toDouble(); \ - else \ - prefs.field = default_prefs.field - -#define GET_INT(name, field) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ - prefs.field = v.toInt(); \ - else \ - prefs.field = default_prefs.field - -#define GET_TXT(name, field) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ - prefs.field = strdup(v.toString().toUtf8().constData()); \ - else \ - prefs.field = default_prefs.field - -#define GET_TXT(name, field) \ - v = s.value(QString(name)); \ - if (v.isValid()) \ - prefs.field = strdup(v.toString().toUtf8().constData()); \ - else \ - prefs.field = default_prefs.field + else \ + prefs.units.field = default_prefs.units.field + +#define GET_BOOL(name, field) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ + prefs.field = v.toInt() ? true : false; \ + else \ + prefs.field = default_prefs.field + +#define GET_DOUBLE(name, field) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ + prefs.field = v.toDouble(); \ + else \ + prefs.field = default_prefs.field + +#define GET_INT(name, field) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ + prefs.field = v.toInt(); \ + else \ + prefs.field = default_prefs.field + +#define GET_TXT(name, field) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ + prefs.field = strdup(v.toString().toUtf8().constData()); \ + else \ + prefs.field = default_prefs.field + +#define GET_TXT(name, field) \ + v = s.value(QString(name)); \ + if (v.isValid()) \ + prefs.field = strdup(v.toString().toUtf8().constData()); \ + else \ + prefs.field = default_prefs.field void PreferencesDialog::syncSettings() { @@ -288,7 +288,7 @@ void PreferencesDialog::loadSettings() s.endGroup(); } -void PreferencesDialog::buttonClicked(QAbstractButton* button) +void PreferencesDialog::buttonClicked(QAbstractButton *button) { switch (ui.buttonBox->standardButton(button)) { case QDialogButtonBox::Discard: @@ -313,7 +313,7 @@ void PreferencesDialog::on_chooseFile_clicked() QFileInfo fi(system_default_filename()); QString choosenFileName = QFileDialog::getOpenFileName(this, tr("Open Default Log File"), fi.absolutePath(), tr("Subsurface XML files (*.ssrf *.xml *.XML)")); - if(!choosenFileName.isEmpty()) + if (!choosenFileName.isEmpty()) ui.defaultfilename->setText(choosenFileName); } diff --git a/qt-ui/preferences.h b/qt-ui/preferences.h index fb3d1f089..5c434ec65 100644 --- a/qt-ui/preferences.h +++ b/qt-ui/preferences.h @@ -9,16 +9,17 @@ class QAbstractButton; -class PreferencesDialog :public QDialog{ -Q_OBJECT +class PreferencesDialog : public QDialog { + Q_OBJECT public: - static PreferencesDialog* instance(); - void showEvent(QShowEvent* ); + static PreferencesDialog *instance(); + void showEvent(QShowEvent *); void emitSettingsChanged(); signals: void settingsChanged(); -public slots: - void buttonClicked(QAbstractButton* button); +public +slots: + void buttonClicked(QAbstractButton *button); void on_chooseFile_clicked(); void syncSettings(); void loadSettings(); @@ -28,7 +29,7 @@ public slots: void gfhighChanged(int gf); private: - explicit PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit PreferencesDialog(QWidget *parent = 0, Qt::WindowFlags f = 0); void setUiFromPrefs(); Ui::PreferencesDialog ui; struct preferences oldPrefs; diff --git a/qt-ui/printdialog.cpp b/qt-ui/printdialog.cpp index f61cd22ac..8f0d21b8e 100644 --- a/qt-ui/printdialog.cpp +++ b/qt-ui/printdialog.cpp @@ -14,7 +14,7 @@ PrintDialog::PrintDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { // options template (are we storing these in the settings?) - struct options tempOptions = {options::PRETTY, 0, 2, false, 65, 15, 12}; + struct options tempOptions = { options::PRETTY, 0, 2, false, 65, 15, 12 }; printOptions = tempOptions; // create a print layout and pass the printer and options diff --git a/qt-ui/printdialog.h b/qt-ui/printdialog.h index 44c2de66d..33cc25f03 100644 --- a/qt-ui/printdialog.h +++ b/qt-ui/printdialog.h @@ -11,7 +11,7 @@ class PrintLayout; // should be based on a custom QPrintDialog class class PrintDialog : public QDialog { -Q_OBJECT + Q_OBJECT public: struct options printOptions; @@ -23,7 +23,8 @@ private: QProgressBar *progressBar; QPrinter printer; -private slots: +private +slots: void previewClicked(); void printClicked(); void onPaintRequested(QPrinter *); diff --git a/qt-ui/printlayout.cpp b/qt-ui/printlayout.cpp index d9a5a5c27..cf566e604 100644 --- a/qt-ui/printlayout.cpp +++ b/qt-ui/printlayout.cpp @@ -43,7 +43,7 @@ PrintLayout::PrintLayout(PrintDialog *dialogPtr, QPrinter *printerPtr, struct op profilePrintColumnWidths.append(dw - 3); profilePrintColumnWidths.append(dw - 3); profilePrintColumnWidths.append(dw + 6); // fit to 100% - const int sr = 12; // smallest row height in pixels + const int sr = 12; // smallest row height in pixels profilePrintRowHeights.append(sr); profilePrintRowHeights.append(sr + 4); profilePrintRowHeights.append(sr); @@ -84,8 +84,8 @@ void PrintLayout::setup() printerDpi = printer->resolution(); pageRect = printer->pageRect(); - scaleX = (qreal)printerDpi/(qreal)screenDpiX; - scaleY = (qreal)printerDpi/(qreal)screenDpiY; + scaleX = (qreal)printerDpi / (qreal)screenDpiX; + scaleY = (qreal)printerDpi / (qreal)screenDpiY; // a printer page scalled to screen DPI scaledPageW = pageRect.width() / scaleX; @@ -114,7 +114,7 @@ int PrintLayout::estimateTotalDives() const * p is the padding between elements */ #define ESTIMATE_DIVE_DIM(S, n, p) \ - ((S) - ((n) - 1) * (p)) / (n); + ((S) - ((n) - 1) * (p)) / (n); void PrintLayout::printProfileDives(int divesPerRow, int divesPerColumn) { @@ -220,7 +220,7 @@ QTableView *PrintLayout::createProfileTable(ProfilePrintModel *model, const int table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); hHeader->setVisible(false); vHeader->setVisible(false); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) hHeader->setResizeMode(QHeaderView::Fixed); vHeader->setResizeMode(QHeaderView::Fixed); #else @@ -269,8 +269,7 @@ QTableView *PrintLayout::createProfileTable(ProfilePrintModel *model, const int table->setShowGrid(false); table->setStyleSheet( "QTableView { border: none }" - "QTableView::item { border: 0px; padding-left: 2px; padding-right: 2px; }" - ); + "QTableView::item { border: 0px; padding-left: 2px; padding-right: 2px; }"); // return return table; } @@ -290,7 +289,7 @@ void PrintLayout::printTable() table.setFocusPolicy(Qt::NoFocus); table.horizontalHeader()->setVisible(false); table.verticalHeader()->setVisible(false); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) table.horizontalHeader()->setResizeMode(QHeaderView::Fixed); table.verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); #else @@ -300,12 +299,11 @@ void PrintLayout::printTable() table.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); table.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // fit table to one page initially - table.resize(scaledPageW, scaledPageH); + table.resize(scaledPageW, scaledPageH); // don't show border table.setStyleSheet( - "QTableView { border: none }" - ); + "QTableView { border: none }"); // create and fill a table model TablePrintModel model; diff --git a/qt-ui/printlayout.h b/qt-ui/printlayout.h index 393bfc54b..e894f3a98 100644 --- a/qt-ui/printlayout.h +++ b/qt-ui/printlayout.h @@ -43,7 +43,7 @@ private: void addTablePrintHeadingRow(TablePrintModel *model, int row) const; signals: - void signalProgress(int); + void signalProgress(int); }; #endif // PRINTLAYOUT_H diff --git a/qt-ui/printoptions.h b/qt-ui/printoptions.h index 29fc61a75..72c089e1a 100644 --- a/qt-ui/printoptions.h +++ b/qt-ui/printoptions.h @@ -9,7 +9,7 @@ // should be based on a custom QPrintDialog class class PrintOptions : public QWidget { -Q_OBJECT + Q_OBJECT public: explicit PrintOptions(QWidget *parent = 0, struct options *printOpt = 0); @@ -23,7 +23,8 @@ private: struct options *printOptions; bool hasSetupSlots; -private slots: +private +slots: void sliderPHeightMoved(int value); void sliderOHeightMoved(int value); void sliderNHeightMoved(int value); diff --git a/qt-ui/profile/animationfunctions.cpp b/qt-ui/profile/animationfunctions.cpp index f70468bde..8cccf616e 100644 --- a/qt-ui/profile/animationfunctions.cpp +++ b/qt-ui/profile/animationfunctions.cpp @@ -2,37 +2,37 @@ #include <QPropertyAnimation> #include <QPointF> -namespace Animations { - -void hide(QObject* obj) +namespace Animations { - QPropertyAnimation *animation = new QPropertyAnimation(obj, "opacity"); - animation->setStartValue(1); - animation->setEndValue(0); - animation->start(QAbstractAnimation::DeleteWhenStopped); -} -void animDelete(QObject* obj) -{ - QPropertyAnimation *animation = new QPropertyAnimation(obj, "opacity"); - obj->connect(animation, SIGNAL(finished()), SLOT(deleteLater())); - animation->setStartValue(1); - animation->setEndValue(0); - animation->start(QAbstractAnimation::DeleteWhenStopped); -} + void hide(QObject *obj) + { + QPropertyAnimation *animation = new QPropertyAnimation(obj, "opacity"); + animation->setStartValue(1); + animation->setEndValue(0); + animation->start(QAbstractAnimation::DeleteWhenStopped); + } -void moveTo(QObject* obj, qreal x, qreal y, int msecs) -{ - QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); - animation->setDuration(msecs); - animation->setStartValue(obj->property("pos").toPointF()); - animation->setEndValue(QPointF(x, y)); - animation->start(QAbstractAnimation::DeleteWhenStopped); -} + void animDelete(QObject *obj) + { + QPropertyAnimation *animation = new QPropertyAnimation(obj, "opacity"); + obj->connect(animation, SIGNAL(finished()), SLOT(deleteLater())); + animation->setStartValue(1); + animation->setEndValue(0); + animation->start(QAbstractAnimation::DeleteWhenStopped); + } -void moveTo(QObject* obj, const QPointF& pos, int msecs) -{ - moveTo(obj, pos.x(), pos.y(), msecs); -} + void moveTo(QObject *obj, qreal x, qreal y, int msecs) + { + QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); + animation->setDuration(msecs); + animation->setStartValue(obj->property("pos").toPointF()); + animation->setEndValue(QPointF(x, y)); + animation->start(QAbstractAnimation::DeleteWhenStopped); + } + void moveTo(QObject *obj, const QPointF &pos, int msecs) + { + moveTo(obj, pos.x(), pos.y(), msecs); + } } diff --git a/qt-ui/profile/animationfunctions.h b/qt-ui/profile/animationfunctions.h index 2ab8c9e47..f6c93c7ae 100644 --- a/qt-ui/profile/animationfunctions.h +++ b/qt-ui/profile/animationfunctions.h @@ -6,10 +6,11 @@ class QObject; -namespace Animations{ +namespace Animations +{ void hide(QObject *obj); void moveTo(QObject *obj, qreal x, qreal y, int msecs = 500); - void moveTo(QObject *obj, const QPointF& pos, int msecs = 500); + void moveTo(QObject *obj, const QPointF &pos, int msecs = 500); void animDelete(QObject *obj); } diff --git a/qt-ui/profile/divecartesianaxis.cpp b/qt-ui/profile/divecartesianaxis.cpp index c2ccdebcd..2373b5f2f 100644 --- a/qt-ui/profile/divecartesianaxis.cpp +++ b/qt-ui/profile/divecartesianaxis.cpp @@ -12,7 +12,8 @@ #include <QStyleOption> #include <QSettings> -static QPen gridPen(){ +static QPen gridPen() +{ QPen pen; pen.setColor(getColor(TIME_GRID)); pen.setWidth(2); @@ -50,7 +51,7 @@ void DiveCartesianAxis::setMinimum(double minimum) min = minimum; } -void DiveCartesianAxis::setTextColor(const QColor& color) +void DiveCartesianAxis::setTextColor(const QColor &color) { textColor = color; } @@ -73,7 +74,6 @@ DiveCartesianAxis::DiveCartesianAxis() : QObject(), DiveCartesianAxis::~DiveCartesianAxis() { - } void DiveCartesianAxis::setLineSize(qreal lineSize) @@ -93,31 +93,33 @@ QColor DiveCartesianAxis::colorForValue(double value) void DiveCartesianAxis::setTextVisible(bool arg1) { - if(textVisibility == arg1){ + if (textVisibility == arg1) { return; } textVisibility = arg1; - Q_FOREACH(DiveTextItem *item, labels){ + Q_FOREACH(DiveTextItem * item, labels) { item->setVisible(textVisibility); } } void DiveCartesianAxis::setLinesVisible(bool arg1) { - if(lineVisibility == arg1){ + if (lineVisibility == arg1) { return; } - lineVisibility = arg1; - Q_FOREACH(DiveLineItem *item, lines){ - item->setVisible(lineVisibility ); + lineVisibility = arg1; + Q_FOREACH(DiveLineItem * item, lines) { + item->setVisible(lineVisibility); } } -template<typename T> void emptyList( QList<T*>& list, double steps){ +template <typename T> +void emptyList(QList<T *> &list, double steps) +{ if (!list.isEmpty() && list.size() > steps) { while (list.size() > steps) { - T *removedItem = list.takeLast(); - Animations::animDelete(removedItem); + T *removedItem = list.takeLast(); + Animations::animDelete(removedItem); } } } @@ -148,7 +150,7 @@ void DiveCartesianAxis::updateTicks() } else if (orientation == BottomToTop) { begin = m.y2(); stepSize = (m.y2() - m.y1()); - } else if (orientation == LeftToRight ) { + } else if (orientation == LeftToRight) { begin = m.x1(); stepSize = (m.x2() - m.x1()); } else if (orientation == RightToLeft) { @@ -159,11 +161,11 @@ void DiveCartesianAxis::updateTicks() for (int i = 0, count = labels.size(); i < count; i++, currValueText += interval) { qreal childPos = (orientation == TopToBottom || orientation == LeftToRight) ? - begin + i * stepSize : - begin - i * stepSize; + begin + i * stepSize : + begin - i * stepSize; labels[i]->setText(textForValue(currValueText)); - if ( orientation == LeftToRight || orientation == RightToLeft) { + if (orientation == LeftToRight || orientation == RightToLeft) { labels[i]->animateMoveTo(childPos, m.y1() + tick_size); } else { labels[i]->animateMoveTo(m.x1() - tick_size, childPos); @@ -172,10 +174,10 @@ void DiveCartesianAxis::updateTicks() for (int i = 0, count = lines.size(); i < count; i++, currValueLine += interval) { qreal childPos = (orientation == TopToBottom || orientation == LeftToRight) ? - begin + i * stepSize : - begin - i * stepSize; + begin + i * stepSize : + begin - i * stepSize; - if ( orientation == LeftToRight || orientation == RightToLeft) { + if (orientation == LeftToRight || orientation == RightToLeft) { lines[i]->animateMoveTo(childPos, m.y1()); } else { lines[i]->animateMoveTo(m.x1(), childPos); @@ -183,10 +185,10 @@ void DiveCartesianAxis::updateTicks() } // Add's the rest of the needed Ticks / Text. - for (int i = labels.size(); i < steps; i++, currValueText += interval) { + for (int i = labels.size(); i < steps; i++, currValueText += interval) { qreal childPos; if (orientation == TopToBottom || orientation == LeftToRight) { - childPos = begin + i * stepSize; + childPos = begin + i * stepSize; } else { childPos = begin - i * stepSize; } @@ -202,17 +204,17 @@ void DiveCartesianAxis::updateTicks() label->setPos(scene()->sceneRect().width() + 10, m.y1() + tick_size); // position it outside of the scene); label->animateMoveTo(childPos, m.y1() + tick_size); } else { - label->setAlignment(Qt::AlignVCenter| Qt::AlignLeft); + label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); label->setPos(m.x1() - tick_size, scene()->sceneRect().height() + 10); label->animateMoveTo(m.x1() - tick_size, childPos); } } // Add's the rest of the needed Ticks / Text. - for (int i = lines.size(); i < steps; i++, currValueText += interval) { + for (int i = lines.size(); i < steps; i++, currValueText += interval) { qreal childPos; if (orientation == TopToBottom || orientation == LeftToRight) { - childPos = begin + i * stepSize; + childPos = begin + i * stepSize; } else { childPos = begin - i * stepSize; } @@ -225,7 +227,7 @@ void DiveCartesianAxis::updateTicks() line->setZValue(0); lines.push_back(line); if (orientation == RightToLeft || orientation == LeftToRight) { - line->setLine(0,-line_size,0, 0); + line->setLine(0, -line_size, 0, 0); line->animateMoveTo(childPos, m.y1()); } else { QPointF p1 = mapFromScene(3, 0); @@ -235,13 +237,13 @@ void DiveCartesianAxis::updateTicks() } } - Q_FOREACH(DiveTextItem *item, labels) - item->setVisible(textVisibility); - Q_FOREACH(DiveLineItem *item, lines) - item->setVisible(lineVisibility); + Q_FOREACH(DiveTextItem * item, labels) + item->setVisible(textVisibility); + Q_FOREACH(DiveLineItem * item, lines) + item->setVisible(lineVisibility); } -void DiveCartesianAxis::animateChangeLine(const QLineF& newLine) +void DiveCartesianAxis::animateChangeLine(const QLineF &newLine) { setLine(newLine); updateTicks(); @@ -263,15 +265,15 @@ void DiveCartesianAxis::setTickInterval(double i) interval = i; } -qreal DiveCartesianAxis::valueAt(const QPointF& p) const +qreal DiveCartesianAxis::valueAt(const QPointF &p) const { QLineF m = line(); QPointF relativePosition = p; relativePosition -= pos(); // normalize p based on the axis' offset on screen - double retValue = (orientation == LeftToRight || orientation == RightToLeft) ? - max * (relativePosition.x() - m.x1()) / (m.x2() - m.x1()) : - max * (relativePosition.y() - m.y1()) / (m.y2() - m.y1()); + double retValue = (orientation == LeftToRight || orientation == RightToLeft) ? + max * (relativePosition.x() - m.x1()) / (m.x2() - m.x1()) : + max * (relativePosition.y() - m.y1()) / (m.y2() - m.y1()); return retValue; } @@ -283,12 +285,12 @@ qreal DiveCartesianAxis::posAtValue(qreal value) double size = max - min; // unused for now: // double distanceFromOrigin = value - min; - double percent = IS_FP_SAME(min,max) ? 0.0 : (value - min) / size; + double percent = IS_FP_SAME(min, max) ? 0.0 : (value - min) / size; - double realSize = orientation == LeftToRight || orientation == RightToLeft? - m.x2() - m.x1() : - m.y2() - m.y1(); + double realSize = orientation == LeftToRight || orientation == RightToLeft ? + m.x2() - m.x1() : + m.y2() - m.y1(); // Inverted axis, just invert the percentage. if (orientation == RightToLeft || orientation == BottomToTop) @@ -296,14 +298,14 @@ qreal DiveCartesianAxis::posAtValue(qreal value) double retValue = realSize * percent; double adjusted = - orientation == LeftToRight ? retValue + m.x1() + p.x() : - orientation == RightToLeft ? retValue + m.x1() + p.x() : - orientation == TopToBottom ? retValue + m.y1() + p.y() : - /* entation == BottomToTop */ retValue + m.y1() + p.y() ; + orientation == LeftToRight ? retValue + m.x1() + p.x() : + orientation == RightToLeft ? retValue + m.x1() + p.x() : + orientation == TopToBottom ? retValue + m.y1() + p.y() : + /* entation == BottomToTop */ retValue + m.y1() + p.y(); return adjusted; } -qreal DiveCartesianAxis::percentAt(const QPointF& p) +qreal DiveCartesianAxis::percentAt(const QPointF &p) { qreal value = valueAt(p); double size = max - min; @@ -326,7 +328,7 @@ double DiveCartesianAxis::fontLabelScale() const return labelScale; } -void DiveCartesianAxis::setColor(const QColor& color) +void DiveCartesianAxis::setColor(const QColor &color) { QPen defaultPen(color); defaultPen.setJoinStyle(Qt::RoundJoin); @@ -361,24 +363,24 @@ DepthAxis::DepthAxis() : showWithPPGraph(false) { connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); - // force the correct size of the line. + // force the correct size of the line. showWithPPGraph = !isPPGraphEnabled(); settingsChanged(); } void DepthAxis::settingsChanged() { -// bool ppGraph = isPPGraphEnabled(); -// if ( ppGraph == showWithPPGraph){ -// return; -// } -// -// if (ppGraph) { -// animateChangeLine(shrinkedLine); -// } else { -// animateChangeLine(expandedLine); -// } -// showWithPPGraph = ppGraph; + // bool ppGraph = isPPGraphEnabled(); + // if ( ppGraph == showWithPPGraph){ + // return; + // } + // + // if (ppGraph) { + // animateChangeLine(shrinkedLine); + // } else { + // animateChangeLine(expandedLine); + // } + // showWithPPGraph = ppGraph; } QColor TimeAxis::colorForValue(double value) @@ -390,16 +392,16 @@ QColor TimeAxis::colorForValue(double value) QString TimeAxis::textForValue(double value) { int nr = value / 60; - if (maximum() < 600 ) - return QString("%1:%2").arg(nr).arg( (int)value%60, 2, 10, QChar('0')); - return QString::number(nr); + if (maximum() < 600) + return QString("%1:%2").arg(nr).arg((int)value % 60, 2, 10, QChar('0')); + return QString::number(nr); } void TimeAxis::updateTicks() { DiveCartesianAxis::updateTicks(); - if (maximum() > 600){ - for(int i = 0; i < labels.count(); i++){ + if (maximum() > 600) { + for (int i = 0; i < labels.count(); i++) { labels[i]->setVisible(i % 2); } } @@ -407,7 +409,7 @@ void TimeAxis::updateTicks() QString TemperatureAxis::textForValue(double value) { - return QString::number(mkelvin_to_C( (int) value)); + return QString::number(mkelvin_to_C((int)value)); } PartialGasPressureAxis::PartialGasPressureAxis() @@ -415,7 +417,7 @@ PartialGasPressureAxis::PartialGasPressureAxis() connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), this, SLOT(preferencesChanged())); } -void PartialGasPressureAxis::setModel(DivePlotDataModel* m) +void PartialGasPressureAxis::setModel(DivePlotDataModel *m) { model = m; connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(preferencesChanged())); @@ -435,8 +437,8 @@ void PartialGasPressureAxis::preferencesChanged() double max = showPhe ? model->pheMax() : -1; if (showPn2 && model->pn2Max() > max) - max = model->pn2Max(); - if( showPo2 && model->po2Max() > max) + max = model->pn2Max(); + if (showPo2 && model->po2Max() > max) max = model->po2Max(); qreal pp = floor(max * 10.0) / 10.0 + 0.2; @@ -444,6 +446,6 @@ void PartialGasPressureAxis::preferencesChanged() return; setMaximum(pp); - setTickInterval( pp > 4 ? 0.5 : 0.25 ); + setTickInterval(pp > 4 ? 0.5 : 0.25); updateTicks(); } diff --git a/qt-ui/profile/divecartesianaxis.h b/qt-ui/profile/divecartesianaxis.h index 1bfb4b913..c430d4704 100644 --- a/qt-ui/profile/divecartesianaxis.h +++ b/qt-ui/profile/divecartesianaxis.h @@ -9,14 +9,19 @@ class DiveTextItem; class DiveLineItem; class DivePlotDataModel; -class DiveCartesianAxis : public QObject, public QGraphicsLineItem{ +class DiveCartesianAxis : public QObject, public QGraphicsLineItem { Q_OBJECT Q_PROPERTY(QLineF line WRITE setLine READ line) Q_PROPERTY(QPointF pos WRITE setPos READ pos) Q_PROPERTY(qreal x WRITE setX READ x) Q_PROPERTY(qreal y WRITE setY READ y) public: - enum Orientation{TopToBottom, BottomToTop, LeftToRight, RightToLeft}; + enum Orientation { + TopToBottom, + BottomToTop, + LeftToRight, + RightToLeft + }; DiveCartesianAxis(); virtual ~DiveCartesianAxis(); void setMinimum(double minimum); @@ -30,28 +35,30 @@ public: double tickInterval() const; double tickSize() const; double fontLabelScale() const; - qreal valueAt(const QPointF& p) const; - qreal percentAt(const QPointF& p); + qreal valueAt(const QPointF &p) const; + qreal percentAt(const QPointF &p); qreal posAtValue(qreal value); - void setColor(const QColor& color); - void setTextColor(const QColor& color); - void animateChangeLine(const QLineF& newLine); + void setColor(const QColor &color); + void setTextColor(const QColor &color); + void animateChangeLine(const QLineF &newLine); void setTextVisible(bool arg1); void setLinesVisible(bool arg1); void setLineSize(qreal lineSize); int unitSystem; -public slots: +public +slots: virtual void updateTicks(); signals: void sizeChanged(); void maxChanged(); + protected: virtual QString textForValue(double value); virtual QColor colorForValue(double value); Orientation orientation; - QList<DiveTextItem*> labels; - QList<DiveLineItem*> lines; + QList<DiveTextItem *> labels; + QList<DiveLineItem *> lines; double min; double max; double interval; @@ -67,11 +74,14 @@ class DepthAxis : public DiveCartesianAxis { Q_OBJECT public: DepthAxis(); + protected: QString textForValue(double value); QColor colorForValue(double value); -private slots: +private +slots: void settingsChanged(); + private: bool showWithPPGraph; }; @@ -80,24 +90,27 @@ class TimeAxis : public DiveCartesianAxis { Q_OBJECT public: virtual void updateTicks(); + protected: QString textForValue(double value); QColor colorForValue(double value); }; -class TemperatureAxis : public DiveCartesianAxis{ +class TemperatureAxis : public DiveCartesianAxis { Q_OBJECT protected: QString textForValue(double value); }; -class PartialGasPressureAxis : public DiveCartesianAxis{ +class PartialGasPressureAxis : public DiveCartesianAxis { Q_OBJECT public: PartialGasPressureAxis(); void setModel(DivePlotDataModel *model); -public slots: +public +slots: void preferencesChanged(); + private: DivePlotDataModel *model; }; diff --git a/qt-ui/profile/diveeventitem.cpp b/qt-ui/profile/diveeventitem.cpp index f3740ef08..40d9e7263 100644 --- a/qt-ui/profile/diveeventitem.cpp +++ b/qt-ui/profile/diveeventitem.cpp @@ -6,26 +6,29 @@ #include "dive.h" #include <QDebug> -DiveEventItem::DiveEventItem(QObject* parent): DivePixmapItem(parent), - vAxis(NULL), hAxis(NULL), dataModel(NULL), internalEvent(NULL) +DiveEventItem::DiveEventItem(QObject *parent) : DivePixmapItem(parent), + vAxis(NULL), + hAxis(NULL), + dataModel(NULL), + internalEvent(NULL) { setFlag(ItemIgnoresTransformations); } -void DiveEventItem::setHorizontalAxis(DiveCartesianAxis* axis) +void DiveEventItem::setHorizontalAxis(DiveCartesianAxis *axis) { hAxis = axis; recalculatePos(true); } -void DiveEventItem::setModel(DivePlotDataModel* model) +void DiveEventItem::setModel(DivePlotDataModel *model) { dataModel = model; recalculatePos(true); } -void DiveEventItem::setVerticalAxis(DiveCartesianAxis* axis) +void DiveEventItem::setVerticalAxis(DiveCartesianAxis *axis) { vAxis = axis; recalculatePos(true); @@ -37,7 +40,7 @@ struct event *DiveEventItem::getEvent() return internalEvent; } -void DiveEventItem::setEvent(struct event* ev) +void DiveEventItem::setEvent(struct event *ev) { if (!ev) return; @@ -49,7 +52,7 @@ void DiveEventItem::setEvent(struct event* ev) void DiveEventItem::setupPixmap() { -#define EVENT_PIXMAP( PIX ) QPixmap(QString(PIX)).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation) +#define EVENT_PIXMAP(PIX) QPixmap(QString(PIX)).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation) if (!internalEvent->name) { setPixmap(EVENT_PIXMAP(":warning")); } else if ((strcmp(internalEvent->name, "bookmark") == 0)) { @@ -84,7 +87,7 @@ void DiveEventItem::setupToolTipString() else name += QString(tr("EAN%1")).arg(o2); } else if (name == "SP change") { - name += QString(":%1").arg((double) value / 1000); + name += QString(":%1").arg((double)value / 1000); } else { name += QString(":%1").arg(value); } @@ -98,7 +101,7 @@ void DiveEventItem::setupToolTipString() setToolTip(name); } -void DiveEventItem::eventVisibilityChanged(const QString& eventName, bool visible) +void DiveEventItem::eventVisibilityChanged(const QString &eventName, bool visible) { } @@ -107,7 +110,7 @@ void DiveEventItem::recalculatePos(bool instant) if (!vAxis || !hAxis || !internalEvent || !dataModel) return; - QModelIndexList result = dataModel->match(dataModel->index(0,DivePlotDataModel::TIME), Qt::DisplayRole, internalEvent->time.seconds ); + QModelIndexList result = dataModel->match(dataModel->index(0, DivePlotDataModel::TIME), Qt::DisplayRole, internalEvent->time.seconds); if (result.isEmpty()) { Q_ASSERT("can't find a spot in the dataModel"); hide(); @@ -122,5 +125,5 @@ void DiveEventItem::recalculatePos(bool instant) if (!instant) Animations::moveTo(this, x, y, 500); else - setPos(x,y); + setPos(x, y); } diff --git a/qt-ui/profile/diveeventitem.h b/qt-ui/profile/diveeventitem.h index d2efb2dc4..1b138163c 100644 --- a/qt-ui/profile/diveeventitem.h +++ b/qt-ui/profile/diveeventitem.h @@ -10,22 +10,24 @@ struct event; class DiveEventItem : public DivePixmapItem { Q_OBJECT public: - DiveEventItem(QObject* parent = 0); + DiveEventItem(QObject *parent = 0); void setEvent(struct event *ev); struct event *getEvent(); - void eventVisibilityChanged(const QString& eventName, bool visible); + void eventVisibilityChanged(const QString &eventName, bool visible); void setVerticalAxis(DiveCartesianAxis *axis); void setHorizontalAxis(DiveCartesianAxis *axis); void setModel(DivePlotDataModel *model); -public slots: +public +slots: void recalculatePos(bool instant = false); + private: void setupToolTipString(); void setupPixmap(); DiveCartesianAxis *vAxis; DiveCartesianAxis *hAxis; DivePlotDataModel *dataModel; - struct event* internalEvent; + struct event *internalEvent; }; #endif // DIVEEVENTITEM_H diff --git a/qt-ui/profile/divelineitem.cpp b/qt-ui/profile/divelineitem.cpp index 834c1b8e3..eb3d1db9c 100644 --- a/qt-ui/profile/divelineitem.cpp +++ b/qt-ui/profile/divelineitem.cpp @@ -4,7 +4,6 @@ DiveLineItem::DiveLineItem(QGraphicsItem *parent) : QGraphicsLineItem(parent) { - } void DiveLineItem::animatedHide() diff --git a/qt-ui/profile/divepixmapitem.cpp b/qt-ui/profile/divepixmapitem.cpp index c62a7a20b..d27d77cba 100644 --- a/qt-ui/profile/divepixmapitem.cpp +++ b/qt-ui/profile/divepixmapitem.cpp @@ -1,6 +1,5 @@ #include "divepixmapitem.h" -DivePixmapItem::DivePixmapItem(QObject* parent): QObject(parent), QGraphicsPixmapItem() +DivePixmapItem::DivePixmapItem(QObject *parent) : QObject(parent), QGraphicsPixmapItem() { - } diff --git a/qt-ui/profile/divepixmapitem.h b/qt-ui/profile/divepixmapitem.h index 855a0d2d7..aa2563877 100644 --- a/qt-ui/profile/divepixmapitem.h +++ b/qt-ui/profile/divepixmapitem.h @@ -4,14 +4,14 @@ #include <QObject> #include <QGraphicsPixmapItem> -class DivePixmapItem : public QObject, public QGraphicsPixmapItem{ +class DivePixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT Q_PROPERTY(qreal opacity WRITE setOpacity READ opacity) Q_PROPERTY(QPointF pos WRITE setPos READ pos) Q_PROPERTY(qreal x WRITE setX READ x) Q_PROPERTY(qreal y WRITE setY READ y) public: - DivePixmapItem(QObject* parent = 0); + DivePixmapItem(QObject *parent = 0); }; #endif // DIVEPIXMAPITEM_H diff --git a/qt-ui/profile/diveplotdatamodel.cpp b/qt-ui/profile/diveplotdatamodel.cpp index f7a0e231b..7412a7764 100644 --- a/qt-ui/profile/diveplotdatamodel.cpp +++ b/qt-ui/profile/diveplotdatamodel.cpp @@ -8,60 +8,76 @@ #include "divelist.h" #include <QDebug> -DivePlotDataModel::DivePlotDataModel(QObject* parent) : QAbstractTableModel(parent) , diveId(0) +DivePlotDataModel::DivePlotDataModel(QObject *parent) : QAbstractTableModel(parent), diveId(0) { memset(&pInfo, 0, sizeof(pInfo)); } -int DivePlotDataModel::columnCount(const QModelIndex& parent) const +int DivePlotDataModel::columnCount(const QModelIndex &parent) const { return COLUMNS; } -QVariant DivePlotDataModel::data(const QModelIndex& index, int role) const +QVariant DivePlotDataModel::data(const QModelIndex &index, int role) const { - if ((!index.isValid())||(index.row() >= pInfo.nr)) + if ((!index.isValid()) || (index.row() >= pInfo.nr)) return QVariant(); plot_data item = pInfo.entry[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { - case DEPTH: return item.depth; - case TIME: return item.sec; - case PRESSURE: return item.pressure[0]; - case TEMPERATURE: return item.temperature; - case COLOR: return item.velocity; - case USERENTERED: return false; - case CYLINDERINDEX: return item.cylinderindex; - case SENSOR_PRESSURE: return item.pressure[0]; - case INTERPOLATED_PRESSURE: return item.pressure[1]; - case CEILING: return item.ceiling; - case SAC: return item.sac; - case PN2: return item.pn2; - case PHE: return item.phe; - case PO2: return item.po2; - case HEARTBEAT: return item.heartbeat; + case DEPTH: + return item.depth; + case TIME: + return item.sec; + case PRESSURE: + return item.pressure[0]; + case TEMPERATURE: + return item.temperature; + case COLOR: + return item.velocity; + case USERENTERED: + return false; + case CYLINDERINDEX: + return item.cylinderindex; + case SENSOR_PRESSURE: + return item.pressure[0]; + case INTERPOLATED_PRESSURE: + return item.pressure[1]; + case CEILING: + return item.ceiling; + case SAC: + return item.sac; + case PN2: + return item.pn2; + case PHE: + return item.phe; + case PO2: + return item.po2; + case HEARTBEAT: + return item.heartbeat; } } - if (role == Qt::DisplayRole && index.column() >= TISSUE_1 && index.column() <= TISSUE_16){ - return item.ceilings[ index.column() - TISSUE_1]; + if (role == Qt::DisplayRole && index.column() >= TISSUE_1 && index.column() <= TISSUE_16) { + return item.ceilings[index.column() - TISSUE_1]; } if (role == Qt::BackgroundRole) { switch (index.column()) { - case COLOR: return getColor((color_indice_t)(VELOCITY_COLORS_START_IDX + item.velocity)); + case COLOR: + return getColor((color_indice_t)(VELOCITY_COLORS_START_IDX + item.velocity)); } } return QVariant(); } -const plot_info& DivePlotDataModel::data() const +const plot_info &DivePlotDataModel::data() const { return pInfo; } -int DivePlotDataModel::rowCount(const QModelIndex& parent) const +int DivePlotDataModel::rowCount(const QModelIndex &parent) const { return pInfo.nr; } @@ -75,22 +91,36 @@ QVariant DivePlotDataModel::headerData(int section, Qt::Orientation orientation, return QVariant(); switch (section) { - case DEPTH: return tr("Depth"); - case TIME: return tr("Time"); - case PRESSURE: return tr("Pressure"); - case TEMPERATURE: return tr("Temperature"); - case COLOR: return tr("Color"); - case USERENTERED: return tr("User Entered"); - case CYLINDERINDEX: return tr("Cylinder Index"); - case SENSOR_PRESSURE: return tr("Pressure S"); - case INTERPOLATED_PRESSURE: return tr("Pressure I"); - case CEILING: return tr("Ceiling"); - case SAC: return tr("SAC"); - case PN2: return tr("PN2"); - case PHE: return tr("PHE"); - case PO2: return tr("PO2"); + case DEPTH: + return tr("Depth"); + case TIME: + return tr("Time"); + case PRESSURE: + return tr("Pressure"); + case TEMPERATURE: + return tr("Temperature"); + case COLOR: + return tr("Color"); + case USERENTERED: + return tr("User Entered"); + case CYLINDERINDEX: + return tr("Cylinder Index"); + case SENSOR_PRESSURE: + return tr("Pressure S"); + case INTERPOLATED_PRESSURE: + return tr("Pressure I"); + case CEILING: + return tr("Ceiling"); + case SAC: + return tr("SAC"); + case PN2: + return tr("PN2"); + case PHE: + return tr("PHE"); + case PO2: + return tr("PO2"); } - if (role == Qt::DisplayRole && section >= TISSUE_1 && section <= TISSUE_16){ + if (role == Qt::DisplayRole && section >= TISSUE_1 && section <= TISSUE_16) { return QString("Ceiling: %1").arg(section - TISSUE_1); } return QVariant(); @@ -107,14 +137,14 @@ void DivePlotDataModel::clear() } } -void DivePlotDataModel::setDive(dive* d, const plot_info& info) +void DivePlotDataModel::setDive(dive *d, const plot_info &info) { clear(); Q_ASSERT(d != NULL); diveId = d->id; dcNr = dc_number; pInfo = info; - beginInsertRows(QModelIndex(), 0, pInfo.nr-1); + beginInsertRows(QModelIndex(), 0, pInfo.nr - 1); endInsertRows(); } @@ -128,16 +158,16 @@ int DivePlotDataModel::dcShown() const return dcNr; } -#define MAX_PPGAS_FUNC( GAS, GASFUNC ) \ -double DivePlotDataModel::GASFUNC() \ -{ \ - double ret = -1; \ - for(int i = 0, count = rowCount(); i < count; i++){ \ - if (pInfo.entry[i].GAS > ret) \ - ret = pInfo.entry[i].GAS; \ - } \ - return ret; \ -} +#define MAX_PPGAS_FUNC(GAS, GASFUNC) \ + double DivePlotDataModel::GASFUNC() \ + { \ + double ret = -1; \ + for (int i = 0, count = rowCount(); i < count; i++) { \ + if (pInfo.entry[i].GAS > ret) \ + ret = pInfo.entry[i].GAS; \ + } \ + return ret; \ + } MAX_PPGAS_FUNC(phe, pheMax); MAX_PPGAS_FUNC(pn2, pn2Max); @@ -156,5 +186,5 @@ void DivePlotDataModel::calculateDecompression() struct divecomputer *dc = select_dc(&d->dc); init_decompression(d); calculate_deco_information(d, dc, &pInfo, false); - dataChanged(index(0, CEILING), index(pInfo.nr-1, TISSUE_16)); + dataChanged(index(0, CEILING), index(pInfo.nr - 1, TISSUE_16)); } diff --git a/qt-ui/profile/diveplotdatamodel.h b/qt-ui/profile/diveplotdatamodel.h index 0a64a6a89..272c0d1c3 100644 --- a/qt-ui/profile/diveplotdatamodel.h +++ b/qt-ui/profile/diveplotdatamodel.h @@ -9,20 +9,51 @@ struct dive; struct plot_data; struct plot_info; -class DivePlotDataModel : public QAbstractTableModel{ -Q_OBJECT +class DivePlotDataModel : public QAbstractTableModel { + Q_OBJECT public: - enum {DEPTH, TIME, PRESSURE, TEMPERATURE, USERENTERED, COLOR, CYLINDERINDEX, SENSOR_PRESSURE, INTERPOLATED_PRESSURE, - SAC, CEILING, TISSUE_1,TISSUE_2,TISSUE_3,TISSUE_4,TISSUE_5,TISSUE_6,TISSUE_7,TISSUE_8,TISSUE_9,TISSUE_10, - TISSUE_11,TISSUE_12,TISSUE_13,TISSUE_14,TISSUE_15,TISSUE_16, PN2,PHE,PO2, HEARTBEAT, COLUMNS}; - explicit DivePlotDataModel(QObject* parent = 0); - virtual int columnCount(const QModelIndex& parent = QModelIndex()) const; + enum { + DEPTH, + TIME, + PRESSURE, + TEMPERATURE, + USERENTERED, + COLOR, + CYLINDERINDEX, + SENSOR_PRESSURE, + INTERPOLATED_PRESSURE, + SAC, + CEILING, + TISSUE_1, + TISSUE_2, + TISSUE_3, + TISSUE_4, + TISSUE_5, + TISSUE_6, + TISSUE_7, + TISSUE_8, + TISSUE_9, + TISSUE_10, + TISSUE_11, + TISSUE_12, + TISSUE_13, + TISSUE_14, + TISSUE_15, + TISSUE_16, + PN2, + PHE, + PO2, + HEARTBEAT, + COLUMNS + }; + explicit DivePlotDataModel(QObject *parent = 0); + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - virtual int rowCount(const QModelIndex& parent = QModelIndex()) const; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; void clear(); - void setDive(struct dive *d, const plot_info& pInfo); - const plot_info& data() const; + void setDive(struct dive *d, const plot_info &pInfo); + const plot_info &data() const; int id() const; int dcShown() const; double pheMax(); @@ -30,6 +61,7 @@ public: double po2Max(); void emitDataChanged(); void calculateDecompression(); + private: plot_info pInfo; int diveId; diff --git a/qt-ui/profile/diveprofileitem.cpp b/qt-ui/profile/diveprofileitem.cpp index fe47e7b5f..8bfad9b40 100644 --- a/qt-ui/profile/diveprofileitem.cpp +++ b/qt-ui/profile/diveprofileitem.cpp @@ -17,8 +17,7 @@ #include <QGraphicsItem> #include <QSettings> -AbstractProfilePolygonItem::AbstractProfilePolygonItem(): QObject(), QGraphicsPolygonItem(), - hAxis(NULL), vAxis(NULL), dataModel(NULL), hDataColumn(-1), vDataColumn(-1) +AbstractProfilePolygonItem::AbstractProfilePolygonItem() : QObject(), QGraphicsPolygonItem(), hAxis(NULL), vAxis(NULL), dataModel(NULL), hDataColumn(-1), vDataColumn(-1) { connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), this, SLOT(preferencesChanged())); } @@ -27,7 +26,7 @@ void AbstractProfilePolygonItem::preferencesChanged() { } -void AbstractProfilePolygonItem::setHorizontalAxis(DiveCartesianAxis* horizontal) +void AbstractProfilePolygonItem::setHorizontalAxis(DiveCartesianAxis *horizontal) { hAxis = horizontal; connect(hAxis, SIGNAL(sizeChanged()), this, SLOT(modelDataChanged())); @@ -40,22 +39,22 @@ void AbstractProfilePolygonItem::setHorizontalDataColumn(int column) modelDataChanged(); } -void AbstractProfilePolygonItem::setModel(DivePlotDataModel* model) +void AbstractProfilePolygonItem::setModel(DivePlotDataModel *model) { dataModel = model; - connect(dataModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(modelDataChanged(QModelIndex, QModelIndex))); - connect(dataModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(modelDataRemoved(QModelIndex, int, int))); + connect(dataModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(modelDataChanged(QModelIndex, QModelIndex))); + connect(dataModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int)), this, SLOT(modelDataRemoved(QModelIndex, int, int))); modelDataChanged(); } -void AbstractProfilePolygonItem::modelDataRemoved(const QModelIndex& parent, int from, int to) +void AbstractProfilePolygonItem::modelDataRemoved(const QModelIndex &parent, int from, int to) { setPolygon(QPolygonF()); qDeleteAll(texts); texts.clear(); } -void AbstractProfilePolygonItem::setVerticalAxis(DiveCartesianAxis* vertical) +void AbstractProfilePolygonItem::setVerticalAxis(DiveCartesianAxis *vertical) { vAxis = vertical; connect(vAxis, SIGNAL(sizeChanged()), this, SLOT(modelDataChanged())); @@ -69,7 +68,7 @@ void AbstractProfilePolygonItem::setVerticalDataColumn(int column) modelDataChanged(); } -bool AbstractProfilePolygonItem::shouldCalculateStuff(const QModelIndex& topLeft, const QModelIndex& bottomRight) +bool AbstractProfilePolygonItem::shouldCalculateStuff(const QModelIndex &topLeft, const QModelIndex &bottomRight) { if (!hAxis || !vAxis) return false; @@ -77,16 +76,16 @@ bool AbstractProfilePolygonItem::shouldCalculateStuff(const QModelIndex& topLeft return false; if (hDataColumn == -1 || vDataColumn == -1) return false; - if ( topLeft.isValid() && bottomRight.isValid()){ - if ((topLeft.column() >= vDataColumn || topLeft.column() >= hDataColumn ) && - (bottomRight.column() <= vDataColumn || topLeft.column() <= hDataColumn )){ + if (topLeft.isValid() && bottomRight.isValid()) { + if ((topLeft.column() >= vDataColumn || topLeft.column() >= hDataColumn) && + (bottomRight.column() <= vDataColumn || topLeft.column() <= hDataColumn)) { return true; } } return true; } -void AbstractProfilePolygonItem::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void AbstractProfilePolygonItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { // We don't have enougth data to calculate things, quit. @@ -99,7 +98,7 @@ void AbstractProfilePolygonItem::modelDataChanged(const QModelIndex& topLeft, co for (int i = 0, modelDataCount = dataModel->rowCount(); i < modelDataCount; i++) { qreal horizontalValue = dataModel->index(i, hDataColumn).data().toReal(); qreal verticalValue = dataModel->index(i, vDataColumn).data().toReal(); - QPointF point( hAxis->posAtValue(horizontalValue), vAxis->posAtValue(verticalValue)); + QPointF point(hAxis->posAtValue(horizontalValue), vAxis->posAtValue(verticalValue)); poly.append(point); } setPolygon(poly); @@ -110,12 +109,12 @@ void AbstractProfilePolygonItem::modelDataChanged(const QModelIndex& topLeft, co DiveProfileItem::DiveProfileItem() : show_reported_ceiling(0), reported_ceiling_in_red(0) { - } -void DiveProfileItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { +void DiveProfileItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ Q_UNUSED(widget); - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; // This paints the Polygon + Background. I'm setting the pen to QPen() so we don't get a black line here, @@ -134,13 +133,13 @@ void DiveProfileItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* o QModelIndex colorIndex = dataModel->index(i, DivePlotDataModel::COLOR); pen.setBrush(QBrush(colorIndex.data(Qt::BackgroundRole).value<QColor>())); painter->setPen(pen); - painter->drawLine(poly[i-1],poly[i]); + painter->drawLine(poly[i - 1], poly[i]); } } -void DiveProfileItem::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void DiveProfileItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { - if(!shouldCalculateStuff(topLeft, bottomRight)) + if (!shouldCalculateStuff(topLeft, bottomRight)) return; AbstractProfilePolygonItem::modelDataChanged(topLeft, bottomRight); @@ -153,7 +152,7 @@ void DiveProfileItem::modelDataChanged(const QModelIndex& topLeft, const QModelI /* Show any ceiling we may have encountered */ if (prefs.profile_dc_ceiling && !prefs.profile_red_ceiling) { QPolygonF p = polygon(); - plot_data *entry = dataModel->data().entry + dataModel->rowCount()-1; + plot_data *entry = dataModel->data().entry + dataModel->rowCount() - 1; for (int i = dataModel->rowCount() - 1; i >= 0; i--, entry--) { if (!entry->in_deco) { /* not in deco implies this is a safety stop, no ceiling */ @@ -167,7 +166,7 @@ void DiveProfileItem::modelDataChanged(const QModelIndex& topLeft, const QModelI setPolygon(p); } - // This is the blueish gradient that the Depth Profile should have. + // This is the blueish gradient that the Depth Profile should have. // It's a simple QLinearGradient with 2 stops, starting from top to bottom. QLinearGradient pat(0, polygon().boundingRect().top(), 0, polygon().boundingRect().bottom()); pat.setColorAt(1, getColor(DEPTH_BOTTOM)); @@ -175,9 +174,9 @@ void DiveProfileItem::modelDataChanged(const QModelIndex& topLeft, const QModelI setBrush(QBrush(pat)); int last = -1; - for (int i = 0, count = dataModel->rowCount(); i < count; i++) { + for (int i = 0, count = dataModel->rowCount(); i < count; i++) { - struct plot_data *entry = dataModel->data().entry+i; + struct plot_data *entry = dataModel->data().entry + i; if (entry->depth < 2000) continue; @@ -201,10 +200,10 @@ void DiveProfileItem::preferencesChanged() //TODO: Only modelDataChanged() here if we need to rebuild the graph ( for instance, // if the prefs.profile_dc_ceiling are enabled, but prefs.profile_red_ceiling is disabled // and only if it changed something. let's not waste cpu cycles repoloting something we don't need to. - modelDataChanged(); + modelDataChanged(); } -void DiveProfileItem::plot_depth_sample(struct plot_data *entry,QFlags<Qt::AlignmentFlag> flags,const QColor& color) +void DiveProfileItem::plot_depth_sample(struct plot_data *entry, QFlags<Qt::AlignmentFlag> flags, const QColor &color) { int decimals; double d = get_depth_units(entry->depth, &decimals, NULL); @@ -231,7 +230,7 @@ void DiveHeartrateItem::modelDataChanged(const QModelIndex &topLeft, const QMode struct { int sec; int hr; - } hist[3] = {0}; + } hist[3] = { 0 }; // We don't have enougth data to calculate things, quit. if (!shouldCalculateStuff(topLeft, bottomRight)) @@ -246,7 +245,7 @@ void DiveHeartrateItem::modelDataChanged(const QModelIndex &topLeft, const QMode if (!hr) continue; sec = dataModel->index(i, hDataColumn).data().toInt(); - QPointF point( hAxis->posAtValue(sec), vAxis->posAtValue(hr)); + QPointF point(hAxis->posAtValue(sec), vAxis->posAtValue(hr)); poly.append(point); if (hr == hist[2].hr) // same as last one, no point in looking at printing @@ -276,7 +275,7 @@ void DiveHeartrateItem::modelDataChanged(const QModelIndex &topLeft, const QMode } setPolygon(poly); - if( texts.count()) + if (texts.count()) texts.last()->setAlignment(Qt::AlignLeft | Qt::AlignBottom); } @@ -291,9 +290,9 @@ void DiveHeartrateItem::createTextItem(int sec, int hr) texts.append(text); } -void DiveHeartrateItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void DiveHeartrateItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; painter->setPen(pen()); painter->drawPolyline(polygon()); @@ -308,7 +307,7 @@ DiveTemperatureItem::DiveTemperatureItem() setPen(pen); } -void DiveTemperatureItem::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void DiveTemperatureItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { int last = -300, last_printed_temp = 0, sec = 0, last_valid_temp = 0; // We don't have enougth data to calculate things, quit. @@ -325,7 +324,7 @@ void DiveTemperatureItem::modelDataChanged(const QModelIndex& topLeft, const QMo continue; last_valid_temp = mkelvin; sec = dataModel->index(i, hDataColumn).data().toInt(); - QPointF point( hAxis->posAtValue(sec), vAxis->posAtValue(mkelvin)); + QPointF point(hAxis->posAtValue(sec), vAxis->posAtValue(mkelvin)); poly.append(point); /* don't print a temperature @@ -338,7 +337,7 @@ void DiveTemperatureItem::modelDataChanged(const QModelIndex& topLeft, const QMo continue; last = sec; if (mkelvin > 200000) - createTextItem(sec,mkelvin); + createTextItem(sec, mkelvin); last_printed_temp = mkelvin; } setPolygon(poly); @@ -350,7 +349,7 @@ void DiveTemperatureItem::modelDataChanged(const QModelIndex& topLeft, const QMo ((abs(last_valid_temp - last_printed_temp) > 500) || ((double)last / (double)sec < 0.75))) { createTextItem(sec, last_valid_temp); } - if( texts.count()) + if (texts.count()) texts.last()->setAlignment(Qt::AlignLeft | Qt::AlignBottom); } @@ -369,15 +368,15 @@ void DiveTemperatureItem::createTextItem(int sec, int mkelvin) texts.append(text); } -void DiveTemperatureItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void DiveTemperatureItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; painter->setPen(pen()); painter->drawPolyline(polygon()); } -void DiveGasPressureItem::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void DiveGasPressureItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { // We don't have enougth data to calculate things, quit. if (!shouldCalculateStuff(topLeft, bottomRight)) @@ -387,7 +386,7 @@ void DiveGasPressureItem::modelDataChanged(const QModelIndex& topLeft, const QMo polygons.clear(); for (int i = 0, count = dataModel->rowCount(); i < count; i++) { - plot_data* entry = dataModel->data().entry + i; + plot_data *entry = dataModel->data().entry + i; int mbar = GET_PRESSURE(entry); if (entry->cylinderindex != last_index) { @@ -399,7 +398,7 @@ void DiveGasPressureItem::modelDataChanged(const QModelIndex& topLeft, const QMo } QPointF point(hAxis->posAtValue(entry->sec), vAxis->posAtValue(mbar)); - boundingPoly.push_back(point); // The BoundingRect + boundingPoly.push_back(point); // The BoundingRect polygons.last().push_back(point); // The polygon thta will be plotted. } setPolygon(boundingPoly); @@ -425,8 +424,8 @@ void DiveGasPressureItem::modelDataChanged(const QModelIndex& topLeft, const QMo if (!seen_cyl[cyl]) { plot_pressure_value(mbar, entry->sec, Qt::AlignRight | Qt::AlignTop); plot_gas_value(mbar, entry->sec, Qt::AlignRight | Qt::AlignBottom, - get_o2(&dive->cylinder[cyl].gasmix), - get_he(&dive->cylinder[cyl].gasmix)); + get_o2(&dive->cylinder[cyl].gasmix), + get_he(&dive->cylinder[cyl].gasmix)); seen_cyl[cyl] = true; } } @@ -446,7 +445,7 @@ void DiveGasPressureItem::plot_pressure_value(int mbar, int sec, QFlags<Qt::Alig const char *unit; int pressure = get_pressure_units(mbar, &unit); DiveTextItem *text = new DiveTextItem(this); - text->setPos(hAxis->posAtValue(sec), vAxis->posAtValue(mbar)-0.5); + text->setPos(hAxis->posAtValue(sec), vAxis->posAtValue(mbar) - 0.5); text->setText(QString("%1 %2").arg(pressure).arg(unit)); text->setAlignment(flags); text->setBrush(getColor(PRESSURE_TEXT)); @@ -455,9 +454,9 @@ void DiveGasPressureItem::plot_pressure_value(int mbar, int sec, QFlags<Qt::Alig void DiveGasPressureItem::plot_gas_value(int mbar, int sec, QFlags<Qt::AlignmentFlag> flags, int o2, int he) { - QString gas = (is_air(o2, he)) ? tr("air") : - (he == 0) ? QString(tr("EAN%1")).arg((o2 + 5) / 10) : - QString("%1/%2").arg((o2 + 5) / 10).arg((he + 5) / 10); + QString gas = (is_air(o2, he)) ? tr("air") : + (he == 0) ? QString(tr("EAN%1")).arg((o2 + 5) / 10) : + QString("%1/%2").arg((o2 + 5) / 10).arg((he + 5) / 10); DiveTextItem *text = new DiveTextItem(this); text->setPos(hAxis->posAtValue(sec), vAxis->posAtValue(mbar)); text->setText(gas); @@ -466,9 +465,9 @@ void DiveGasPressureItem::plot_gas_value(int mbar, int sec, QFlags<Qt::Alignment texts.push_back(text); } -void DiveGasPressureItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void DiveGasPressureItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; QPen pen; pen.setCosmetic(true); @@ -477,11 +476,11 @@ void DiveGasPressureItem::paint(QPainter* painter, const QStyleOptionGraphicsIte if (!d) return; struct plot_data *entry = dataModel->data().entry; - Q_FOREACH(const QPolygonF& poly, polygons) { + Q_FOREACH(const QPolygonF & poly, polygons) { for (int i = 1, count = poly.count(); i < count; i++, entry++) { pen.setBrush(getSacColor(entry->sac, d->sac)); painter->setPen(pen); - painter->drawLine(poly[i-1],poly[i]); + painter->drawLine(poly[i - 1], poly[i]); } } } @@ -494,7 +493,7 @@ DiveCalculatedCeiling::DiveCalculatedCeiling() : is3mIncrement(false), gradientF preferencesChanged(); } -void DiveCalculatedCeiling::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void DiveCalculatedCeiling::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { // We don't have enougth data to calculate things, quit. if (!shouldCalculateStuff(topLeft, bottomRight)) @@ -514,16 +513,16 @@ void DiveCalculatedCeiling::modelDataChanged(const QModelIndex& topLeft, const Q QLinearGradient pat(0, polygon().boundingRect().top(), 0, polygon().boundingRect().bottom()); pat.setColorAt(0, getColor(CALC_CEILING_SHALLOW)); pat.setColorAt(1, getColor(CALC_CEILING_DEEP)); - setPen(QPen(QBrush(Qt::NoBrush),0)); + setPen(QPen(QBrush(Qt::NoBrush), 0)); setBrush(pat); - gradientFactor->setX(poly.boundingRect().width()/2 + poly.boundingRect().x()); + gradientFactor->setX(poly.boundingRect().width() / 2 + poly.boundingRect().x()); gradientFactor->setText(QString("GF %1/%2").arg(prefs.gflow).arg(prefs.gfhigh)); } -void DiveCalculatedCeiling::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void DiveCalculatedCeiling::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; QGraphicsPolygonItem::paint(painter, option, widget); } @@ -540,9 +539,9 @@ void DiveCalculatedTissue::preferencesChanged() setVisible(s.value("calcalltissues").toBool() && s.value("calcceiling").toBool()); } -void DiveReportedCeiling::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void DiveReportedCeiling::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { - if(!shouldCalculateStuff(topLeft, bottomRight)) + if (!shouldCalculateStuff(topLeft, bottomRight)) return; QPolygonF p; @@ -563,7 +562,7 @@ void DiveReportedCeiling::modelDataChanged(const QModelIndex& topLeft, const QMo QLinearGradient pat(0, p.boundingRect().top(), 0, p.boundingRect().bottom()); pat.setColorAt(0, getColor(CEILING_SHALLOW)); pat.setColorAt(1, getColor(CEILING_DEEP)); - setPen(QPen(QBrush(Qt::NoBrush),0)); + setPen(QPen(QBrush(Qt::NoBrush), 0)); setBrush(pat); } @@ -573,7 +572,7 @@ void DiveCalculatedCeiling::preferencesChanged() s.beginGroup("TecDetails"); bool shouldShow3mIncrement = s.value("calcceiling3m").toBool(); - if ( dataModel && is3mIncrement != shouldShow3mIncrement){ + if (dataModel && is3mIncrement != shouldShow3mIncrement) { // recalculate that part. dataModel->calculateDecompression(); } @@ -588,9 +587,9 @@ void DiveReportedCeiling::preferencesChanged() setVisible(s.value("redceiling").toBool()); } -void DiveReportedCeiling::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void DiveReportedCeiling::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - if(polygon().isEmpty()) + if (polygon().isEmpty()) return; QGraphicsPolygonItem::paint(painter, option, widget); } @@ -619,18 +618,18 @@ void MeanDepthLine::setMeanDepth(int value) meanDepth = value; } -void MeanDepthLine::setAxis(DiveCartesianAxis* a) +void MeanDepthLine::setAxis(DiveCartesianAxis *a) { connect(a, SIGNAL(sizeChanged()), this, SLOT(axisLineChanged())); } void MeanDepthLine::axisLineChanged() { - DiveCartesianAxis *axis = qobject_cast<DiveCartesianAxis*>(sender()); - animateMoveTo(x(),axis->posAtValue(meanDepth)); + DiveCartesianAxis *axis = qobject_cast<DiveCartesianAxis *>(sender()); + animateMoveTo(x(), axis->posAtValue(meanDepth)); } -void PartialPressureGasItem::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) +void PartialPressureGasItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { //AbstractProfilePolygonItem::modelDataChanged(); if (!shouldCalculateStuff(topLeft, bottomRight)) @@ -642,11 +641,11 @@ void PartialPressureGasItem::modelDataChanged(const QModelIndex& topLeft, const QSettings s; s.beginGroup("TecDetails"); double threshould = s.value(threshouldKey).toDouble(); - for(int i = 0; i < dataModel->rowCount(); i++, entry++){ + for (int i = 0; i < dataModel->rowCount(); i++, entry++) { double value = dataModel->index(i, vDataColumn).data().toDouble(); int time = dataModel->index(i, hDataColumn).data().toInt(); QPointF point(hAxis->posAtValue(time), vAxis->posAtValue(value)); - poly.push_back( point ); + poly.push_back(point); if (value >= threshould) alertPoly.push_back(point); } @@ -656,7 +655,7 @@ void PartialPressureGasItem::modelDataChanged(const QModelIndex& topLeft, const */ } -void PartialPressureGasItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void PartialPressureGasItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->setPen(normalColor); painter->drawPolyline(polygon()); @@ -664,7 +663,7 @@ void PartialPressureGasItem::paint(QPainter* painter, const QStyleOptionGraphics painter->drawPolyline(alertPoly); } -void PartialPressureGasItem::setThreshouldSettingsKey(const QString& threshouldSettingsKey) +void PartialPressureGasItem::setThreshouldSettingsKey(const QString &threshouldSettingsKey) { threshouldKey = threshouldSettingsKey; } @@ -677,15 +676,15 @@ void PartialPressureGasItem::preferencesChanged() { QSettings s; s.beginGroup("TecDetails"); - setVisible( s.value(visibilityKey).toBool() ); + setVisible(s.value(visibilityKey).toBool()); } -void PartialPressureGasItem::setVisibilitySettingsKey(const QString& key) +void PartialPressureGasItem::setVisibilitySettingsKey(const QString &key) { visibilityKey = key; } -void PartialPressureGasItem::setColors(const QColor& normal, const QColor& alert) +void PartialPressureGasItem::setColors(const QColor &normal, const QColor &alert) { normalColor = normal; alertColor = alert; diff --git a/qt-ui/profile/diveprofileitem.h b/qt-ui/profile/diveprofileitem.h index 86ea01c64..ee7132c40 100644 --- a/qt-ui/profile/diveprofileitem.h +++ b/qt-ui/profile/diveprofileitem.h @@ -28,7 +28,7 @@ class DiveCartesianAxis; class QAbstractTableModel; struct plot_data; -class AbstractProfilePolygonItem : public QObject, public QGraphicsPolygonItem{ +class AbstractProfilePolygonItem : public QObject, public QGraphicsPolygonItem { Q_OBJECT Q_PROPERTY(QPointF pos WRITE setPos READ pos) Q_PROPERTY(qreal x WRITE setX READ x) @@ -40,12 +40,16 @@ public: void setModel(DivePlotDataModel *model); void setHorizontalDataColumn(int column); void setVerticalDataColumn(int column); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0) = 0; - virtual void clear(){} -public slots: + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0; + virtual void clear() + { + } +public +slots: virtual void preferencesChanged(); - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); - virtual void modelDataRemoved(const QModelIndex& parent, int from, int to); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); + virtual void modelDataRemoved(const QModelIndex &parent, int from, int to); + protected: /* when the model emits a 'datachanged' signal, this method below should be used to check if the * modified data affects this particular item ( for example, when setting the '3m increment' @@ -54,36 +58,38 @@ protected: * into consideration when returning 'true' for "yes, continue the calculation', and 'false' for * 'do not recalculate, we already have the right data. */ - bool shouldCalculateStuff(const QModelIndex& topLeft, const QModelIndex& bottomRight); + bool shouldCalculateStuff(const QModelIndex &topLeft, const QModelIndex &bottomRight); DiveCartesianAxis *hAxis; DiveCartesianAxis *vAxis; DivePlotDataModel *dataModel; int hDataColumn; int vDataColumn; - QList<DiveTextItem*> texts; + QList<DiveTextItem *> texts; }; -class DiveProfileItem : public AbstractProfilePolygonItem{ +class DiveProfileItem : public AbstractProfilePolygonItem { Q_OBJECT public: DiveProfileItem(); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); virtual void preferencesChanged(); - void plot_depth_sample(struct plot_data *entry,QFlags<Qt::AlignmentFlag> flags,const QColor& color); + void plot_depth_sample(struct plot_data *entry, QFlags<Qt::AlignmentFlag> flags, const QColor &color); + private: unsigned int show_reported_ceiling; unsigned int reported_ceiling_in_red; }; -class DiveTemperatureItem : public AbstractProfilePolygonItem{ +class DiveTemperatureItem : public AbstractProfilePolygonItem { Q_OBJECT public: DiveTemperatureItem(); - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + private: void createTextItem(int seconds, int mkelvin); }; @@ -94,41 +100,44 @@ public: DiveHeartrateItem(); virtual void modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + private: void createTextItem(int seconds, int hr); }; -class DiveGasPressureItem : public AbstractProfilePolygonItem{ +class DiveGasPressureItem : public AbstractProfilePolygonItem { Q_OBJECT public: - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + private: void plot_pressure_value(int mbar, int sec, QFlags<Qt::AlignmentFlag> align); void plot_gas_value(int mbar, int sec, QFlags<Qt::AlignmentFlag> align, int o2, int he); QVector<QPolygonF> polygons; }; -class DiveCalculatedCeiling : public AbstractProfilePolygonItem{ +class DiveCalculatedCeiling : public AbstractProfilePolygonItem { Q_OBJECT public: DiveCalculatedCeiling(); - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); virtual void preferencesChanged(); + private: bool is3mIncrement; DiveTextItem *gradientFactor; }; -class DiveReportedCeiling : public AbstractProfilePolygonItem{ +class DiveReportedCeiling : public AbstractProfilePolygonItem { Q_OBJECT public: - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); virtual void preferencesChanged(); }; @@ -146,24 +155,27 @@ public: void setMeanDepth(int value); void setLine(qreal x1, qreal y1, qreal x2, qreal y2); void setAxis(DiveCartesianAxis *a); -public slots: +public +slots: void axisLineChanged(); + private: int meanDepth; DiveTextItem *leftText; DiveTextItem *rightText; }; -class PartialPressureGasItem : public AbstractProfilePolygonItem{ +class PartialPressureGasItem : public AbstractProfilePolygonItem { Q_OBJECT public: PartialPressureGasItem(); - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0); - virtual void modelDataChanged(const QModelIndex& topLeft = QModelIndex(), const QModelIndex& bottomRight = QModelIndex()); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + virtual void modelDataChanged(const QModelIndex &topLeft = QModelIndex(), const QModelIndex &bottomRight = QModelIndex()); virtual void preferencesChanged(); - void setThreshouldSettingsKey(const QString& threshouldSettingsKey); - void setVisibilitySettingsKey(const QString& setVisibilitySettingsKey); - void setColors(const QColor& normalColor, const QColor& alertColor); + void setThreshouldSettingsKey(const QString &threshouldSettingsKey); + void setVisibilitySettingsKey(const QString &setVisibilitySettingsKey); + void setColors(const QColor &normalColor, const QColor &alertColor); + private: QPolygonF alertPoly; QString threshouldKey; diff --git a/qt-ui/profile/diverectitem.cpp b/qt-ui/profile/diverectitem.cpp index 6bdad1142..8cb60c3f5 100644 --- a/qt-ui/profile/diverectitem.cpp +++ b/qt-ui/profile/diverectitem.cpp @@ -1,6 +1,5 @@ #include "diverectitem.h" -DiveRectItem::DiveRectItem(QObject* parent, QGraphicsItem* parentItem): QObject(parent), QGraphicsRectItem(parentItem ) +DiveRectItem::DiveRectItem(QObject *parent, QGraphicsItem *parentItem) : QObject(parent), QGraphicsRectItem(parentItem) { - } diff --git a/qt-ui/profile/diverectitem.h b/qt-ui/profile/diverectitem.h index 9216fe9a1..e616cf591 100644 --- a/qt-ui/profile/diverectitem.h +++ b/qt-ui/profile/diverectitem.h @@ -4,7 +4,7 @@ #include <QObject> #include <QGraphicsRectItem> -class DiveRectItem : public QObject, public QGraphicsRectItem{ +class DiveRectItem : public QObject, public QGraphicsRectItem { Q_OBJECT Q_PROPERTY(QRectF rect WRITE setRect READ rect) Q_PROPERTY(QPointF pos WRITE setPos READ pos) diff --git a/qt-ui/profile/divetextitem.cpp b/qt-ui/profile/divetextitem.cpp index 10116e19f..582cc4070 100644 --- a/qt-ui/profile/divetextitem.cpp +++ b/qt-ui/profile/divetextitem.cpp @@ -9,7 +9,7 @@ #include <QPen> #include <QDebug> -DiveTextItem::DiveTextItem(QGraphicsItem* parent): QGraphicsItemGroup(parent), +DiveTextItem::DiveTextItem(QGraphicsItem *parent) : QGraphicsItemGroup(parent), internalAlignFlags(Qt::AlignHCenter | Qt::AlignVCenter), textBackgroundItem(NULL), textItem(NULL), @@ -25,7 +25,7 @@ void DiveTextItem::setAlignment(int alignFlags) updateText(); } -void DiveTextItem::setBrush(const QBrush& b) +void DiveTextItem::setBrush(const QBrush &b) { brush = b; updateText(); @@ -36,13 +36,13 @@ void DiveTextItem::setScale(double newscale) scale = newscale; } -void DiveTextItem::setText(const QString& t) +void DiveTextItem::setText(const QString &t) { internalText = t; updateText(); } -const QString& DiveTextItem::text() +const QString &DiveTextItem::text() { return internalText; } @@ -54,7 +54,7 @@ void DiveTextItem::updateText() textItem = NULL; delete textBackgroundItem; textBackgroundItem = NULL; - if(internalText.isEmpty()){ + if (internalText.isEmpty()) { return; } @@ -75,14 +75,14 @@ void DiveTextItem::updateText() QRectF rect = fm.boundingRect(internalText); yPos = (internalAlignFlags & Qt::AlignTop) ? 0 : - (internalAlignFlags & Qt::AlignBottom) ? +rect.height() : - /*(internalAlignFlags & Qt::AlignVCenter ? */ +rect.height() / 4; + (internalAlignFlags & Qt::AlignBottom) ? +rect.height() : + /*(internalAlignFlags & Qt::AlignVCenter ? */ +rect.height() / 4; - xPos = (internalAlignFlags & Qt::AlignLeft ) ? -rect.width() : - (internalAlignFlags & Qt::AlignHCenter) ? -rect.width()/2 : - /* (internalAlignFlags & Qt::AlignRight) */ 0; + xPos = (internalAlignFlags & Qt::AlignLeft) ? -rect.width() : + (internalAlignFlags & Qt::AlignHCenter) ? -rect.width() / 2 : + /* (internalAlignFlags & Qt::AlignRight) */ 0; - textPath.addText( xPos, yPos, fnt, internalText); + textPath.addText(xPos, yPos, fnt, internalText); QPainterPathStroker stroker; stroker.setWidth(3); textBackgroundItem = new QGraphicsPathItem(stroker.createStroke(textPath), this); diff --git a/qt-ui/profile/divetextitem.h b/qt-ui/profile/divetextitem.h index e0aa3e9b1..19bf00a73 100644 --- a/qt-ui/profile/divetextitem.h +++ b/qt-ui/profile/divetextitem.h @@ -7,19 +7,20 @@ #include <QBrush> /* A Line Item that has animated-properties. */ -class DiveTextItem :public QObject, public QGraphicsItemGroup{ +class DiveTextItem : public QObject, public QGraphicsItemGroup { Q_OBJECT Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) public: - DiveTextItem(QGraphicsItem* parent = 0); - void setText(const QString& text); + DiveTextItem(QGraphicsItem *parent = 0); + void setText(const QString &text); void setAlignment(int alignFlags); void setScale(double newscale); - void setBrush(const QBrush& brush); + void setBrush(const QBrush &brush); void animatedHide(); void animateMoveTo(qreal x, qreal y); - const QString& text(); + const QString &text(); + private: void updateText(); int internalAlignFlags; diff --git a/qt-ui/profile/divetooltipitem.cpp b/qt-ui/profile/divetooltipitem.cpp index 7171a8a2c..0442f0793 100644 --- a/qt-ui/profile/divetooltipitem.cpp +++ b/qt-ui/profile/divetooltipitem.cpp @@ -17,7 +17,7 @@ #include "display.h" #endif -void ToolTipItem::addToolTip(const QString& toolTip, const QIcon& icon) +void ToolTipItem::addToolTip(const QString &toolTip, const QIcon &icon) { QGraphicsPixmapItem *iconItem = 0; double yValue = title->boundingRect().height() + SPACING; @@ -25,7 +25,7 @@ void ToolTipItem::addToolTip(const QString& toolTip, const QIcon& icon) yValue += t.second->boundingRect().height(); } if (!icon.isNull()) { - iconItem = new QGraphicsPixmapItem(icon.pixmap(ICON_SMALL,ICON_SMALL), this); + iconItem = new QGraphicsPixmapItem(icon.pixmap(ICON_SMALL, ICON_SMALL), this); iconItem->setPos(SPACING, yValue); } @@ -47,8 +47,8 @@ void ToolTipItem::refresh(struct graphics_context *gc, QPointF pos) addToolTip(QString::fromUtf8(mb.buffer, mb.len)); free_buffer(&mb); - QList<QGraphicsItem*> items = scene()->items(pos, Qt::IntersectsItemShape, Qt::DescendingOrder, transform()); - Q_FOREACH(QGraphicsItem *item, items) { + QList<QGraphicsItem *> items = scene()->items(pos, Qt::IntersectsItemShape, Qt::DescendingOrder, transform()); + Q_FOREACH(QGraphicsItem * item, items) { if (!item->toolTip().isEmpty()) addToolTip(item->toolTip()); } @@ -63,7 +63,7 @@ void ToolTipItem::clear() toolTips.clear(); } -void ToolTipItem::setRect(const QRectF& r) +void ToolTipItem::setRect(const QRectF &r) { // qDeleteAll(childItems()); delete background; @@ -74,8 +74,8 @@ void ToolTipItem::setRect(const QRectF& r) // Creates a 2pixels border QPainterPath border; - border.addRoundedRect(-4, -4, rectangle.width() + 8, rectangle.height() + 10, 3, 3); - border.addRoundedRect(-1, -1, rectangle.width() + 3, rectangle.height() + 4, 3, 3); + border.addRoundedRect(-4, -4, rectangle.width() + 8, rectangle.height() + 10, 3, 3); + border.addRoundedRect(-1, -1, rectangle.width() + 3, rectangle.height() + 4, 3, 3); setPath(border); QPainterPath bg; @@ -119,10 +119,10 @@ void ToolTipItem::expand() height += t.second->boundingRect().height(); } /* Left padding, Icon Size, space, right padding */ - width += SPACING + ICON_SMALL + SPACING + SPACING; + width += SPACING + ICON_SMALL + SPACING + SPACING; - if (width < title->boundingRect().width() + SPACING*2) - width = title->boundingRect().width() + SPACING*2; + if (width < title->boundingRect().width() + SPACING * 2) + width = title->boundingRect().width() + SPACING * 2; if (height < ICON_SMALL) height = ICON_SMALL; @@ -139,7 +139,7 @@ void ToolTipItem::expand() status = EXPANDED; } -ToolTipItem::ToolTipItem(QGraphicsItem* parent) : QGraphicsPathItem(parent), +ToolTipItem::ToolTipItem(QGraphicsItem *parent) : QGraphicsPathItem(parent), background(0), separator(new QGraphicsLineItem(this)), title(new QGraphicsSimpleTextItem(tr("Information"), this)), @@ -161,21 +161,21 @@ ToolTipItem::~ToolTipItem() void ToolTipItem::updateTitlePosition() { - if (rectangle.width() < title->boundingRect().width() + SPACING*4) { + if (rectangle.width() < title->boundingRect().width() + SPACING * 4) { QRectF newRect = rectangle; - newRect.setWidth(title->boundingRect().width() + SPACING*4); + newRect.setWidth(title->boundingRect().width() + SPACING * 4); newRect.setHeight((newRect.height() && isExpanded()) ? newRect.height() : ICON_SMALL); setRect(newRect); } - title->setPos(boundingRect().width()/2 - title->boundingRect().width()/2 -1, 0); + title->setPos(boundingRect().width() / 2 - title->boundingRect().width() / 2 - 1, 0); title->setFlag(ItemIgnoresTransformations); title->setPen(QPen(Qt::white, 1)); title->setBrush(Qt::white); if (toolTips.size() > 0) { double x1 = 3; - double y1 = title->pos().y() + SPACING/2 + title->boundingRect().height(); + double y1 = title->pos().y() + SPACING / 2 + title->boundingRect().height(); double x2 = boundingRect().width() - 10; double y2 = y1; @@ -188,11 +188,12 @@ void ToolTipItem::updateTitlePosition() } } -bool ToolTipItem::isExpanded() const { +bool ToolTipItem::isExpanded() const +{ return status == EXPANDED; } -void ToolTipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) +void ToolTipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { persistPos(); QGraphicsPathItem::mouseReleaseEvent(event); @@ -212,27 +213,26 @@ void ToolTipItem::readPos() QSettings s; s.beginGroup("ProfileMap"); QPointF value = scene()->views().at(0)->mapToScene( - s.value("tooltip_position").toPoint() - ); + s.value("tooltip_position").toPoint()); if (!scene()->sceneRect().contains(value)) { - value = QPointF(0,0); + value = QPointF(0, 0); } setPos(value); } -void ToolTipItem::setPlotInfo(const plot_info& plot) +void ToolTipItem::setPlotInfo(const plot_info &plot) { pInfo = plot; } -void ToolTipItem::setTimeAxis(DiveCartesianAxis* axis) +void ToolTipItem::setTimeAxis(DiveCartesianAxis *axis) { timeAxis = axis; } -void ToolTipItem::refresh(const QPointF& pos) +void ToolTipItem::refresh(const QPointF &pos) { - int time = timeAxis->valueAt( pos ); + int time = timeAxis->valueAt(pos); if (time == lastTime) return; @@ -244,8 +244,8 @@ void ToolTipItem::refresh(const QPointF& pos) addToolTip(QString::fromUtf8(mb.buffer, mb.len)); free_buffer(&mb); - QList<QGraphicsItem*> items = scene()->items(pos, Qt::IntersectsItemShape, Qt::DescendingOrder, scene()->views().first()->transform()); - Q_FOREACH(QGraphicsItem *item, items) { + QList<QGraphicsItem *> items = scene()->items(pos, Qt::IntersectsItemShape, Qt::DescendingOrder, scene()->views().first()->transform()); + Q_FOREACH(QGraphicsItem * item, items) { if (!item->toolTip().isEmpty()) addToolTip(item->toolTip()); } diff --git a/qt-ui/profile/divetooltipitem.h b/qt-ui/profile/divetooltipitem.h index 5deb0001a..566b21770 100644 --- a/qt-ui/profile/divetooltipitem.h +++ b/qt-ui/profile/divetooltipitem.h @@ -17,36 +17,44 @@ struct graphics_context; /* To use a tooltip, simply ->setToolTip on the QGraphicsItem that you want * or, if it's a "global" tooltip, set it on the mouseMoveEvent of the ProfileGraphicsView. */ -class ToolTipItem :public QObject, public QGraphicsPathItem -{ +class ToolTipItem : public QObject, public QGraphicsPathItem { Q_OBJECT void updateTitlePosition(); Q_PROPERTY(QRectF rect READ boundingRect WRITE setRect) public: - enum Status{COLLAPSED, EXPANDED}; - enum {ICON_SMALL = 16, ICON_MEDIUM = 24, ICON_BIG = 32, SPACING=4}; + enum Status { + COLLAPSED, + EXPANDED + }; + enum { + ICON_SMALL = 16, + ICON_MEDIUM = 24, + ICON_BIG = 32, + SPACING = 4 + }; - explicit ToolTipItem(QGraphicsItem* parent = 0); + explicit ToolTipItem(QGraphicsItem *parent = 0); virtual ~ToolTipItem(); void collapse(); void expand(); void clear(); - void addToolTip(const QString& toolTip, const QIcon& icon = QIcon()); - void refresh(struct graphics_context* gc, QPointF pos); - void refresh(const QPointF& pos); + void addToolTip(const QString &toolTip, const QIcon &icon = QIcon()); + void refresh(struct graphics_context *gc, QPointF pos); + void refresh(const QPointF &pos); bool isExpanded() const; void persistPos(); void readPos(); - void mouseReleaseEvent(QGraphicsSceneMouseEvent* event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void setTimeAxis(DiveCartesianAxis *axis); - void setPlotInfo(const plot_info& plot); -public slots: - void setRect(const QRectF& rect); + void setPlotInfo(const plot_info &plot); +public +slots: + void setRect(const QRectF &rect); private: - typedef QPair<QGraphicsPixmapItem*, QGraphicsSimpleTextItem*> ToolTip; + typedef QPair<QGraphicsPixmapItem *, QGraphicsSimpleTextItem *> ToolTip; QVector<ToolTip> toolTips; QGraphicsPathItem *background; QGraphicsLineItem *separator; diff --git a/qt-ui/profile/profilewidget2.cpp b/qt-ui/profile/profilewidget2.cpp index ee9e80be6..1cbc6c1a5 100644 --- a/qt-ui/profile/profilewidget2.cpp +++ b/qt-ui/profile/profilewidget2.cpp @@ -35,15 +35,15 @@ * hard coding the item on the scene with a random * value. */ -static struct _ItemPos{ - struct _Pos{ +static struct _ItemPos { + struct _Pos { QPointF on; QPointF off; }; - struct _Axis{ - _Pos pos; - QLineF shrinked; - QLineF expanded; + struct _Axis { + _Pos pos; + QLineF shrinked; + QLineF expanded; }; _Pos background; _Pos dcLabel; @@ -55,12 +55,11 @@ static struct _ItemPos{ _Axis heartBeat; } itemPos; -ProfileWidget2::ProfileWidget2(QWidget *parent) : - QGraphicsView(parent), +ProfileWidget2::ProfileWidget2(QWidget *parent) : QGraphicsView(parent), dataModel(new DivePlotDataModel(this)), currentState(INVALID), zoomLevel(0), - background (new DivePixmapItem()), + background(new DivePixmapItem()), toolTipItem(new ToolTipItem()), profileYAxis(new DepthAxis()), gasYAxis(new PartialGasPressureAxis()), @@ -74,9 +73,9 @@ ProfileWidget2::ProfileWidget2(QWidget *parent) : diveComputerText(new DiveTextItem()), diveCeiling(new DiveCalculatedCeiling()), reportedCeiling(new DiveReportedCeiling()), - pn2GasItem( new PartialPressureGasItem()), - pheGasItem( new PartialPressureGasItem()), - po2GasItem( new PartialPressureGasItem()), + pn2GasItem(new PartialPressureGasItem()), + pheGasItem(new PartialPressureGasItem()), + po2GasItem(new PartialPressureGasItem()), heartBeatAxis(new DiveCartesianAxis()), heartBeatItem(new DiveHeartrateItem()), isPlotZoomed(prefs.zoomed_plot), @@ -123,7 +122,7 @@ void ProfileWidget2::addItemsToScene() scene()->addItem(rulerItem); scene()->addItem(rulerItem->sourceNode()); scene()->addItem(rulerItem->destNode()); - Q_FOREACH(DiveCalculatedTissue *tissue, allTissues){ + Q_FOREACH(DiveCalculatedTissue * tissue, allTissues) { scene()->addItem(tissue); } } @@ -135,7 +134,7 @@ void ProfileWidget2::setupItemOnScene() profileYAxis->setOrientation(DiveCartesianAxis::TopToBottom); profileYAxis->setMinimum(0); - profileYAxis->setTickInterval(M_OR_FT(10,30)); + profileYAxis->setTickInterval(M_OR_FT(10, 30)); profileYAxis->setTickSize(1); profileYAxis->setLineSize(96); @@ -163,7 +162,7 @@ void ProfileWidget2::setupItemOnScene() cylinderPressureAxis->setTickSize(2); cylinderPressureAxis->setTickInterval(30000); - meanDepth->setLine(0,0,96,0); + meanDepth->setLine(0, 0, 96, 0); meanDepth->setX(3); meanDepth->setPen(QPen(QBrush(Qt::red), 0, Qt::SolidLine)); meanDepth->setZValue(1); @@ -176,9 +175,9 @@ void ProfileWidget2::setupItemOnScene() setupItem(reportedCeiling, timeAxis, profileYAxis, dataModel, DivePlotDataModel::CEILING, DivePlotDataModel::TIME, 1); setupItem(diveCeiling, timeAxis, profileYAxis, dataModel, DivePlotDataModel::CEILING, DivePlotDataModel::TIME, 1); - for(int i = 0; i < 16; i++){ + for (int i = 0; i < 16; i++) { DiveCalculatedTissue *tissueItem = new DiveCalculatedTissue(); - setupItem(tissueItem, timeAxis, profileYAxis, dataModel, DivePlotDataModel::TISSUE_1 + i, DivePlotDataModel::TIME, 1+i); + setupItem(tissueItem, timeAxis, profileYAxis, dataModel, DivePlotDataModel::TISSUE_1 + i, DivePlotDataModel::TIME, 1 + i); allTissues.append(tissueItem); } setupItem(gasPressureItem, timeAxis, cylinderPressureAxis, dataModel, DivePlotDataModel::TEMPERATURE, DivePlotDataModel::TIME, 1); @@ -186,17 +185,17 @@ void ProfileWidget2::setupItemOnScene() setupItem(heartBeatItem, timeAxis, heartBeatAxis, dataModel, DivePlotDataModel::HEARTBEAT, DivePlotDataModel::TIME, 1); setupItem(diveProfileItem, timeAxis, profileYAxis, dataModel, DivePlotDataModel::DEPTH, DivePlotDataModel::TIME, 0); -#define CREATE_PP_GAS( ITEM, VERTICAL_COLUMN, COLOR, COLOR_ALERT, THRESHOULD_SETTINGS, VISIBILITY_SETTINGS ) \ +#define CREATE_PP_GAS(ITEM, VERTICAL_COLUMN, COLOR, COLOR_ALERT, THRESHOULD_SETTINGS, VISIBILITY_SETTINGS) \ setupItem(ITEM, timeAxis, gasYAxis, dataModel, DivePlotDataModel::VERTICAL_COLUMN, DivePlotDataModel::TIME, 0); \ - ITEM->setThreshouldSettingsKey(THRESHOULD_SETTINGS); \ - ITEM->setVisibilitySettingsKey(VISIBILITY_SETTINGS); \ - ITEM->setColors(getColor(COLOR), getColor(COLOR_ALERT)); \ - ITEM->preferencesChanged(); \ + ITEM->setThreshouldSettingsKey(THRESHOULD_SETTINGS); \ + ITEM->setVisibilitySettingsKey(VISIBILITY_SETTINGS); \ + ITEM->setColors(getColor(COLOR), getColor(COLOR_ALERT)); \ + ITEM->preferencesChanged(); \ ITEM->setZValue(99); - CREATE_PP_GAS( pn2GasItem, PN2, PN2, PN2_ALERT, "pn2threshold", "pn2graph"); - CREATE_PP_GAS( pheGasItem, PHE, PHE, PHE_ALERT, "phethreshold", "phegraph"); - CREATE_PP_GAS( po2GasItem, PO2, PO2, PO2_ALERT, "po2threshold", "po2graph"); + CREATE_PP_GAS(pn2GasItem, PN2, PN2, PN2_ALERT, "pn2threshold", "pn2graph"); + CREATE_PP_GAS(pheGasItem, PHE, PHE, PHE_ALERT, "phethreshold", "phegraph"); + CREATE_PP_GAS(po2GasItem, PO2, PO2, PO2_ALERT, "po2threshold", "po2graph"); #undef CREATE_PP_GAS temperatureAxis->setTextVisible(false); @@ -205,7 +204,7 @@ void ProfileWidget2::setupItemOnScene() cylinderPressureAxis->setLinesVisible(false); timeAxis->setLinesVisible(true); profileYAxis->setLinesVisible(true); - gasYAxis->setZValue(timeAxis->zValue()+1); + gasYAxis->setZValue(timeAxis->zValue() + 1); heartBeatAxis->setTextVisible(true); heartBeatAxis->setLinesVisible(true); } @@ -229,51 +228,51 @@ void ProfileWidget2::setupItemSizes() itemPos.depth.pos.on.setY(3); itemPos.depth.pos.off.setX(-2); itemPos.depth.pos.off.setY(3); - itemPos.depth.expanded.setP1(QPointF(0,0)); - itemPos.depth.expanded.setP2(QPointF(0,86)); - itemPos.depth.shrinked.setP1(QPointF(0,0)); - itemPos.depth.shrinked.setP2(QPointF(0,60)); + itemPos.depth.expanded.setP1(QPointF(0, 0)); + itemPos.depth.expanded.setP2(QPointF(0, 86)); + itemPos.depth.shrinked.setP1(QPointF(0, 0)); + itemPos.depth.shrinked.setP2(QPointF(0, 60)); // Time Axis Config itemPos.time.pos.on.setX(3); itemPos.time.pos.on.setY(95); itemPos.time.pos.off.setX(3); itemPos.time.pos.off.setY(110); - itemPos.time.expanded.setP1(QPointF(0,0)); - itemPos.time.expanded.setP2(QPointF(94,0)); + itemPos.time.expanded.setP1(QPointF(0, 0)); + itemPos.time.expanded.setP2(QPointF(94, 0)); // Partial Gas Axis Config itemPos.partialPressure.pos.on.setX(97); itemPos.partialPressure.pos.on.setY(65); itemPos.partialPressure.pos.off.setX(110); itemPos.partialPressure.pos.off.setY(63); - itemPos.partialPressure.expanded.setP1(QPointF(0,0)); - itemPos.partialPressure.expanded.setP2(QPointF(0,30)); + itemPos.partialPressure.expanded.setP1(QPointF(0, 0)); + itemPos.partialPressure.expanded.setP2(QPointF(0, 30)); // cylinder axis config itemPos.cylinder.pos.on.setX(3); itemPos.cylinder.pos.on.setY(20); itemPos.cylinder.pos.off.setX(-10); itemPos.cylinder.pos.off.setY(20); - itemPos.cylinder.expanded.setP1(QPointF(0,15)); - itemPos.cylinder.expanded.setP2(QPointF(0,50)); - itemPos.cylinder.shrinked.setP1(QPointF(0,0)); - itemPos.cylinder.shrinked.setP2(QPointF(0,20)); + itemPos.cylinder.expanded.setP1(QPointF(0, 15)); + itemPos.cylinder.expanded.setP2(QPointF(0, 50)); + itemPos.cylinder.shrinked.setP1(QPointF(0, 0)); + itemPos.cylinder.shrinked.setP2(QPointF(0, 20)); // Temperature axis config itemPos.temperature.pos.on.setX(3); itemPos.temperature.pos.on.setY(40); itemPos.temperature.pos.off.setX(-10); itemPos.temperature.pos.off.setY(40); - itemPos.temperature.expanded.setP1(QPointF(0,30)); - itemPos.temperature.expanded.setP2(QPointF(0,50)); - itemPos.temperature.shrinked.setP1(QPointF(0,5)); - itemPos.temperature.shrinked.setP2(QPointF(0,15)); + itemPos.temperature.expanded.setP1(QPointF(0, 30)); + itemPos.temperature.expanded.setP2(QPointF(0, 50)); + itemPos.temperature.shrinked.setP1(QPointF(0, 5)); + itemPos.temperature.shrinked.setP2(QPointF(0, 15)); itemPos.heartBeat.pos.on.setX(3); itemPos.heartBeat.pos.on.setY(60); - itemPos.heartBeat.expanded.setP1(QPointF(0,0)); - itemPos.heartBeat.expanded.setP2(QPointF(0,20)); + itemPos.heartBeat.expanded.setP1(QPointF(0, 0)); + itemPos.heartBeat.expanded.setP2(QPointF(0, 20)); itemPos.dcLabel.on.setX(3); itemPos.dcLabel.on.setY(100); @@ -281,7 +280,7 @@ void ProfileWidget2::setupItemSizes() itemPos.dcLabel.off.setY(100); } -void ProfileWidget2::setupItem(AbstractProfilePolygonItem* item, DiveCartesianAxis* hAxis, DiveCartesianAxis* vAxis, DivePlotDataModel* model, int vData, int hData, int zValue) +void ProfileWidget2::setupItem(AbstractProfilePolygonItem *item, DiveCartesianAxis *hAxis, DiveCartesianAxis *vAxis, DivePlotDataModel *model, int vData, int hData, int zValue) { item->setHorizontalAxis(hAxis); item->setVerticalAxis(vAxis); @@ -306,7 +305,7 @@ void ProfileWidget2::setupSceneAndFlags() } // Currently just one dive, but the plan is to enable All of the selected dives. -void ProfileWidget2::plotDives(QList<dive*> dives) +void ProfileWidget2::plotDives(QList<dive *> dives) { // I Know that it's a list, but currently we are // using just the first. @@ -368,7 +367,7 @@ void ProfileWidget2::plotDives(QList<dive*> dives) timeAxis->setMaximum(maxtime); rulerItem->setPlotInfo(pInfo); int i, incr; - static int increments[8] = { 10, 20, 30, 60, 5*60, 10*60, 15*60, 30*60 }; + static int increments[8] = { 10, 20, 30, 60, 5 * 60, 10 * 60, 15 * 60, 30 * 60 }; /* Time markers: at most every 10 seconds, but no more than 12 markers. * We start out with 10 seconds and increment up to 30 minutes, * depending on the dive time. @@ -387,7 +386,7 @@ void ProfileWidget2::plotDives(QList<dive*> dives) cylinderPressureAxis->setMinimum(pInfo.minpressure); cylinderPressureAxis->setMaximum(pInfo.maxpressure); meanDepth->setMeanDepth(pInfo.meandepth); - meanDepth->setLine(0,0,timeAxis->posAtValue(d->duration.seconds),0); + meanDepth->setLine(0, 0, timeAxis->posAtValue(d->duration.seconds), 0); meanDepth->animateMoveTo(3, profileYAxis->posAtValue(pInfo.meandepth)); dataModel->emitDataChanged(); @@ -409,7 +408,7 @@ void ProfileWidget2::plotDives(QList<dive*> dives) event = event->next; } // Only set visible the ones that should be visible, but how? - Q_FOREACH(DiveEventItem *event, eventItems){ + Q_FOREACH(DiveEventItem * event, eventItems) { event->setVisible(true); // qDebug() << event->getEvent()->name << "@" << event->getEvent()->time.seconds; } @@ -420,35 +419,35 @@ void ProfileWidget2::settingsChanged() { QSettings s; s.beginGroup("TecDetails"); - if(s.value("phegraph").toBool()|| s.value("po2graph").toBool()|| s.value("pn2graph").toBool()){ + if (s.value("phegraph").toBool() || s.value("po2graph").toBool() || s.value("pn2graph").toBool()) { profileYAxis->animateChangeLine(itemPos.depth.shrinked); temperatureAxis->animateChangeLine(itemPos.temperature.shrinked); cylinderPressureAxis->animateChangeLine(itemPos.cylinder.shrinked); - }else{ + } else { profileYAxis->animateChangeLine(itemPos.depth.expanded); temperatureAxis->animateChangeLine(itemPos.temperature.expanded); cylinderPressureAxis->animateChangeLine(itemPos.cylinder.expanded); } - if(s.value("zoomed_plot").toBool() != isPlotZoomed){ + if (s.value("zoomed_plot").toBool() != isPlotZoomed) { isPlotZoomed = s.value("zoomed_plot").toBool(); int diveId = dataModel->id(); dataModel->clear(); - plotDives(QList<dive*>() << getDiveById(diveId)); + plotDives(QList<dive *>() << getDiveById(diveId)); } - if(currentState == PROFILE){ + if (currentState == PROFILE) { bool rulerVisible = s.value("rulergraph", false).toBool(); rulerItem->setVisible(rulerVisible); - rulerItem->destNode()->setVisible(rulerVisible ); - rulerItem->sourceNode()->setVisible(rulerVisible ); - }else{ + rulerItem->destNode()->setVisible(rulerVisible); + rulerItem->sourceNode()->setVisible(rulerVisible); + } else { rulerItem->setVisible(false); rulerItem->destNode()->setVisible(false); rulerItem->sourceNode()->setVisible(false); } } -void ProfileWidget2::resizeEvent(QResizeEvent* event) +void ProfileWidget2::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); fitInView(sceneRect(), Qt::IgnoreAspectRatio); @@ -457,10 +456,10 @@ void ProfileWidget2::resizeEvent(QResizeEvent* event) void ProfileWidget2::fixBackgroundPos() { - if(currentState != EMPTY) + if (currentState != EMPTY) return; QPixmap toBeScaled; - if (!backgrounds.keys().contains(backgroundFile)){ + if (!backgrounds.keys().contains(backgroundFile)) { backgrounds[backgroundFile] = QPixmap(backgroundFile); } toBeScaled = backgrounds[backgroundFile]; @@ -470,7 +469,7 @@ void ProfileWidget2::fixBackgroundPos() background->setX(mapToScene(x, 0).x()); } -void ProfileWidget2::wheelEvent(QWheelEvent* event) +void ProfileWidget2::wheelEvent(QWheelEvent *event) { QPoint toolTipPos = mapFromScene(toolTipItem->pos()); double scaleFactor = 1.15; @@ -486,9 +485,9 @@ void ProfileWidget2::wheelEvent(QWheelEvent* event) toolTipItem->setPos(mapToScene(toolTipPos)); } -void ProfileWidget2::scrollViewTo(const QPoint& pos) +void ProfileWidget2::scrollViewTo(const QPoint &pos) { -/* since we cannot use translate() directly on the scene we hack on + /* since we cannot use translate() directly on the scene we hack on * the scroll bars (hidden) functionality */ if (!zoomLevel) return; @@ -500,7 +499,7 @@ void ProfileWidget2::scrollViewTo(const QPoint& pos) hs->setValue(xRat * hs->maximum()); } -void ProfileWidget2::mouseMoveEvent(QMouseEvent* event) +void ProfileWidget2::mouseMoveEvent(QMouseEvent *event) { toolTipItem->refresh(mapToScene(event->pos())); QPoint toolTipPos = mapFromScene(toolTipItem->pos()); @@ -514,8 +513,8 @@ void ProfileWidget2::mouseMoveEvent(QMouseEvent* event) bool ProfileWidget2::eventFilter(QObject *object, QEvent *event) { - QGraphicsScene *s = qobject_cast<QGraphicsScene*>(object); - if (s && event->type() == QEvent::GraphicsSceneHelp){ + QGraphicsScene *s = qobject_cast<QGraphicsScene *>(object); + if (s && event->type() == QEvent::GraphicsSceneHelp) { event->ignore(); return true; } @@ -529,13 +528,13 @@ void ProfileWidget2::setEmptyState() return; dataModel->clear(); - backgroundFile = QString(":poster%1").arg( rand()%3 +1); + backgroundFile = QString(":poster%1").arg(rand() % 3 + 1); currentState = EMPTY; fixBackgroundPos(); profileYAxis->setPos(itemPos.depth.pos.off); gasYAxis->setPos(itemPos.partialPressure.pos.off); timeAxis->setPos(itemPos.time.pos.off); - background->setY( itemPos.background.on.y()); + background->setY(itemPos.background.on.y()); background->setVisible(true); toolTipItem->setVisible(false); temperatureAxis->setPos(itemPos.temperature.pos.off); @@ -547,10 +546,10 @@ void ProfileWidget2::setEmptyState() rulerItem->setVisible(false); rulerItem->destNode()->setVisible(false); rulerItem->sourceNode()->setVisible(false); - Q_FOREACH(DiveCalculatedTissue *tissue, allTissues){ + Q_FOREACH(DiveCalculatedTissue * tissue, allTissues) { tissue->setVisible(false); } - Q_FOREACH(DiveEventItem *event, eventItems){ + Q_FOREACH(DiveEventItem * event, eventItems) { event->setVisible(false); } } @@ -570,11 +569,11 @@ void ProfileWidget2::setProfileState() profileYAxis->setPos(itemPos.depth.pos.on); QSettings s; s.beginGroup("TecDetails"); - if(s.value("phegraph").toBool()|| s.value("po2graph").toBool()|| s.value("pn2graph").toBool()){ + if (s.value("phegraph").toBool() || s.value("po2graph").toBool() || s.value("pn2graph").toBool()) { profileYAxis->setLine(itemPos.depth.shrinked); temperatureAxis->setLine(itemPos.temperature.shrinked); cylinderPressureAxis->setLine(itemPos.cylinder.shrinked); - }else{ + } else { profileYAxis->setLine(itemPos.depth.expanded); temperatureAxis->setLine(itemPos.temperature.expanded); cylinderPressureAxis->setLine(itemPos.cylinder.expanded); @@ -598,23 +597,23 @@ void ProfileWidget2::setProfileState() diveCeiling->setVisible(s.value("calcceiling").toBool()); reportedCeiling->setVisible(s.value("dcceiling").toBool()); - if(s.value("calcalltissues").toBool()){ - Q_FOREACH(DiveCalculatedTissue *tissue, allTissues){ + if (s.value("calcalltissues").toBool()) { + Q_FOREACH(DiveCalculatedTissue * tissue, allTissues) { tissue->setVisible(true); } } bool rulerVisible = s.value("rulergraph", false).toBool(); rulerItem->setVisible(rulerVisible); - rulerItem->destNode()->setVisible(rulerVisible ); - rulerItem->sourceNode()->setVisible(rulerVisible ); + rulerItem->destNode()->setVisible(rulerVisible); + rulerItem->sourceNode()->setVisible(rulerVisible); } extern struct ev_select *ev_namelist; extern int evn_allocated; extern int evn_used; -void ProfileWidget2::contextMenuEvent(QContextMenuEvent* event) +void ProfileWidget2::contextMenuEvent(QContextMenuEvent *event) { if (selected_dive == -1) return; @@ -625,26 +624,26 @@ void ProfileWidget2::contextMenuEvent(QContextMenuEvent* event) int rowCount = model->rowCount(); for (int i = 0; i < rowCount; i++) { QAction *action = new QAction(&m); - action->setText( model->data(model->index(i, 0),Qt::DisplayRole).toString()); + action->setText(model->data(model->index(i, 0), Qt::DisplayRole).toString()); connect(action, SIGNAL(triggered(bool)), this, SLOT(changeGas())); action->setData(event->globalPos()); gasChange->addAction(action); } QAction *action = m.addAction(tr("Add Bookmark"), this, SLOT(addBookmark())); action->setData(event->globalPos()); - QList<QGraphicsItem*> itemsAtPos = scene()->items(mapToScene(mapFromGlobal(event->globalPos()))); - Q_FOREACH(QGraphicsItem *i, itemsAtPos) { - EventItem *item = dynamic_cast<EventItem*>(i); + QList<QGraphicsItem *> itemsAtPos = scene()->items(mapToScene(mapFromGlobal(event->globalPos()))); + Q_FOREACH(QGraphicsItem * i, itemsAtPos) { + EventItem *item = dynamic_cast<EventItem *>(i); if (!item) continue; action = new QAction(&m); action->setText(tr("Remove Event")); - action->setData(QVariant::fromValue<void*>(item)); // so we know what to remove. + action->setData(QVariant::fromValue<void *>(item)); // so we know what to remove. connect(action, SIGNAL(triggered(bool)), this, SLOT(removeEvent())); m.addAction(action); action = new QAction(&m); action->setText(tr("Hide similar events")); - action->setData(QVariant::fromValue<void*>(item)); + action->setData(QVariant::fromValue<void *>(item)); connect(action, SIGNAL(triggered(bool)), this, SLOT(hideEvents())); m.addAction(action); break; @@ -665,7 +664,7 @@ void ProfileWidget2::contextMenuEvent(QContextMenuEvent* event) void ProfileWidget2::changeGas() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); QPointF scenePos = mapToScene(mapFromGlobal(action->data().toPoint())); QString gas = action->text(); // backup the things on the dataModel, since we will clear that out. @@ -684,5 +683,5 @@ void ProfileWidget2::changeGas() // force the redraw of the dive. //TODO: find a way to make this do not need a full redraw dataModel->clear(); - plotDives(QList<dive*>() << getDiveById(diveId)); + plotDives(QList<dive *>() << getDiveById(diveId)); } diff --git a/qt-ui/profile/profilewidget2.h b/qt-ui/profile/profilewidget2.h index e8246980d..9393f4f03 100644 --- a/qt-ui/profile/profilewidget2.h +++ b/qt-ui/profile/profilewidget2.h @@ -44,32 +44,50 @@ class AbstractProfilePolygonItem; class ProfileWidget2 : public QGraphicsView { Q_OBJECT public: - enum State{ EMPTY, PROFILE, EDIT, ADD, PLAN, INVALID }; - enum Items{BACKGROUND, PROFILE_Y_AXIS, GAS_Y_AXIS, TIME_AXIS, DEPTH_CONTROLLER, TIME_CONTROLLER, COLUMNS}; + enum State { + EMPTY, + PROFILE, + EDIT, + ADD, + PLAN, + INVALID + }; + enum Items { + BACKGROUND, + PROFILE_Y_AXIS, + GAS_Y_AXIS, + TIME_AXIS, + DEPTH_CONTROLLER, + TIME_CONTROLLER, + COLUMNS + }; ProfileWidget2(QWidget *parent); - void plotDives(QList<dive*> dives); - virtual bool eventFilter(QObject*, QEvent*); - void setupItem( AbstractProfilePolygonItem *item, DiveCartesianAxis *hAxis, DiveCartesianAxis *vAxis, DivePlotDataModel *model, int vData, int hData, int zValue); + void plotDives(QList<dive *> dives); + virtual bool eventFilter(QObject *, QEvent *); + void setupItem(AbstractProfilePolygonItem *item, DiveCartesianAxis *hAxis, DiveCartesianAxis *vAxis, DivePlotDataModel *model, int vData, int hData, int zValue); -public slots: // Necessary to call from QAction's signals. +public +slots: // Necessary to call from QAction's signals. void settingsChanged(); void setEmptyState(); void setProfileState(); void changeGas(); + protected: - virtual void resizeEvent(QResizeEvent* event); - virtual void wheelEvent(QWheelEvent* event); - virtual void mouseMoveEvent(QMouseEvent* event); - virtual void contextMenuEvent(QContextMenuEvent* event); + virtual void resizeEvent(QResizeEvent *event); + virtual void wheelEvent(QWheelEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void contextMenuEvent(QContextMenuEvent *event); private: /*methods*/ void fixBackgroundPos(); - void scrollViewTo(const QPoint& pos); + void scrollViewTo(const QPoint &pos); void setupSceneAndFlags(); void setupItemSizes(); void addItemsToScene(); void setupItemOnScene(); + private: DivePlotDataModel *dataModel; State currentState; @@ -92,10 +110,10 @@ private: DiveCartesianAxis *cylinderPressureAxis; DiveGasPressureItem *gasPressureItem; MeanDepthLine *meanDepth; - QList<DiveEventItem*> eventItems; + QList<DiveEventItem *> eventItems; DiveTextItem *diveComputerText; DiveCalculatedCeiling *diveCeiling; - QList<DiveCalculatedTissue*> allTissues; + QList<DiveCalculatedTissue *> allTissues; DiveReportedCeiling *reportedCeiling; PartialPressureGasItem *pn2GasItem; PartialPressureGasItem *pheGasItem; diff --git a/qt-ui/profile/ruleritem.cpp b/qt-ui/profile/ruleritem.cpp index 04b7fd996..042742a23 100644 --- a/qt-ui/profile/ruleritem.cpp +++ b/qt-ui/profile/ruleritem.cpp @@ -13,9 +13,9 @@ #include "profile.h" #include "display.h" -RulerNodeItem2::RulerNodeItem2(struct plot_info& info) : pInfo(info), entry(NULL) , ruler(NULL) +RulerNodeItem2::RulerNodeItem2(struct plot_info &info) : pInfo(info), entry(NULL), ruler(NULL) { - setRect(QRect(QPoint(-8,8),QPoint(8,-8))); + setRect(QRect(QPoint(-8, 8), QPoint(8, -8))); setBrush(QColor(0xff, 0, 0, 127)); setPen(QColor("#FF0000")); setFlag(QGraphicsItem::ItemIsMovable); @@ -30,7 +30,7 @@ void RulerNodeItem2::setRuler(RulerItem2 *r) void RulerNodeItem2::recalculate() { - struct plot_data *data = pInfo.entry+(pInfo.nr-1); + struct plot_data *data = pInfo.entry + (pInfo.nr - 1); uint16_t count = 0; if (x() < 0) { setPos(0, y()); @@ -38,13 +38,13 @@ void RulerNodeItem2::recalculate() setPos(timeAxis->posAtValue(data->sec), y()); } else { data = pInfo.entry; - count=0; + count = 0; while (timeAxis->posAtValue(data->sec) < x() && count < pInfo.nr) { - data = pInfo.entry+count; + data = pInfo.entry + count; count++; } setPos(timeAxis->posAtValue(data->sec), depthAxis->posAtValue(data->depth)); - entry=data; + entry = data; } } @@ -61,8 +61,7 @@ QVariant RulerNodeItem2::itemChange(GraphicsItemChange change, const QVariant &v return QGraphicsEllipseItem::itemChange(change, value); } -RulerItem2::RulerItem2(): - timeAxis(NULL), +RulerItem2::RulerItem2() : timeAxis(NULL), depthAxis(NULL), source(new RulerNodeItem2(pInfo)), dest(new RulerNodeItem2(pInfo)), @@ -112,7 +111,6 @@ void RulerItem2::recalculate() textItem->resetTransform(); textItem->setPos(startPoint); textItem->rotate(globalLine.angle() * -1); - } RulerNodeItem2 *RulerItem2::sourceNode() const @@ -147,7 +145,7 @@ QPainterPath RulerItem2::shape() const QLineF line_n = line.normalVector(); line_n.setLength(height); if (paint_direction == 1) - line_n.setAngle(line_n.angle()+180); + line_n.setAngle(line_n.angle() + 180); path.moveTo(startPoint); path.lineTo(line_n.p2()); path.lineTo(line_n.p2() + QPointF(line.dx(), line.dy())); @@ -164,7 +162,7 @@ void RulerItem2::setPlotInfo(plot_info info) source->recalculate(); } -void RulerItem2::setAxis(DiveCartesianAxis* time, DiveCartesianAxis* depth) +void RulerItem2::setAxis(DiveCartesianAxis *time, DiveCartesianAxis *depth) { timeAxis = time; depthAxis = depth; diff --git a/qt-ui/profile/ruleritem.h b/qt-ui/profile/ruleritem.h index f9cc98577..f2ff61c09 100644 --- a/qt-ui/profile/ruleritem.h +++ b/qt-ui/profile/ruleritem.h @@ -10,37 +10,36 @@ struct plot_data; class RulerItem2; -class RulerNodeItem2 : public QObject, public QGraphicsEllipseItem -{ +class RulerNodeItem2 : public QObject, public QGraphicsEllipseItem { Q_OBJECT friend class RulerItem2; + public: - explicit RulerNodeItem2(struct plot_info& info); + explicit RulerNodeItem2(struct plot_info &info); void setRuler(RulerItem2 *r); void recalculate(); protected: - QVariant itemChange(GraphicsItemChange change, const QVariant & value ); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); private: struct plot_info &pInfo; struct plot_data *entry; - RulerItem2* ruler; + RulerItem2 *ruler; DiveCartesianAxis *timeAxis; DiveCartesianAxis *depthAxis; }; -class RulerItem2 : public QGraphicsObject -{ +class RulerItem2 : public QGraphicsObject { Q_OBJECT public: explicit RulerItem2(); void recalculate(); void setPlotInfo(struct plot_info pInfo); - RulerNodeItem2* sourceNode() const; - RulerNodeItem2* destNode() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * widget = 0); + RulerNodeItem2 *sourceNode() const; + RulerNodeItem2 *destNode() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); QRectF boundingRect() const; QPainterPath shape() const; void setAxis(DiveCartesianAxis *time, DiveCartesianAxis *depth); diff --git a/qt-ui/profilegraphics.cpp b/qt-ui/profilegraphics.cpp index 2ec903950..f94a27c8c 100644 --- a/qt-ui/profilegraphics.cpp +++ b/qt-ui/profilegraphics.cpp @@ -43,12 +43,15 @@ extern struct ev_select *ev_namelist; extern int evn_allocated; extern int evn_used; -#define TOOLBAR_POS \ -QPoint(viewport()->geometry().width() - toolBarProxy->boundingRect().width(), \ - viewport()->geometry().height() - toolBarProxy->boundingRect().height() ) - -ProfileGraphicsView::ProfileGraphicsView(QWidget* parent) : QGraphicsView(parent), - toolTip(0) , diveId(0), diveDC(0), rulerItem(0), toolBarProxy(0) +#define TOOLBAR_POS QPoint(viewport()->geometry().width() - toolBarProxy->boundingRect().width(), \ + viewport()->geometry().height() - toolBarProxy->boundingRect().height()) + +ProfileGraphicsView::ProfileGraphicsView(QWidget *parent) : QGraphicsView(parent), + toolTip(0), + diveId(0), + diveDC(0), + rulerItem(0), + toolBarProxy(0) { printMode = false; isGrayscale = false; @@ -68,8 +71,8 @@ ProfileGraphicsView::ProfileGraphicsView(QWidget* parent) : QGraphicsView(parent defaultPen.setWidth(2); defaultPen.setCosmetic(true); - setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } /* since we cannot use translate() directly on the scene we hack on @@ -91,7 +94,7 @@ void ProfileGraphicsView::scrollViewTo(const QPoint pos) hs->setValue(xRat * (hMax - hMin) + hMin * 0.9); } -void ProfileGraphicsView::wheelEvent(QWheelEvent* event) +void ProfileGraphicsView::wheelEvent(QWheelEvent *event) { if (!toolTip) return; @@ -122,7 +125,7 @@ void ProfileGraphicsView::wheelEvent(QWheelEvent* event) } } -void ProfileGraphicsView::contextMenuEvent(QContextMenuEvent* event) +void ProfileGraphicsView::contextMenuEvent(QContextMenuEvent *event) { if (selected_dive == -1) return; @@ -133,26 +136,26 @@ void ProfileGraphicsView::contextMenuEvent(QContextMenuEvent* event) int rowCount = model->rowCount(); for (int i = 0; i < rowCount; i++) { QAction *action = new QAction(&m); - action->setText( model->data(model->index(i, 0),Qt::DisplayRole).toString()); + action->setText(model->data(model->index(i, 0), Qt::DisplayRole).toString()); connect(action, SIGNAL(triggered(bool)), this, SLOT(changeGas())); action->setData(event->globalPos()); gasChange->addAction(action); } QAction *action = m.addAction(tr("Add Bookmark"), this, SLOT(addBookmark())); action->setData(event->globalPos()); - QList<QGraphicsItem*> itemsAtPos = scene()->items(mapToScene(mapFromGlobal(event->globalPos()))); - Q_FOREACH(QGraphicsItem *i, itemsAtPos) { - EventItem *item = dynamic_cast<EventItem*>(i); + QList<QGraphicsItem *> itemsAtPos = scene()->items(mapToScene(mapFromGlobal(event->globalPos()))); + Q_FOREACH(QGraphicsItem * i, itemsAtPos) { + EventItem *item = dynamic_cast<EventItem *>(i); if (!item) continue; action = new QAction(&m); action->setText(tr("Remove Event")); - action->setData(QVariant::fromValue<void*>(item)); // so we know what to remove. + action->setData(QVariant::fromValue<void *>(item)); // so we know what to remove. connect(action, SIGNAL(triggered(bool)), this, SLOT(removeEvent())); m.addAction(action); action = new QAction(&m); action->setText(tr("Hide similar events")); - action->setData(QVariant::fromValue<void*>(item)); + action->setData(QVariant::fromValue<void *>(item)); connect(action, SIGNAL(triggered(bool)), this, SLOT(hideEvents())); m.addAction(action); break; @@ -173,7 +176,7 @@ void ProfileGraphicsView::contextMenuEvent(QContextMenuEvent* event) void ProfileGraphicsView::addBookmark() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); QPoint globalPos = action->data().toPoint(); QPoint viewPos = mapFromGlobal(globalPos); QPointF scenePos = mapToScene(viewPos); @@ -185,7 +188,7 @@ void ProfileGraphicsView::addBookmark() void ProfileGraphicsView::changeGas() { - QAction *action = qobject_cast<QAction*>(sender()); + QAction *action = qobject_cast<QAction *>(sender()); QPoint globalPos = action->data().toPoint(); QPoint viewPos = mapFromGlobal(globalPos); QPointF scenePos = mapToScene(viewPos); @@ -203,17 +206,17 @@ void ProfileGraphicsView::changeGas() void ProfileGraphicsView::hideEvents() { - QAction *action = qobject_cast<QAction*>(sender()); - EventItem *item = static_cast<EventItem*>(action->data().value<void*>()); + QAction *action = qobject_cast<QAction *>(sender()); + EventItem *item = static_cast<EventItem *>(action->data().value<void *>()); struct event *event = item->ev; if (QMessageBox::question(MainWindow::instance(), TITLE_OR_TEXT( - tr("Hide events"), - tr("Hide all %1 events?").arg(event->name)), + tr("Hide events"), + tr("Hide all %1 events?").arg(event->name)), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) { if (event->name) { for (int i = 0; i < evn_used; i++) { - if (! strcmp(event->name, ev_namelist[i].ev_name)) { + if (!strcmp(event->name, ev_namelist[i].ev_name)) { ev_namelist[i].plot_ev = false; break; } @@ -233,15 +236,13 @@ void ProfileGraphicsView::unhideEvents() void ProfileGraphicsView::removeEvent() { - QAction *action = qobject_cast<QAction*>(sender()); - EventItem *item = static_cast<EventItem*>(action->data().value<void*>()); + QAction *action = qobject_cast<QAction *>(sender()); + EventItem *item = static_cast<EventItem *>(action->data().value<void *>()); struct event *event = item->ev; if (QMessageBox::question(MainWindow::instance(), TITLE_OR_TEXT( - tr("Remove the selected event?"), - tr("%1 @ %2:%3").arg(event->name) - .arg(event->time.seconds / 60) - .arg(event->time.seconds % 60, 2, 10, QChar('0'))), + tr("Remove the selected event?"), + tr("%1 @ %2:%3").arg(event->name).arg(event->time.seconds / 60).arg(event->time.seconds % 60, 2, 10, QChar('0'))), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) { struct event **ep = ¤t_dc->events; while (ep && *ep != event) @@ -256,12 +257,12 @@ void ProfileGraphicsView::removeEvent() } -void ProfileGraphicsView::mouseMoveEvent(QMouseEvent* event) +void ProfileGraphicsView::mouseMoveEvent(QMouseEvent *event) { if (!toolTip) return; - toolTip->refresh(&gc, mapToScene(event->pos())); + toolTip->refresh(&gc, mapToScene(event->pos())); QPoint toolTipPos = mapFromScene(toolTip->pos()); scrollViewTo(event->pos()); @@ -273,7 +274,7 @@ void ProfileGraphicsView::mouseMoveEvent(QMouseEvent* event) } } -bool ProfileGraphicsView::eventFilter(QObject* obj, QEvent* event) +bool ProfileGraphicsView::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::Leave) { if (toolTip && toolTip->isExpanded()) @@ -306,7 +307,7 @@ static void plot_set_scale(scale_mode_t scale) } #endif -void ProfileGraphicsView::showEvent(QShowEvent* event) +void ProfileGraphicsView::showEvent(QShowEvent *event) { // Program just opened, // but the dive was not ploted. @@ -339,7 +340,7 @@ void ProfileGraphicsView::clear() rulerItem->destNode()->deleteLater(); rulerItem->sourceNode()->deleteLater(); rulerItem->deleteLater(); - rulerItem=0; + rulerItem = 0; } scene()->clear(); } @@ -382,7 +383,7 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) // best place to put the focus stealer code. setFocusProxy(MainWindow::instance()->dive_list()); - scene()->setSceneRect(0,0, viewport()->width()-50, viewport()->height()-50); + scene()->setSceneRect(0, 0, viewport()->width() - 50, viewport()->height() - 50); toolTip = new ToolTipItem(); installEventFilter(toolTip); @@ -404,7 +405,7 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) if (nick.isEmpty()) nick = tr("unknown divecomputer"); - if ( tr("unknown divecomputer") == nick) { + if (tr("unknown divecomputer") == nick) { mode = PLAN; } else { mode = DIVE; @@ -432,16 +433,16 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) /* Depth profile */ plot_depth_profile(); // TODO: PARTIALLY PORTED. - plot_events(dc); // PORTED + plot_events(dc); // PORTED if (rulerEnabled && !printMode) // TODO: NOT PORTED. create_ruler(); /* Temperature profile */ - plot_temperature_profile(); // PORTED + plot_temperature_profile(); // PORTED /* Cylinder pressure plot */ - plot_cylinder_pressure(); // PORTED + plot_cylinder_pressure(); // PORTED /* Text on top of all graphs.. */ // TODO: NOT PORTED, ANY TEXT. plot_temperature_text(); @@ -451,10 +452,12 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) // NOT PORTED. /* Put the dive computer name in the lower left corner */ - gc.leftx = 0; gc.rightx = 1.0; - gc.topy = 0; gc.bottomy = 1.0; + gc.leftx = 0; + gc.rightx = 1.0; + gc.topy = 0; + gc.bottomy = 1.0; - text_render_options_t computer = {DC_TEXT_SIZE, TIME_TEXT, LEFT, TOP}; + text_render_options_t computer = { DC_TEXT_SIZE, TIME_TEXT, LEFT, TOP }; diveComputer = plot_text(&computer, QPointF(gc.leftx, gc.bottomy), nick); // The Time ruler should be right after the DiveComputer: timeMarkers->setPos(0, diveComputer->y()); @@ -477,7 +480,7 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) #endif QRectF r = scene()->itemsBoundingRect(); - scene()->setSceneRect(r.x() - 15, r.y() -15, r.width() + 30, r.height() + 30); + scene()->setSceneRect(r.x() - 15, r.y() - 15, r.width() + 30, r.height() + 30); if (zoomLevel == 0) { fitInView(sceneRect()); } @@ -485,7 +488,7 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) if (mode == PLAN) { timeEditor = new GraphicsTextEditor(); - timeEditor->setPlainText(d->duration.seconds ? QString::number(d->duration.seconds/60) : tr("Set Duration: 10 minutes")); + timeEditor->setPlainText(d->duration.seconds ? QString::number(d->duration.seconds / 60) : tr("Set Duration: 10 minutes")); timeEditor->setPos(profile_grid_area.width() - timeEditor->boundingRect().width(), timeMarkers->y()); timeEditor->document(); connect(timeEditor, SIGNAL(editingFinished(QString)), this, SLOT(edit_dive_time(QString))); @@ -504,12 +507,13 @@ void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw) void ProfileGraphicsView::plot_depth_scale() { int i, maxdepth, marker; - static text_render_options_t tro = {DEPTH_TEXT_SIZE, SAMPLE_DEEP, RIGHT, MIDDLE}; + static text_render_options_t tro = { DEPTH_TEXT_SIZE, SAMPLE_DEEP, RIGHT, MIDDLE }; /* Depth markers: every 30 ft or 10 m*/ maxdepth = get_maxdepth(&gc.pi); - gc.topy = 0; gc.bottomy = maxdepth; - marker = M_OR_FT(10,30); + gc.topy = 0; + gc.bottomy = maxdepth; + marker = M_OR_FT(10, 30); /* don't write depth labels all the way to the bottom as * there may be other graphs below the depth plot (like @@ -557,7 +561,7 @@ void ProfileGraphicsView::plot_pp_text() { double pp, dpp, m; int hpos; - static text_render_options_t tro = {PP_TEXT_SIZE, PP_LINES, LEFT, -0.75}; + static text_render_options_t tro = { PP_TEXT_SIZE, PP_LINES, LEFT, -0.75 }; QGraphicsRectItem *pressureMarkers = new QGraphicsRectItem(); setup_pp_limits(&gc); @@ -571,7 +575,7 @@ void ProfileGraphicsView::plot_pp_text() QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(0, m), SCALEGC(hpos, m)); QPen pen(defaultPen); pen.setColor(c); - if ( IS_FP_SAME(QString::number(m).toDouble(), QString::number(m).toInt())) { + if (IS_FP_SAME(QString::number(m).toDouble(), QString::number(m).toInt())) { pen.setStyle(Qt::DashLine); pen.setWidthF(1.2); } @@ -606,7 +610,7 @@ void ProfileGraphicsView::plot_pp_gas_profile() setup_pp_limits(&gc); QColor c; QPointF from, to; - QPointF legendPos = QPointF(scene()->sceneRect().width() * 0.4, scene()->sceneRect().height() - scene()->sceneRect().height()*0.02); + QPointF legendPos = QPointF(scene()->sceneRect().width() * 0.4, scene()->sceneRect().height() - scene()->sceneRect().height() * 0.02); if (prefs.pp_graphs.pn2) { c = getColor(PN2); @@ -630,7 +634,7 @@ void ProfileGraphicsView::plot_pp_gas_profile() else from = QPointF(SCALEGC(entry->sec, entry->pn2)); } - createPPLegend(trUtf8("pN" UTF8_SUBSCRIPT_2),getColor(PN2), legendPos); + createPPLegend(trUtf8("pN" UTF8_SUBSCRIPT_2), getColor(PN2), legendPos); } if (prefs.pp_graphs.phe) { @@ -656,7 +660,7 @@ void ProfileGraphicsView::plot_pp_gas_profile() else from = QPointF(SCALEGC(entry->sec, entry->phe)); } - createPPLegend(trUtf8("pHe"),getColor(PHE), legendPos); + createPPLegend(trUtf8("pHe"), getColor(PHE), legendPos); } if (prefs.pp_graphs.po2) { c = getColor(PO2); @@ -677,27 +681,27 @@ void ProfileGraphicsView::plot_pp_gas_profile() entry++; if (entry->po2 >= prefs.pp_graphs.po2_threshold) plot_add_line(entry->sec, entry->po2, c, from); - else + else from = QPointF(SCALEGC(entry->sec, entry->po2)); } - createPPLegend(trUtf8("pO" UTF8_SUBSCRIPT_2),getColor(PO2), legendPos); + createPPLegend(trUtf8("pO" UTF8_SUBSCRIPT_2), getColor(PO2), legendPos); } } -void ProfileGraphicsView::createPPLegend(QString title, const QColor& c, QPointF& legendPos) +void ProfileGraphicsView::createPPLegend(QString title, const QColor &c, QPointF &legendPos) { QGraphicsRectItem *rect = new QGraphicsRectItem(0, 0, scene()->sceneRect().width() * 0.01, scene()->sceneRect().width() * 0.01); rect->setBrush(QBrush(c)); rect->setPos(legendPos); rect->setPen(QPen(QColor(Qt::transparent))); QGraphicsSimpleTextItem *text = new QGraphicsSimpleTextItem(title); - text->setPos(legendPos.x() + rect->boundingRect().width() + 5, legendPos.y() ); + text->setPos(legendPos.x() + rect->boundingRect().width() + 5, legendPos.y()); scene()->addItem(rect); scene()->addItem(text); legendPos.setX(text->pos().x() + text->boundingRect().width() + 20); if (printMode) { QFont f = text->font(); - f.setPointSizeF( f.pointSizeF() * 0.7); + f.setPointSizeF(f.pointSizeF() * 0.7); text->setFont(f); } } @@ -707,7 +711,7 @@ void ProfileGraphicsView::plot_deco_text() if (prefs.profile_calc_ceiling) { float x = gc.leftx + (gc.rightx - gc.leftx) / 2; float y = gc.topy = 1.0; - static text_render_options_t tro = {PRESSURE_TEXT_SIZE, PRESSURE_TEXT, CENTER, BOTTOM}; + static text_render_options_t tro = { PRESSURE_TEXT_SIZE, PRESSURE_TEXT, CENTER, BOTTOM }; gc.bottomy = 0.0; plot_text(&tro, QPointF(x, y), QString("GF %1/%2").arg(prefs.gflow).arg(prefs.gfhigh)); } @@ -740,8 +744,8 @@ void ProfileGraphicsView::plot_cylinder_pressure_text() if (!seen_cyl[cyl]) { plot_pressure_value(mbar, entry->sec, LEFT, BOTTOM); plot_gas_value(mbar, entry->sec, LEFT, TOP, - get_o2(&dive->cylinder[cyl].gasmix), - get_he(&dive->cylinder[cyl].gasmix)); + get_o2(&dive->cylinder[cyl].gasmix), + get_he(&dive->cylinder[cyl].gasmix)); seen_cyl[cyl] = true; } } @@ -762,7 +766,7 @@ void ProfileGraphicsView::plot_pressure_value(int mbar, int sec, double xalign, const char *unit; pressure = get_pressure_units(mbar, &unit); - static text_render_options_t tro = {PRESSURE_TEXT_SIZE, PRESSURE_TEXT, xalign, yalign}; + static text_render_options_t tro = { PRESSURE_TEXT_SIZE, PRESSURE_TEXT, xalign, yalign }; plot_text(&tro, QPointF(sec, mbar), QString("%1 %2").arg(pressure).arg(unit)); } @@ -775,9 +779,8 @@ void ProfileGraphicsView::plot_gas_value(int mbar, int sec, double xalign, doubl gas = QString(tr("EAN%1")).arg((o2 + 5) / 10); else gas = QString("%1/%2").arg((o2 + 5) / 10).arg((he + 5) / 10); - static text_render_options_t tro = {PRESSURE_TEXT_SIZE, PRESSURE_TEXT, xalign, yalign}; + static text_render_options_t tro = { PRESSURE_TEXT_SIZE, PRESSURE_TEXT, xalign, yalign }; plot_text(&tro, QPointF(sec, mbar), gas); - } void ProfileGraphicsView::plot_depth_text() @@ -788,20 +791,22 @@ void ProfileGraphicsView::plot_depth_text() maxtime = get_maxtime(&gc.pi); maxdepth = get_maxdepth(&gc.pi); - gc.leftx = 0; gc.rightx = maxtime; - gc.topy = 0; gc.bottomy = maxdepth; + gc.leftx = 0; + gc.rightx = maxtime; + gc.topy = 0; + gc.bottomy = maxdepth; plot_text_samples(); } void ProfileGraphicsView::plot_text_samples() { - static text_render_options_t deep = {14, SAMPLE_DEEP, CENTER, TOP}; - static text_render_options_t shallow = {14, SAMPLE_SHALLOW, CENTER, BOTTOM}; + static text_render_options_t deep = { 14, SAMPLE_DEEP, CENTER, TOP }; + static text_render_options_t shallow = { 14, SAMPLE_SHALLOW, CENTER, BOTTOM }; int i; int last = -1; - struct plot_info* pi = &gc.pi; + struct plot_info *pi = &gc.pi; for (i = 0; i < pi->nr; i++) { struct plot_data *entry = pi->entry + i; @@ -824,7 +829,7 @@ void ProfileGraphicsView::plot_text_samples() } } -void ProfileGraphicsView::plot_depth_sample(struct plot_data *entry,text_render_options_t *tro) +void ProfileGraphicsView::plot_depth_sample(struct plot_data *entry, text_render_options_t *tro) { int sec = entry->sec, decimals; double d; @@ -845,7 +850,7 @@ void ProfileGraphicsView::plot_temperature_text() return; for (i = 0; i < pi->nr; i++) { - struct plot_data *entry = pi->entry+i; + struct plot_data *entry = pi->entry + i; int mkelvin = entry->temperature; sec = entry->sec; @@ -862,7 +867,7 @@ void ProfileGraphicsView::plot_temperature_text() continue; last = sec; if (mkelvin > 200000) - plot_single_temp_text(sec,mkelvin); + plot_single_temp_text(sec, mkelvin); last_printed_temp = mkelvin; } /* it would be nice to print the end temperature, if it's @@ -877,7 +882,7 @@ void ProfileGraphicsView::plot_single_temp_text(int sec, int mkelvin) { double deg; const char *unit; - static text_render_options_t tro = {TEMP_TEXT_SIZE, TEMP_TEXT, LEFT, TOP}; + static text_render_options_t tro = { TEMP_TEXT_SIZE, TEMP_TEXT, LEFT, TOP }; deg = get_temp_units(mkelvin, &unit); plot_text(&tro, QPointF(sec, mkelvin), QString("%1%2").arg(deg, 0, 'f', 1).arg(unit)); //"%.2g%s" } @@ -917,7 +922,7 @@ void ProfileGraphicsView::plot_cylinder_pressure() int prev_pr; prev_pr = GET_PRESSURE(entry - 1); - QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC((entry-1)->sec, prev_pr), SCALEGC(entry->sec, mbar)); + QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC((entry - 1)->sec, prev_pr), SCALEGC(entry->sec, mbar)); QPen pen(defaultPen); pen.setColor(c); item->setPen(pen); @@ -965,9 +970,9 @@ void ProfileGraphicsView::plot_events(struct divecomputer *dc) { struct event *event = dc->events; -// if (gc->printer) { -// return; -// } + // if (gc->printer) { + // return; + // } while (event) { plot_one_event(event); @@ -984,7 +989,7 @@ void ProfileGraphicsView::plot_one_event(struct event *ev) /* is plotting of this event disabled? */ if (ev->name) { for (i = 0; i < evn_used; i++) { - if (! strcmp(ev->name, ev_namelist[i].ev_name)) { + if (!strcmp(ev->name, ev_namelist[i].ev_name)) { if (ev_namelist[i].plot_ev) break; else @@ -1018,7 +1023,7 @@ void ProfileGraphicsView::plot_one_event(struct event *ev) item->setPos(x, y); scene()->addItem(item); - if (ev->type == 123){ + if (ev->type == 123) { QPixmap picture; picture.load(ev->name); scene()->addPixmap(picture.scaledToHeight(100, Qt::SmoothTransformation))->setPos(x, y + 10); @@ -1041,7 +1046,7 @@ void ProfileGraphicsView::plot_one_event(struct event *ev) name += QString(tr("EAN%1")).arg((o2 + 5) / 10); } else if (ev->name && !strcmp(ev->name, "SP change")) { - name += QString(":%1").arg((double) ev->value / 1000); + name += QString(":%1").arg((double)ev->value / 1000); } else { name += QString(":%1").arg(ev->value); } @@ -1049,7 +1054,7 @@ void ProfileGraphicsView::plot_one_event(struct event *ev) name += "\n" + tr("Bailing out to OC"); } else { name += ev->flags == SAMPLE_FLAGS_BEGIN ? tr(" begin", "Starts with space!") : - ev->flags == SAMPLE_FLAGS_END ? tr(" end", "Starts with space!") : ""; + ev->flags == SAMPLE_FLAGS_END ? tr(" end", "Starts with space!") : ""; } //item->setToolTipController(toolTip); @@ -1059,7 +1064,7 @@ void ProfileGraphicsView::plot_one_event(struct event *ev) void ProfileGraphicsView::create_ruler() { - int x,y; + int x, y; struct plot_info *pi = &gc.pi; struct plot_data *data = pi->entry; @@ -1069,13 +1074,13 @@ void ProfileGraphicsView::create_ruler() x = SCALEXGC(data->sec); y = data->depth; - first->setPos(x,y); + first->setPos(x, y); - data = pi->entry+(pi->nr-1); + data = pi->entry + (pi->nr - 1); x = SCALEXGC(data->sec); y = data->depth; - second->setPos(x,y); + second->setPos(x, y); //Make sure that both points already have their entries first->recalculate(); second->recalculate(); @@ -1087,7 +1092,7 @@ void ProfileGraphicsView::create_ruler() void ProfileGraphicsView::add_ruler() { - if (! scene()->items().contains(rulerItem)) { + if (!scene()->items().contains(rulerItem)) { scene()->addItem(rulerItem->sourceNode()); scene()->addItem(rulerItem->destNode()); scene()->addItem(rulerItem); @@ -1113,7 +1118,7 @@ void ProfileGraphicsView::plot_depth_profile() int sec, depth; struct plot_data *entry; int maxtime, maxdepth, marker, maxline; - int increments[8] = { 10, 20, 30, 60, 5*60, 10*60, 15*60, 30*60 }; + int increments[8] = { 10, 20, 30, 60, 5 * 60, 10 * 60, 15 * 60, 30 * 60 }; /* Get plot scaling limits */ maxtime = get_maxtime(&gc.pi); @@ -1135,8 +1140,10 @@ void ProfileGraphicsView::plot_depth_profile() while (maxtime / incr > 12) incr *= 2; - gc.leftx = 0; gc.rightx = maxtime; - gc.topy = 0; gc.bottomy = 1.0; + gc.leftx = 0; + gc.rightx = maxtime; + gc.topy = 0; + gc.bottomy = 1.0; last_gc = gc; @@ -1151,23 +1158,25 @@ void ProfileGraphicsView::plot_depth_profile() timeMarkers = new QGraphicsRectItem(); /* now the text on the time markers */ - struct text_render_options tro = {DEPTH_TEXT_SIZE, TIME_TEXT, CENTER, LINE_DOWN}; + struct text_render_options tro = { DEPTH_TEXT_SIZE, TIME_TEXT, CENTER, LINE_DOWN }; if (maxtime < 600) { /* Be a bit more verbose with shorter dives */ for (i = incr; i < maxtime; i += incr) - plot_text(&tro, QPointF(i, 0), QString("%1:%2").arg(i/60).arg(i%60, 2, 10, QChar('0')), timeMarkers); + plot_text(&tro, QPointF(i, 0), QString("%1:%2").arg(i / 60).arg(i % 60, 2, 10, QChar('0')), timeMarkers); } else { /* Only render the time on every second marker for normal dives */ for (i = incr; i < maxtime; i += 2 * incr) - plot_text(&tro, QPointF(i, 0), QString("%1").arg(QString::number(i/60)), timeMarkers); + plot_text(&tro, QPointF(i, 0), QString("%1").arg(QString::number(i / 60)), timeMarkers); } - timeMarkers->setPos(0,0); + timeMarkers->setPos(0, 0); scene()->addItem(timeMarkers); /* Depth markers: every 30 ft or 10 m*/ - gc.leftx = 0; gc.rightx = 1.0; - gc.topy = 0; gc.bottomy = maxdepth; - marker = M_OR_FT(10,30); + gc.leftx = 0; + gc.rightx = 1.0; + gc.topy = 0; + gc.bottomy = maxdepth; + marker = M_OR_FT(10, 30); maxline = qMax(gc.pi.maxdepth + marker, maxdepth * 2 / 3); c = getColor(DEPTH_GRID); @@ -1180,11 +1189,12 @@ void ProfileGraphicsView::plot_depth_profile() scene()->addItem(item); } - gc.leftx = 0; gc.rightx = maxtime; + gc.leftx = 0; + gc.rightx = maxtime; c = getColor(MEAN_DEPTH); /* Show mean depth */ - if (! gc.printer) { + if (!gc.printer) { QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(0, gc.pi.meandepth), SCALEGC(gc.pi.entry[gc.pi.nr - 1].sec, gc.pi.meandepth)); QPen pen(defaultPen); @@ -1192,7 +1202,7 @@ void ProfileGraphicsView::plot_depth_profile() item->setPen(pen); scene()->addItem(item); - struct text_render_options depth_tro = {DEPTH_TEXT_SIZE, MEAN_DEPTH, LEFT, TOP}; + struct text_render_options depth_tro = { DEPTH_TEXT_SIZE, MEAN_DEPTH, LEFT, TOP }; QString depthLabel = get_depth_string(gc.pi.meandepth, true, true); plot_text(&depth_tro, QPointF(gc.leftx, gc.pi.meandepth), depthLabel, item); tro.hpos = RIGHT; @@ -1211,12 +1221,13 @@ void ProfileGraphicsView::plot_depth_profile() #endif /* Do the depth profile for the neat fill */ - gc.topy = 0; gc.bottomy = maxdepth; + gc.topy = 0; + gc.bottomy = maxdepth; entry = gc.pi.entry; QPolygonF p; - QLinearGradient pat(0.0,0.0,0.0,scene()->height()); + QLinearGradient pat(0.0, 0.0, 0.0, scene()->height()); QGraphicsPolygonItem *neatFill = NULL; p.append(QPointF(SCALEGC(0, 0))); @@ -1242,7 +1253,7 @@ void ProfileGraphicsView::plot_depth_profile() neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setBrush(QBrush(pat)); - neatFill->setPen(QPen(QBrush(Qt::transparent),0)); + neatFill->setPen(QPen(QBrush(Qt::transparent), 0)); scene()->addItem(neatFill); @@ -1271,7 +1282,7 @@ void ProfileGraphicsView::plot_depth_profile() neatFill = new QGraphicsPolygonItem(); neatFill->setBrush(QBrush(pat)); neatFill->setPolygon(p); - neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); + neatFill->setPen(QPen(QBrush(Qt::NoBrush), 0)); scene()->addItem(neatFill); } @@ -1289,10 +1300,10 @@ void ProfileGraphicsView::plot_depth_profile() else p.append(QPointF(SCALEGC(entry->sec, 0))); } - p.append(QPointF(SCALEGC((entry-1)->sec, 0))); + p.append(QPointF(SCALEGC((entry - 1)->sec, 0))); neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); - neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); + neatFill->setPen(QPen(QBrush(Qt::NoBrush), 0)); neatFill->setBrush(pat); scene()->addItem(neatFill); } @@ -1300,7 +1311,7 @@ void ProfileGraphicsView::plot_depth_profile() /* plot the calculated ceiling for all tissues */ if (prefs.profile_calc_ceiling && prefs.calc_all_tissues) { int k; - for (k=0; k<16; k++) { + for (k = 0; k < 16; k++) { pat.setColorAt(0, getColor(CALC_CEILING_SHALLOW)); pat.setColorAt(1, QColor(100, 100, 100, 50)); @@ -1313,7 +1324,7 @@ void ProfileGraphicsView::plot_depth_profile() else p.append(QPointF(SCALEGC(entry->sec, 0))); } - p.append(QPointF(SCALEGC((entry-1)->sec, 0))); + p.append(QPointF(SCALEGC((entry - 1)->sec, 0))); neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setBrush(pat); @@ -1332,7 +1343,7 @@ void ProfileGraphicsView::plot_depth_profile() for (i = 0; i < gc.pi.nr; i++, entry++) p.append(QPointF(SCALEGC(entry->sec, entry->depth))); - for (i-- , entry--; i >= 0; i--, entry--) { + for (i--, entry--; i >= 0; i--, entry--) { if (entry->in_deco && entry->stopdepth > entry->depth) { p.append(QPointF(SCALEGC(entry->sec, entry->stopdepth))); } else { @@ -1342,7 +1353,7 @@ void ProfileGraphicsView::plot_depth_profile() } neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); - neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); + neatFill->setPen(QPen(QBrush(Qt::NoBrush), 0)); neatFill->setBrush(QBrush(pat)); scene()->addItem(neatFill); @@ -1363,7 +1374,7 @@ void ProfileGraphicsView::plot_depth_profile() } } -QGraphicsItemGroup *ProfileGraphicsView::plot_text(text_render_options_t *tro,const QPointF& pos, const QString& text, QGraphicsItem *parent) +QGraphicsItemGroup *ProfileGraphicsView::plot_text(text_render_options_t *tro, const QPointF &pos, const QString &text, QGraphicsItem *parent) { QFont fnt(font()); QFontMetrics fm(fnt); @@ -1439,7 +1450,7 @@ void ProfileGraphicsView::plot_temperature_profile() } } -void ProfileGraphicsView::edit_dive_time(const QString& time) +void ProfileGraphicsView::edit_dive_time(const QString &time) { // this should set the full time of the dive. refresh(); @@ -1462,18 +1473,18 @@ QColor EventItem::getColor(const color_indice_t i) return profile_color[i].at((isGrayscale) ? 1 : 0); } -EventItem::EventItem(struct event *ev, QGraphicsItem* parent, bool grayscale): QGraphicsPixmapItem(parent), ev(ev), isGrayscale(grayscale) +EventItem::EventItem(struct event *ev, QGraphicsItem *parent, bool grayscale) : QGraphicsPixmapItem(parent), ev(ev), isGrayscale(grayscale) { if (ev->name && (strcmp(ev->name, "bookmark") == 0 || strcmp(ev->name, "heading") == 0)) { - setPixmap( QPixmap(QString(":flag")).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + setPixmap(QPixmap(QString(":flag")).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } else { - setPixmap( QPixmap(QString(":warning")).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + setPixmap(QPixmap(QString(":warning")).scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } -RulerNodeItem::RulerNodeItem(QGraphicsItem *parent, graphics_context context) : QGraphicsEllipseItem(parent), gc(context), entry(NULL) , ruler(NULL) +RulerNodeItem::RulerNodeItem(QGraphicsItem *parent, graphics_context context) : QGraphicsEllipseItem(parent), gc(context), entry(NULL), ruler(NULL) { - setRect(QRect(QPoint(-8,8),QPoint(8,-8))); + setRect(QRect(QPoint(-8, 8), QPoint(8, -8))); setBrush(QColor(0xff, 0, 0, 127)); setPen(QColor("#FF0000")); setFlag(QGraphicsItem::ItemIsMovable); @@ -1489,7 +1500,7 @@ void RulerNodeItem::setRuler(RulerItem *r) void RulerNodeItem::recalculate() { struct plot_info *pi = &gc.pi; - struct plot_data *data = pi->entry+(pi->nr-1); + struct plot_data *data = pi->entry + (pi->nr - 1); uint16_t count = 0; if (x() < 0) { setPos(0, y()); @@ -1497,13 +1508,13 @@ void RulerNodeItem::recalculate() setPos(SCALEXGC(data->sec), y()); } else { data = pi->entry; - count=0; + count = 0; while (SCALEXGC(data->sec) < x() && count < pi->nr) { - data = pi->entry+count; + data = pi->entry + count; count++; } setPos(SCALEGC(data->sec, data->depth)); - entry=data; + entry = data; } } @@ -1548,7 +1559,7 @@ void RulerItem::recalculate() compare_samples(source->entry, dest->entry, buffer, 500, 1); text = QString(buffer); - QRect r = fm.boundingRect(QRect(QPoint(10,-1*INT_MAX), QPoint(line.length()-10, 0)), Qt::TextWordWrap, text); + QRect r = fm.boundingRect(QRect(QPoint(10, -1 * INT_MAX), QPoint(line.length() - 10, 0)), Qt::TextWordWrap, text); if (r.height() < 10) height = 10; else @@ -1559,7 +1570,7 @@ void RulerItem::recalculate() if (scene()) { /* Determine whether we draw down or upwards */ if (scene()->sceneRect().contains(line_n.p2()) && - scene()->sceneRect().contains(endPoint+QPointF(line_n.dx(),line_n.dy()))) + scene()->sceneRect().contains(endPoint + QPointF(line_n.dx(), line_n.dy()))) paint_direction = -1; else paint_direction = 1; @@ -1585,7 +1596,7 @@ void RulerItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, line_n.setLength(height); if (paint_direction == 1) - line_n.setAngle(line_n.angle()+180); + line_n.setAngle(line_n.angle() + 180); painter->drawLine(line); painter->drawLine(line_n); painter->drawLine(line_n.p1() + QPointF(line.dx(), line.dy()), line_n.p2() + QPointF(line.dx(), line.dy())); @@ -1593,11 +1604,11 @@ void RulerItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, //Draw Text painter->save(); painter->translate(startPoint.x(), startPoint.y()); - painter->rotate(line.angle()*-1); + painter->rotate(line.angle() * -1); if (paint_direction == 1) painter->translate(0, height); painter->setPen(Qt::black); - painter->drawText(QRectF(QPointF(10,-1*height), QPointF(line.length()-10, 0)), Qt::TextWordWrap, text); + painter->drawText(QRectF(QPointF(10, -1 * height), QPointF(line.length() - 10, 0)), Qt::TextWordWrap, text); painter->restore(); } @@ -1613,7 +1624,7 @@ QPainterPath RulerItem::shape() const QLineF line_n = line.normalVector(); line_n.setLength(height); if (paint_direction == 1) - line_n.setAngle(line_n.angle()+180); + line_n.setAngle(line_n.angle() + 180); path.moveTo(startPoint); path.lineTo(line_n.p2()); path.lineTo(line_n.p2() + QPointF(line.dx(), line.dy())); @@ -1622,25 +1633,25 @@ QPainterPath RulerItem::shape() const return path; } -GraphicsTextEditor::GraphicsTextEditor(QGraphicsItem* parent): QGraphicsTextItem(parent) +GraphicsTextEditor::GraphicsTextEditor(QGraphicsItem *parent) : QGraphicsTextItem(parent) { } -void GraphicsTextEditor::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) +void GraphicsTextEditor::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { // Remove the proxy filter so we can focus here. MainWindow::instance()->graphics()->setFocusProxy(0); setTextInteractionFlags(Qt::TextEditorInteraction | Qt::TextEditable); } -void GraphicsTextEditor::keyReleaseEvent(QKeyEvent* event) +void GraphicsTextEditor::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { setTextInteractionFlags(Qt::NoTextInteraction); - emit editingFinished( toPlainText() ); + emit editingFinished(toPlainText()); MainWindow::instance()->graphics()->setFocusProxy(MainWindow::instance()->dive_list()); return; } - emit textChanged( toPlainText() ); + emit textChanged(toPlainText()); QGraphicsTextItem::keyReleaseEvent(event); } diff --git a/qt-ui/profilegraphics.h b/qt-ui/profilegraphics.h index 42006bdf8..cfba4427f 100644 --- a/qt-ui/profilegraphics.h +++ b/qt-ui/profilegraphics.h @@ -15,36 +15,35 @@ struct plot_info; class RulerItem; class ToolTipItem; -class RulerNodeItem : public QObject, public QGraphicsEllipseItem -{ +class RulerNodeItem : public QObject, public QGraphicsEllipseItem { Q_OBJECT friend class RulerItem; + public: - explicit RulerNodeItem(QGraphicsItem* parent, graphics_context gc); + explicit RulerNodeItem(QGraphicsItem *parent, graphics_context gc); void setRuler(RulerItem *r); void recalculate(); protected: - QVariant itemChange(GraphicsItemChange change, const QVariant & value ); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); private: graphics_context gc; struct plot_data *entry; - RulerItem* ruler; + RulerItem *ruler; }; -class RulerItem : public QGraphicsObject -{ +class RulerItem : public QGraphicsObject { Q_OBJECT public: - explicit RulerItem(QGraphicsItem* parent, + explicit RulerItem(QGraphicsItem *parent, RulerNodeItem *sourceMarker, RulerNodeItem *destMarker); void recalculate(); - RulerNodeItem* sourceNode() const; - RulerNodeItem* destNode() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * widget = 0); + RulerNodeItem *sourceNode() const; + RulerNodeItem *destNode() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); QRectF boundingRect() const; QPainterPath shape() const; @@ -56,11 +55,10 @@ private: int paint_direction; }; -class EventItem : public QGraphicsPixmapItem -{ +class EventItem : public QGraphicsPixmapItem { public: - explicit EventItem(struct event *ev, QGraphicsItem* parent = 0, bool grayscale = false); - struct event* ev; + explicit EventItem(struct event *ev, QGraphicsItem *parent = 0, bool grayscale = false); + struct event *ev; private: QString text; @@ -69,42 +67,45 @@ private: QColor getColor(const color_indice_t i); }; -class GraphicsTextEditor : public QGraphicsTextItem{ +class GraphicsTextEditor : public QGraphicsTextItem { Q_OBJECT public: - GraphicsTextEditor(QGraphicsItem* parent = 0); + GraphicsTextEditor(QGraphicsItem *parent = 0); protected: - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event); - virtual void keyReleaseEvent(QKeyEvent* event); + virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); + virtual void keyReleaseEvent(QKeyEvent *event); signals: - void textChanged(const QString& text); - void editingFinished(const QString& text); + void textChanged(const QString &text); + void editingFinished(const QString &text); }; -class ProfileGraphicsView : public QGraphicsView -{ -Q_OBJECT +class ProfileGraphicsView : public QGraphicsView { + Q_OBJECT public: - enum Mode{DIVE, PLAN}; + enum Mode { + DIVE, + PLAN + }; - ProfileGraphicsView(QWidget* parent = 0); + ProfileGraphicsView(QWidget *parent = 0); void plot(struct dive *d, bool forceRedraw = false); - bool eventFilter(QObject* obj, QEvent* event); + bool eventFilter(QObject *obj, QEvent *event); void clear(); void setPrintMode(bool mode, bool grayscale = false); protected: void resizeEvent(QResizeEvent *event); - void mouseMoveEvent(QMouseEvent* event); - void wheelEvent(QWheelEvent* event); - void showEvent(QShowEvent* event); - void contextMenuEvent(QContextMenuEvent* event); + void mouseMoveEvent(QMouseEvent *event); + void wheelEvent(QWheelEvent *event); + void showEvent(QShowEvent *event); + void contextMenuEvent(QContextMenuEvent *event); -public slots: +public +slots: void refresh(); - void edit_dive_time(const QString& time); + void edit_dive_time(const QString &time); void on_rulerAction(); void on_scaleAction(); void changeGas(); @@ -112,9 +113,10 @@ public slots: void unhideEvents(); void removeEvent(); void addBookmark(); + private: void plot_depth_profile(); - QGraphicsItemGroup *plot_text(text_render_options_t *tro, const QPointF& pos, const QString &text, QGraphicsItem *parent = 0); + QGraphicsItemGroup *plot_text(text_render_options_t *tro, const QPointF &pos, const QString &text, QGraphicsItem *parent = 0); void plot_events(struct divecomputer *dc); void plot_one_event(struct event *event); void plot_temperature_profile(); @@ -123,7 +125,7 @@ private: void plot_single_temp_text(int sec, int mkelvin); void plot_depth_text(); void plot_text_samples(); - void plot_depth_sample(plot_data* entry, text_render_options_t* tro); + void plot_depth_sample(plot_data *entry, text_render_options_t *tro); void plot_cylinder_pressure_text(); void plot_pressure_value(int mbar, int sec, double xalign, double yalign); void plot_gas_value(int mbar, int sec, double xalign, double yalign, int o2, int he); @@ -143,7 +145,7 @@ private: QColor getColor(const color_indice_t i); QColor get_sac_color(int sac, int avg_sac); void scrollViewTo(const QPoint pos); - void createPPLegend(QString tr, const QColor& c, QPointF& legendPos); + void createPPLegend(QString tr, const QColor &c, QPointF &legendPos); QPen defaultPen; QBrush defaultBrush; @@ -158,10 +160,10 @@ private: bool isGrayscale; // Top Level Items. - QGraphicsItem* profileGrid; - QGraphicsItem* timeMarkers; - QGraphicsItem* depthMarkers; - QGraphicsItem* diveComputer; + QGraphicsItem *profileGrid; + QGraphicsItem *timeMarkers; + QGraphicsItem *depthMarkers; + QGraphicsItem *diveComputer; RulerItem *rulerItem; QGraphicsProxyWidget *toolBarProxy; diff --git a/qt-ui/simplewidgets.cpp b/qt-ui/simplewidgets.cpp index 565df4901..2ec984b7a 100644 --- a/qt-ui/simplewidgets.cpp +++ b/qt-ui/simplewidgets.cpp @@ -25,15 +25,16 @@ public: QLabel *minIco, *minValue; QLabel *maxIco, *maxValue; - MinMaxAvgWidgetPrivate(MinMaxAvgWidget *owner) { + MinMaxAvgWidgetPrivate(MinMaxAvgWidget *owner) + { avgIco = new QLabel(owner); - avgIco->setPixmap(QIcon(":/average").pixmap(16,16)); + avgIco->setPixmap(QIcon(":/average").pixmap(16, 16)); avgIco->setToolTip(QObject::tr("Average")); minIco = new QLabel(owner); - minIco->setPixmap(QIcon(":/minimum").pixmap(16,16)); + minIco->setPixmap(QIcon(":/minimum").pixmap(16, 16)); minIco->setToolTip(QObject::tr("Minimum")); maxIco = new QLabel(owner); - maxIco->setPixmap(QIcon(":/maximum").pixmap(16,16)); + maxIco->setPixmap(QIcon(":/maximum").pixmap(16, 16)); maxIco->setToolTip(QObject::tr("Maximum")); avgValue = new QLabel(owner); minValue = new QLabel(owner); @@ -64,9 +65,8 @@ double MinMaxAvgWidget::minimum() const return d->minValue->text().toDouble(); } -MinMaxAvgWidget::MinMaxAvgWidget(QWidget* parent) : d(new MinMaxAvgWidgetPrivate(this)) +MinMaxAvgWidget::MinMaxAvgWidget(QWidget *parent) : d(new MinMaxAvgWidgetPrivate(this)) { - } MinMaxAvgWidget::~MinMaxAvgWidget() @@ -94,28 +94,28 @@ void MinMaxAvgWidget::setMinimum(double minimum) d->minValue->setText(QString::number(minimum)); } -void MinMaxAvgWidget::setAverage(const QString& average) +void MinMaxAvgWidget::setAverage(const QString &average) { d->avgValue->setText(average); } -void MinMaxAvgWidget::setMaximum(const QString& maximum) +void MinMaxAvgWidget::setMaximum(const QString &maximum) { d->maxValue->setText(maximum); } -void MinMaxAvgWidget::setMinimum(const QString& minimum) +void MinMaxAvgWidget::setMinimum(const QString &minimum) { d->minValue->setText(minimum); } -RenumberDialog* RenumberDialog::instance() +RenumberDialog *RenumberDialog::instance() { - static RenumberDialog* self = new RenumberDialog(MainWindow::instance()); + static RenumberDialog *self = new RenumberDialog(MainWindow::instance()); return self; } -void RenumberDialog::buttonClicked(QAbstractButton* button) +void RenumberDialog::buttonClicked(QAbstractButton *button) { if (ui.buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) { qDebug() << "Renumbering."; @@ -123,19 +123,19 @@ void RenumberDialog::buttonClicked(QAbstractButton* button) } } -RenumberDialog::RenumberDialog(QWidget *parent): QDialog(parent) +RenumberDialog::RenumberDialog(QWidget *parent) : QDialog(parent) { ui.setupUi(this); - connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonClicked(QAbstractButton*))); + connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonClicked(QAbstractButton *))); } -ShiftTimesDialog* ShiftTimesDialog::instance() +ShiftTimesDialog *ShiftTimesDialog::instance() { - static ShiftTimesDialog* self = new ShiftTimesDialog(MainWindow::instance()); + static ShiftTimesDialog *self = new ShiftTimesDialog(MainWindow::instance()); return self; } -void ShiftTimesDialog::buttonClicked(QAbstractButton* button) +void ShiftTimesDialog::buttonClicked(QAbstractButton *button) { int amount; @@ -155,19 +155,18 @@ void ShiftTimesDialog::buttonClicked(QAbstractButton* button) } } -ShiftTimesDialog::ShiftTimesDialog(QWidget *parent): QDialog(parent) +ShiftTimesDialog::ShiftTimesDialog(QWidget *parent) : QDialog(parent) { ui.setupUi(this); - connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonClicked(QAbstractButton*))); + connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonClicked(QAbstractButton *))); } -void ShiftImageTimesDialog::buttonClicked(QAbstractButton* button) +void ShiftImageTimesDialog::buttonClicked(QAbstractButton *button) { if (ui.buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) { m_amount = ui.timeEdit->time().hour() * 3600 + ui.timeEdit->time().minute() * 60; if (ui.backwards->isChecked()) m_amount *= -1; - } } @@ -187,13 +186,13 @@ void ShiftImageTimesDialog::syncCameraClicked() picture.load(fileNames.at(0)); ui.displayDC->setEnabled(true); - QGraphicsScene *scene = new QGraphicsScene (this); + QGraphicsScene *scene = new QGraphicsScene(this); scene->addPixmap(picture.scaled(ui.DCImage->size())); ui.DCImage->setScene(scene); if (readfile(fileNames.at(0).toUtf8().data(), &mem) <= 0) return; - retval = exiv.parseFrom((const unsigned char *) mem.buffer, (unsigned) mem.size); + retval = exiv.parseFrom((const unsigned char *)mem.buffer, (unsigned)mem.size); free(mem.buffer); if (retval != PARSE_EXIF_SUCCESS) return; @@ -228,12 +227,12 @@ void ShiftImageTimesDialog::dcDateTimeChanged(const QDateTime &newDateTime) setOffset(newDateTime.toTime_t() - dcImageEpoch); } -ShiftImageTimesDialog::ShiftImageTimesDialog(QWidget *parent): QDialog(parent), m_amount(0) +ShiftImageTimesDialog::ShiftImageTimesDialog(QWidget *parent) : QDialog(parent), m_amount(0) { ui.setupUi(this); - connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonClicked(QAbstractButton*))); + connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonClicked(QAbstractButton *))); connect(ui.syncCamera, SIGNAL(clicked()), this, SLOT(syncCameraClicked())); - dcImageEpoch = (time_t) 0; + dcImageEpoch = (time_t)0; } time_t ShiftImageTimesDialog::amount() const @@ -260,7 +259,7 @@ bool isGnome3Session() if (qApp->style()->objectName() != "gtk+") return false; QProcess p; - p.start("pidof", QStringList() << "gnome-shell" ); + p.start("pidof", QStringList() << "gnome-shell"); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); return !p_stdout.isEmpty(); diff --git a/qt-ui/simplewidgets.h b/qt-ui/simplewidgets.h index 098b227f6..6e4166f35 100644 --- a/qt-ui/simplewidgets.h +++ b/qt-ui/simplewidgets.h @@ -12,7 +12,7 @@ class QAbstractButton; #include "ui_shiftimagetimes.h" #include "exif.h" -class MinMaxAvgWidget : public QWidget{ +class MinMaxAvgWidget : public QWidget { Q_OBJECT Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) @@ -26,10 +26,11 @@ public: void setMinimum(double minimum); void setMaximum(double maximum); void setAverage(double average); - void setMinimum(const QString& minimum); - void setMaximum(const QString& maximum); - void setAverage(const QString& average); + void setMinimum(const QString &minimum); + void setMaximum(const QString &maximum); + void setAverage(const QString &average); void clear(); + private: QScopedPointer<MinMaxAvgWidgetPrivate> d; }; @@ -38,8 +39,10 @@ class RenumberDialog : public QDialog { Q_OBJECT public: static RenumberDialog *instance(); -private slots: +private +slots: void buttonClicked(QAbstractButton *button); + private: explicit RenumberDialog(QWidget *parent); Ui::RenumberDialog ui; @@ -49,8 +52,10 @@ class ShiftTimesDialog : public QDialog { Q_OBJECT public: static ShiftTimesDialog *instance(); -private slots: +private +slots: void buttonClicked(QAbstractButton *button); + private: explicit ShiftTimesDialog(QWidget *parent); Ui::ShiftTimesDialog ui; @@ -63,10 +68,12 @@ public: time_t amount() const; void setOffset(time_t offset); time_t epochFromExiv(EXIFInfo *exif); -private slots: +private +slots: void buttonClicked(QAbstractButton *button); void syncCameraClicked(); void dcDateTimeChanged(const QDateTime &); + private: Ui::ShiftImageTimesDialog ui; time_t m_amount; diff --git a/qt-ui/starwidget.cpp b/qt-ui/starwidget.cpp index 8cb368ed7..ff185a4a0 100644 --- a/qt-ui/starwidget.cpp +++ b/qt-ui/starwidget.cpp @@ -8,8 +8,8 @@ #include <QStyle> #include <QStyleOption> -QPixmap* StarWidget::activeStar = 0; -QPixmap* StarWidget::inactiveStar = 0; +QPixmap *StarWidget::activeStar = 0; +QPixmap *StarWidget::inactiveStar = 0; QPixmap StarWidget::starActive() { @@ -26,7 +26,7 @@ int StarWidget::currentStars() const return current; } -void StarWidget::mouseReleaseEvent(QMouseEvent* event) +void StarWidget::mouseReleaseEvent(QMouseEvent *event) { if (readOnly) { return; @@ -45,14 +45,14 @@ void StarWidget::mouseReleaseEvent(QMouseEvent* event) update(); } -void StarWidget::paintEvent(QPaintEvent* event) +void StarWidget::paintEvent(QPaintEvent *event) { QPainter p(this); - for(int i = 0; i < current; i++) + for (int i = 0; i < current; i++) p.drawPixmap(i * IMG_SIZE + SPACING, 0, starActive()); - for(int i = current; i < TOTALSTARS; i++) + for (int i = current; i < TOTALSTARS; i++) p.drawPixmap(i * IMG_SIZE + SPACING, 0, starInactive()); if (hasFocus()) { @@ -70,8 +70,7 @@ void StarWidget::setCurrentStars(int value) Q_EMIT valueChanged(current); } -StarWidget::StarWidget(QWidget* parent, Qt::WindowFlags f): - QWidget(parent, f), +StarWidget::StarWidget(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f), current(0), readOnly(false) { @@ -93,7 +92,7 @@ StarWidget::StarWidget(QWidget* parent, Qt::WindowFlags f): setFocusPolicy(Qt::StrongFocus); } -QPixmap StarWidget::grayImage(QPixmap* coloredImg) +QPixmap StarWidget::grayImage(QPixmap *coloredImg) { QImage img = coloredImg->toImage(); for (int i = 0; i < img.width(); ++i) { @@ -113,7 +112,7 @@ QPixmap StarWidget::grayImage(QPixmap* coloredImg) QSize StarWidget::sizeHint() const { - return QSize(IMG_SIZE * TOTALSTARS + SPACING * (TOTALSTARS-1), IMG_SIZE); + return QSize(IMG_SIZE * TOTALSTARS + SPACING * (TOTALSTARS - 1), IMG_SIZE); } void StarWidget::setReadOnly(bool r) @@ -121,27 +120,27 @@ void StarWidget::setReadOnly(bool r) readOnly = r; } -void StarWidget::focusInEvent(QFocusEvent* event) +void StarWidget::focusInEvent(QFocusEvent *event) { setFocus(); QWidget::focusInEvent(event); } -void StarWidget::focusOutEvent(QFocusEvent* event) +void StarWidget::focusOutEvent(QFocusEvent *event) { QWidget::focusOutEvent(event); } -void StarWidget::keyPressEvent(QKeyEvent* event) +void StarWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Right) { if (currentStars() < TOTALSTARS) { - setCurrentStars( currentStars()+1); + setCurrentStars(currentStars() + 1); } } else if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Left) { if (currentStars() > 0) { - setCurrentStars( currentStars()-1); + setCurrentStars(currentStars() - 1); } } } diff --git a/qt-ui/starwidget.h b/qt-ui/starwidget.h index 6bbaafc85..79b01c951 100644 --- a/qt-ui/starwidget.h +++ b/qt-ui/starwidget.h @@ -3,13 +3,16 @@ #include <QWidget> -enum StarConfig {SPACING = 2, IMG_SIZE = 16, TOTALSTARS = 5}; +enum StarConfig { + SPACING = 2, + IMG_SIZE = 16, + TOTALSTARS = 5 +}; -class StarWidget : public QWidget -{ +class StarWidget : public QWidget { Q_OBJECT public: - explicit StarWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit StarWidget(QWidget *parent = 0, Qt::WindowFlags f = 0); int currentStars() const; /*reimp*/ QSize sizeHint() const; @@ -20,22 +23,24 @@ public: signals: void valueChanged(int stars); -public slots: +public +slots: void setCurrentStars(int value); - void setReadOnly( bool readOnly); + void setReadOnly(bool readOnly); protected: - /*reimp*/ void mouseReleaseEvent(QMouseEvent* ); - /*reimp*/ void paintEvent(QPaintEvent* ); - /*reimp*/ void focusInEvent(QFocusEvent*); - /*reimp*/ void focusOutEvent(QFocusEvent*); - /*reimp*/ void keyPressEvent(QKeyEvent*); + /*reimp*/ void mouseReleaseEvent(QMouseEvent *); + /*reimp*/ void paintEvent(QPaintEvent *); + /*reimp*/ void focusInEvent(QFocusEvent *); + /*reimp*/ void focusOutEvent(QFocusEvent *); + /*reimp*/ void keyPressEvent(QKeyEvent *); + private: int current; bool readOnly; - static QPixmap* activeStar; - static QPixmap* inactiveStar; + static QPixmap *activeStar; + static QPixmap *inactiveStar; QPixmap grayImage(QPixmap *coloredImg); }; diff --git a/qt-ui/subsurfacewebservices.cpp b/qt-ui/subsurfacewebservices.cpp index 1fcfca15f..25aa56cb2 100644 --- a/qt-ui/subsurfacewebservices.cpp +++ b/qt-ui/subsurfacewebservices.cpp @@ -19,11 +19,11 @@ #include "../divelist.h" #ifdef Q_OS_UNIX -# include <unistd.h> // for dup(2) +#include <unistd.h> // for dup(2) #endif -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) -# include <QUrlQuery> +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) +#include <QUrlQuery> #endif struct dive_table gps_location_table; @@ -32,13 +32,13 @@ static bool merge_locations_into_dives(void); static bool is_automatic_fix(struct dive *gpsfix) { if (gpsfix && gpsfix->location && - (!strcmp(gpsfix->location, "automatic fix") || - !strcmp(gpsfix->location, "Auto-created dive"))) + (!strcmp(gpsfix->location, "automatic fix") || + !strcmp(gpsfix->location, "Auto-created dive"))) return true; return false; } -#define SAME_GROUP 6 * 3600 // six hours +#define SAME_GROUP 6 * 3600 // six hours static bool merge_locations_into_dives(void) { @@ -56,7 +56,7 @@ static bool merge_locations_into_dives(void) utc_mkdate(gpsfix->when, &tm); printf("found dive named %s @ %04d-%02d-%02d %02d:%02d:%02d\n", gpsfix->location, - tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); #endif changed++; @@ -85,7 +85,7 @@ static bool merge_locations_into_dives(void) #if DEBUG_WEBSERVICE printf("didn't find dive matching gps fix named %s @ %04d-%02d-%02d %02d:%02d:%02d\n", gpsfix->location, - tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); #endif } @@ -126,7 +126,7 @@ bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, char buffer[1024]; zip_error_to_str(buffer, sizeof buffer, error_code, errno); *errorMsg = tr("failed to create zip file for upload: %1") - .arg(QString::fromLocal8Bit(buffer)); + .arg(QString::fromLocal8Bit(buffer)); return false; } @@ -183,7 +183,7 @@ bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, free((void *)membuf); transformed = xsltApplyStylesheet(xslt, doc, NULL); - xmlDocDumpMemory(transformed, (xmlChar **) &membuf, &streamsize); + xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize); xmlFreeDoc(doc); xmlFreeDoc(transformed); @@ -209,11 +209,10 @@ error_close_zip: return false; } -WebServices::WebServices(QWidget* parent, Qt::WindowFlags f): QDialog(parent, f) -, reply(0) +WebServices::WebServices(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), reply(0) { ui.setupUi(this); - connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonClicked(QAbstractButton*))); + connect(ui.buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonClicked(QAbstractButton *))); connect(ui.download, SIGNAL(clicked(bool)), this, SLOT(startDownload())); connect(ui.upload, SIGNAL(clicked(bool)), this, SLOT(startUpload())); connect(&timeout, SIGNAL(timeout()), this, SLOT(downloadTimedOut())); @@ -286,8 +285,8 @@ void WebServices::connectSignalsForDownload(QNetworkReply *reply) connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(downloadError(QNetworkReply::NetworkError))); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, - SLOT(updateProgress(qint64,qint64))); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, + SLOT(updateProgress(qint64, qint64))); timeout.start(30000); // 30s } @@ -299,7 +298,7 @@ void WebServices::resetState() ui.userID->setEnabled(true); ui.password->setEnabled(true); ui.progressBar->reset(); - ui.progressBar->setRange(0,1); + ui.progressBar->setRange(0, 1); ui.status->setText(QString()); ui.buttonBox->button(QDialogButtonBox::Apply)->setText(defaultApplyText); } @@ -310,18 +309,18 @@ void WebServices::resetState() // # // # -SubsurfaceWebServices::SubsurfaceWebServices(QWidget* parent, Qt::WindowFlags f) : WebServices(parent, f) +SubsurfaceWebServices::SubsurfaceWebServices(QWidget *parent, Qt::WindowFlags f) : WebServices(parent, f) { QSettings s; ui.userID->setText(s.value("subsurface_webservice_uid").toString().toUpper()); hidePassword(); hideUpload(); ui.progressBar->setFormat("Enter User ID and click Download"); - ui.progressBar->setRange(0,1); + ui.progressBar->setRange(0, 1); ui.progressBar->setValue(-1); } -void SubsurfaceWebServices::buttonClicked(QAbstractButton* button) +void SubsurfaceWebServices::buttonClicked(QAbstractButton *button) { ui.buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); switch (ui.buttonBox->buttonRole(button)) { @@ -345,8 +344,7 @@ void SubsurfaceWebServices::buttonClicked(QAbstractButton* button) hide(); close(); resetState(); - } - break; + } break; case QDialogButtonBox::RejectRole: if (reply != NULL && reply->isOpen()) { reply->abort(); @@ -366,7 +364,7 @@ void SubsurfaceWebServices::buttonClicked(QAbstractButton* button) void SubsurfaceWebServices::startDownload() { QUrl url("http://api.hohndel.org/api/dive/get/"); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) url.addQueryItem("login", ui.userID->text().toUpper()); #else QUrlQuery query; @@ -380,7 +378,7 @@ void SubsurfaceWebServices::startDownload() reply = manager()->get(request); ui.status->setText(tr("Connecting...")); ui.progressBar->setEnabled(true); - ui.progressBar->setRange(0,0); // this makes the progressbar do an 'infinite spin' + ui.progressBar->setRange(0, 0); // this makes the progressbar do an 'infinite spin' ui.download->setEnabled(false); ui.buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); connectSignalsForDownload(reply); @@ -391,7 +389,7 @@ void SubsurfaceWebServices::downloadFinished() if (!reply) return; - ui.progressBar->setRange(0,1); + ui.progressBar->setRange(0, 1); ui.progressBar->setValue(1); ui.progressBar->setFormat("%p%"); downloadedData = reply->readAll(); @@ -420,10 +418,18 @@ void SubsurfaceWebServices::setStatusText(int status) { QString text; switch (status) { - case DD_STATUS_ERROR_CONNECT: text = tr("Connection Error: "); break; - case DD_STATUS_ERROR_ID: text = tr("Invalid user identifier!"); break; - case DD_STATUS_ERROR_PARSE: text = tr("Cannot parse response!"); break; - case DD_STATUS_OK: text = tr("Download Success!"); break; + case DD_STATUS_ERROR_CONNECT: + text = tr("Connection Error: "); + break; + case DD_STATUS_ERROR_ID: + text = tr("Invalid user identifier!"); + break; + case DD_STATUS_ERROR_PARSE: + text = tr("Cannot parse response!"); + break; + case DD_STATUS_OK: + text = tr("Download Success!"); + break; } ui.status->setText(text); } @@ -434,17 +440,17 @@ void SubsurfaceWebServices::download_dialog_traverse_xml(xmlNodePtr node, unsign xmlNodePtr cur_node; for (cur_node = node; cur_node; cur_node = cur_node->next) { if ((!strcmp((const char *)cur_node->name, (const char *)"download")) && - (!strcmp((const char *)xmlNodeGetContent(cur_node), (const char *)"ok"))) { + (!strcmp((const char *)xmlNodeGetContent(cur_node), (const char *)"ok"))) { *download_status = DD_STATUS_OK; return; - } else if (!strcmp((const char *)cur_node->name, (const char *)"error")) { + } else if (!strcmp((const char *)cur_node->name, (const char *)"error")) { *download_status = DD_STATUS_ERROR_ID; return; } } } -unsigned int SubsurfaceWebServices::download_dialog_parse_response(const QByteArray& xml) +unsigned int SubsurfaceWebServices::download_dialog_parse_response(const QByteArray &xml) { xmlNodePtr root; xmlDocPtr doc = xmlParseMemory(xml.data(), xml.length()); @@ -470,8 +476,7 @@ end: // # // # -struct DiveListResult -{ +struct DiveListResult { QString errorCondition; QString errorDetails; QByteArray idList; // comma-separated, suitable to be sent in the fetch request @@ -497,8 +502,8 @@ static DiveListResult parseDiveLogsDeDiveList(const QByteArray &xmlData) if (reader.readNextStartElement() && reader.name() != "DiveDateReader") { result.errorCondition = invalidXmlError; result.errorDetails = - DivelogsDeWebServices::tr("Expected XML tag 'DiveDateReader', got instead '%1") - .arg(reader.name().toString()); + DivelogsDeWebServices::tr("Expected XML tag 'DiveDateReader', got instead '%1") + .arg(reader.name().toString()); goto out; } @@ -551,12 +556,13 @@ out: // if there was an XML error, overwrite the result or other error conditions result.errorCondition = invalidXmlError; result.errorDetails = DivelogsDeWebServices::tr("Malformed XML response. Line %1: %2") - .arg(reader.lineNumber()).arg(reader.errorString()); + .arg(reader.lineNumber()) + .arg(reader.errorString()); } return result; } -DivelogsDeWebServices* DivelogsDeWebServices::instance() +DivelogsDeWebServices *DivelogsDeWebServices::instance() { static DivelogsDeWebServices *self = new DivelogsDeWebServices(MainWindow::instance()); self->setAttribute(Qt::WA_QuitOnClose, false); @@ -617,7 +623,7 @@ void DivelogsDeWebServices::uploadDives(QIODevice *dldContent) } } -DivelogsDeWebServices::DivelogsDeWebServices(QWidget* parent, Qt::WindowFlags f) : WebServices(parent, f), uploadMode(false) +DivelogsDeWebServices::DivelogsDeWebServices(QWidget *parent, Qt::WindowFlags f) : WebServices(parent, f), uploadMode(false) { QSettings s; ui.userID->setText(s.value("divelogde_user").toString()); @@ -633,7 +639,7 @@ void DivelogsDeWebServices::startUpload() s.sync(); ui.status->setText(tr("Uploading dive list...")); - ui.progressBar->setRange(0,0); // this makes the progressbar do an 'infinite spin' + ui.progressBar->setRange(0, 0); // this makes the progressbar do an 'infinite spin' ui.upload->setEnabled(false); ui.userID->setEnabled(false); ui.password->setEnabled(false); @@ -655,8 +661,8 @@ void DivelogsDeWebServices::startUpload() connect(reply, SIGNAL(finished()), this, SLOT(uploadFinished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(uploadError(QNetworkReply::NetworkError))); - connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, - SLOT(updateProgress(qint64,qint64))); + connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, + SLOT(updateProgress(qint64, qint64))); timeout.start(30000); // 30s } @@ -664,7 +670,7 @@ void DivelogsDeWebServices::startUpload() void DivelogsDeWebServices::startDownload() { ui.status->setText(tr("Downloading dive list...")); - ui.progressBar->setRange(0,0); // this makes the progressbar do an 'infinite spin' + ui.progressBar->setRange(0, 0); // this makes the progressbar do an 'infinite spin' ui.download->setEnabled(false); ui.userID->setEnabled(false); ui.password->setEnabled(false); @@ -674,7 +680,7 @@ void DivelogsDeWebServices::startDownload() request.setRawHeader("Accept", "text/xml, application/xml"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QUrl body; body.addQueryItem("user", ui.userID->text()); body.addQueryItem("pass", ui.password->text()); @@ -718,7 +724,7 @@ void DivelogsDeWebServices::listDownloadFinished() request.setRawHeader("Accept", "application/zip, */*"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QUrl body; body.addQueryItem("user", ui.userID->text()); body.addQueryItem("pass", ui.password->text()); @@ -788,7 +794,7 @@ void DivelogsDeWebServices::uploadFinished() if (!reply) return; - ui.progressBar->setRange(0,1); + ui.progressBar->setRange(0, 1); ui.upload->setEnabled(true); ui.userID->setEnabled(true); ui.password->setEnabled(true); @@ -823,7 +829,6 @@ void DivelogsDeWebServices::uploadFinished() void DivelogsDeWebServices::setStatusText(int status) { - } void DivelogsDeWebServices::downloadError(QNetworkReply::NetworkError) @@ -839,7 +844,7 @@ void DivelogsDeWebServices::uploadError(QNetworkReply::NetworkError error) downloadError(error); } -void DivelogsDeWebServices::buttonClicked(QAbstractButton* button) +void DivelogsDeWebServices::buttonClicked(QAbstractButton *button) { ui.buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); switch (ui.buttonBox->buttonRole(button)) { @@ -869,8 +874,7 @@ void DivelogsDeWebServices::buttonClicked(QAbstractButton* button) hide(); close(); resetState(); - } - break; + } break; case QDialogButtonBox::RejectRole: // these two seem to be causing a crash: // reply->deleteLater(); diff --git a/qt-ui/subsurfacewebservices.h b/qt-ui/subsurfacewebservices.h index 4d1ec0002..872cf377d 100644 --- a/qt-ui/subsurfacewebservices.h +++ b/qt-ui/subsurfacewebservices.h @@ -13,23 +13,25 @@ class QAbstractButton; class QNetworkReply; class QHttpMultiPart; -class WebServices : public QDialog{ +class WebServices : public QDialog { Q_OBJECT public: - explicit WebServices(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit WebServices(QWidget *parent = 0, Qt::WindowFlags f = 0); void hidePassword(); void hideUpload(); void hideDownload(); static QNetworkAccessManager *manager(); -private slots: +private +slots: virtual void startDownload() = 0; virtual void startUpload() = 0; - virtual void buttonClicked(QAbstractButton* button) = 0; + virtual void buttonClicked(QAbstractButton *button) = 0; virtual void downloadTimedOut(); -protected slots: +protected +slots: void updateProgress(qint64 current, qint64 total); protected: @@ -47,30 +49,34 @@ protected: class SubsurfaceWebServices : public WebServices { Q_OBJECT public: - explicit SubsurfaceWebServices(QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit SubsurfaceWebServices(QWidget *parent = 0, Qt::WindowFlags f = 0); -private slots: +private +slots: void startDownload(); - void buttonClicked(QAbstractButton* button); + void buttonClicked(QAbstractButton *button); void downloadFinished(); void downloadError(QNetworkReply::NetworkError error); - void startUpload(){} /*no op*/ + void startUpload() + { + } /*no op*/ private: void setStatusText(int status); void download_dialog_traverse_xml(xmlNodePtr node, unsigned int *download_status); - unsigned int download_dialog_parse_response(const QByteArray& length); + unsigned int download_dialog_parse_response(const QByteArray &length); }; class DivelogsDeWebServices : public WebServices { Q_OBJECT public: - static DivelogsDeWebServices * instance(); + static DivelogsDeWebServices *instance(); void downloadDives(); void prepareDivesForUpload(); -private slots: +private +slots: void startDownload(); - void buttonClicked(QAbstractButton* button); + void buttonClicked(QAbstractButton *button); void saveToZipFile(); void listDownloadFinished(); void downloadFinished(); @@ -78,13 +84,14 @@ private slots: void downloadError(QNetworkReply::NetworkError error); void uploadError(QNetworkReply::NetworkError error); void startUpload(); + private: void uploadDives(QIODevice *dldContent); - explicit DivelogsDeWebServices (QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit DivelogsDeWebServices(QWidget *parent = 0, Qt::WindowFlags f = 0); void setStatusText(int status); bool prepare_dives_for_divelogs(const QString &filename, bool selected, QString *errorMsg); void download_dialog_traverse_xml(xmlNodePtr node, unsigned int *download_status); - unsigned int download_dialog_parse_response(const QByteArray& length); + unsigned int download_dialog_parse_response(const QByteArray &length); QHttpMultiPart *multipart; QTemporaryFile zipFile; diff --git a/qt-ui/tableview.cpp b/qt-ui/tableview.cpp index 6bb1944b8..f00f2ae48 100644 --- a/qt-ui/tableview.cpp +++ b/qt-ui/tableview.cpp @@ -21,7 +21,7 @@ TableView::TableView(QWidget *parent) : QWidget(parent) plusBtn = new QPushButton(plusIcon, QString(), ui.groupBox); plusBtn->setFlat(true); plusBtn->setToolTip(tr("Add Cylinder")); - plusBtn->setIconSize(QSize(16,16)); + plusBtn->setIconSize(QSize(16, 16)); connect(plusBtn, SIGNAL(clicked(bool)), this, SIGNAL(addButtonClicked())); } @@ -35,12 +35,12 @@ TableView::~TableView() s.endGroup(); } -void TableView::setBtnToolTip(const QString& tooltip) +void TableView::setBtnToolTip(const QString &tooltip) { plusBtn->setToolTip(tooltip); } -void TableView::setTitle(const QString& title) +void TableView::setTitle(const QString &title) { ui.groupBox->setTitle(title); } @@ -54,7 +54,7 @@ void TableView::setModel(QAbstractItemModel *model) s.beginGroup(objectName()); const int columnCount = ui.tableView->model()->columnCount(); for (int i = 0; i < columnCount; i++) { - QVariant width = s.value(QString("colwidth%1").arg(i), i == CylindersModel::REMOVE ? 30 : 80 ); + QVariant width = s.value(QString("colwidth%1").arg(i), i == CylindersModel::REMOVE ? 30 : 80); ui.tableView->setColumnWidth(i, width.toInt()); } s.endGroup(); @@ -65,23 +65,23 @@ void TableView::setModel(QAbstractItemModel *model) void TableView::fixPlusPosition() { - plusBtn->setGeometry(ui.groupBox->contentsRect().width() - 30, 2, 24,24); + plusBtn->setGeometry(ui.groupBox->contentsRect().width() - 30, 2, 24, 24); } // We need to manually position the 'plus' on cylinder and weight. -void TableView::resizeEvent(QResizeEvent* event) +void TableView::resizeEvent(QResizeEvent *event) { fixPlusPosition(); QWidget::resizeEvent(event); } -void TableView::showEvent(QShowEvent* event) +void TableView::showEvent(QShowEvent *event) { QWidget::showEvent(event); fixPlusPosition(); } -void TableView::edit(const QModelIndex& index) +void TableView::edit(const QModelIndex &index) { ui.tableView->edit(index); } diff --git a/qt-ui/tableview.h b/qt-ui/tableview.h index f89a7b6ba..d2289b2d9 100644 --- a/qt-ui/tableview.h +++ b/qt-ui/tableview.h @@ -15,23 +15,24 @@ class QModelIndex; class QTableView; class TableView : public QWidget { -Q_OBJECT + Q_OBJECT public: TableView(QWidget *parent = 0); virtual ~TableView(); - void setTitle(const QString& title); + void setTitle(const QString &title); /* The model is expected to have a 'remove' slot, that takes a QModelIndex as parameter. * It's also expected to have the column '1' as a trash icon. I most probably should create a * proxy model and add that column, will mark that as TODO. see? marked. */ - void setModel(QAbstractItemModel* model); - void setBtnToolTip(const QString& tooltip); + void setModel(QAbstractItemModel *model); + void setBtnToolTip(const QString &tooltip); void fixPlusPosition(); - void edit(const QModelIndex& index); + void edit(const QModelIndex &index); QTableView *view(); + protected: - virtual void showEvent(QShowEvent* ); - virtual void resizeEvent(QResizeEvent* ); + virtual void showEvent(QShowEvent *); + virtual void resizeEvent(QResizeEvent *); signals: void addButtonClicked(); diff --git a/qt-ui/tagwidget.cpp b/qt-ui/tagwidget.cpp index e7585dff1..6ba4a0404 100644 --- a/qt-ui/tagwidget.cpp +++ b/qt-ui/tagwidget.cpp @@ -14,18 +14,18 @@ TagWidget::TagWidget(QWidget *parent) : GroupedLineEdit(parent), m_completer(NUL qreal h, s, l, a; textColor.getHslF(&h, &s, &l, &a); // I use dark themes - if (l <= 0.3 ) { // very dark text. get a brigth background - addColor( QColor(Qt::red).lighter(120) ); - addColor( QColor(Qt::green).lighter(120) ); - addColor( QColor(Qt::blue).lighter(120) ); - } else if ( l <= 0.6 ) { // moderated dark text. get a somewhat brigth background - addColor( QColor(Qt::red).lighter(60) ); - addColor( QColor(Qt::green).lighter(60) ); - addColor( QColor(Qt::blue).lighter(60) ); + if (l <= 0.3) { // very dark text. get a brigth background + addColor(QColor(Qt::red).lighter(120)); + addColor(QColor(Qt::green).lighter(120)); + addColor(QColor(Qt::blue).lighter(120)); + } else if (l <= 0.6) { // moderated dark text. get a somewhat brigth background + addColor(QColor(Qt::red).lighter(60)); + addColor(QColor(Qt::green).lighter(60)); + addColor(QColor(Qt::blue).lighter(60)); } else { - addColor( QColor(Qt::red).darker(120) ); - addColor( QColor(Qt::green).darker(120) ); - addColor( QColor(Qt::blue).darker(120) ); + addColor(QColor(Qt::red).darker(120)); + addColor(QColor(Qt::green).darker(120)); + addColor(QColor(Qt::blue).darker(120)); } // light text. get a dark background. setFocusPolicy(Qt::StrongFocus); } @@ -38,13 +38,14 @@ void TagWidget::setCompleter(QCompleter *completer) connect(m_completer, SIGNAL(highlighted(QString)), this, SLOT(completionSelected(QString))); } -QPair<int,int> TagWidget::getCursorTagPosition() { +QPair<int, int> TagWidget::getCursorTagPosition() +{ int i = 0, start = 0, end = 0; /* Parse string near cursor */ i = cursorPosition(); while (--i > 0) { if (text().at(i) == ',') { - if (i > 0 && text().at(i-1) != '\\') { + if (i > 0 && text().at(i - 1) != '\\') { i++; break; } @@ -53,7 +54,7 @@ QPair<int,int> TagWidget::getCursorTagPosition() { start = i; while (++i < text().length()) { if (text().at(i) == ',') { - if (i > 0 && text().at(i-1) != '\\') + if (i > 0 && text().at(i - 1) != '\\') break; } } @@ -62,24 +63,28 @@ QPair<int,int> TagWidget::getCursorTagPosition() { start = 0; end = 0; } - return qMakePair(start,end); + return qMakePair(start, end); } -enum ParseState {FINDSTART, FINDEND}; +enum ParseState { + FINDSTART, + FINDEND +}; -void TagWidget::highlight() { +void TagWidget::highlight() +{ int i = 0, start = 0, end = 0; ParseState state = FINDEND; removeAllBlocks(); - while(i < text().length()) { + while (i < text().length()) { if (text().at(i) == ',') { if (state == FINDSTART) { /* Detect empty tags */ } else if (state == FINDEND) { /* Found end of tag */ if (i > 1) { - if (text().at(i-1) != '\\') { + if (text().at(i - 1) != '\\') { addBlock(start, end); state = FINDSTART; } @@ -102,7 +107,7 @@ void TagWidget::highlight() { } if (state == FINDEND) { if (end < start) - end = text().length()-1; + end = text().length() - 1; if (text().length() > 0) addBlock(start, end); } @@ -111,10 +116,10 @@ void TagWidget::highlight() { void TagWidget::reparse() { highlight(); - QPair<int,int> pos = getCursorTagPosition(); + QPair<int, int> pos = getCursorTagPosition(); QString currentText; if (pos.first >= 0 && pos.second > 0) - currentText = text().mid(pos.first, pos.second-pos.first).trimmed(); + currentText = text().mid(pos.first, pos.second - pos.first).trimmed(); else currentText = ""; if (m_completer) { @@ -133,12 +138,13 @@ void TagWidget::reparse() } } -void TagWidget::completionSelected(QString completion) { - QPair <int,int> pos; +void TagWidget::completionSelected(QString completion) +{ + QPair<int, int> pos; pos = getCursorTagPosition(); if (pos.first >= 0 && pos.second > 0) { - setText(text().remove(pos.first, pos.second-pos.first).insert(pos.first, completion)); - setCursorPosition(pos.first+completion.length()); + setText(text().remove(pos.first, pos.second - pos.first).insert(pos.first, completion)); + setCursorPosition(pos.first + completion.length()); } else { setText(completion.append(", ")); setCursorPosition(text().length()); @@ -146,26 +152,30 @@ void TagWidget::completionSelected(QString completion) { emit(textChanged()); } -void TagWidget::setCursorPosition(int position) { +void TagWidget::setCursorPosition(int position) +{ blockSignals(true); GroupedLineEdit::setCursorPosition(position); blockSignals(false); } -void TagWidget::setText(QString text) { +void TagWidget::setText(QString text) +{ blockSignals(true); GroupedLineEdit::setText(text); blockSignals(false); highlight(); } -void TagWidget::clear() { +void TagWidget::clear() +{ blockSignals(true); GroupedLineEdit::clear(); blockSignals(false); } -void TagWidget::keyPressEvent(QKeyEvent *e) { +void TagWidget::keyPressEvent(QKeyEvent *e) +{ switch (e->key()) { case Qt::Key_Return: case Qt::Key_Enter: @@ -188,7 +198,8 @@ void TagWidget::keyPressEvent(QKeyEvent *e) { } } -void TagWidget::wheelEvent(QWheelEvent *event) { +void TagWidget::wheelEvent(QWheelEvent *event) +{ if (hasFocus()) { GroupedLineEdit::wheelEvent(event); } diff --git a/qt-ui/tagwidget.h b/qt-ui/tagwidget.h index 5f8fb331b..161ec0601 100644 --- a/qt-ui/tagwidget.h +++ b/qt-ui/tagwidget.h @@ -5,11 +5,10 @@ #include <QCompleter> #include <QPair> -class TagWidget : public GroupedLineEdit -{ - Q_OBJECT +class TagWidget : public GroupedLineEdit { + Q_OBJECT public: - explicit TagWidget(QWidget *parent = 0); + explicit TagWidget(QWidget *parent = 0); void setCompleter(QCompleter *completer); QPair<int, int> getCursorTagPosition(); void highlight(); @@ -17,11 +16,14 @@ public: void clear(); void setCursorPosition(int position); void wheelEvent(QWheelEvent *event); -public slots: +public +slots: void reparse(); void completionSelected(QString); + protected: void keyPressEvent(QKeyEvent *e); + private: QCompleter *m_completer; }; diff --git a/qt-ui/usermanual.cpp b/qt-ui/usermanual.cpp index cb9b4da50..58cc82f7f 100644 --- a/qt-ui/usermanual.cpp +++ b/qt-ui/usermanual.cpp @@ -5,8 +5,7 @@ #include "../helpers.h" -UserManual::UserManual(QWidget *parent) : - QMainWindow(parent), +UserManual::UserManual(QWidget *parent) : QMainWindow(parent), ui(new Ui::UserManual) { ui->setupUi(this); @@ -56,14 +55,15 @@ void UserManual::hideSearchPanel() void UserManual::search(QString text, QWebPage::FindFlags flags = 0) { - if (ui->webView->findText(text, QWebPage::FindWrapsAroundDocument|flags) || text.length() == 0) { + if (ui->webView->findText(text, QWebPage::FindWrapsAroundDocument | flags) || text.length() == 0) { ui->searchEdit->setStyleSheet(""); } else { ui->searchEdit->setStyleSheet("QLineEdit{background: red;}"); } } -void UserManual::searchTextChanged(QString text) { +void UserManual::searchTextChanged(QString text) +{ bool hasText = text.length() > 0; ui->findPrev->setEnabled(hasText); diff --git a/qt-ui/usermanual.h b/qt-ui/usermanual.h index 6c5860206..280ca3896 100644 --- a/qt-ui/usermanual.h +++ b/qt-ui/usermanual.h @@ -4,19 +4,20 @@ #include <QMainWindow> #include <QWebPage> -namespace Ui { -class UserManual; +namespace Ui +{ + class UserManual; } -class UserManual : public QMainWindow -{ +class UserManual : public QMainWindow { Q_OBJECT public: explicit UserManual(QWidget *parent = 0); ~UserManual(); -private slots: +private +slots: void showSearchPanel(); void hideSearchPanel(); void searchTextChanged(QString); |